58#include "llvm/IR/IntrinsicsWebAssembly.h"
91#define DEBUG_TYPE "local"
93STATISTIC(NumRemoved,
"Number of unreachable basic blocks removed");
94STATISTIC(NumPHICSEs,
"Number of PHI's that got CSE'd");
98#ifdef EXPENSIVE_CHECKS
104 cl::desc(
"Perform extra assertion checking to verify that PHINodes's hash "
105 "function is well-behaved w.r.t. its isEqual predicate"));
110 "When the basic block contains not more than this number of PHI nodes, "
111 "perform a (faster!) exhaustive search instead of set-driven one."));
114 "max-phi-entries-increase-after-removing-empty-block",
cl::init(1000),
116 cl::desc(
"Stop removing an empty block if removing it will introduce more "
117 "than this number of phi entries in its successor"));
141 if (
auto *BI = dyn_cast<BranchInst>(
T)) {
142 if (BI->isUnconditional())
return false;
147 if (Dest2 == Dest1) {
153 assert(BI->getParent() &&
"Terminator not inserted in block!");
160 NewBI->
copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
161 LLVMContext::MD_annotation});
164 BI->eraseFromParent();
165 if (DeleteDeadConditions)
170 if (
auto *
Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
184 NewBI->
copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
185 LLVMContext::MD_annotation});
187 BI->eraseFromParent();
189 DTU->
applyUpdates({{DominatorTree::Delete, BB, OldDest}});
196 if (
auto *SI = dyn_cast<SwitchInst>(
T)) {
199 auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
200 BasicBlock *DefaultDest = SI->getDefaultDest();
204 if (SI->defaultDestUnreachable() && SI->getNumCases() > 0)
205 TheOnlyDest = SI->case_begin()->getCaseSuccessor();
207 bool Changed =
false;
210 for (
auto It = SI->case_begin(),
End = SI->case_end(); It !=
End;) {
212 if (It->getCaseValue() == CI) {
213 TheOnlyDest = It->getCaseSuccessor();
219 if (It->getCaseSuccessor() == DefaultDest) {
221 unsigned NCases = SI->getNumCases();
224 if (NCases > 1 && MD) {
230 unsigned Idx = It->getCaseIndex();
232 Weights[0] += Weights[
Idx + 1];
241 It = SI->removeCase(It);
242 End = SI->case_end();
246 if (
auto *NewCI = dyn_cast<ConstantInt>(SI->getCondition())) {
248 It = SI->case_begin();
258 if (It->getCaseSuccessor() != TheOnlyDest)
259 TheOnlyDest =
nullptr;
265 if (CI && !TheOnlyDest) {
268 TheOnlyDest = SI->getDefaultDest();
283 if (DTU && Succ != TheOnlyDest)
284 RemovedSuccessors.
insert(Succ);
286 if (Succ == SuccToKeep) {
287 SuccToKeep =
nullptr;
295 SI->eraseFromParent();
296 if (DeleteDeadConditions)
299 std::vector<DominatorTree::UpdateType> Updates;
300 Updates.reserve(RemovedSuccessors.
size());
301 for (
auto *RemovedSuccessor : RemovedSuccessors)
302 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
308 if (SI->getNumCases() == 1) {
311 auto FirstCase = *SI->case_begin();
313 FirstCase.getCaseValue(),
"cond");
317 FirstCase.getCaseSuccessor(),
318 SI->getDefaultDest());
330 MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
332 NewBr->
setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
335 SI->eraseFromParent();
341 if (
auto *IBI = dyn_cast<IndirectBrInst>(
T)) {
344 dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
345 BasicBlock *TheOnlyDest = BA->getBasicBlock();
352 for (
unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
354 if (DTU && DestBB != TheOnlyDest)
355 RemovedSuccessors.
insert(DestBB);
356 if (IBI->getDestination(i) == SuccToKeep) {
357 SuccToKeep =
nullptr;
363 IBI->eraseFromParent();
364 if (DeleteDeadConditions)
371 BA->destroyConstant();
382 std::vector<DominatorTree::UpdateType> Updates;
383 Updates.reserve(RemovedSuccessors.
size());
384 for (
auto *RemovedSuccessor : RemovedSuccessors)
385 Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
414 if (
II->getIntrinsicID() == Intrinsic::stacksave ||
415 II->getIntrinsicID() == Intrinsic::launder_invariant_group ||
416 II->isLifetimeStartOrEnd())
423 if (
I->isTerminator())
437 if (
auto *CB = dyn_cast<CallBase>(
I))
441 if (!
I->willReturn()) {
442 auto *
II = dyn_cast<IntrinsicInst>(
I);
446 switch (
II->getIntrinsicID()) {
447 case Intrinsic::experimental_guard: {
451 auto *
Cond = dyn_cast<ConstantInt>(
II->getArgOperand(0));
456 case Intrinsic::wasm_trunc_signed:
457 case Intrinsic::wasm_trunc_unsigned:
458 case Intrinsic::ptrauth_auth:
459 case Intrinsic::ptrauth_resign:
466 if (!
I->mayHaveSideEffects())
473 if (
II->getIntrinsicID() == Intrinsic::stacksave ||
474 II->getIntrinsicID() == Intrinsic::launder_invariant_group)
479 if (
II->getIntrinsicID() == Intrinsic::allow_runtime_check ||
480 II->getIntrinsicID() == Intrinsic::allow_ubsan_check)
483 if (
II->isLifetimeStartOrEnd()) {
484 auto *Arg =
II->getArgOperand(0);
485 if (isa<PoisonValue>(Arg))
491 return isa<LifetimeIntrinsic>(Use.getUser());
496 if (
II->getIntrinsicID() == Intrinsic::assume &&
499 return !
Cond->isZero();
504 if (
auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(
I)) {
505 std::optional<fp::ExceptionBehavior> ExBehavior =
506 FPI->getExceptionBehavior();
511 if (
auto *Call = dyn_cast<CallBase>(
I)) {
513 if (
Constant *
C = dyn_cast<Constant>(FreedOp))
514 return C->isNullValue() || isa<UndefValue>(
C);
520 if (
auto *LI = dyn_cast<LoadInst>(
I))
521 if (
auto *GV = dyn_cast<GlobalVariable>(
522 LI->getPointerOperand()->stripPointerCasts()))
523 if (!LI->isVolatile() && GV->isConstant())
535 std::function<
void(
Value *)> AboutToDeleteCallback) {
543 AboutToDeleteCallback);
551 std::function<
void(
Value *)> AboutToDeleteCallback) {
552 unsigned S = 0, E = DeadInsts.
size(), Alive = 0;
553 for (; S != E; ++S) {
554 auto *
I = dyn_cast_or_null<Instruction>(DeadInsts[S]);
556 DeadInsts[S] =
nullptr;
563 AboutToDeleteCallback);
570 std::function<
void(
Value *)> AboutToDeleteCallback) {
572 while (!DeadInsts.
empty()) {
578 "Live instruction found in dead worklist!");
579 assert(
I->use_empty() &&
"Instructions with uses are not dead.");
584 if (AboutToDeleteCallback)
585 AboutToDeleteCallback(
I);
589 for (
Use &OpU :
I->operands()) {
590 Value *OpV = OpU.get();
606 I->eraseFromParent();
613 for (
auto *DVR : DPUsers)
614 DVR->setKillLocation();
615 return !DPUsers.
empty();
629 for (++UI; UI != UE; ++UI) {
646 I = cast<Instruction>(*
I->user_begin())) {
652 if (!Visited.
insert(
I).second) {
672 for (
unsigned i = 0, e =
I->getNumOperands(); i != e; ++i) {
673 Value *OpV =
I->getOperand(i);
674 I->setOperand(i,
nullptr);
687 I->eraseFromParent();
695 for (
User *U :
I->users()) {
697 WorkList.
insert(cast<Instruction>(U));
702 bool Changed =
false;
703 if (!
I->use_empty()) {
704 I->replaceAllUsesWith(SimpleV);
708 I->eraseFromParent();
723 bool MadeChange =
false;
740 assert(!BI->isTerminator());
750 while (!WorkList.
empty()) {
765 while (
PHINode *PN = dyn_cast<PHINode>(DestBB->
begin())) {
766 Value *NewVal = PN->getIncomingValue(0);
769 PN->replaceAllUsesWith(NewVal);
770 PN->eraseFromParent();
774 assert(PredBB &&
"Block doesn't have a single predecessor!");
788 if (PredOfPredBB != PredBB)
789 if (SeenPreds.
insert(PredOfPredBB).second)
790 Updates.
push_back({DominatorTree::Insert, PredOfPredBB, DestBB});
793 if (SeenPreds.
insert(PredOfPredBB).second)
794 Updates.
push_back({DominatorTree::Delete, PredOfPredBB, PredBB});
795 Updates.
push_back({DominatorTree::Delete, PredBB, DestBB});
825 "The successor list of PredBB isn't empty before "
826 "applying corresponding DTU updates.");
847 return First == Second || isa<UndefValue>(
First) || isa<UndefValue>(Second);
878 if (BBPreds.
count(IBB) &&
882 <<
"Can't fold, phi node " << PN->
getName() <<
" in "
883 << Succ->
getName() <<
" is conflicting with "
884 << BBPN->
getName() <<
" with regard to common predecessor "
896 if (BBPreds.
count(IBB) &&
900 <<
" is conflicting with regard to common "
901 <<
"predecessor " << IBB->
getName() <<
"\n");
928 if (!isa<UndefValue>(OldVal)) {
930 IncomingValues.
find(BB)->second == OldVal) &&
931 "Expected OldVal to match incoming value from BB!");
933 IncomingValues.
insert(std::make_pair(BB, OldVal));
938 if (It != IncomingValues.
end())
return It->second;
957 if (!isa<UndefValue>(V))
958 IncomingValues.
insert(std::make_pair(BB, V));
973 if (!isa<UndefValue>(V))
continue;
982 if (It == IncomingValues.
end()) {
995 unsigned PoisonCount =
count_if(TrueUndefOps, [&](
unsigned i) {
998 if (PoisonCount != 0 && PoisonCount != TrueUndefOps.
size()) {
999 for (
unsigned i : TrueUndefOps)
1013 if (BB->
phis().empty() || Succ->
phis().empty())
1028 if (BBPreds.
count(SuccPred)) {
1031 CommonPred = SuccPred;
1047 unsigned NumChangedPhi = 0;
1048 for (
auto &Phi : Succ->
phis()) {
1051 if (
auto *IncomingPhi = dyn_cast<PHINode>(Phi.getIncomingValueForBlock(BB)))
1052 if (IncomingPhi->getParent() == BB)
1061 return (NumPreds - 1) * NumChangedPhi >
1078 assert(OldVal &&
"No entry in PHI for Pred BB!");
1095 if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->
getParent() == BB) {
1096 PHINode *OldValPN = cast<PHINode>(OldVal);
1105 if (PredBB == CommonPred)
1123 if (PredBB == CommonPred)
1143 "TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
1160 BB, Succ, BBPreds, CommonPred);
1182 while (isa<PHINode>(*BBI)) {
1183 for (
Use &U : BBI->uses()) {
1184 if (
PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
1185 if (PN->getIncomingBlock(U) != BB)
1195 if (BBPhisMergeable && CommonPred)
1197 <<
" and " << Succ->
getName() <<
" : "
1198 << CommonPred->
getName() <<
"\n");
1266 if (TI->hasNonDebugLocLoopMetadata())
1269 if (PredTI->hasNonDebugLocLoopMetadata())
1274 else if (BBPhisMergeable)
1290 if (SeenPreds.
insert(PredOfBB).second)
1291 Updates.
push_back({DominatorTree::Insert, PredOfBB, Succ});
1299 if (SeenPreds.
insert(PredOfBB).second && PredOfBB != CommonPred)
1300 Updates.
push_back({DominatorTree::Delete, PredOfBB, BB});
1303 Updates.
push_back({DominatorTree::Delete, BB, Succ});
1306 if (isa<PHINode>(Succ->
begin())) {
1326 while (
PHINode *PN = dyn_cast<PHINode>(&BB->
front())) {
1328 assert(PN->use_empty() &&
"There shouldn't be any uses here!");
1329 PN->eraseFromParent();
1337 if (TI->hasNonDebugLocLoopMetadata()) {
1338 MDNode *LoopMD = TI->getMetadata(LLVMContext::MD_loop);
1340 Pred->getTerminator()->setMetadata(LLVMContext::MD_loop, LoopMD);
1356 "applying corresponding DTU updates.");
1357 }
else if (BBPhisMergeable) {
1360 if (
Instruction *UseInst = dyn_cast<Instruction>(U.getUser()))
1361 return UseInst->
getParent() != CommonPred &&
1362 BBPreds.
contains(UseInst->getParent());
1383 bool Changed =
false;
1388 for (
auto I = BB->
begin();
PHINode *PN = dyn_cast<PHINode>(
I);) {
1393 for (
auto J =
I;
PHINode *DuplicatePN = dyn_cast<PHINode>(J); ++J) {
1394 if (
ToRemove.contains(DuplicatePN))
1419 struct PHIDenseMapInfo {
1420 static PHINode *getEmptyKey() {
1424 static PHINode *getTombstoneKey() {
1429 return PN == getEmptyKey() || PN == getTombstoneKey();
1438 return static_cast<unsigned>(
1443 static unsigned getHashValue(
PHINode *PN) {
1458 return LHS->isIdenticalTo(
RHS);
1476 bool Changed =
false;
1477 for (
auto I = BB->
begin();
PHINode *PN = dyn_cast<PHINode>(
I++);) {
1480 auto Inserted = PHISet.
insert(PN);
1481 if (!Inserted.second) {
1484 PN->replaceAllUsesWith(*Inserted.first);
1513 PN->eraseFromParent();
1519 V = V->stripPointerCasts();
1521 if (
AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1527 Align CurrentAlign = AI->getAlign();
1528 if (PrefAlign <= CurrentAlign)
1529 return CurrentAlign;
1534 if (StackAlign && PrefAlign > *StackAlign)
1535 return CurrentAlign;
1536 AI->setAlignment(PrefAlign);
1540 if (
auto *GV = dyn_cast<GlobalVariable>(V)) {
1542 Align CurrentAlign = GV->getPointerAlignment(
DL);
1543 if (PrefAlign <= CurrentAlign)
1544 return CurrentAlign;
1550 if (!GV->canIncreaseAlignment())
1551 return CurrentAlign;
1553 if (GV->isThreadLocal()) {
1554 unsigned MaxTLSAlign = GV->getParent()->getMaxTLSAlignment() / CHAR_BIT;
1555 if (MaxTLSAlign && PrefAlign >
Align(MaxTLSAlign))
1556 PrefAlign =
Align(MaxTLSAlign);
1559 GV->setAlignment(PrefAlign);
1571 assert(V->getType()->isPointerTy() &&
1572 "getOrEnforceKnownAlignment expects a pointer!");
1584 if (PrefAlign && *PrefAlign > Alignment)
1606 if ((DVR->getVariable() == DIVar) && (DVR->getExpression() == DIExpr))
1622 TypeSize ValueSize =
DL.getTypeAllocSizeInBits(ValTy);
1623 if (std::optional<uint64_t> FragmentSize =
1633 "address of variable must have exactly 1 location operand.");
1636 if (std::optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(
DL)) {
1637 return TypeSize::isKnownGE(ValueSize, *FragmentSize);
1653 Instr->getParent()->insertDbgRecordBefore(DVRec, Instr);
1658 return DIExpression::get(DIExpr->
getContext(),
1666 assert(DIVar &&
"Missing variable");
1668 Value *DV = SI->getValueOperand();
1685 DIExpr->isDeref() || (!DIExpr->startsWithDeref() &&
1695 LLVM_DEBUG(
dbgs() <<
"Failed to convert dbg.declare to dbg.value: " << *DVR
1705 SI->getParent()->insertDbgRecordBefore(NewDVR, SI->getIterator());
1711 assert(DIVar &&
"Missing variable");
1714 Value *DV = SI->getValueOperand();
1726 assert(DIVar &&
"Missing variable");
1732 LLVM_DEBUG(
dbgs() <<
"Failed to convert dbg.declare to DbgVariableRecord: "
1748 LI->
getParent()->insertDbgRecordAfter(DV, LI);
1765 assert(DIVar &&
"Missing variable");
1774 LLVM_DEBUG(
dbgs() <<
"Failed to convert dbg.declare to DbgVariableRecord: "
1787 if (InsertionPt != BB->
end()) {
1796 bool Changed =
false;
1800 for (
auto &FI :
F) {
1802 if (
auto *DDI = dyn_cast<DbgDeclareInst>(&BI))
1805 if (DVR.getType() == DbgVariableRecord::LocationType::Declare)
1816 dyn_cast_or_null<AllocaInst>(DDI->getVariableLocationOp(0));
1828 if (LoadInst *LI = dyn_cast<LoadInst>(U))
1829 return LI->isVolatile();
1830 if (StoreInst *SI = dyn_cast<StoreInst>(U))
1831 return SI->isVolatile();
1838 while (!WorkList.
empty()) {
1840 for (
const auto &AIUse : V->uses()) {
1841 User *U = AIUse.getUser();
1842 if (
StoreInst *SI = dyn_cast<StoreInst>(U)) {
1843 if (AIUse.getOperandNo() == 1)
1845 }
else if (
LoadInst *LI = dyn_cast<LoadInst>(U)) {
1847 }
else if (
CallInst *CI = dyn_cast<CallInst>(U)) {
1851 if (!CI->isLifetimeStartOrEnd()) {
1859 }
else if (
BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
1860 if (BI->getType()->isPointerTy())
1865 DDI->eraseFromParent();
1881 assert(BB &&
"No BasicBlock to clone DbgVariableRecord(s) from.");
1882 if (InsertedPHIs.
size() == 0)
1887 for (
auto &
I : *BB) {
1889 for (
Value *V : DVR.location_ops())
1890 if (
auto *Loc = dyn_cast_or_null<PHINode>(V))
1891 DbgValueMap.
insert({Loc, &DVR});
1894 if (DbgValueMap.
size() == 0)
1909 for (
auto PHI : InsertedPHIs) {
1914 for (
auto VI :
PHI->operand_values()) {
1915 auto V = DbgValueMap.
find(VI);
1916 if (V != DbgValueMap.
end()) {
1918 auto NewDI = NewDbgValueMap.
find({Parent, DbgII});
1919 if (NewDI == NewDbgValueMap.
end()) {
1921 NewDI = NewDbgValueMap.
insert({{Parent, DbgII}, NewDbgII}).first;
1932 for (
auto DI : NewDbgValueMap) {
1936 assert(InsertionPt != Parent->
end() &&
"Ill-formed basic block");
1948 assert(DII->getVariable() &&
"Missing variable");
1949 auto *DIExpr = DII->getExpression();
1951 DII->setExpression(DIExpr);
1952 DII->replaceVariableLocationOp(
Address, NewAddress);
1957 return !DVRDeclares.
empty();
1965 assert(DIVar &&
"Missing variable");
1990 DVR->getExpression(), NewAllocaAddress, DVR,
2003 Instruction *
I = dyn_cast<Instruction>(Assign->getAddress());
2008 assert(!Assign->getAddressExpression()->getFragmentInfo().has_value() &&
2009 "address-expression shouldn't have fragment info");
2022 Assign->getAddressExpression(), Ops, 0,
false);
2024 "address-expression shouldn't have fragment info");
2029 if (AdditionalValues.
empty()) {
2030 Assign->setAddress(NewV);
2031 Assign->setAddressExpression(SalvagedExpr);
2033 Assign->setKillAddress();
2042 const unsigned MaxDebugArgs = 16;
2043 const unsigned MaxExpressionSize = 128;
2044 bool Salvaged =
false;
2046 for (
auto *DVR : DPUsers) {
2047 if (DVR->isDbgAssign()) {
2048 if (DVR->getAddress() == &
I) {
2052 if (DVR->getValue() != &
I)
2060 DVR->getType() != DbgVariableRecord::LocationType::Declare;
2061 auto DVRLocation = DVR->location_ops();
2064 "DbgVariableIntrinsic must use salvaged instruction as its location");
2070 Value *Op0 =
nullptr;
2072 auto LocItr =
find(DVRLocation, &
I);
2073 while (SalvagedExpr && LocItr != DVRLocation.end()) {
2075 unsigned LocNo = std::distance(DVRLocation.begin(), LocItr);
2082 LocItr = std::find(++LocItr, DVRLocation.end(), &
I);
2090 DVR->replaceVariableLocationOp(&
I, Op0);
2091 bool IsValidSalvageExpr =
2093 if (AdditionalValues.
empty() && IsValidSalvageExpr) {
2094 DVR->setExpression(SalvagedExpr);
2095 }
else if (DVR->getType() != DbgVariableRecord::LocationType::Declare &&
2096 IsValidSalvageExpr &&
2097 DVR->getNumVariableLocationOps() + AdditionalValues.
size() <=
2099 DVR->addVariableLocationOps(AdditionalValues, SalvagedExpr);
2105 DVR->setKillLocation();
2114 for (
auto *DVR : DPUsers)
2115 DVR->setKillLocation();
2122 unsigned BitWidth =
DL.getIndexSizeInBits(
GEP->getPointerAddressSpace());
2126 if (!
GEP->collectOffset(
DL,
BitWidth, VariableOffsets, ConstantOffset))
2128 if (!VariableOffsets.
empty() && !CurrentLocOps) {
2129 Opcodes.
insert(Opcodes.
begin(), {dwarf::DW_OP_LLVM_arg, 0});
2132 for (
const auto &
Offset : VariableOffsets) {
2135 "Expected strictly positive multiplier for offset.");
2137 Offset.second.getZExtValue(), dwarf::DW_OP_mul,
2138 dwarf::DW_OP_plus});
2141 return GEP->getOperand(0);
2146 case Instruction::Add:
2147 return dwarf::DW_OP_plus;
2148 case Instruction::Sub:
2149 return dwarf::DW_OP_minus;
2150 case Instruction::Mul:
2151 return dwarf::DW_OP_mul;
2152 case Instruction::SDiv:
2153 return dwarf::DW_OP_div;
2154 case Instruction::SRem:
2155 return dwarf::DW_OP_mod;
2156 case Instruction::Or:
2157 return dwarf::DW_OP_or;
2158 case Instruction::And:
2159 return dwarf::DW_OP_and;
2160 case Instruction::Xor:
2161 return dwarf::DW_OP_xor;
2162 case Instruction::Shl:
2163 return dwarf::DW_OP_shl;
2164 case Instruction::LShr:
2165 return dwarf::DW_OP_shr;
2166 case Instruction::AShr:
2167 return dwarf::DW_OP_shra;
2178 if (!CurrentLocOps) {
2183 AdditionalValues.
push_back(
I->getOperand(1));
2190 auto *ConstInt = dyn_cast<ConstantInt>(BI->
getOperand(1));
2192 if (ConstInt && ConstInt->getBitWidth() > 64)
2198 uint64_t Val = ConstInt->getSExtValue();
2201 if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {
2202 uint64_t Offset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);
2206 Opcodes.
append({dwarf::DW_OP_constu, Val});
2225 return dwarf::DW_OP_eq;
2227 return dwarf::DW_OP_ne;
2230 return dwarf::DW_OP_gt;
2233 return dwarf::DW_OP_ge;
2236 return dwarf::DW_OP_lt;
2239 return dwarf::DW_OP_le;
2249 auto *ConstInt = dyn_cast<ConstantInt>(Icmp->
getOperand(1));
2251 if (ConstInt && ConstInt->getBitWidth() > 64)
2259 uint64_t Val = ConstInt->getSExtValue();
2277 auto &M = *
I.getModule();
2278 auto &
DL = M.getDataLayout();
2280 if (
auto *CI = dyn_cast<CastInst>(&
I)) {
2281 Value *FromValue = CI->getOperand(0);
2283 if (CI->isNoopCast(
DL)) {
2292 !(isa<TruncInst>(&
I) || isa<SExtInst>(&
I) || isa<ZExtInst>(&
I) ||
2293 isa<IntToPtrInst>(&
I) || isa<PtrToIntInst>(&
I)))
2297 if (FromType->isPointerTy())
2298 FromType =
DL.getIntPtrType(FromType);
2300 unsigned FromTypeBitSize = FromType->getScalarSizeInBits();
2305 Ops.
append(ExtOps.begin(), ExtOps.end());
2309 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(&
I))
2311 if (
auto *BI = dyn_cast<BinaryOperator>(&
I))
2313 if (
auto *IC = dyn_cast<ICmpInst>(&
I))
2334 if (DPUsers.
empty())
2338 bool Changed =
false;
2341 if (isa<Instruction>(&To)) {
2342 bool DomPointAfterFrom =
From.getNextNode() == &DomPoint;
2345 for (
auto *DVR : DPUsers) {
2351 if (DomPointAfterFrom && NextNonDebug == &DomPoint) {
2354 DomPoint.
getParent()->insertDbgRecordAfter(DVR, &DomPoint);
2359 }
else if (!DT.
dominates(&DomPoint, MarkedInstr)) {
2360 UndefOrSalvageDVR.
insert(DVR);
2366 for (
auto *DVR : DPUsers) {
2367 if (UndefOrSalvageDVR.
count(DVR))
2380 if (!UndefOrSalvageDVR.
empty()) {
2404 bool SameSize =
DL.getTypeSizeInBits(FromTy) ==
DL.getTypeSizeInBits(ToTy);
2405 bool LosslessConversion = !
DL.isNonIntegralPointerType(FromTy) &&
2406 !
DL.isNonIntegralPointerType(ToTy);
2407 return SameSize && LosslessConversion;
2417 if (!
From.isUsedByMetadata())
2420 assert(&
From != &To &&
"Can't replace something with itself");
2426 return DVR.getExpression();
2440 assert(FromBits != ToBits &&
"Unexpected no-op conversion");
2444 if (FromBits < ToBits)
2455 return std::nullopt;
2457 bool Signed = *Signedness == DIBasicType::Signedness::Signed;
2470 bool Changed =
false;
2472 I->dropDbgRecords();
2473 for (
Use &U :
I->operands()) {
2475 if (isa<Instruction>(
Op) && !
Op->getType()->isTokenTy()) {
2486 unsigned NumDeadInst = 0;
2493 while (EndInst != &BB->
front()) {
2526 Successor->removePredecessor(BB, PreserveLCSSA);
2531 UI->setDebugLoc(
I->getDebugLoc());
2534 unsigned NumInstrsRemoved = 0;
2536 while (BBI != BBE) {
2537 if (!BBI->use_empty())
2539 BBI++->eraseFromParent();
2545 for (
BasicBlock *UniqueSuccessor : UniqueSuccessors)
2546 Updates.
push_back({DominatorTree::Delete, BB, UniqueSuccessor});
2550 return NumInstrsRemoved;
2556 II->getOperandBundlesAsDefs(OpBundles);
2558 II->getCalledOperand(), Args, OpBundles);
2569 auto NewWeights =
uint32_t(TotalWeight) != TotalWeight
2572 NewCall->
setMetadata(LLVMContext::MD_prof, NewWeights);
2583 II->replaceAllUsesWith(NewCall);
2591 BI->setDebugLoc(
II->getDebugLoc());
2597 II->eraseFromParent();
2599 DTU->
applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
2628 UnwindEdge, InvokeArgs, OpBundles, CI->
getName(), BB);
2632 II->setMetadata(LLVMContext::MD_prof, CI->
getMetadata(LLVMContext::MD_prof));
2635 DTU->
applyUpdates({{DominatorTree::Insert, BB, UnwindEdge}});
2642 Split->front().eraseFromParent();
2653 bool Changed =
false;
2661 if (
auto *CI = dyn_cast<CallInst>(&
I)) {
2662 Value *Callee = CI->getCalledOperand();
2664 if (
Function *
F = dyn_cast<Function>(Callee)) {
2665 auto IntrinsicID =
F->getIntrinsicID();
2670 if (IntrinsicID == Intrinsic::assume) {
2677 }
else if (IntrinsicID == Intrinsic::experimental_guard) {
2688 if (!isa<UnreachableInst>(CI->getNextNode())) {
2694 }
else if ((isa<ConstantPointerNull>(Callee) &&
2696 cast<PointerType>(Callee->getType())
2697 ->getAddressSpace())) ||
2698 isa<UndefValue>(Callee)) {
2703 if (CI->doesNotReturn() && !CI->isMustTailCall()) {
2707 if (!isa<UnreachableInst>(CI->getNextNode())) {
2714 }
else if (
auto *SI = dyn_cast<StoreInst>(&
I)) {
2720 if (SI->isVolatile())
continue;
2724 if (isa<UndefValue>(
Ptr) ||
2725 (isa<ConstantPointerNull>(
Ptr) &&
2727 SI->getPointerAddressSpace()))) {
2736 if (
auto *
II = dyn_cast<InvokeInst>(Terminator)) {
2738 Value *Callee =
II->getCalledOperand();
2739 if ((isa<ConstantPointerNull>(Callee) &&
2741 isa<UndefValue>(Callee)) {
2745 if (
II->doesNotReturn() &&
2746 !isa<UnreachableInst>(
II->getNormalDest()->front())) {
2756 Ctx, OrigNormalDest->
getName() +
".unreachable",
2757 II->getFunction(), OrigNormalDest);
2760 II->setNormalDest(UnreachableNormalDest);
2763 {{DominatorTree::Delete, BB, OrigNormalDest},
2764 {DominatorTree::Insert, BB, UnreachableNormalDest}});
2768 if (
II->use_empty() && !
II->mayHaveSideEffects()) {
2774 II->eraseFromParent();
2776 DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
2782 }
else if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
2784 struct CatchPadDenseMapInfo {
2799 if (
LHS == getEmptyKey() ||
LHS == getTombstoneKey() ||
2800 RHS == getEmptyKey() ||
RHS == getTombstoneKey())
2802 return LHS->isIdenticalTo(
RHS);
2813 E = CatchSwitch->handler_end();
2817 ++NumPerSuccessorCases[HandlerBB];
2819 if (!HandlerSet.insert({CatchPad, Empty}).second) {
2821 --NumPerSuccessorCases[HandlerBB];
2822 CatchSwitch->removeHandler(
I);
2829 std::vector<DominatorTree::UpdateType> Updates;
2830 for (
const std::pair<BasicBlock *, int> &
I : NumPerSuccessorCases)
2832 Updates.push_back({DominatorTree::Delete, BB,
I.first});
2833 DTU->applyUpdates(Updates);
2841 }
while (!Worklist.
empty());
2848 if (
auto *
II = dyn_cast<InvokeInst>(TI))
2854 if (
auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
2856 UnwindDest = CRI->getUnwindDest();
2857 }
else if (
auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
2859 CatchSwitch->getParentPad(),
nullptr, CatchSwitch->getNumHandlers(),
2860 CatchSwitch->getName(), CatchSwitch->getIterator());
2861 for (
BasicBlock *PadBB : CatchSwitch->handlers())
2862 NewCatchSwitch->addHandler(PadBB);
2864 NewTI = NewCatchSwitch;
2865 UnwindDest = CatchSwitch->getUnwindDest();
2876 DTU->
applyUpdates({{DominatorTree::Delete, BB, UnwindDest}});
2889 if (Reachable.
size() ==
F.size())
2898 if (Reachable.
count(&BB))
2903 BlocksToRemove.
insert(&BB);
2906 if (BlocksToRemove.
empty())
2910 NumRemoved += BlocksToRemove.
size();
2923 bool DoesKMove,
bool AAOnly =
false) {
2925 K->getAllMetadataOtherThanDebugLoc(
Metadata);
2927 unsigned Kind = MD.first;
2934 K->setMetadata(Kind,
nullptr);
2936 case LLVMContext::MD_dbg:
2938 case LLVMContext::MD_DIAssignID:
2940 K->mergeDIAssignID(J);
2942 case LLVMContext::MD_tbaa:
2946 case LLVMContext::MD_alias_scope:
2950 case LLVMContext::MD_noalias:
2951 case LLVMContext::MD_mem_parallel_loop_access:
2955 case LLVMContext::MD_access_group:
2957 K->setMetadata(LLVMContext::MD_access_group,
2960 case LLVMContext::MD_range:
2961 if (!AAOnly && (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef)))
2964 case LLVMContext::MD_fpmath:
2968 case LLVMContext::MD_invariant_load:
2972 K->setMetadata(Kind, JMD);
2974 case LLVMContext::MD_nonnull:
2975 if (!AAOnly && (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef)))
2976 K->setMetadata(Kind, JMD);
2978 case LLVMContext::MD_invariant_group:
2984 case LLVMContext::MD_prof:
2985 case LLVMContext::MD_mmra:
2986 case LLVMContext::MD_memprof:
2987 case LLVMContext::MD_callsite:
2989 case LLVMContext::MD_callee_type:
2991 K->setMetadata(LLVMContext::MD_callee_type,
2995 case LLVMContext::MD_align:
2996 if (!AAOnly && (DoesKMove || !K->hasMetadata(LLVMContext::MD_noundef)))
3000 case LLVMContext::MD_dereferenceable:
3001 case LLVMContext::MD_dereferenceable_or_null:
3002 if (!AAOnly && DoesKMove)
3003 K->setMetadata(Kind,
3006 case LLVMContext::MD_preserve_access_index:
3009 case LLVMContext::MD_noundef:
3011 if (!AAOnly && DoesKMove)
3012 K->setMetadata(Kind, JMD);
3014 case LLVMContext::MD_nontemporal:
3017 K->setMetadata(Kind, JMD);
3019 case LLVMContext::MD_noalias_addrspace:
3021 K->setMetadata(Kind,
3024 case LLVMContext::MD_nosanitize:
3026 K->setMetadata(Kind, JMD);
3036 if (
auto *JMD = J->
getMetadata(LLVMContext::MD_invariant_group))
3037 if (isa<LoadInst>(K) || isa<StoreInst>(K))
3038 K->setMetadata(LLVMContext::MD_invariant_group, JMD);
3043 auto JMMRA = J->
getMetadata(LLVMContext::MD_mmra);
3044 auto KMMRA = K->getMetadata(LLVMContext::MD_mmra);
3045 if (JMMRA || KMMRA) {
3046 K->setMetadata(LLVMContext::MD_mmra,
3053 auto *JMemProf = J->
getMetadata(LLVMContext::MD_memprof);
3054 auto *KMemProf = K->getMetadata(LLVMContext::MD_memprof);
3055 if (!AAOnly && (JMemProf || KMemProf)) {
3056 K->setMetadata(LLVMContext::MD_memprof,
3063 auto *JCallSite = J->
getMetadata(LLVMContext::MD_callsite);
3064 auto *KCallSite = K->getMetadata(LLVMContext::MD_callsite);
3065 if (!AAOnly && (JCallSite || KCallSite)) {
3066 K->setMetadata(LLVMContext::MD_callsite,
3073 auto *JProf = J->
getMetadata(LLVMContext::MD_prof);
3074 auto *KProf = K->getMetadata(LLVMContext::MD_prof);
3075 if (!AAOnly && (JProf || KProf)) {
3076 K->setMetadata(LLVMContext::MD_prof,
3092 Source.getAllMetadata(MD);
3096 for (
const auto &MDPair : MD) {
3097 unsigned ID = MDPair.first;
3107 case LLVMContext::MD_dbg:
3108 case LLVMContext::MD_tbaa:
3109 case LLVMContext::MD_prof:
3110 case LLVMContext::MD_fpmath:
3111 case LLVMContext::MD_tbaa_struct:
3112 case LLVMContext::MD_invariant_load:
3113 case LLVMContext::MD_alias_scope:
3114 case LLVMContext::MD_noalias:
3115 case LLVMContext::MD_nontemporal:
3116 case LLVMContext::MD_mem_parallel_loop_access:
3117 case LLVMContext::MD_access_group:
3118 case LLVMContext::MD_noundef:
3119 case LLVMContext::MD_noalias_addrspace:
3124 case LLVMContext::MD_nonnull:
3128 case LLVMContext::MD_align:
3129 case LLVMContext::MD_dereferenceable:
3130 case LLVMContext::MD_dereferenceable_or_null:
3136 case LLVMContext::MD_range:
3144 auto *ReplInst = dyn_cast<Instruction>(Repl);
3153 if (isa<OverflowingBinaryOperator>(ReplInst) &&
3160 else if (!isa<LoadInst>(
I))
3161 ReplInst->andIRFlags(
I);
3164 if (
auto *CB1 = dyn_cast<CallBase>(ReplInst)) {
3165 if (
auto *CB2 = dyn_cast<CallBase>(
I)) {
3166 bool Success = CB1->tryIntersectAttributes(CB2);
3167 assert(
Success &&
"We should not be trying to sink callbases "
3168 "with non-intersectable attributes");
3186template <
typename ShouldReplaceFn>
3188 const ShouldReplaceFn &ShouldReplace) {
3193 auto *
II = dyn_cast<IntrinsicInst>(U.getUser());
3194 if (
II &&
II->getIntrinsicID() == Intrinsic::fake_use)
3196 if (!ShouldReplace(U))
3200 dbgs() <<
"' with " << *To <<
" in " << *U.getUser() <<
"\n");
3209 auto *BB =
From->getParent();
3213 auto *
I = cast<Instruction>(U.getUser());
3214 if (
I->getParent() == BB)
3225 auto Dominates = [&](
const Use &U) {
return DT.
dominates(Root, U); };
3226 return ::replaceDominatedUsesWith(
From, To, Dominates);
3232 auto Dominates = [&](
const Use &U) {
return DT.
dominates(BB, U); };
3233 return ::replaceDominatedUsesWith(
From, To, Dominates);
3239 auto DominatesAndShouldReplace = [&](
const Use &U) {
3240 return DT.
dominates(Root, U) && ShouldReplace(U, To);
3242 return ::replaceDominatedUsesWith(
From, To, DominatesAndShouldReplace);
3248 auto DominatesAndShouldReplace = [&](
const Use &U) {
3249 return DT.
dominates(BB, U) && ShouldReplace(U, To);
3251 return ::replaceDominatedUsesWith(
From, To, DominatesAndShouldReplace);
3257 if (Call->hasFnAttr(
"gc-leaf-function"))
3259 if (
const Function *
F = Call->getCalledFunction()) {
3260 if (
F->hasFnAttribute(
"gc-leaf-function"))
3263 if (
auto IID =
F->getIntrinsicID()) {
3265 return IID != Intrinsic::experimental_gc_statepoint &&
3266 IID != Intrinsic::experimental_deoptimize &&
3267 IID != Intrinsic::memcpy_element_unordered_atomic &&
3268 IID != Intrinsic::memmove_element_unordered_atomic;
3285 auto *NewTy = NewLI.
getType();
3288 if (NewTy->isPointerTy()) {
3295 if (!NewTy->isIntegerTy())
3300 auto *ITy = cast<IntegerType>(NewTy);
3310 auto *NewTy = NewLI.
getType();
3312 if (NewTy == OldLI.
getType()) {
3321 if (!NewTy->isPointerTy())
3324 unsigned BitWidth =
DL.getPointerTypeSizeInBits(NewTy);
3335 for (
auto *DVR : DPUsers)
3336 DVR->eraseFromParent();
3365 I->dropUBImplyingAttrsAndMetadata();
3366 if (
I->isUsedByMetadata())
3369 I->dropDbgRecords();
3370 if (
I->isDebugOrPseudoInst()) {
3372 II =
I->eraseFromParent();
3386 const APInt &API = cast<ConstantInt>(&CV)->getValue();
3387 std::optional<int64_t> InitIntOpt = API.
trySExtValue();
3389 static_cast<uint64_t>(*InitIntOpt))
3393 if (isa<ConstantInt>(
C))
3394 return createIntegerExpression(
C);
3396 auto *
FP = dyn_cast<ConstantFP>(&
C);
3408 if (isa<ConstantPointerNull>(
C))
3412 if (CE->getOpcode() == Instruction::IntToPtr) {
3413 const Value *V = CE->getOperand(0);
3414 if (
auto CI = dyn_cast_or_null<ConstantInt>(V))
3415 return createIntegerExpression(*CI);
3421 auto RemapDebugOperands = [&Mapping](
auto *DV,
auto Set) {
3422 for (
auto *
Op : Set) {
3424 if (
I != Mapping.
end())
3425 DV->replaceVariableLocationOp(
Op,
I->second,
true);
3428 auto RemapAssignAddress = [&Mapping](
auto *DA) {
3429 auto I = Mapping.
find(DA->getAddress());
3430 if (
I != Mapping.
end())
3431 DA->setAddress(
I->second);
3434 RemapDebugOperands(&DVR, DVR.location_ops());
3435 if (DVR.isDbgAssign())
3436 RemapAssignAddress(&DVR);
3445 BitPart(
Value *
P,
unsigned BW) : Provider(
P) {
3456 enum {
Unset = -1 };
3488static const std::optional<BitPart> &
3490 std::map<
Value *, std::optional<BitPart>> &BPS,
int Depth,
3492 auto [
I, Inserted] = BPS.try_emplace(V);
3496 auto &Result =
I->second;
3497 auto BitWidth = V->getType()->getScalarSizeInBits();
3505 LLVM_DEBUG(
dbgs() <<
"collectBitParts max recursion depth reached.\n");
3509 if (
auto *
I = dyn_cast<Instruction>(V)) {
3517 Depth + 1, FoundRoot);
3518 if (!
A || !
A->Provider)
3522 Depth + 1, FoundRoot);
3523 if (!
B ||
A->Provider !=
B->Provider)
3527 Result = BitPart(
A->Provider,
BitWidth);
3528 for (
unsigned BitIdx = 0; BitIdx <
BitWidth; ++BitIdx) {
3529 if (
A->Provenance[BitIdx] != BitPart::Unset &&
3530 B->Provenance[BitIdx] != BitPart::Unset &&
3531 A->Provenance[BitIdx] !=
B->Provenance[BitIdx])
3532 return Result = std::nullopt;
3534 if (
A->Provenance[BitIdx] == BitPart::Unset)
3535 Result->Provenance[BitIdx] =
B->Provenance[BitIdx];
3537 Result->Provenance[BitIdx] =
A->Provenance[BitIdx];
3545 const APInt &BitShift = *
C;
3552 if (!MatchBitReversals && (BitShift.
getZExtValue() % 8) != 0)
3556 Depth + 1, FoundRoot);
3562 auto &
P = Result->Provenance;
3563 if (
I->getOpcode() == Instruction::Shl) {
3577 const APInt &AndMask = *
C;
3581 unsigned NumMaskedBits = AndMask.
popcount();
3582 if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
3586 Depth + 1, FoundRoot);
3591 for (
unsigned BitIdx = 0; BitIdx <
BitWidth; ++BitIdx)
3593 if (AndMask[BitIdx] == 0)
3594 Result->Provenance[BitIdx] = BitPart::Unset;
3601 Depth + 1, FoundRoot);
3605 Result = BitPart(Res->Provider,
BitWidth);
3606 auto NarrowBitWidth =
X->getType()->getScalarSizeInBits();
3607 for (
unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
3608 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3609 for (
unsigned BitIdx = NarrowBitWidth; BitIdx <
BitWidth; ++BitIdx)
3610 Result->Provenance[BitIdx] = BitPart::Unset;
3617 Depth + 1, FoundRoot);
3621 Result = BitPart(Res->Provider,
BitWidth);
3622 for (
unsigned BitIdx = 0; BitIdx <
BitWidth; ++BitIdx)
3623 Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
3631 Depth + 1, FoundRoot);
3635 Result = BitPart(Res->Provider,
BitWidth);
3636 for (
unsigned BitIdx = 0; BitIdx <
BitWidth; ++BitIdx)
3637 Result->Provenance[(
BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
3644 Depth + 1, FoundRoot);
3649 Result = BitPart(Res->Provider,
BitWidth);
3650 for (
unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
3651 unsigned ByteBitOfs = ByteIdx * 8;
3652 for (
unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
3653 Result->Provenance[(
BitWidth - 8 - ByteBitOfs) + BitIdx] =
3654 Res->Provenance[ByteBitOfs + BitIdx];
3671 if (!MatchBitReversals && (ModAmt % 8) != 0)
3676 Depth + 1, FoundRoot);
3677 if (!
LHS || !
LHS->Provider)
3681 Depth + 1, FoundRoot);
3682 if (!
RHS ||
LHS->Provider !=
RHS->Provider)
3685 unsigned StartBitRHS =
BitWidth - ModAmt;
3687 for (
unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
3688 Result->Provenance[BitIdx + ModAmt] =
LHS->Provenance[BitIdx];
3689 for (
unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
3690 Result->Provenance[BitIdx] =
RHS->Provenance[BitIdx + StartBitRHS];
3704 for (
unsigned BitIdx = 0; BitIdx <
BitWidth; ++BitIdx)
3705 Result->Provenance[BitIdx] = BitIdx;
3711 if (
From % 8 != To % 8)
3726 Instruction *
I,
bool MatchBSwaps,
bool MatchBitReversals,
3733 if (!MatchBSwaps && !MatchBitReversals)
3735 Type *ITy =
I->getType();
3741 bool FoundRoot =
false;
3742 std::map<Value *, std::optional<BitPart>> BPS;
3749 [](int8_t
I) {
return I == BitPart::Unset || 0 <=
I; }) &&
3750 "Illegal bit provenance index");
3753 Type *DemandedTy = ITy;
3754 if (BitProvenance.
back() == BitPart::Unset) {
3755 while (!BitProvenance.
empty() && BitProvenance.
back() == BitPart::Unset)
3756 BitProvenance = BitProvenance.
drop_back();
3757 if (BitProvenance.
empty())
3760 if (
auto *IVecTy = dyn_cast<VectorType>(ITy))
3761 DemandedTy = VectorType::get(DemandedTy, IVecTy);
3772 bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;
3773 bool OKForBitReverse = MatchBitReversals;
3774 for (
unsigned BitIdx = 0;
3775 (BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
3776 if (BitProvenance[BitIdx] == BitPart::Unset) {
3783 BitIdx, DemandedBW);
3788 Intrin = Intrinsic::bswap;
3789 else if (OKForBitReverse)
3790 Intrin = Intrinsic::bitreverse;
3796 Value *Provider = Res->Provider;
3799 if (DemandedTy != Provider->
getType()) {
3810 auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);
3816 if (ITy != Result->getType()) {
3833 if (
F && !
F->hasLocalLinkage() &&
F->hasName() &&
3835 !
F->doesNotAccessMemory())
3840 const auto *
Op =
I->getOperand(
OpIdx);
3842 if (
Op->getType()->isMetadataTy() ||
Op->getType()->isTokenLikeTy())
3848 if (
Op->isSwiftError())
3852 if (
I->isLifetimeStartOrEnd())
3856 if (!isa<Constant, InlineAsm>(
Op))
3859 switch (
I->getOpcode()) {
3862 case Instruction::Call:
3863 case Instruction::Invoke: {
3864 const auto &CB = cast<CallBase>(*
I);
3867 if (CB.isInlineAsm())
3872 if (CB.isBundleOperand(
OpIdx))
3875 if (
OpIdx < CB.arg_size()) {
3878 if (isa<IntrinsicInst>(CB) &&
3879 OpIdx >= CB.getFunctionType()->getNumParams()) {
3881 return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
3886 if (CB.getIntrinsicID() == Intrinsic::gcroot)
3890 return !CB.paramHasAttr(
OpIdx, Attribute::ImmArg);
3895 return !isa<IntrinsicInst>(CB);
3897 case Instruction::ShuffleVector:
3900 case Instruction::Switch:
3901 case Instruction::ExtractValue:
3904 case Instruction::InsertValue:
3907 case Instruction::Alloca:
3911 return !cast<AllocaInst>(
I)->isStaticAlloca();
3912 case Instruction::GetElementPtr:
3916 for (
auto E = std::next(It,
OpIdx); It != E; ++It)
3925 if (
Constant *
C = dyn_cast<Constant>(Condition))
3929 Value *NotCondition;
3931 return NotCondition;
3934 Instruction *Inst = dyn_cast<Instruction>(Condition);
3937 else if (
Argument *Arg = dyn_cast<Argument>(Condition))
3939 assert(Parent &&
"Unsupported condition to invert");
3950 if (Inst && !isa<PHINode>(Inst))
3961 bool Changed =
false;
3963 if (!
F.hasFnAttribute(Attribute::NoSync) &&
3964 F.doesNotAccessMemory() && !
F.isConvergent()) {
3970 if (!
F.hasFnAttribute(Attribute::NoFree) &&
F.onlyReadsMemory()) {
3971 F.setDoesNotFreeMemory();
3976 if (!
F.hasFnAttribute(Attribute::MustProgress) &&
F.willReturn()) {
3977 F.setMustProgress();
3991 "can only use mergeFlags on instructions with matching opcodes");
3995 if (isa<OverflowingBinaryOperator>(&
I)) {
3996 HasNUW &=
I.hasNoUnsignedWrap();
3997 HasNSW &=
I.hasNoSignedWrap();
3999 if (
auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&
I))
4004 I.clearSubclassOptionalData();
4005 if (
I.getOpcode() == Instruction::Add ||
4008 I.setHasNoUnsignedWrap();
4010 I.setHasNoSignedWrap();
4012 if (
auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&
I))
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static unsigned getIntrinsicID(const SDNode *N)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
ReachingDefAnalysis InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static bool isEqual(const Function &Caller, const Function &Callee)
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
BlockVerifier::State From
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool isSentinel(const DWARFDebugNames::AttributeEncoding &AE)
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
This file defines the DenseSet and SmallDenseSet classes.
This file contains constants used for implementing Dwarf debug support.
static unsigned getHashValueImpl(SimpleValue Val)
static bool isEqualImpl(SimpleValue LHS, SimpleValue RHS)
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
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.
This file provides utility for Memory Model Relaxation Annotations (MMRAs).
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
This file contains the declarations for profiling metadata utility functions.
const SmallVectorImpl< MachineOperand > & Cond
Remove Loads Into Fake Uses
This file implements a set that has insertion order iteration characteristics.
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)
APInt bitcastToAPInt() const
Class for arbitrary precision integers.
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
void clearBit(unsigned BitPosition)
Set a given bit to 0.
uint64_t getZExtValue() const
Get zero extended value.
unsigned popcount() const
Count the number of bits set.
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
const uint64_t * getRawData() const
This function returns a pointer to the internal storage of the APInt.
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
int64_t getSExtValue() const
Get sign extended value.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
an instruction to allocate memory on the stack
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
LLVM_ABI bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
This class represents an incoming formal argument to a Function.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
const T & back() const
back - Get the last element.
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
size_t size() const
size - Get the array size.
ArrayRef< T > drop_back(size_t N=1) const
Drop the last N elements of the array.
bool empty() const
empty - Check if the array is empty.
Value handle that asserts if the Value is deleted.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
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...
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
const Instruction & front() const
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI bool isEntryBlock() const
Return true if this is the entry block of the containing function.
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
LLVM_ABI SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
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...
LLVM_ABI bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
const Instruction & back() const
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
BinaryOps getOpcode() const
static LLVM_ABI BinaryOperator * CreateNot(Value *Op, const Twine &Name="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a no-op cast from one type to another.
The address of a basic block.
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
void setCallingConv(CallingConv::ID CC)
void addFnAttr(Attribute::AttrKind Kind)
Adds the attribute to the function.
LLVM_ABI void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
Return the list of operand bundles attached to this instruction as a vector of OperandBundleDefs.
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
CallingConv::ID getCallingConv() const
Value * getCalledOperand() const
void setAttributes(AttributeList A)
Set the attributes for this call.
FunctionType * getFunctionType() const
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
AttributeList getAttributes() const
Return the attributes for this call.
This class represents a function call, abstracting a target machine's calling convention.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * CreateIntegerCast(Value *S, Type *Ty, bool isSigned, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a ZExt, BitCast, or Trunc for int -> int casts.
static CatchSwitchInst * Create(Value *ParentPad, BasicBlock *UnwindDest, unsigned NumHandlers, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static CleanupReturnInst * Create(Value *CleanupPad, BasicBlock *UnwindBB=nullptr, InsertPosition InsertBefore=nullptr)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ ICMP_UGE
unsigned greater or equal
@ ICMP_UGT
unsigned greater than
@ ICMP_SGT
signed greater than
@ ICMP_ULT
unsigned less than
@ ICMP_SGE
signed greater or equal
@ ICMP_ULE
unsigned less or equal
Predicate getPredicate() const
Return the predicate for this instruction.
A constant value that is initialized with an expression using other constant values.
static LLVM_ABI Constant * getIntToPtr(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getNot(Constant *C)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
This is the shared class of boolean and integer constants.
static LLVM_ABI ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
This is an important base class in LLVM.
LLVM_ABI void destroyConstant()
Called if some element of this constant is no longer valid.
DIExpression * createConstantValueExpression(uint64_t Val)
Create an expression for a variable that does not have an address, but does have a constant value.
static LLVM_ABI DIExpression * append(const DIExpression *Expr, ArrayRef< uint64_t > Ops)
Append the opcodes Ops to DIExpr.
unsigned getNumElements() const
static LLVM_ABI ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed)
Returns the ops for a zero- or sign-extension in a DIExpression.
static LLVM_ABI void appendOffset(SmallVectorImpl< uint64_t > &Ops, int64_t Offset)
Append Ops with operations to apply the Offset.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
static LLVM_ABI std::optional< FragmentInfo > getFragmentInfo(expr_op_iterator Start, expr_op_iterator End)
Retrieve the details of this fragment expression.
LLVM_ABI DIExpression * foldConstantMath()
Try to shorten an expression with constant math operations that can be evaluated at compile time.
LLVM_ABI uint64_t getNumLocationOperands() const
Return the number of unique location operands referred to (via DW_OP_LLVM_arg) in this expression; th...
ArrayRef< uint64_t > getElements() const
LLVM_ABI std::optional< uint64_t > getActiveBits(DIVariable *Var)
Return the number of bits that have an active value, i.e.
uint64_t getElement(unsigned I) const
static LLVM_ABI DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
static LLVM_ABI DIExpression * appendExt(const DIExpression *Expr, unsigned FromSize, unsigned ToSize, bool Signed)
Append a zero- or sign-extension to Expr.
std::optional< DIBasicType::Signedness > getSignedness() const
Return the signedness of this variable's type, or std::nullopt if this type is neither signed nor uns...
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
This represents the llvm.dbg.label instruction.
Instruction * MarkedInstr
Link back to the Instruction that owns this marker.
LLVM_ABI void removeFromParent()
LLVM_ABI Module * getModule()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
bool isAddressOfVariable() const
Does this describe the address of a local variable.
LLVM_ABI DbgVariableRecord * clone() const
void setExpression(DIExpression *NewExpr)
DIExpression * getExpression() const
LLVM_ABI Value * getVariableLocationOp(unsigned OpIdx) const
DILocalVariable * getVariable() const
LLVM_ABI unsigned getNumVariableLocationOps() const
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
LLVM_ABI iterator_range< location_op_iterator > location_ops() const
Get the locations corresponding to the variable referenced by the debug info intrinsic.
LLVM_ABI DILocation * get() const
Get the underlying DILocation.
static DebugLoc getTemporary()
iterator find(const_arg_type_t< KeyT > Val)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Implements a dense probed hash-table based set.
LLVM_ABI void deleteBB(BasicBlock *DelBB)
Delete DelBB.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
const BasicBlock & getEntryBlock() const
void applyUpdatesPermissive(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
bool hasDomTree() const
Returns true if it holds a DomTreeT.
void recalculate(FuncT &F)
Notify DTU that the entry block was replaced.
bool isBBPendingDeletion(BasicBlockT *DelBB) const
Returns true if DelBB is awaiting deletion.
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
This instruction compares its operands according to the predicate given to the constructor.
Value * CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name="")
BranchInst * CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False, MDNode *BranchWeights=nullptr, MDNode *Unpredictable=nullptr)
Create a conditional 'br Cond, TrueDest, FalseDest' instruction.
BranchInst * CreateBr(BasicBlock *Dest)
Create an unconditional 'br label X' instruction.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI bool extractProfTotalWeight(uint64_t &TotalVal) const
Retrieve total raw weight values of a branch.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isIdenticalToWhenDefined(const Instruction *I, bool IntersectAttrs=false) const LLVM_READONLY
This is like isIdenticalTo, except that it ignores the SubclassOptionalData flags,...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
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 dropDbgRecords()
Erase any DbgRecords attached to this instruction.
A wrapper class for inspecting calls to intrinsic functions.
static InvokeInst * Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr, InsertPosition InsertBefore=nullptr)
This is an important class for using LLVM in a threaded context.
An instruction for reading from memory.
Value * getPointerOperand()
LLVM_ABI MDNode * createBranchWeights(uint32_t TrueWeight, uint32_t FalseWeight, bool IsExpected=false)
Return metadata containing two branch weights.
LLVM_ABI MDNode * createRange(const APInt &Lo, const APInt &Hi)
Return metadata describing the range [Lo, Hi).
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMergedCallsiteMetadata(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMergedCalleeTypeMetadata(const MDNode *A, const MDNode *B)
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
static LLVM_ABI MDNode * getMergedProfMetadata(MDNode *A, MDNode *B, const Instruction *AInstr, const Instruction *BInstr)
Merge !prof metadata from two instructions.
static LLVM_ABI MDNode * getMostGenericFPMath(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMostGenericRange(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * getMergedMemProfMetadata(MDNode *A, MDNode *B)
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
LLVMContext & getContext() const
static LLVM_ABI MDNode * getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B)
This class implements a map that also provides access to all stored values in a deterministic order.
iterator find(const KeyT &Key)
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
LLVM_ABI void changeToUnreachable(const Instruction *I)
Instruction I will be changed to an unreachable.
LLVM_ABI void removeBlocks(const SmallSetVector< BasicBlock *, 8 > &DeadBlocks)
Remove all MemoryAcceses in a set of BasicBlocks about to be deleted.
LLVM_ABI void removeMemoryAccess(MemoryAccess *, bool OptimizePhis=false)
Remove a MemoryAccess from MemorySSA, including updating all definitions and uses.
A Module instance is used to store all the information related to an LLVM module.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
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.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
size_type size() const
Determine the number of elements in the SetVector.
Vector takeVector()
Clear the SetVector and return the underlying vector.
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
bool empty() const
Determine if the SetVector is empty or not.
bool insert(const value_type &X)
Insert a new element into the SetVector.
value_type pop_back_val()
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
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.
Provides information about what library functions are available for the current target.
bool hasOptimizedCodeGen(LibFunc F) const
Tests if the function is both available and a candidate for optimized code generation.
bool has(LibFunc F) const
Tests whether a library function is available.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
static constexpr TypeSize getFixed(ScalarTy ExactSize)
The instances of the Type class are immutable: once they are created, they are never changed.
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool isVectorTy() const
True if this is an instance of VectorType.
bool isArrayTy() const
True if this is an instance of ArrayType.
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
bool isPointerTy() const
True if this is an instance of PointerType.
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
bool isStructTy() const
True if this is an instance of StructType.
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
bool isIntegerTy() const
True if this is an instance of IntegerType.
bool isTokenTy() const
Return true if this is 'token'.
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
This function has undefined behavior.
A Use represents the edge between a Value definition and its users.
value_op_iterator value_op_end()
Value * getOperand(unsigned i) const
value_op_iterator value_op_begin()
iterator_range< value_op_iterator > operand_values()
iterator find(const KeyT &Val)
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
iterator_range< user_iterator > users()
LLVM_ABI void replaceUsesWithIf(Value *New, llvm::function_ref< bool(Use &U)> ShouldReplace)
Go through the uses list for this definition and make each use point to "V" if the callback ShouldRep...
LLVM_ABI LLVMContext & getContext() const
All values hold a context through their type.
static constexpr unsigned MaxAlignmentExponent
The maximum alignment for instructions.
user_iterator_impl< User > user_iterator
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Represents an op.with.overflow intrinsic.
std::pair< iterator, bool > insert(const ValueT &V)
void reserve(size_t Size)
Grow the DenseSet so that it can contain at least NumEntries items before resizing again.
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > Tys={})
Look up the Function declaration of the intrinsic id in the Module M.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
m_Intrinsic_Ty< Opnd0 >::Ty m_BitReverse(const Opnd0 &Op0)
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
bind_ty< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
m_Intrinsic_Ty< Opnd0, Opnd1, Opnd2 >::Ty m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
m_Intrinsic_Ty< Opnd0, Opnd1, Opnd2 >::Ty m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2)
auto m_Undef()
Match an arbitrary undef constant.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
m_Intrinsic_Ty< Opnd0 >::Ty m_BSwap(const Opnd0 &Op0)
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
match_combine_or< LTy, RTy > m_CombineOr(const LTy &L, const RTy &R)
Combine two pattern matchers matching L || R.
initializer< Ty > init(const Ty &Val)
@ DW_OP_LLVM_arg
Only used in LLVM metadata.
@ ebStrict
This corresponds to "fpexcept.strict".
This is an optimization pass for GlobalISel generic memory operations.
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than its terminator and any present EH pad instructi...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
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.
bool succ_empty(const Instruction *I)
LLVM_ABI BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge, DomTreeUpdater *DTU=nullptr)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
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...
LLVM_ABI unsigned replaceDominatedUsesWithIf(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge, function_ref< bool(const Use &U, const Value *To)> ShouldReplace)
Replace each use of 'From' with 'To' if that use is dominated by the given edge and the callback Shou...
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
auto successors(const MachineBasicBlock *BB)
LLVM_ABI bool isRemovableAlloc(const CallBase *V, const TargetLibraryInfo *TLI)
Return true if this is a call to an allocation function that does not have side effects that we are r...
LLVM_ABI CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
LLVM_ABI bool isMathLibCallNoop(const CallBase *Call, const TargetLibraryInfo *TLI)
Check whether the given call has no side-effects.
LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
constexpr from_range_t from_range
bool hasNItemsOrLess(IterTy &&Begin, IterTy &&End, unsigned N, Pred &&ShouldBeCounted=[](const decltype(*std::declval< IterTy >()) &) { return true;})
Returns true if the sequence [Begin, End) has N or less items.
LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst)
Remap the operands of the debug records attached to Inst, and the operands of Inst itself if it's a d...
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...
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI 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...
LLVM_ABI bool isAssumeWithEmptyBundle(const AssumeInst &Assume)
Return true iff the operand bundles of the provided llvm.assume doesn't contain any valuable informat...
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
LLVM_ABI void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode * > &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI MDNode * intersectAccessGroups(const Instruction *Inst1, const Instruction *Inst2)
Compute the access-group list of access groups that Inst1 and Inst2 are both in.
LLVM_ABI bool handleUnreachableTerminator(Instruction *I, SmallVectorImpl< Value * > &PoisonedValues)
If a terminator in an unreachable basic block has an operand of type Instruction, transform it into p...
LLVM_ABI bool canSimplifyInvokeNoUnwind(const Function *F)
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
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,...
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
LLVM_ABI MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign 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_ABI bool wouldInstructionBeTriviallyDeadOnUnusedPaths(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction has no side effects on any paths other than whe...
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool LowerDbgDeclare(Function &F)
Lowers dbg.declare records into appropriate set of dbg.value records.
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 DIExpression * getExpressionForConstant(DIBuilder &DIB, const Constant &C, Type &Ty)
Given a constant, create a debug information expression.
LLVM_ABI CallInst * createCallMatchingInvoke(InvokeInst *II)
Create a call that matches the invoke II in terms of arguments, attributes, debug information,...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
Inserts a dbg.value record before a store to an alloca'd value that has an associated dbg....
LLVM_ABI Instruction * removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
LLVM_ABI void salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableRecord * > DPInsns)
Implementation of salvageDebugInfo, applying only to instructions in Insns, rather than all debug use...
LLVM_ABI 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.
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
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.
LLVM_ABI void dropDebugUsers(Instruction &I)
Remove the debug intrinsic instructions for the given instruction.
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
LLVM_ABI void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!...
LLVM_ABI bool replaceDbgUsesWithUndef(Instruction *I)
Replace all the uses of an SSA value in @llvm.dbg intrinsics with undef.
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...
LLVM_ABI void copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a range metadata node to a new load instruction.
LLVM_ABI DebugLoc getDebugValueLoc(DbgVariableRecord *DVR)
Produce a DebugLoc to use for each dbg.declare that is promoted to a dbg.value.
LLVM_ABI void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a nonnull metadata node to a new load instruction.
LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
LLVM_ABI void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, int Offset=0)
Replaces multiple dbg.value records when the alloca it describes is replaced with a new value.
LLVM_ABI Align tryEnforceAlignment(Value *V, Align PrefAlign, const DataLayout &DL)
If the specified pointer points to an object that we control, try to modify the object's alignment to...
LLVM_ABI Value * getFreedOperand(const CallBase *CB, const TargetLibraryInfo *TLI)
If this if a call to a free function, return the freed operand.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow instructions that are not...
constexpr unsigned BitWidth
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...
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="", bool Before=false)
Split the specified block at the specified instruction.
gep_type_iterator gep_type_begin(const User *GEP)
LLVM_ABI TinyPtrVector< DbgVariableRecord * > findDVRDeclares(Value *V)
Finds dbg.declare records declaring local variables as living in the memory that 'V' points to.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
LLVM_ABI void combineAAMetadata(Instruction *K, const Instruction *J)
Combine metadata of two instructions, where instruction J is a memory access that has been merged int...
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
LLVM_ABI bool inferAttributesFromOthers(Function &F)
If we can infer one attribute from another on the declaration of a function, explicitly materialize t...
LLVM_ABI Value * invertCondition(Value *Condition)
Invert the given true/false value, possibly reusing an existing copy.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
LLVM_ABI void DeleteDeadBlocks(ArrayRef< BasicBlock * > BBs, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified blocks from BB.
LLVM_ABI 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 auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
LLVM_ABI void findDbgUsers(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the debug info records describing a value.
LLVM_ABI bool callsGCLeafFunction(const CallBase *Call, const TargetLibraryInfo &TLI)
Return true if this call calls a gc leaf function.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
LLVM_ABI bool replaceDbgDeclare(Value *Address, Value *NewAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces dbg.declare record when the address it describes is replaced with a new value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
This struct is a compact representation of a valid (non-zero power of two) alignment.
An information struct used to provide DenseMap with the various necessary components for a given valu...
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
unsigned getBitWidth() const
Get the bit width of this value.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
std::optional< unsigned > Opcode
Opcode of merged instructions.
LLVM_ABI void mergeFlags(Instruction &I)
Merge in the no-wrap flags from I.
LLVM_ABI void applyFlags(Instruction &I)
Apply the no-wrap flags to I if applicable.
A MapVector that performs no allocations if smaller than a certain size.