#include "llvm/Transforms/Utils/Local.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AssumeBundleQueries.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/DomTreeUpdater.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Analysis/VectorUtils.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/GlobalObject.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <iterator>
#include <map>
#include <utility>
using namespace llvm;
using namespace llvm::PatternMatch;
#define DEBUG_TYPE "local"
STATISTIC(NumRemoved, "Number of unreachable basic blocks removed");
STATISTIC(NumPHICSEs, "Number of PHI's that got CSE'd");
static cl::opt<bool> PHICSEDebugHash(
"phicse-debug-hash",
#ifdef EXPENSIVE_CHECKS
cl::init(true),
#else
cl::init(false),
#endif
cl::Hidden,
cl::desc("Perform extra assertion checking to verify that PHINodes's hash "
"function is well-behaved w.r.t. its isEqual predicate"));
static cl::opt<unsigned> PHICSENumPHISmallSize(
"phicse-num-phi-smallsize", cl::init(32), cl::Hidden,
cl::desc(
"When the basic block contains not more than this number of PHI nodes, "
"perform a (faster!) exhaustive search instead of set-driven one."));
static const unsigned BitPartRecursionMaxDepth = 48;
bool llvm::ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions,
const TargetLibraryInfo *TLI,
DomTreeUpdater *DTU) {
Instruction *T = BB->getTerminator();
IRBuilder<> Builder(T);
if (auto *BI = dyn_cast<BranchInst>(T)) {
if (BI->isUnconditional()) return false;
BasicBlock *Dest1 = BI->getSuccessor(0);
BasicBlock *Dest2 = BI->getSuccessor(1);
if (Dest2 == Dest1) {
assert(BI->getParent() && "Terminator not inserted in block!");
Dest1->removePredecessor(BI->getParent());
BranchInst *NewBI = Builder.CreateBr(Dest1);
NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
LLVMContext::MD_annotation});
Value *Cond = BI->getCondition();
BI->eraseFromParent();
if (DeleteDeadConditions)
RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
return true;
}
if (auto *Cond = dyn_cast<ConstantInt>(BI->getCondition())) {
BasicBlock *Destination = Cond->getZExtValue() ? Dest1 : Dest2;
BasicBlock *OldDest = Cond->getZExtValue() ? Dest2 : Dest1;
OldDest->removePredecessor(BB);
BranchInst *NewBI = Builder.CreateBr(Destination);
NewBI->copyMetadata(*BI, {LLVMContext::MD_loop, LLVMContext::MD_dbg,
LLVMContext::MD_annotation});
BI->eraseFromParent();
if (DTU)
DTU->applyUpdates({{DominatorTree::Delete, BB, OldDest}});
return true;
}
return false;
}
if (auto *SI = dyn_cast<SwitchInst>(T)) {
auto *CI = dyn_cast<ConstantInt>(SI->getCondition());
BasicBlock *DefaultDest = SI->getDefaultDest();
BasicBlock *TheOnlyDest = DefaultDest;
if (isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg()) &&
SI->getNumCases() > 0) {
TheOnlyDest = SI->case_begin()->getCaseSuccessor();
}
bool Changed = false;
for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
if (i->getCaseValue() == CI) {
TheOnlyDest = i->getCaseSuccessor();
break;
}
if (i->getCaseSuccessor() == DefaultDest) {
MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
unsigned NCases = SI->getNumCases();
if (NCases > 1 && MD && MD->getNumOperands() == 2 + NCases) {
SmallVector<uint32_t, 8> Weights;
for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
++MD_i) {
auto *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
Weights.push_back(CI->getValue().getZExtValue());
}
unsigned idx = i->getCaseIndex();
Weights[0] += Weights[idx+1];
std::swap(Weights[idx+1], Weights.back());
Weights.pop_back();
SI->setMetadata(LLVMContext::MD_prof,
MDBuilder(BB->getContext()).
createBranchWeights(Weights));
}
BasicBlock *ParentBB = SI->getParent();
DefaultDest->removePredecessor(ParentBB);
i = SI->removeCase(i);
e = SI->case_end();
Changed = true;
continue;
}
if (i->getCaseSuccessor() != TheOnlyDest)
TheOnlyDest = nullptr;
++i;
}
if (CI && !TheOnlyDest) {
TheOnlyDest = SI->getDefaultDest();
}
if (TheOnlyDest) {
Builder.CreateBr(TheOnlyDest);
BasicBlock *BB = SI->getParent();
SmallSet<BasicBlock *, 8> RemovedSuccessors;
BasicBlock *SuccToKeep = TheOnlyDest;
for (BasicBlock *Succ : successors(SI)) {
if (DTU && Succ != TheOnlyDest)
RemovedSuccessors.insert(Succ);
if (Succ == SuccToKeep) {
SuccToKeep = nullptr; } else {
Succ->removePredecessor(BB);
}
}
Value *Cond = SI->getCondition();
SI->eraseFromParent();
if (DeleteDeadConditions)
RecursivelyDeleteTriviallyDeadInstructions(Cond, TLI);
if (DTU) {
std::vector<DominatorTree::UpdateType> Updates;
Updates.reserve(RemovedSuccessors.size());
for (auto *RemovedSuccessor : RemovedSuccessors)
Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
DTU->applyUpdates(Updates);
}
return true;
}
if (SI->getNumCases() == 1) {
auto FirstCase = *SI->case_begin();
Value *Cond = Builder.CreateICmpEQ(SI->getCondition(),
FirstCase.getCaseValue(), "cond");
BranchInst *NewBr = Builder.CreateCondBr(Cond,
FirstCase.getCaseSuccessor(),
SI->getDefaultDest());
MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
if (MD && MD->getNumOperands() == 3) {
ConstantInt *SICase =
mdconst::dyn_extract<ConstantInt>(MD->getOperand(2));
ConstantInt *SIDef =
mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
assert(SICase && SIDef);
NewBr->setMetadata(LLVMContext::MD_prof,
MDBuilder(BB->getContext()).
createBranchWeights(SICase->getValue().getZExtValue(),
SIDef->getValue().getZExtValue()));
}
MDNode *MakeImplicitMD = SI->getMetadata(LLVMContext::MD_make_implicit);
if (MakeImplicitMD)
NewBr->setMetadata(LLVMContext::MD_make_implicit, MakeImplicitMD);
SI->eraseFromParent();
return true;
}
return Changed;
}
if (auto *IBI = dyn_cast<IndirectBrInst>(T)) {
if (auto *BA =
dyn_cast<BlockAddress>(IBI->getAddress()->stripPointerCasts())) {
BasicBlock *TheOnlyDest = BA->getBasicBlock();
SmallSet<BasicBlock *, 8> RemovedSuccessors;
Builder.CreateBr(TheOnlyDest);
BasicBlock *SuccToKeep = TheOnlyDest;
for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
BasicBlock *DestBB = IBI->getDestination(i);
if (DTU && DestBB != TheOnlyDest)
RemovedSuccessors.insert(DestBB);
if (IBI->getDestination(i) == SuccToKeep) {
SuccToKeep = nullptr;
} else {
DestBB->removePredecessor(BB);
}
}
Value *Address = IBI->getAddress();
IBI->eraseFromParent();
if (DeleteDeadConditions)
RecursivelyDeleteTriviallyDeadInstructions(Address, TLI);
if (BA->use_empty())
BA->destroyConstant();
if (SuccToKeep) {
BB->getTerminator()->eraseFromParent();
new UnreachableInst(BB->getContext(), BB);
}
if (DTU) {
std::vector<DominatorTree::UpdateType> Updates;
Updates.reserve(RemovedSuccessors.size());
for (auto *RemovedSuccessor : RemovedSuccessors)
Updates.push_back({DominatorTree::Delete, BB, RemovedSuccessor});
DTU->applyUpdates(Updates);
}
return true;
}
}
return false;
}
bool llvm::isInstructionTriviallyDead(Instruction *I,
const TargetLibraryInfo *TLI) {
if (!I->use_empty())
return false;
return wouldInstructionBeTriviallyDead(I, TLI);
}
bool llvm::wouldInstructionBeTriviallyDeadOnUnusedPaths(
Instruction *I, const TargetLibraryInfo *TLI) {
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
if (II->getIntrinsicID() == Intrinsic::stacksave ||
II->getIntrinsicID() == Intrinsic::launder_invariant_group ||
II->isLifetimeStartOrEnd())
return false;
return wouldInstructionBeTriviallyDead(I, TLI);
}
bool llvm::wouldInstructionBeTriviallyDead(Instruction *I,
const TargetLibraryInfo *TLI) {
if (I->isTerminator())
return false;
if (I->isEHPad())
return false;
if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(I)) {
if (DDI->getAddress())
return false;
return true;
}
if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(I)) {
if (DVI->hasArgList() || DVI->getValue(0))
return false;
return true;
}
if (DbgLabelInst *DLI = dyn_cast<DbgLabelInst>(I)) {
if (DLI->getLabel())
return false;
return true;
}
if (auto *CB = dyn_cast<CallBase>(I))
if (isRemovableAlloc(CB, TLI))
return true;
if (!I->willReturn())
return false;
if (!I->mayHaveSideEffects())
return true;
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
if (II->getIntrinsicID() == Intrinsic::stacksave ||
II->getIntrinsicID() == Intrinsic::launder_invariant_group)
return true;
if (II->isLifetimeStartOrEnd()) {
auto *Arg = II->getArgOperand(1);
if (isa<UndefValue>(Arg))
return true;
if (isa<AllocaInst>(Arg) || isa<GlobalValue>(Arg) || isa<Argument>(Arg))
return llvm::all_of(Arg->uses(), [](Use &Use) {
if (IntrinsicInst *IntrinsicUse =
dyn_cast<IntrinsicInst>(Use.getUser()))
return IntrinsicUse->isLifetimeStartOrEnd();
return false;
});
return false;
}
if ((II->getIntrinsicID() == Intrinsic::assume &&
isAssumeWithEmptyBundle(cast<AssumeInst>(*II))) ||
II->getIntrinsicID() == Intrinsic::experimental_guard) {
if (ConstantInt *Cond = dyn_cast<ConstantInt>(II->getArgOperand(0)))
return !Cond->isZero();
return false;
}
if (auto *FPI = dyn_cast<ConstrainedFPIntrinsic>(I)) {
Optional<fp::ExceptionBehavior> ExBehavior = FPI->getExceptionBehavior();
return *ExBehavior != fp::ebStrict;
}
}
if (auto *Call = dyn_cast<CallBase>(I)) {
if (Value *FreedOp = getFreedOperand(Call, TLI))
if (Constant *C = dyn_cast<Constant>(FreedOp))
return C->isNullValue() || isa<UndefValue>(C);
if (isMathLibCallNoop(Call, TLI))
return true;
}
if (auto *LI = dyn_cast<LoadInst>(I))
if (auto *GV = dyn_cast<GlobalVariable>(
LI->getPointerOperand()->stripPointerCasts()))
if (!LI->isVolatile() && GV->isConstant())
return true;
return false;
}
bool llvm::RecursivelyDeleteTriviallyDeadInstructions(
Value *V, const TargetLibraryInfo *TLI, MemorySSAUpdater *MSSAU,
std::function<void(Value *)> AboutToDeleteCallback) {
Instruction *I = dyn_cast<Instruction>(V);
if (!I || !isInstructionTriviallyDead(I, TLI))
return false;
SmallVector<WeakTrackingVH, 16> DeadInsts;
DeadInsts.push_back(I);
RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
AboutToDeleteCallback);
return true;
}
bool llvm::RecursivelyDeleteTriviallyDeadInstructionsPermissive(
SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
MemorySSAUpdater *MSSAU,
std::function<void(Value *)> AboutToDeleteCallback) {
unsigned S = 0, E = DeadInsts.size(), Alive = 0;
for (; S != E; ++S) {
auto *I = dyn_cast<Instruction>(DeadInsts[S]);
if (!I || !isInstructionTriviallyDead(I)) {
DeadInsts[S] = nullptr;
++Alive;
}
}
if (Alive == E)
return false;
RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI, MSSAU,
AboutToDeleteCallback);
return true;
}
void llvm::RecursivelyDeleteTriviallyDeadInstructions(
SmallVectorImpl<WeakTrackingVH> &DeadInsts, const TargetLibraryInfo *TLI,
MemorySSAUpdater *MSSAU,
std::function<void(Value *)> AboutToDeleteCallback) {
while (!DeadInsts.empty()) {
Value *V = DeadInsts.pop_back_val();
Instruction *I = cast_or_null<Instruction>(V);
if (!I)
continue;
assert(isInstructionTriviallyDead(I, TLI) &&
"Live instruction found in dead worklist!");
assert(I->use_empty() && "Instructions with uses are not dead.");
salvageDebugInfo(*I);
if (AboutToDeleteCallback)
AboutToDeleteCallback(I);
for (Use &OpU : I->operands()) {
Value *OpV = OpU.get();
OpU.set(nullptr);
if (!OpV->use_empty())
continue;
if (Instruction *OpI = dyn_cast<Instruction>(OpV))
if (isInstructionTriviallyDead(OpI, TLI))
DeadInsts.push_back(OpI);
}
if (MSSAU)
MSSAU->removeMemoryAccess(I);
I->eraseFromParent();
}
}
bool llvm::replaceDbgUsesWithUndef(Instruction *I) {
SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
findDbgUsers(DbgUsers, I);
for (auto *DII : DbgUsers) {
Value *Undef = UndefValue::get(I->getType());
DII->replaceVariableLocationOp(I, Undef);
}
return !DbgUsers.empty();
}
static bool areAllUsesEqual(Instruction *I) {
Value::user_iterator UI = I->user_begin();
Value::user_iterator UE = I->user_end();
if (UI == UE)
return true;
User *TheUse = *UI;
for (++UI; UI != UE; ++UI) {
if (*UI != TheUse)
return false;
}
return true;
}
bool llvm::RecursivelyDeleteDeadPHINode(PHINode *PN,
const TargetLibraryInfo *TLI,
llvm::MemorySSAUpdater *MSSAU) {
SmallPtrSet<Instruction*, 4> Visited;
for (Instruction *I = PN; areAllUsesEqual(I) && !I->mayHaveSideEffects();
I = cast<Instruction>(*I->user_begin())) {
if (I->use_empty())
return RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
if (!Visited.insert(I).second) {
I->replaceAllUsesWith(PoisonValue::get(I->getType()));
(void)RecursivelyDeleteTriviallyDeadInstructions(I, TLI, MSSAU);
return true;
}
}
return false;
}
static bool
simplifyAndDCEInstruction(Instruction *I,
SmallSetVector<Instruction *, 16> &WorkList,
const DataLayout &DL,
const TargetLibraryInfo *TLI) {
if (isInstructionTriviallyDead(I, TLI)) {
salvageDebugInfo(*I);
for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Value *OpV = I->getOperand(i);
I->setOperand(i, nullptr);
if (!OpV->use_empty() || I == OpV)
continue;
if (Instruction *OpI = dyn_cast<Instruction>(OpV))
if (isInstructionTriviallyDead(OpI, TLI))
WorkList.insert(OpI);
}
I->eraseFromParent();
return true;
}
if (Value *SimpleV = simplifyInstruction(I, DL)) {
for (User *U : I->users()) {
if (U != I) {
WorkList.insert(cast<Instruction>(U));
}
}
bool Changed = false;
if (!I->use_empty()) {
I->replaceAllUsesWith(SimpleV);
Changed = true;
}
if (isInstructionTriviallyDead(I, TLI)) {
I->eraseFromParent();
Changed = true;
}
return Changed;
}
return false;
}
bool llvm::SimplifyInstructionsInBlock(BasicBlock *BB,
const TargetLibraryInfo *TLI) {
bool MadeChange = false;
const DataLayout &DL = BB->getModule()->getDataLayout();
#ifndef NDEBUG
AssertingVH<Instruction> TerminatorVH(&BB->back());
#endif
SmallSetVector<Instruction *, 16> WorkList;
for (BasicBlock::iterator BI = BB->begin(), E = std::prev(BB->end());
BI != E;) {
assert(!BI->isTerminator());
Instruction *I = &*BI;
++BI;
if (!WorkList.count(I))
MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
}
while (!WorkList.empty()) {
Instruction *I = WorkList.pop_back_val();
MadeChange |= simplifyAndDCEInstruction(I, WorkList, DL, TLI);
}
return MadeChange;
}
void llvm::MergeBasicBlockIntoOnlyPred(BasicBlock *DestBB,
DomTreeUpdater *DTU) {
while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
Value *NewVal = PN->getIncomingValue(0);
if (NewVal == PN) NewVal = PoisonValue::get(PN->getType());
PN->replaceAllUsesWith(NewVal);
PN->eraseFromParent();
}
BasicBlock *PredBB = DestBB->getSinglePredecessor();
assert(PredBB && "Block doesn't have a single predecessor!");
bool ReplaceEntryBB = PredBB->isEntryBlock();
SmallVector<DominatorTree::UpdateType, 32> Updates;
if (DTU) {
SmallPtrSet<BasicBlock *, 2> SeenPreds;
Updates.reserve(Updates.size() + 2 * pred_size(PredBB) + 1);
for (BasicBlock *PredOfPredBB : predecessors(PredBB))
if (PredOfPredBB != PredBB)
if (SeenPreds.insert(PredOfPredBB).second)
Updates.push_back({DominatorTree::Insert, PredOfPredBB, DestBB});
SeenPreds.clear();
for (BasicBlock *PredOfPredBB : predecessors(PredBB))
if (SeenPreds.insert(PredOfPredBB).second)
Updates.push_back({DominatorTree::Delete, PredOfPredBB, PredBB});
Updates.push_back({DominatorTree::Delete, PredBB, DestBB});
}
if (DestBB->hasAddressTaken()) {
BlockAddress *BA = BlockAddress::get(DestBB);
Constant *Replacement =
ConstantInt::get(Type::getInt32Ty(BA->getContext()), 1);
BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
BA->getType()));
BA->destroyConstant();
}
PredBB->replaceAllUsesWith(DestBB);
PredBB->getTerminator()->eraseFromParent();
DestBB->getInstList().splice(DestBB->begin(), PredBB->getInstList());
new UnreachableInst(PredBB->getContext(), PredBB);
if (ReplaceEntryBB)
DestBB->moveAfter(PredBB);
if (DTU) {
assert(PredBB->getInstList().size() == 1 &&
isa<UnreachableInst>(PredBB->getTerminator()) &&
"The successor list of PredBB isn't empty before "
"applying corresponding DTU updates.");
DTU->applyUpdatesPermissive(Updates);
DTU->deleteBB(PredBB);
if (ReplaceEntryBB && DTU->hasDomTree()) {
DTU->recalculate(*(DestBB->getParent()));
}
}
else {
PredBB->eraseFromParent(); }
}
static bool CanMergeValues(Value *First, Value *Second) {
return First == Second || isa<UndefValue>(First) || isa<UndefValue>(Second);
}
static bool CanPropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
LLVM_DEBUG(dbgs() << "Looking to fold " << BB->getName() << " into "
<< Succ->getName() << "\n");
if (Succ->getSinglePredecessor()) return true;
SmallPtrSet<BasicBlock*, 16> BBPreds(pred_begin(BB), pred_end(BB));
for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
PHINode *PN = cast<PHINode>(I);
PHINode *BBPN = dyn_cast<PHINode>(PN->getIncomingValueForBlock(BB));
if (BBPN && BBPN->getParent() == BB) {
for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
BasicBlock *IBB = PN->getIncomingBlock(PI);
if (BBPreds.count(IBB) &&
!CanMergeValues(BBPN->getIncomingValueForBlock(IBB),
PN->getIncomingValue(PI))) {
LLVM_DEBUG(dbgs()
<< "Can't fold, phi node " << PN->getName() << " in "
<< Succ->getName() << " is conflicting with "
<< BBPN->getName() << " with regard to common predecessor "
<< IBB->getName() << "\n");
return false;
}
}
} else {
Value* Val = PN->getIncomingValueForBlock(BB);
for (unsigned PI = 0, PE = PN->getNumIncomingValues(); PI != PE; ++PI) {
BasicBlock *IBB = PN->getIncomingBlock(PI);
if (BBPreds.count(IBB) &&
!CanMergeValues(Val, PN->getIncomingValue(PI))) {
LLVM_DEBUG(dbgs() << "Can't fold, phi node " << PN->getName()
<< " in " << Succ->getName()
<< " is conflicting with regard to common "
<< "predecessor " << IBB->getName() << "\n");
return false;
}
}
}
}
return true;
}
using PredBlockVector = SmallVector<BasicBlock *, 16>;
using IncomingValueMap = DenseMap<BasicBlock *, Value *>;
static Value *selectIncomingValueForBlock(Value *OldVal, BasicBlock *BB,
IncomingValueMap &IncomingValues) {
if (!isa<UndefValue>(OldVal)) {
assert((!IncomingValues.count(BB) ||
IncomingValues.find(BB)->second == OldVal) &&
"Expected OldVal to match incoming value from BB!");
IncomingValues.insert(std::make_pair(BB, OldVal));
return OldVal;
}
IncomingValueMap::const_iterator It = IncomingValues.find(BB);
if (It != IncomingValues.end()) return It->second;
return OldVal;
}
static void gatherIncomingValuesToPhi(PHINode *PN,
IncomingValueMap &IncomingValues) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
BasicBlock *BB = PN->getIncomingBlock(i);
Value *V = PN->getIncomingValue(i);
if (!isa<UndefValue>(V))
IncomingValues.insert(std::make_pair(BB, V));
}
}
static void replaceUndefValuesInPhi(PHINode *PN,
const IncomingValueMap &IncomingValues) {
SmallVector<unsigned> TrueUndefOps;
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Value *V = PN->getIncomingValue(i);
if (!isa<UndefValue>(V)) continue;
BasicBlock *BB = PN->getIncomingBlock(i);
IncomingValueMap::const_iterator It = IncomingValues.find(BB);
if (It == IncomingValues.end()) {
TrueUndefOps.push_back(i);
continue;
}
PN->setIncomingValue(i, It->second);
}
unsigned PoisonCount = count_if(TrueUndefOps, [&](unsigned i) {
return isa<PoisonValue>(PN->getIncomingValue(i));
});
if (PoisonCount != 0 && PoisonCount != TrueUndefOps.size()) {
for (unsigned i : TrueUndefOps)
PN->setIncomingValue(i, UndefValue::get(PN->getType()));
}
}
static void redirectValuesFromPredecessorsToPhi(BasicBlock *BB,
const PredBlockVector &BBPreds,
PHINode *PN) {
Value *OldVal = PN->removeIncomingValue(BB, false);
assert(OldVal && "No entry in PHI for Pred BB!");
IncomingValueMap IncomingValues;
gatherIncomingValuesToPhi(PN, IncomingValues);
if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
PHINode *OldValPN = cast<PHINode>(OldVal);
for (unsigned i = 0, e = OldValPN->getNumIncomingValues(); i != e; ++i) {
BasicBlock *PredBB = OldValPN->getIncomingBlock(i);
Value *PredVal = OldValPN->getIncomingValue(i);
Value *Selected = selectIncomingValueForBlock(PredVal, PredBB,
IncomingValues);
PN->addIncoming(Selected, PredBB);
}
} else {
for (unsigned i = 0, e = BBPreds.size(); i != e; ++i) {
BasicBlock *PredBB = BBPreds[i];
Value *Selected = selectIncomingValueForBlock(OldVal, PredBB,
IncomingValues);
PN->addIncoming(Selected, PredBB);
}
}
replaceUndefValuesInPhi(PN, IncomingValues);
}
bool llvm::TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB,
DomTreeUpdater *DTU) {
assert(BB != &BB->getParent()->getEntryBlock() &&
"TryToSimplifyUncondBranchFromEmptyBlock called on entry block!");
BasicBlock *Succ = cast<BranchInst>(BB->getTerminator())->getSuccessor(0);
if (BB == Succ) return false;
if (!CanPropagatePredecessorsForPHIs(BB, Succ)) return false;
if (!Succ->getSinglePredecessor()) {
BasicBlock::iterator BBI = BB->begin();
while (isa<PHINode>(*BBI)) {
for (Use &U : BBI->uses()) {
if (PHINode* PN = dyn_cast<PHINode>(U.getUser())) {
if (PN->getIncomingBlock(U) != BB)
return false;
} else {
return false;
}
}
++BBI;
}
}
for (BasicBlock *PredBB : predecessors(BB)) {
if (auto *CBI = dyn_cast<CallBrInst>(PredBB->getTerminator())) {
if (Succ == CBI->getDefaultDest())
return false;
for (unsigned i = 0, e = CBI->getNumIndirectDests(); i != e; ++i)
if (Succ == CBI->getIndirectDest(i))
return false;
}
}
LLVM_DEBUG(dbgs() << "Killing Trivial BB: \n" << *BB);
SmallVector<DominatorTree::UpdateType, 32> Updates;
if (DTU) {
SmallPtrSet<BasicBlock *, 8> SeenPreds;
SmallPtrSet<BasicBlock *, 8> PredsOfSucc(pred_begin(Succ), pred_end(Succ));
Updates.reserve(Updates.size() + 2 * pred_size(BB) + 1);
for (auto *PredOfBB : predecessors(BB))
if (!PredsOfSucc.contains(PredOfBB))
if (SeenPreds.insert(PredOfBB).second)
Updates.push_back({DominatorTree::Insert, PredOfBB, Succ});
SeenPreds.clear();
for (auto *PredOfBB : predecessors(BB))
if (SeenPreds.insert(PredOfBB).second)
Updates.push_back({DominatorTree::Delete, PredOfBB, BB});
Updates.push_back({DominatorTree::Delete, BB, Succ});
}
if (isa<PHINode>(Succ->begin())) {
const PredBlockVector BBPreds(predecessors(BB));
for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
PHINode *PN = cast<PHINode>(I);
redirectValuesFromPredecessorsToPhi(BB, BBPreds, PN);
}
}
if (Succ->getSinglePredecessor()) {
BB->getTerminator()->eraseFromParent();
Succ->getInstList().splice(Succ->getFirstNonPHI()->getIterator(),
BB->getInstList());
} else {
while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
assert(PN->use_empty() && "There shouldn't be any uses here!");
PN->eraseFromParent();
}
}
unsigned LoopMDKind = BB->getContext().getMDKindID("llvm.loop");
Instruction *TI = BB->getTerminator();
if (TI)
if (MDNode *LoopMD = TI->getMetadata(LoopMDKind))
for (BasicBlock *Pred : predecessors(BB))
Pred->getTerminator()->setMetadata(LoopMDKind, LoopMD);
BB->replaceAllUsesWith(Succ);
if (!Succ->hasName()) Succ->takeName(BB);
if (BB->getTerminator())
BB->getInstList().pop_back();
new UnreachableInst(BB->getContext(), BB);
assert(succ_empty(BB) && "The successor list of BB isn't empty before "
"applying corresponding DTU updates.");
if (DTU)
DTU->applyUpdates(Updates);
DeleteDeadBlock(BB, DTU);
return true;
}
static bool EliminateDuplicatePHINodesNaiveImpl(BasicBlock *BB) {
bool Changed = false;
for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I);) {
++I;
for (auto J = I; PHINode *DuplicatePN = dyn_cast<PHINode>(J); ++J) {
if (!DuplicatePN->isIdenticalToWhenDefined(PN))
continue;
++NumPHICSEs;
DuplicatePN->replaceAllUsesWith(PN);
DuplicatePN->eraseFromParent();
Changed = true;
I = BB->begin();
break; }
}
return Changed;
}
static bool EliminateDuplicatePHINodesSetBasedImpl(BasicBlock *BB) {
struct PHIDenseMapInfo {
static PHINode *getEmptyKey() {
return DenseMapInfo<PHINode *>::getEmptyKey();
}
static PHINode *getTombstoneKey() {
return DenseMapInfo<PHINode *>::getTombstoneKey();
}
static bool isSentinel(PHINode *PN) {
return PN == getEmptyKey() || PN == getTombstoneKey();
}
static unsigned getHashValueImpl(PHINode *PN) {
return static_cast<unsigned>(hash_combine(
hash_combine_range(PN->value_op_begin(), PN->value_op_end()),
hash_combine_range(PN->block_begin(), PN->block_end())));
}
static unsigned getHashValue(PHINode *PN) {
#ifndef NDEBUG
if (PHICSEDebugHash)
return 0;
#endif
return getHashValueImpl(PN);
}
static bool isEqualImpl(PHINode *LHS, PHINode *RHS) {
if (isSentinel(LHS) || isSentinel(RHS))
return LHS == RHS;
return LHS->isIdenticalTo(RHS);
}
static bool isEqual(PHINode *LHS, PHINode *RHS) {
bool Result = isEqualImpl(LHS, RHS);
assert(!Result || (isSentinel(LHS) && LHS == RHS) ||
getHashValueImpl(LHS) == getHashValueImpl(RHS));
return Result;
}
};
DenseSet<PHINode *, PHIDenseMapInfo> PHISet;
PHISet.reserve(4 * PHICSENumPHISmallSize);
bool Changed = false;
for (auto I = BB->begin(); PHINode *PN = dyn_cast<PHINode>(I++);) {
auto Inserted = PHISet.insert(PN);
if (!Inserted.second) {
++NumPHICSEs;
PN->replaceAllUsesWith(*Inserted.first);
PN->eraseFromParent();
Changed = true;
PHISet.clear();
I = BB->begin();
}
}
return Changed;
}
bool llvm::EliminateDuplicatePHINodes(BasicBlock *BB) {
if (
#ifndef NDEBUG
!PHICSEDebugHash &&
#endif
hasNItemsOrLess(BB->phis(), PHICSENumPHISmallSize))
return EliminateDuplicatePHINodesNaiveImpl(BB);
return EliminateDuplicatePHINodesSetBasedImpl(BB);
}
static Align tryEnforceAlignment(Value *V, Align PrefAlign,
const DataLayout &DL) {
V = V->stripPointerCasts();
if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
Align CurrentAlign = AI->getAlign();
if (PrefAlign <= CurrentAlign)
return CurrentAlign;
if (DL.exceedsNaturalStackAlignment(PrefAlign))
return CurrentAlign;
AI->setAlignment(PrefAlign);
return PrefAlign;
}
if (auto *GO = dyn_cast<GlobalObject>(V)) {
Align CurrentAlign = GO->getPointerAlignment(DL);
if (PrefAlign <= CurrentAlign)
return CurrentAlign;
if (!GO->canIncreaseAlignment())
return CurrentAlign;
GO->setAlignment(PrefAlign);
return PrefAlign;
}
return Align(1);
}
Align llvm::getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,
const DataLayout &DL,
const Instruction *CxtI,
AssumptionCache *AC,
const DominatorTree *DT) {
assert(V->getType()->isPointerTy() &&
"getOrEnforceKnownAlignment expects a pointer!");
KnownBits Known = computeKnownBits(V, DL, 0, AC, CxtI, DT);
unsigned TrailZ = Known.countMinTrailingZeros();
TrailZ = std::min(TrailZ, +Value::MaxAlignmentExponent);
Align Alignment = Align(1ull << std::min(Known.getBitWidth() - 1, TrailZ));
if (PrefAlign && *PrefAlign > Alignment)
Alignment = std::max(Alignment, tryEnforceAlignment(V, *PrefAlign, DL));
return Alignment;
}
static bool PhiHasDebugValue(DILocalVariable *DIVar,
DIExpression *DIExpr,
PHINode *APN) {
SmallVector<DbgValueInst *, 1> DbgValues;
findDbgValues(DbgValues, APN);
for (auto *DVI : DbgValues) {
assert(is_contained(DVI->getValues(), APN));
if ((DVI->getVariable() == DIVar) && (DVI->getExpression() == DIExpr))
return true;
}
return false;
}
static bool valueCoversEntireFragment(Type *ValTy, DbgVariableIntrinsic *DII) {
const DataLayout &DL = DII->getModule()->getDataLayout();
TypeSize ValueSize = DL.getTypeAllocSizeInBits(ValTy);
if (Optional<uint64_t> FragmentSize = DII->getFragmentSizeInBits()) {
assert(!ValueSize.isScalable() &&
"Fragments don't work on scalable types.");
return ValueSize.getFixedSize() >= *FragmentSize;
}
if (DII->isAddressOfVariable()) {
assert(DII->getNumVariableLocationOps() == 1 &&
"address of variable must have exactly 1 location operand.");
if (auto *AI =
dyn_cast_or_null<AllocaInst>(DII->getVariableLocationOp(0))) {
if (Optional<TypeSize> FragmentSize = AI->getAllocationSizeInBits(DL)) {
return TypeSize::isKnownGE(ValueSize, *FragmentSize);
}
}
}
return false;
}
static DebugLoc getDebugValueLoc(DbgVariableIntrinsic *DII, Instruction *Src) {
const DebugLoc &DeclareLoc = DII->getDebugLoc();
MDNode *Scope = DeclareLoc.getScope();
DILocation *InlinedAt = DeclareLoc.getInlinedAt();
return DILocation::get(DII->getContext(), 0, 0, Scope, InlinedAt);
}
void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
StoreInst *SI, DIBuilder &Builder) {
assert(DII->isAddressOfVariable());
auto *DIVar = DII->getVariable();
assert(DIVar && "Missing variable");
auto *DIExpr = DII->getExpression();
Value *DV = SI->getValueOperand();
DebugLoc NewLoc = getDebugValueLoc(DII, SI);
if (!valueCoversEntireFragment(DV->getType(), DII)) {
LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
<< *DII << '\n');
DV = UndefValue::get(DV->getType());
Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
return;
}
Builder.insertDbgValueIntrinsic(DV, DIVar, DIExpr, NewLoc, SI);
}
void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
LoadInst *LI, DIBuilder &Builder) {
auto *DIVar = DII->getVariable();
auto *DIExpr = DII->getExpression();
assert(DIVar && "Missing variable");
if (!valueCoversEntireFragment(LI->getType(), DII)) {
LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
<< *DII << '\n');
return;
}
DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
Instruction *DbgValue = Builder.insertDbgValueIntrinsic(
LI, DIVar, DIExpr, NewLoc, (Instruction *)nullptr);
DbgValue->insertAfter(LI);
}
void llvm::ConvertDebugDeclareToDebugValue(DbgVariableIntrinsic *DII,
PHINode *APN, DIBuilder &Builder) {
auto *DIVar = DII->getVariable();
auto *DIExpr = DII->getExpression();
assert(DIVar && "Missing variable");
if (PhiHasDebugValue(DIVar, DIExpr, APN))
return;
if (!valueCoversEntireFragment(APN->getType(), DII)) {
LLVM_DEBUG(dbgs() << "Failed to convert dbg.declare to dbg.value: "
<< *DII << '\n');
return;
}
BasicBlock *BB = APN->getParent();
auto InsertionPt = BB->getFirstInsertionPt();
DebugLoc NewLoc = getDebugValueLoc(DII, nullptr);
if (InsertionPt != BB->end())
Builder.insertDbgValueIntrinsic(APN, DIVar, DIExpr, NewLoc, &*InsertionPt);
}
static bool isArray(AllocaInst *AI) {
return AI->isArrayAllocation() ||
(AI->getAllocatedType() && AI->getAllocatedType()->isArrayTy());
}
static bool isStructure(AllocaInst *AI) {
return AI->getAllocatedType() && AI->getAllocatedType()->isStructTy();
}
bool llvm::LowerDbgDeclare(Function &F) {
bool Changed = false;
DIBuilder DIB(*F.getParent(), false);
SmallVector<DbgDeclareInst *, 4> Dbgs;
for (auto &FI : F)
for (Instruction &BI : FI)
if (auto DDI = dyn_cast<DbgDeclareInst>(&BI))
Dbgs.push_back(DDI);
if (Dbgs.empty())
return Changed;
for (auto &I : Dbgs) {
DbgDeclareInst *DDI = I;
AllocaInst *AI = dyn_cast_or_null<AllocaInst>(DDI->getAddress());
if (!AI || isArray(AI) || isStructure(AI))
continue;
if (llvm::any_of(AI->users(), [](User *U) -> bool {
if (LoadInst *LI = dyn_cast<LoadInst>(U))
return LI->isVolatile();
if (StoreInst *SI = dyn_cast<StoreInst>(U))
return SI->isVolatile();
return false;
}))
continue;
SmallVector<const Value *, 8> WorkList;
WorkList.push_back(AI);
while (!WorkList.empty()) {
const Value *V = WorkList.pop_back_val();
for (auto &AIUse : V->uses()) {
User *U = AIUse.getUser();
if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
if (AIUse.getOperandNo() == 1)
ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
} else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
} else if (CallInst *CI = dyn_cast<CallInst>(U)) {
if (!CI->isLifetimeStartOrEnd()) {
DebugLoc NewLoc = getDebugValueLoc(DDI, nullptr);
auto *DerefExpr =
DIExpression::append(DDI->getExpression(), dwarf::DW_OP_deref);
DIB.insertDbgValueIntrinsic(AI, DDI->getVariable(), DerefExpr,
NewLoc, CI);
}
} else if (BitCastInst *BI = dyn_cast<BitCastInst>(U)) {
if (BI->getType()->isPointerTy())
WorkList.push_back(BI);
}
}
}
DDI->eraseFromParent();
Changed = true;
}
if (Changed)
for (BasicBlock &BB : F)
RemoveRedundantDbgInstrs(&BB);
return Changed;
}
void llvm::insertDebugValuesForPHIs(BasicBlock *BB,
SmallVectorImpl<PHINode *> &InsertedPHIs) {
assert(BB && "No BasicBlock to clone dbg.value(s) from.");
if (InsertedPHIs.size() == 0)
return;
ValueToValueMapTy DbgValueMap;
for (auto &I : *BB) {
if (auto DbgII = dyn_cast<DbgVariableIntrinsic>(&I)) {
for (Value *V : DbgII->location_ops())
if (auto *Loc = dyn_cast_or_null<PHINode>(V))
DbgValueMap.insert({Loc, DbgII});
}
}
if (DbgValueMap.size() == 0)
return;
MapVector<std::pair<BasicBlock *, DbgVariableIntrinsic *>,
DbgVariableIntrinsic *>
NewDbgValueMap;
for (auto PHI : InsertedPHIs) {
BasicBlock *Parent = PHI->getParent();
if (Parent->getFirstNonPHI()->isEHPad())
continue;
for (auto VI : PHI->operand_values()) {
auto V = DbgValueMap.find(VI);
if (V != DbgValueMap.end()) {
auto *DbgII = cast<DbgVariableIntrinsic>(V->second);
auto NewDI = NewDbgValueMap.find({Parent, DbgII});
if (NewDI == NewDbgValueMap.end()) {
auto *NewDbgII = cast<DbgVariableIntrinsic>(DbgII->clone());
NewDI = NewDbgValueMap.insert({{Parent, DbgII}, NewDbgII}).first;
}
DbgVariableIntrinsic *NewDbgII = NewDI->second;
if (is_contained(NewDbgII->location_ops(), VI))
NewDbgII->replaceVariableLocationOp(VI, PHI);
}
}
}
for (auto DI : NewDbgValueMap) {
BasicBlock *Parent = DI.first.first;
auto *NewDbgII = DI.second;
auto InsertionPt = Parent->getFirstInsertionPt();
assert(InsertionPt != Parent->end() && "Ill-formed basic block");
NewDbgII->insertBefore(&*InsertionPt);
}
}
bool llvm::replaceDbgDeclare(Value *Address, Value *NewAddress,
DIBuilder &Builder, uint8_t DIExprFlags,
int Offset) {
auto DbgAddrs = FindDbgAddrUses(Address);
for (DbgVariableIntrinsic *DII : DbgAddrs) {
const DebugLoc &Loc = DII->getDebugLoc();
auto *DIVar = DII->getVariable();
auto *DIExpr = DII->getExpression();
assert(DIVar && "Missing variable");
DIExpr = DIExpression::prepend(DIExpr, DIExprFlags, Offset);
Builder.insertDeclare(NewAddress, DIVar, DIExpr, Loc, DII);
DII->eraseFromParent();
}
return !DbgAddrs.empty();
}
static void replaceOneDbgValueForAlloca(DbgValueInst *DVI, Value *NewAddress,
DIBuilder &Builder, int Offset) {
const DebugLoc &Loc = DVI->getDebugLoc();
auto *DIVar = DVI->getVariable();
auto *DIExpr = DVI->getExpression();
assert(DIVar && "Missing variable");
if (!DIExpr || DIExpr->getNumElements() < 1 ||
DIExpr->getElement(0) != dwarf::DW_OP_deref)
return;
if (Offset)
DIExpr = DIExpression::prepend(DIExpr, 0, Offset);
Builder.insertDbgValueIntrinsic(NewAddress, DIVar, DIExpr, Loc, DVI);
DVI->eraseFromParent();
}
void llvm::replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
DIBuilder &Builder, int Offset) {
if (auto *L = LocalAsMetadata::getIfExists(AI))
if (auto *MDV = MetadataAsValue::getIfExists(AI->getContext(), L))
for (Use &U : llvm::make_early_inc_range(MDV->uses()))
if (auto *DVI = dyn_cast<DbgValueInst>(U.getUser()))
replaceOneDbgValueForAlloca(DVI, NewAllocaAddress, Builder, Offset);
}
void llvm::salvageDebugInfo(Instruction &I) {
SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
findDbgUsers(DbgUsers, &I);
salvageDebugInfoForDbgValues(I, DbgUsers);
}
void llvm::salvageDebugInfoForDbgValues(
Instruction &I, ArrayRef<DbgVariableIntrinsic *> DbgUsers) {
const unsigned MaxDebugArgs = 16;
const unsigned MaxExpressionSize = 128;
bool Salvaged = false;
for (auto *DII : DbgUsers) {
bool StackValue = isa<DbgValueInst>(DII);
auto DIILocation = DII->location_ops();
assert(
is_contained(DIILocation, &I) &&
"DbgVariableIntrinsic must use salvaged instruction as its location");
SmallVector<Value *, 4> AdditionalValues;
Value *Op0 = nullptr;
DIExpression *SalvagedExpr = DII->getExpression();
auto LocItr = find(DIILocation, &I);
while (SalvagedExpr && LocItr != DIILocation.end()) {
SmallVector<uint64_t, 16> Ops;
unsigned LocNo = std::distance(DIILocation.begin(), LocItr);
uint64_t CurrentLocOps = SalvagedExpr->getNumLocationOperands();
Op0 = salvageDebugInfoImpl(I, CurrentLocOps, Ops, AdditionalValues);
if (!Op0)
break;
SalvagedExpr =
DIExpression::appendOpsToArg(SalvagedExpr, Ops, LocNo, StackValue);
LocItr = std::find(++LocItr, DIILocation.end(), &I);
}
if (!Op0)
break;
DII->replaceVariableLocationOp(&I, Op0);
bool IsValidSalvageExpr = SalvagedExpr->getNumElements() <= MaxExpressionSize;
if (AdditionalValues.empty() && IsValidSalvageExpr) {
DII->setExpression(SalvagedExpr);
} else if (isa<DbgValueInst>(DII) && IsValidSalvageExpr &&
DII->getNumVariableLocationOps() + AdditionalValues.size() <=
MaxDebugArgs) {
DII->addVariableLocationOps(AdditionalValues, SalvagedExpr);
} else {
Value *Undef = UndefValue::get(I.getOperand(0)->getType());
DII->replaceVariableLocationOp(I.getOperand(0), Undef);
}
LLVM_DEBUG(dbgs() << "SALVAGE: " << *DII << '\n');
Salvaged = true;
}
if (Salvaged)
return;
for (auto *DII : DbgUsers) {
Value *Undef = UndefValue::get(I.getType());
DII->replaceVariableLocationOp(&I, Undef);
}
}
Value *getSalvageOpsForGEP(GetElementPtrInst *GEP, const DataLayout &DL,
uint64_t CurrentLocOps,
SmallVectorImpl<uint64_t> &Opcodes,
SmallVectorImpl<Value *> &AdditionalValues) {
unsigned BitWidth = DL.getIndexSizeInBits(GEP->getPointerAddressSpace());
MapVector<Value *, APInt> VariableOffsets;
APInt ConstantOffset(BitWidth, 0);
if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
return nullptr;
if (!VariableOffsets.empty() && !CurrentLocOps) {
Opcodes.insert(Opcodes.begin(), {dwarf::DW_OP_LLVM_arg, 0});
CurrentLocOps = 1;
}
for (auto Offset : VariableOffsets) {
AdditionalValues.push_back(Offset.first);
assert(Offset.second.isStrictlyPositive() &&
"Expected strictly positive multiplier for offset.");
Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps++, dwarf::DW_OP_constu,
Offset.second.getZExtValue(), dwarf::DW_OP_mul,
dwarf::DW_OP_plus});
}
DIExpression::appendOffset(Opcodes, ConstantOffset.getSExtValue());
return GEP->getOperand(0);
}
uint64_t getDwarfOpForBinOp(Instruction::BinaryOps Opcode) {
switch (Opcode) {
case Instruction::Add:
return dwarf::DW_OP_plus;
case Instruction::Sub:
return dwarf::DW_OP_minus;
case Instruction::Mul:
return dwarf::DW_OP_mul;
case Instruction::SDiv:
return dwarf::DW_OP_div;
case Instruction::SRem:
return dwarf::DW_OP_mod;
case Instruction::Or:
return dwarf::DW_OP_or;
case Instruction::And:
return dwarf::DW_OP_and;
case Instruction::Xor:
return dwarf::DW_OP_xor;
case Instruction::Shl:
return dwarf::DW_OP_shl;
case Instruction::LShr:
return dwarf::DW_OP_shr;
case Instruction::AShr:
return dwarf::DW_OP_shra;
default:
return 0;
}
}
Value *getSalvageOpsForBinOp(BinaryOperator *BI, uint64_t CurrentLocOps,
SmallVectorImpl<uint64_t> &Opcodes,
SmallVectorImpl<Value *> &AdditionalValues) {
auto *ConstInt = dyn_cast<ConstantInt>(BI->getOperand(1));
if (ConstInt && ConstInt->getBitWidth() > 64)
return nullptr;
Instruction::BinaryOps BinOpcode = BI->getOpcode();
if (ConstInt) {
uint64_t Val = ConstInt->getSExtValue();
if (BinOpcode == Instruction::Add || BinOpcode == Instruction::Sub) {
uint64_t Offset = BinOpcode == Instruction::Add ? Val : -int64_t(Val);
DIExpression::appendOffset(Opcodes, Offset);
return BI->getOperand(0);
}
Opcodes.append({dwarf::DW_OP_constu, Val});
} else {
if (!CurrentLocOps) {
Opcodes.append({dwarf::DW_OP_LLVM_arg, 0});
CurrentLocOps = 1;
}
Opcodes.append({dwarf::DW_OP_LLVM_arg, CurrentLocOps});
AdditionalValues.push_back(BI->getOperand(1));
}
uint64_t DwarfBinOp = getDwarfOpForBinOp(BinOpcode);
if (!DwarfBinOp)
return nullptr;
Opcodes.push_back(DwarfBinOp);
return BI->getOperand(0);
}
Value *llvm::salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps,
SmallVectorImpl<uint64_t> &Ops,
SmallVectorImpl<Value *> &AdditionalValues) {
auto &M = *I.getModule();
auto &DL = M.getDataLayout();
if (auto *CI = dyn_cast<CastInst>(&I)) {
Value *FromValue = CI->getOperand(0);
if (CI->isNoopCast(DL)) {
return FromValue;
}
Type *Type = CI->getType();
if (Type->isPointerTy())
Type = DL.getIntPtrType(Type);
if (Type->isVectorTy() ||
!(isa<TruncInst>(&I) || isa<SExtInst>(&I) || isa<ZExtInst>(&I) ||
isa<IntToPtrInst>(&I) || isa<PtrToIntInst>(&I)))
return nullptr;
llvm::Type *FromType = FromValue->getType();
if (FromType->isPointerTy())
FromType = DL.getIntPtrType(FromType);
unsigned FromTypeBitSize = FromType->getScalarSizeInBits();
unsigned ToTypeBitSize = Type->getScalarSizeInBits();
auto ExtOps = DIExpression::getExtOps(FromTypeBitSize, ToTypeBitSize,
isa<SExtInst>(&I));
Ops.append(ExtOps.begin(), ExtOps.end());
return FromValue;
}
if (auto *GEP = dyn_cast<GetElementPtrInst>(&I))
return getSalvageOpsForGEP(GEP, DL, CurrentLocOps, Ops, AdditionalValues);
if (auto *BI = dyn_cast<BinaryOperator>(&I))
return getSalvageOpsForBinOp(BI, CurrentLocOps, Ops, AdditionalValues);
return nullptr;
}
using DbgValReplacement = Optional<DIExpression *>;
static bool rewriteDebugUsers(
Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT,
function_ref<DbgValReplacement(DbgVariableIntrinsic &DII)> RewriteExpr) {
SmallVector<DbgVariableIntrinsic *, 1> Users;
findDbgUsers(Users, &From);
if (Users.empty())
return false;
bool Changed = false;
SmallPtrSet<DbgVariableIntrinsic *, 1> UndefOrSalvage;
if (isa<Instruction>(&To)) {
bool DomPointAfterFrom = From.getNextNonDebugInstruction() == &DomPoint;
for (auto *DII : Users) {
if (DomPointAfterFrom && DII->getNextNonDebugInstruction() == &DomPoint) {
LLVM_DEBUG(dbgs() << "MOVE: " << *DII << '\n');
DII->moveAfter(&DomPoint);
Changed = true;
} else if (!DT.dominates(&DomPoint, DII)) {
UndefOrSalvage.insert(DII);
}
}
}
for (auto *DII : Users) {
if (UndefOrSalvage.count(DII))
continue;
DbgValReplacement DVR = RewriteExpr(*DII);
if (!DVR)
continue;
DII->replaceVariableLocationOp(&From, &To);
DII->setExpression(*DVR);
LLVM_DEBUG(dbgs() << "REWRITE: " << *DII << '\n');
Changed = true;
}
if (!UndefOrSalvage.empty()) {
salvageDebugInfo(From);
Changed = true;
}
return Changed;
}
static bool isBitCastSemanticsPreserving(const DataLayout &DL, Type *FromTy,
Type *ToTy) {
if (FromTy == ToTy)
return true;
if (FromTy->isIntOrPtrTy() && ToTy->isIntOrPtrTy()) {
bool SameSize = DL.getTypeSizeInBits(FromTy) == DL.getTypeSizeInBits(ToTy);
bool LosslessConversion = !DL.isNonIntegralPointerType(FromTy) &&
!DL.isNonIntegralPointerType(ToTy);
return SameSize && LosslessConversion;
}
return false;
}
bool llvm::replaceAllDbgUsesWith(Instruction &From, Value &To,
Instruction &DomPoint, DominatorTree &DT) {
if (!From.isUsedByMetadata())
return false;
assert(&From != &To && "Can't replace something with itself");
Type *FromTy = From.getType();
Type *ToTy = To.getType();
auto Identity = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
return DII.getExpression();
};
Module &M = *From.getModule();
const DataLayout &DL = M.getDataLayout();
if (isBitCastSemanticsPreserving(DL, FromTy, ToTy))
return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
if (FromTy->isIntegerTy() && ToTy->isIntegerTy()) {
uint64_t FromBits = FromTy->getPrimitiveSizeInBits();
uint64_t ToBits = ToTy->getPrimitiveSizeInBits();
assert(FromBits != ToBits && "Unexpected no-op conversion");
if (FromBits < ToBits)
return rewriteDebugUsers(From, To, DomPoint, DT, Identity);
auto SignOrZeroExt = [&](DbgVariableIntrinsic &DII) -> DbgValReplacement {
DILocalVariable *Var = DII.getVariable();
auto Signedness = Var->getSignedness();
if (!Signedness)
return None;
bool Signed = *Signedness == DIBasicType::Signedness::Signed;
return DIExpression::appendExt(DII.getExpression(), ToBits, FromBits,
Signed);
};
return rewriteDebugUsers(From, To, DomPoint, DT, SignOrZeroExt);
}
return false;
}
std::pair<unsigned, unsigned>
llvm::removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB) {
unsigned NumDeadInst = 0;
unsigned NumDeadDbgInst = 0;
Instruction *EndInst = BB->getTerminator(); while (EndInst != &BB->front()) {
Instruction *Inst = &*--EndInst->getIterator();
if (!Inst->use_empty() && !Inst->getType()->isTokenTy())
Inst->replaceAllUsesWith(PoisonValue::get(Inst->getType()));
if (Inst->isEHPad() || Inst->getType()->isTokenTy()) {
EndInst = Inst;
continue;
}
if (isa<DbgInfoIntrinsic>(Inst))
++NumDeadDbgInst;
else
++NumDeadInst;
Inst->eraseFromParent();
}
return {NumDeadInst, NumDeadDbgInst};
}
unsigned llvm::changeToUnreachable(Instruction *I, bool PreserveLCSSA,
DomTreeUpdater *DTU,
MemorySSAUpdater *MSSAU) {
BasicBlock *BB = I->getParent();
if (MSSAU)
MSSAU->changeToUnreachable(I);
SmallSet<BasicBlock *, 8> UniqueSuccessors;
for (BasicBlock *Successor : successors(BB)) {
Successor->removePredecessor(BB, PreserveLCSSA);
if (DTU)
UniqueSuccessors.insert(Successor);
}
auto *UI = new UnreachableInst(I->getContext(), I);
UI->setDebugLoc(I->getDebugLoc());
unsigned NumInstrsRemoved = 0;
BasicBlock::iterator BBI = I->getIterator(), BBE = BB->end();
while (BBI != BBE) {
if (!BBI->use_empty())
BBI->replaceAllUsesWith(PoisonValue::get(BBI->getType()));
BB->getInstList().erase(BBI++);
++NumInstrsRemoved;
}
if (DTU) {
SmallVector<DominatorTree::UpdateType, 8> Updates;
Updates.reserve(UniqueSuccessors.size());
for (BasicBlock *UniqueSuccessor : UniqueSuccessors)
Updates.push_back({DominatorTree::Delete, BB, UniqueSuccessor});
DTU->applyUpdates(Updates);
}
return NumInstrsRemoved;
}
CallInst *llvm::createCallMatchingInvoke(InvokeInst *II) {
SmallVector<Value *, 8> Args(II->args());
SmallVector<OperandBundleDef, 1> OpBundles;
II->getOperandBundlesAsDefs(OpBundles);
CallInst *NewCall = CallInst::Create(II->getFunctionType(),
II->getCalledOperand(), Args, OpBundles);
NewCall->setCallingConv(II->getCallingConv());
NewCall->setAttributes(II->getAttributes());
NewCall->setDebugLoc(II->getDebugLoc());
NewCall->copyMetadata(*II);
uint64_t TotalWeight;
if (NewCall->extractProfTotalWeight(TotalWeight)) {
MDBuilder MDB(NewCall->getContext());
auto NewWeights = uint32_t(TotalWeight) != TotalWeight
? nullptr
: MDB.createBranchWeights({uint32_t(TotalWeight)});
NewCall->setMetadata(LLVMContext::MD_prof, NewWeights);
}
return NewCall;
}
CallInst *llvm::changeToCall(InvokeInst *II, DomTreeUpdater *DTU) {
CallInst *NewCall = createCallMatchingInvoke(II);
NewCall->takeName(II);
NewCall->insertBefore(II);
II->replaceAllUsesWith(NewCall);
BasicBlock *NormalDestBB = II->getNormalDest();
BranchInst::Create(NormalDestBB, II);
BasicBlock *BB = II->getParent();
BasicBlock *UnwindDestBB = II->getUnwindDest();
UnwindDestBB->removePredecessor(BB);
II->eraseFromParent();
if (DTU)
DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
return NewCall;
}
BasicBlock *llvm::changeToInvokeAndSplitBasicBlock(CallInst *CI,
BasicBlock *UnwindEdge,
DomTreeUpdater *DTU) {
BasicBlock *BB = CI->getParent();
BasicBlock *Split = SplitBlock(BB, CI, DTU, nullptr, nullptr,
CI->getName() + ".noexc");
BB->getInstList().pop_back();
SmallVector<Value *, 8> InvokeArgs(CI->args());
SmallVector<OperandBundleDef, 1> OpBundles;
CI->getOperandBundlesAsDefs(OpBundles);
InvokeInst *II =
InvokeInst::Create(CI->getFunctionType(), CI->getCalledOperand(), Split,
UnwindEdge, InvokeArgs, OpBundles, CI->getName(), BB);
II->setDebugLoc(CI->getDebugLoc());
II->setCallingConv(CI->getCallingConv());
II->setAttributes(CI->getAttributes());
II->setMetadata(LLVMContext::MD_prof, CI->getMetadata(LLVMContext::MD_prof));
if (DTU)
DTU->applyUpdates({{DominatorTree::Insert, BB, UnwindEdge}});
CI->replaceAllUsesWith(II);
Split->getInstList().pop_front();
return Split;
}
static bool markAliveBlocks(Function &F,
SmallPtrSetImpl<BasicBlock *> &Reachable,
DomTreeUpdater *DTU = nullptr) {
SmallVector<BasicBlock*, 128> Worklist;
BasicBlock *BB = &F.front();
Worklist.push_back(BB);
Reachable.insert(BB);
bool Changed = false;
do {
BB = Worklist.pop_back_val();
for (Instruction &I : *BB) {
if (auto *CI = dyn_cast<CallInst>(&I)) {
Value *Callee = CI->getCalledOperand();
if (Function *F = dyn_cast<Function>(Callee)) {
auto IntrinsicID = F->getIntrinsicID();
if (IntrinsicID == Intrinsic::assume) {
if (match(CI->getArgOperand(0), m_CombineOr(m_Zero(), m_Undef()))) {
changeToUnreachable(CI, false, DTU);
Changed = true;
break;
}
} else if (IntrinsicID == Intrinsic::experimental_guard) {
if (match(CI->getArgOperand(0), m_Zero()))
if (!isa<UnreachableInst>(CI->getNextNode())) {
changeToUnreachable(CI->getNextNode(), false, DTU);
Changed = true;
break;
}
}
} else if ((isa<ConstantPointerNull>(Callee) &&
!NullPointerIsDefined(CI->getFunction())) ||
isa<UndefValue>(Callee)) {
changeToUnreachable(CI, false, DTU);
Changed = true;
break;
}
if (CI->doesNotReturn() && !CI->isMustTailCall()) {
if (!isa<UnreachableInst>(CI->getNextNode())) {
changeToUnreachable(CI->getNextNode(), false, DTU);
Changed = true;
}
break;
}
} else if (auto *SI = dyn_cast<StoreInst>(&I)) {
if (SI->isVolatile()) continue;
Value *Ptr = SI->getOperand(1);
if (isa<UndefValue>(Ptr) ||
(isa<ConstantPointerNull>(Ptr) &&
!NullPointerIsDefined(SI->getFunction(),
SI->getPointerAddressSpace()))) {
changeToUnreachable(SI, false, DTU);
Changed = true;
break;
}
}
}
Instruction *Terminator = BB->getTerminator();
if (auto *II = dyn_cast<InvokeInst>(Terminator)) {
Value *Callee = II->getCalledOperand();
if ((isa<ConstantPointerNull>(Callee) &&
!NullPointerIsDefined(BB->getParent())) ||
isa<UndefValue>(Callee)) {
changeToUnreachable(II, false, DTU);
Changed = true;
} else {
if (II->doesNotReturn() &&
!isa<UnreachableInst>(II->getNormalDest()->front())) {
BasicBlock *OrigNormalDest = II->getNormalDest();
OrigNormalDest->removePredecessor(II->getParent());
LLVMContext &Ctx = II->getContext();
BasicBlock *UnreachableNormalDest = BasicBlock::Create(
Ctx, OrigNormalDest->getName() + ".unreachable",
II->getFunction(), OrigNormalDest);
new UnreachableInst(Ctx, UnreachableNormalDest);
II->setNormalDest(UnreachableNormalDest);
if (DTU)
DTU->applyUpdates(
{{DominatorTree::Delete, BB, OrigNormalDest},
{DominatorTree::Insert, BB, UnreachableNormalDest}});
Changed = true;
}
if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(&F)) {
if (II->use_empty() && !II->mayHaveSideEffects()) {
BasicBlock *NormalDestBB = II->getNormalDest();
BasicBlock *UnwindDestBB = II->getUnwindDest();
BranchInst::Create(NormalDestBB, II);
UnwindDestBB->removePredecessor(II->getParent());
II->eraseFromParent();
if (DTU)
DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDestBB}});
} else
changeToCall(II, DTU);
Changed = true;
}
}
} else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Terminator)) {
struct CatchPadDenseMapInfo {
static CatchPadInst *getEmptyKey() {
return DenseMapInfo<CatchPadInst *>::getEmptyKey();
}
static CatchPadInst *getTombstoneKey() {
return DenseMapInfo<CatchPadInst *>::getTombstoneKey();
}
static unsigned getHashValue(CatchPadInst *CatchPad) {
return static_cast<unsigned>(hash_combine_range(
CatchPad->value_op_begin(), CatchPad->value_op_end()));
}
static bool isEqual(CatchPadInst *LHS, CatchPadInst *RHS) {
if (LHS == getEmptyKey() || LHS == getTombstoneKey() ||
RHS == getEmptyKey() || RHS == getTombstoneKey())
return LHS == RHS;
return LHS->isIdenticalTo(RHS);
}
};
SmallDenseMap<BasicBlock *, int, 8> NumPerSuccessorCases;
SmallDenseMap<CatchPadInst *, detail::DenseSetEmpty, 4,
CatchPadDenseMapInfo, detail::DenseSetPair<CatchPadInst *>>
HandlerSet;
detail::DenseSetEmpty Empty;
for (CatchSwitchInst::handler_iterator I = CatchSwitch->handler_begin(),
E = CatchSwitch->handler_end();
I != E; ++I) {
BasicBlock *HandlerBB = *I;
if (DTU)
++NumPerSuccessorCases[HandlerBB];
auto *CatchPad = cast<CatchPadInst>(HandlerBB->getFirstNonPHI());
if (!HandlerSet.insert({CatchPad, Empty}).second) {
if (DTU)
--NumPerSuccessorCases[HandlerBB];
CatchSwitch->removeHandler(I);
--I;
--E;
Changed = true;
}
}
if (DTU) {
std::vector<DominatorTree::UpdateType> Updates;
for (const std::pair<BasicBlock *, int> &I : NumPerSuccessorCases)
if (I.second == 0)
Updates.push_back({DominatorTree::Delete, BB, I.first});
DTU->applyUpdates(Updates);
}
}
Changed |= ConstantFoldTerminator(BB, true, nullptr, DTU);
for (BasicBlock *Successor : successors(BB))
if (Reachable.insert(Successor).second)
Worklist.push_back(Successor);
} while (!Worklist.empty());
return Changed;
}
void llvm::removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU) {
Instruction *TI = BB->getTerminator();
if (auto *II = dyn_cast<InvokeInst>(TI)) {
changeToCall(II, DTU);
return;
}
Instruction *NewTI;
BasicBlock *UnwindDest;
if (auto *CRI = dyn_cast<CleanupReturnInst>(TI)) {
NewTI = CleanupReturnInst::Create(CRI->getCleanupPad(), nullptr, CRI);
UnwindDest = CRI->getUnwindDest();
} else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
auto *NewCatchSwitch = CatchSwitchInst::Create(
CatchSwitch->getParentPad(), nullptr, CatchSwitch->getNumHandlers(),
CatchSwitch->getName(), CatchSwitch);
for (BasicBlock *PadBB : CatchSwitch->handlers())
NewCatchSwitch->addHandler(PadBB);
NewTI = NewCatchSwitch;
UnwindDest = CatchSwitch->getUnwindDest();
} else {
llvm_unreachable("Could not find unwind successor");
}
NewTI->takeName(TI);
NewTI->setDebugLoc(TI->getDebugLoc());
UnwindDest->removePredecessor(BB);
TI->replaceAllUsesWith(NewTI);
TI->eraseFromParent();
if (DTU)
DTU->applyUpdates({{DominatorTree::Delete, BB, UnwindDest}});
}
bool llvm::removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU,
MemorySSAUpdater *MSSAU) {
SmallPtrSet<BasicBlock *, 16> Reachable;
bool Changed = markAliveBlocks(F, Reachable, DTU);
if (Reachable.size() == F.size())
return Changed;
assert(Reachable.size() < F.size());
SmallSetVector<BasicBlock *, 8> BlocksToRemove;
for (BasicBlock &BB : F) {
if (Reachable.count(&BB))
continue;
if (DTU && DTU->isBBPendingDeletion(&BB))
continue;
BlocksToRemove.insert(&BB);
}
if (BlocksToRemove.empty())
return Changed;
Changed = true;
NumRemoved += BlocksToRemove.size();
if (MSSAU)
MSSAU->removeBlocks(BlocksToRemove);
DeleteDeadBlocks(BlocksToRemove.takeVector(), DTU);
return Changed;
}
void llvm::combineMetadata(Instruction *K, const Instruction *J,
ArrayRef<unsigned> KnownIDs, bool DoesKMove) {
SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
K->dropUnknownNonDebugMetadata(KnownIDs);
K->getAllMetadataOtherThanDebugLoc(Metadata);
for (const auto &MD : Metadata) {
unsigned Kind = MD.first;
MDNode *JMD = J->getMetadata(Kind);
MDNode *KMD = MD.second;
switch (Kind) {
default:
K->setMetadata(Kind, nullptr); break;
case LLVMContext::MD_dbg:
llvm_unreachable("getAllMetadataOtherThanDebugLoc returned a MD_dbg");
case LLVMContext::MD_tbaa:
K->setMetadata(Kind, MDNode::getMostGenericTBAA(JMD, KMD));
break;
case LLVMContext::MD_alias_scope:
K->setMetadata(Kind, MDNode::getMostGenericAliasScope(JMD, KMD));
break;
case LLVMContext::MD_noalias:
case LLVMContext::MD_mem_parallel_loop_access:
K->setMetadata(Kind, MDNode::intersect(JMD, KMD));
break;
case LLVMContext::MD_access_group:
K->setMetadata(LLVMContext::MD_access_group,
intersectAccessGroups(K, J));
break;
case LLVMContext::MD_range:
if (DoesKMove)
K->setMetadata(Kind, MDNode::getMostGenericRange(JMD, KMD));
break;
case LLVMContext::MD_fpmath:
K->setMetadata(Kind, MDNode::getMostGenericFPMath(JMD, KMD));
break;
case LLVMContext::MD_invariant_load:
K->setMetadata(Kind, JMD);
break;
case LLVMContext::MD_nonnull:
if (DoesKMove)
K->setMetadata(Kind, JMD);
break;
case LLVMContext::MD_invariant_group:
break;
case LLVMContext::MD_align:
K->setMetadata(Kind,
MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
break;
case LLVMContext::MD_dereferenceable:
case LLVMContext::MD_dereferenceable_or_null:
K->setMetadata(Kind,
MDNode::getMostGenericAlignmentOrDereferenceable(JMD, KMD));
break;
case LLVMContext::MD_preserve_access_index:
break;
}
}
if (auto *JMD = J->getMetadata(LLVMContext::MD_invariant_group))
if (isa<LoadInst>(K) || isa<StoreInst>(K))
K->setMetadata(LLVMContext::MD_invariant_group, JMD);
}
void llvm::combineMetadataForCSE(Instruction *K, const Instruction *J,
bool KDominatesJ) {
unsigned KnownIDs[] = {
LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
LLVMContext::MD_noalias, LLVMContext::MD_range,
LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
LLVMContext::MD_invariant_group, LLVMContext::MD_align,
LLVMContext::MD_dereferenceable,
LLVMContext::MD_dereferenceable_or_null,
LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
combineMetadata(K, J, KnownIDs, KDominatesJ);
}
void llvm::copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source) {
SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
Source.getAllMetadata(MD);
MDBuilder MDB(Dest.getContext());
Type *NewType = Dest.getType();
const DataLayout &DL = Source.getModule()->getDataLayout();
for (const auto &MDPair : MD) {
unsigned ID = MDPair.first;
MDNode *N = MDPair.second;
switch (ID) {
case LLVMContext::MD_dbg:
case LLVMContext::MD_tbaa:
case LLVMContext::MD_prof:
case LLVMContext::MD_fpmath:
case LLVMContext::MD_tbaa_struct:
case LLVMContext::MD_invariant_load:
case LLVMContext::MD_alias_scope:
case LLVMContext::MD_noalias:
case LLVMContext::MD_nontemporal:
case LLVMContext::MD_mem_parallel_loop_access:
case LLVMContext::MD_access_group:
Dest.setMetadata(ID, N);
break;
case LLVMContext::MD_nonnull:
copyNonnullMetadata(Source, N, Dest);
break;
case LLVMContext::MD_align:
case LLVMContext::MD_dereferenceable:
case LLVMContext::MD_dereferenceable_or_null:
if (NewType->isPointerTy())
Dest.setMetadata(ID, N);
break;
case LLVMContext::MD_range:
copyRangeMetadata(DL, Source, N, Dest);
break;
}
}
}
void llvm::patchReplacementInstruction(Instruction *I, Value *Repl) {
auto *ReplInst = dyn_cast<Instruction>(Repl);
if (!ReplInst)
return;
if (!isa<LoadInst>(I))
ReplInst->andIRFlags(I);
static const unsigned KnownIDs[] = {
LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
LLVMContext::MD_noalias, LLVMContext::MD_range,
LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
LLVMContext::MD_invariant_group, LLVMContext::MD_nonnull,
LLVMContext::MD_access_group, LLVMContext::MD_preserve_access_index};
combineMetadata(ReplInst, I, KnownIDs, false);
}
template <typename RootType, typename DominatesFn>
static unsigned replaceDominatedUsesWith(Value *From, Value *To,
const RootType &Root,
const DominatesFn &Dominates) {
assert(From->getType() == To->getType());
unsigned Count = 0;
for (Use &U : llvm::make_early_inc_range(From->uses())) {
if (!Dominates(Root, U))
continue;
U.set(To);
LLVM_DEBUG(dbgs() << "Replace dominated use of '" << From->getName()
<< "' as " << *To << " in " << *U << "\n");
++Count;
}
return Count;
}
unsigned llvm::replaceNonLocalUsesWith(Instruction *From, Value *To) {
assert(From->getType() == To->getType());
auto *BB = From->getParent();
unsigned Count = 0;
for (Use &U : llvm::make_early_inc_range(From->uses())) {
auto *I = cast<Instruction>(U.getUser());
if (I->getParent() == BB)
continue;
U.set(To);
++Count;
}
return Count;
}
unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
DominatorTree &DT,
const BasicBlockEdge &Root) {
auto Dominates = [&DT](const BasicBlockEdge &Root, const Use &U) {
return DT.dominates(Root, U);
};
return ::replaceDominatedUsesWith(From, To, Root, Dominates);
}
unsigned llvm::replaceDominatedUsesWith(Value *From, Value *To,
DominatorTree &DT,
const BasicBlock *BB) {
auto Dominates = [&DT](const BasicBlock *BB, const Use &U) {
return DT.dominates(BB, U);
};
return ::replaceDominatedUsesWith(From, To, BB, Dominates);
}
bool llvm::callsGCLeafFunction(const CallBase *Call,
const TargetLibraryInfo &TLI) {
if (Call->hasFnAttr("gc-leaf-function"))
return true;
if (const Function *F = Call->getCalledFunction()) {
if (F->hasFnAttribute("gc-leaf-function"))
return true;
if (auto IID = F->getIntrinsicID()) {
return IID != Intrinsic::experimental_gc_statepoint &&
IID != Intrinsic::experimental_deoptimize &&
IID != Intrinsic::memcpy_element_unordered_atomic &&
IID != Intrinsic::memmove_element_unordered_atomic;
}
}
LibFunc LF;
if (TLI.getLibFunc(*Call, LF)) {
return TLI.has(LF);
}
return false;
}
void llvm::copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
LoadInst &NewLI) {
auto *NewTy = NewLI.getType();
if (NewTy->isPointerTy()) {
NewLI.setMetadata(LLVMContext::MD_nonnull, N);
return;
}
if (!NewTy->isIntegerTy())
return;
MDBuilder MDB(NewLI.getContext());
const Value *Ptr = OldLI.getPointerOperand();
auto *ITy = cast<IntegerType>(NewTy);
auto *NullInt = ConstantExpr::getPtrToInt(
ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
auto *NonNullInt = ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
NewLI.setMetadata(LLVMContext::MD_range,
MDB.createRange(NonNullInt, NullInt));
}
void llvm::copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
MDNode *N, LoadInst &NewLI) {
auto *NewTy = NewLI.getType();
if (!NewTy->isPointerTy())
return;
unsigned BitWidth = DL.getPointerTypeSizeInBits(NewTy);
if (!getConstantRangeFromMetadata(*N).contains(APInt(BitWidth, 0))) {
MDNode *NN = MDNode::get(OldLI.getContext(), None);
NewLI.setMetadata(LLVMContext::MD_nonnull, NN);
}
}
void llvm::dropDebugUsers(Instruction &I) {
SmallVector<DbgVariableIntrinsic *, 1> DbgUsers;
findDbgUsers(DbgUsers, &I);
for (auto *DII : DbgUsers)
DII->eraseFromParent();
}
void llvm::hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt,
BasicBlock *BB) {
for (BasicBlock::iterator II = BB->begin(), IE = BB->end(); II != IE;) {
Instruction *I = &*II;
I->dropUndefImplyingAttrsAndUnknownMetadata();
if (I->isUsedByMetadata())
dropDebugUsers(*I);
if (I->isDebugOrPseudoInst()) {
II = I->eraseFromParent();
continue;
}
I->setDebugLoc(InsertPt->getDebugLoc());
++II;
}
DomBlock->getInstList().splice(InsertPt->getIterator(), BB->getInstList(),
BB->begin(),
BB->getTerminator()->getIterator());
}
namespace {
struct BitPart {
BitPart(Value *P, unsigned BW) : Provider(P) {
Provenance.resize(BW);
}
Value *Provider;
SmallVector<int8_t, 32> Provenance;
enum { Unset = -1 };
};
}
static const Optional<BitPart> &
collectBitParts(Value *V, bool MatchBSwaps, bool MatchBitReversals,
std::map<Value *, Optional<BitPart>> &BPS, int Depth,
bool &FoundRoot) {
auto I = BPS.find(V);
if (I != BPS.end())
return I->second;
auto &Result = BPS[V] = None;
auto BitWidth = V->getType()->getScalarSizeInBits();
if (BitWidth > 128)
return Result;
if (Depth == BitPartRecursionMaxDepth) {
LLVM_DEBUG(dbgs() << "collectBitParts max recursion depth reached.\n");
return Result;
}
if (auto *I = dyn_cast<Instruction>(V)) {
Value *X, *Y;
const APInt *C;
if (match(V, m_Or(m_Value(X), m_Value(Y)))) {
const auto &A = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
Depth + 1, FoundRoot);
if (!A || !A->Provider)
return Result;
const auto &B = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
Depth + 1, FoundRoot);
if (!B || A->Provider != B->Provider)
return Result;
Result = BitPart(A->Provider, BitWidth);
for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx) {
if (A->Provenance[BitIdx] != BitPart::Unset &&
B->Provenance[BitIdx] != BitPart::Unset &&
A->Provenance[BitIdx] != B->Provenance[BitIdx])
return Result = None;
if (A->Provenance[BitIdx] == BitPart::Unset)
Result->Provenance[BitIdx] = B->Provenance[BitIdx];
else
Result->Provenance[BitIdx] = A->Provenance[BitIdx];
}
return Result;
}
if (match(V, m_LogicalShift(m_Value(X), m_APInt(C)))) {
const APInt &BitShift = *C;
if (BitShift.uge(BitWidth))
return Result;
if (!MatchBitReversals && (BitShift.getZExtValue() % 8) != 0)
return Result;
const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
Depth + 1, FoundRoot);
if (!Res)
return Result;
Result = Res;
auto &P = Result->Provenance;
if (I->getOpcode() == Instruction::Shl) {
P.erase(std::prev(P.end(), BitShift.getZExtValue()), P.end());
P.insert(P.begin(), BitShift.getZExtValue(), BitPart::Unset);
} else {
P.erase(P.begin(), std::next(P.begin(), BitShift.getZExtValue()));
P.insert(P.end(), BitShift.getZExtValue(), BitPart::Unset);
}
return Result;
}
if (match(V, m_And(m_Value(X), m_APInt(C)))) {
const APInt &AndMask = *C;
unsigned NumMaskedBits = AndMask.countPopulation();
if (!MatchBitReversals && (NumMaskedBits % 8) != 0)
return Result;
const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
Depth + 1, FoundRoot);
if (!Res)
return Result;
Result = Res;
for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
if (AndMask[BitIdx] == 0)
Result->Provenance[BitIdx] = BitPart::Unset;
return Result;
}
if (match(V, m_ZExt(m_Value(X)))) {
const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
Depth + 1, FoundRoot);
if (!Res)
return Result;
Result = BitPart(Res->Provider, BitWidth);
auto NarrowBitWidth = X->getType()->getScalarSizeInBits();
for (unsigned BitIdx = 0; BitIdx < NarrowBitWidth; ++BitIdx)
Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
for (unsigned BitIdx = NarrowBitWidth; BitIdx < BitWidth; ++BitIdx)
Result->Provenance[BitIdx] = BitPart::Unset;
return Result;
}
if (match(V, m_Trunc(m_Value(X)))) {
const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
Depth + 1, FoundRoot);
if (!Res)
return Result;
Result = BitPart(Res->Provider, BitWidth);
for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
Result->Provenance[BitIdx] = Res->Provenance[BitIdx];
return Result;
}
if (match(V, m_BitReverse(m_Value(X)))) {
const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
Depth + 1, FoundRoot);
if (!Res)
return Result;
Result = BitPart(Res->Provider, BitWidth);
for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
Result->Provenance[(BitWidth - 1) - BitIdx] = Res->Provenance[BitIdx];
return Result;
}
if (match(V, m_BSwap(m_Value(X)))) {
const auto &Res = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
Depth + 1, FoundRoot);
if (!Res)
return Result;
unsigned ByteWidth = BitWidth / 8;
Result = BitPart(Res->Provider, BitWidth);
for (unsigned ByteIdx = 0; ByteIdx < ByteWidth; ++ByteIdx) {
unsigned ByteBitOfs = ByteIdx * 8;
for (unsigned BitIdx = 0; BitIdx < 8; ++BitIdx)
Result->Provenance[(BitWidth - 8 - ByteBitOfs) + BitIdx] =
Res->Provenance[ByteBitOfs + BitIdx];
}
return Result;
}
if (match(V, m_FShl(m_Value(X), m_Value(Y), m_APInt(C))) ||
match(V, m_FShr(m_Value(X), m_Value(Y), m_APInt(C)))) {
unsigned ModAmt = C->urem(BitWidth);
if (cast<IntrinsicInst>(I)->getIntrinsicID() == Intrinsic::fshr)
ModAmt = BitWidth - ModAmt;
if (!MatchBitReversals && (ModAmt % 8) != 0)
return Result;
const auto &LHS = collectBitParts(X, MatchBSwaps, MatchBitReversals, BPS,
Depth + 1, FoundRoot);
if (!LHS || !LHS->Provider)
return Result;
const auto &RHS = collectBitParts(Y, MatchBSwaps, MatchBitReversals, BPS,
Depth + 1, FoundRoot);
if (!RHS || LHS->Provider != RHS->Provider)
return Result;
unsigned StartBitRHS = BitWidth - ModAmt;
Result = BitPart(LHS->Provider, BitWidth);
for (unsigned BitIdx = 0; BitIdx < StartBitRHS; ++BitIdx)
Result->Provenance[BitIdx + ModAmt] = LHS->Provenance[BitIdx];
for (unsigned BitIdx = 0; BitIdx < ModAmt; ++BitIdx)
Result->Provenance[BitIdx] = RHS->Provenance[BitIdx + StartBitRHS];
return Result;
}
}
if (FoundRoot)
return Result;
FoundRoot = true;
Result = BitPart(V, BitWidth);
for (unsigned BitIdx = 0; BitIdx < BitWidth; ++BitIdx)
Result->Provenance[BitIdx] = BitIdx;
return Result;
}
static bool bitTransformIsCorrectForBSwap(unsigned From, unsigned To,
unsigned BitWidth) {
if (From % 8 != To % 8)
return false;
From >>= 3;
To >>= 3;
BitWidth >>= 3;
return From == BitWidth - To - 1;
}
static bool bitTransformIsCorrectForBitReverse(unsigned From, unsigned To,
unsigned BitWidth) {
return From == BitWidth - To - 1;
}
bool llvm::recognizeBSwapOrBitReverseIdiom(
Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
SmallVectorImpl<Instruction *> &InsertedInsts) {
if (!match(I, m_Or(m_Value(), m_Value())) &&
!match(I, m_FShl(m_Value(), m_Value(), m_Value())) &&
!match(I, m_FShr(m_Value(), m_Value(), m_Value())))
return false;
if (!MatchBSwaps && !MatchBitReversals)
return false;
Type *ITy = I->getType();
if (!ITy->isIntOrIntVectorTy() || ITy->getScalarSizeInBits() > 128)
return false;
bool FoundRoot = false;
std::map<Value *, Optional<BitPart>> BPS;
const auto &Res =
collectBitParts(I, MatchBSwaps, MatchBitReversals, BPS, 0, FoundRoot);
if (!Res)
return false;
ArrayRef<int8_t> BitProvenance = Res->Provenance;
assert(all_of(BitProvenance,
[](int8_t I) { return I == BitPart::Unset || 0 <= I; }) &&
"Illegal bit provenance index");
Type *DemandedTy = ITy;
if (BitProvenance.back() == BitPart::Unset) {
while (!BitProvenance.empty() && BitProvenance.back() == BitPart::Unset)
BitProvenance = BitProvenance.drop_back();
if (BitProvenance.empty())
return false; DemandedTy = Type::getIntNTy(I->getContext(), BitProvenance.size());
if (auto *IVecTy = dyn_cast<VectorType>(ITy))
DemandedTy = VectorType::get(DemandedTy, IVecTy);
}
unsigned DemandedBW = DemandedTy->getScalarSizeInBits();
if (DemandedBW > ITy->getScalarSizeInBits())
return false;
APInt DemandedMask = APInt::getAllOnes(DemandedBW);
bool OKForBSwap = MatchBSwaps && (DemandedBW % 16) == 0;
bool OKForBitReverse = MatchBitReversals;
for (unsigned BitIdx = 0;
(BitIdx < DemandedBW) && (OKForBSwap || OKForBitReverse); ++BitIdx) {
if (BitProvenance[BitIdx] == BitPart::Unset) {
DemandedMask.clearBit(BitIdx);
continue;
}
OKForBSwap &= bitTransformIsCorrectForBSwap(BitProvenance[BitIdx], BitIdx,
DemandedBW);
OKForBitReverse &= bitTransformIsCorrectForBitReverse(BitProvenance[BitIdx],
BitIdx, DemandedBW);
}
Intrinsic::ID Intrin;
if (OKForBSwap)
Intrin = Intrinsic::bswap;
else if (OKForBitReverse)
Intrin = Intrinsic::bitreverse;
else
return false;
Function *F = Intrinsic::getDeclaration(I->getModule(), Intrin, DemandedTy);
Value *Provider = Res->Provider;
if (DemandedTy != Provider->getType()) {
auto *Trunc =
CastInst::CreateIntegerCast(Provider, DemandedTy, false, "trunc", I);
InsertedInsts.push_back(Trunc);
Provider = Trunc;
}
Instruction *Result = CallInst::Create(F, Provider, "rev", I);
InsertedInsts.push_back(Result);
if (!DemandedMask.isAllOnes()) {
auto *Mask = ConstantInt::get(DemandedTy, DemandedMask);
Result = BinaryOperator::Create(Instruction::And, Result, Mask, "mask", I);
InsertedInsts.push_back(Result);
}
if (ITy != Result->getType()) {
auto *ExtInst = CastInst::CreateIntegerCast(Result, ITy, false, "zext", I);
InsertedInsts.push_back(ExtInst);
}
return true;
}
void llvm::maybeMarkSanitizerLibraryCallNoBuiltin(
CallInst *CI, const TargetLibraryInfo *TLI) {
Function *F = CI->getCalledFunction();
LibFunc Func;
if (F && !F->hasLocalLinkage() && F->hasName() &&
TLI->getLibFunc(F->getName(), Func) && TLI->hasOptimizedCodeGen(Func) &&
!F->doesNotAccessMemory())
CI->addFnAttr(Attribute::NoBuiltin);
}
bool llvm::canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx) {
if (I->getOperand(OpIdx)->getType()->isMetadataTy())
return false;
if (!isa<Constant>(I->getOperand(OpIdx)))
return true;
switch (I->getOpcode()) {
default:
return true;
case Instruction::Call:
case Instruction::Invoke: {
const auto &CB = cast<CallBase>(*I);
if (CB.isInlineAsm())
return false;
if (CB.isBundleOperand(OpIdx))
return false;
if (OpIdx < CB.arg_size()) {
if (isa<IntrinsicInst>(CB) &&
OpIdx >= CB.getFunctionType()->getNumParams()) {
return CB.getIntrinsicID() == Intrinsic::experimental_stackmap;
}
if (CB.getIntrinsicID() == Intrinsic::gcroot)
return false;
return !CB.paramHasAttr(OpIdx, Attribute::ImmArg);
}
return !isa<IntrinsicInst>(CB);
}
case Instruction::ShuffleVector:
return OpIdx != 2;
case Instruction::Switch:
case Instruction::ExtractValue:
return OpIdx == 0;
case Instruction::InsertValue:
return OpIdx < 2;
case Instruction::Alloca:
return !cast<AllocaInst>(I)->isStaticAlloca();
case Instruction::GetElementPtr:
if (OpIdx == 0)
return true;
gep_type_iterator It = gep_type_begin(I);
for (auto E = std::next(It, OpIdx); It != E; ++It)
if (It.isStruct())
return false;
return true;
}
}
Value *llvm::invertCondition(Value *Condition) {
if (Constant *C = dyn_cast<Constant>(Condition))
return ConstantExpr::getNot(C);
Value *NotCondition;
if (match(Condition, m_Not(m_Value(NotCondition))))
return NotCondition;
BasicBlock *Parent = nullptr;
Instruction *Inst = dyn_cast<Instruction>(Condition);
if (Inst)
Parent = Inst->getParent();
else if (Argument *Arg = dyn_cast<Argument>(Condition))
Parent = &Arg->getParent()->getEntryBlock();
assert(Parent && "Unsupported condition to invert");
for (User *U : Condition->users())
if (Instruction *I = dyn_cast<Instruction>(U))
if (I->getParent() == Parent && match(I, m_Not(m_Specific(Condition))))
return I;
auto *Inverted =
BinaryOperator::CreateNot(Condition, Condition->getName() + ".inv");
if (Inst && !isa<PHINode>(Inst))
Inverted->insertAfter(Inst);
else
Inverted->insertBefore(&*Parent->getFirstInsertionPt());
return Inverted;
}
bool llvm::inferAttributesFromOthers(Function &F) {
bool Changed = false;
if (!F.hasFnAttribute(Attribute::NoSync) &&
F.doesNotAccessMemory() && !F.isConvergent()) {
F.setNoSync();
Changed = true;
}
if (!F.hasFnAttribute(Attribute::NoFree) && F.onlyReadsMemory()) {
F.setDoesNotFreeMemory();
Changed = true;
}
if (!F.hasFnAttribute(Attribute::MustProgress) && F.willReturn()) {
F.setMustProgress();
Changed = true;
}
return Changed;
}