#include "llvm/CodeGen/Analysis.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include "llvm/Transforms/Utils/GlobalStatus.h"
using namespace llvm;
unsigned llvm::ComputeLinearIndex(Type *Ty,
const unsigned *Indices,
const unsigned *IndicesEnd,
unsigned CurIndex) {
if (Indices && Indices == IndicesEnd)
return CurIndex;
if (StructType *STy = dyn_cast<StructType>(Ty)) {
for (StructType::element_iterator EB = STy->element_begin(),
EI = EB,
EE = STy->element_end();
EI != EE; ++EI) {
if (Indices && *Indices == unsigned(EI - EB))
return ComputeLinearIndex(*EI, Indices+1, IndicesEnd, CurIndex);
CurIndex = ComputeLinearIndex(*EI, nullptr, nullptr, CurIndex);
}
assert(!Indices && "Unexpected out of bound");
return CurIndex;
}
else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Type *EltTy = ATy->getElementType();
unsigned NumElts = ATy->getNumElements();
unsigned EltLinearOffset = ComputeLinearIndex(EltTy, nullptr, nullptr, 0);
if (Indices) {
assert(*Indices < NumElts && "Unexpected out of bound");
CurIndex += EltLinearOffset* *Indices;
return ComputeLinearIndex(EltTy, Indices+1, IndicesEnd, CurIndex);
}
CurIndex += EltLinearOffset*NumElts;
return CurIndex;
}
return CurIndex + 1;
}
void llvm::ComputeValueVTs(const TargetLowering &TLI, Type *Ty,
SmallVectorImpl<EVT> &ValueVTs,
SmallVectorImpl<uint64_t> *Offsets,
uint64_t StartingOffset) {
if (StructType *STy = dyn_cast<StructType>(Ty)) {
const StructLayout *SL = TLI.getDataLayout()->getStructLayout(STy);
for (StructType::element_iterator EB = STy->element_begin(),
EI = EB,
EE = STy->element_end();
EI != EE; ++EI)
ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
StartingOffset + SL->getElementOffset(EI - EB));
return;
}
if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Type *EltTy = ATy->getElementType();
uint64_t EltSize = TLI.getDataLayout()->getTypeAllocSize(EltTy);
for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
StartingOffset + i * EltSize);
return;
}
if (Ty->isVoidTy())
return;
ValueVTs.push_back(TLI.getValueType(Ty));
if (Offsets)
Offsets->push_back(StartingOffset);
}
GlobalValue *llvm::ExtractTypeInfo(Value *V) {
V = V->stripPointerCasts();
GlobalValue *GV = dyn_cast<GlobalValue>(V);
GlobalVariable *Var = dyn_cast<GlobalVariable>(V);
if (Var && Var->getName() == "llvm.eh.catch.all.value") {
assert(Var->hasInitializer() &&
"The EH catch-all value must have an initializer");
Value *Init = Var->getInitializer();
GV = dyn_cast<GlobalValue>(Init);
if (!GV) V = cast<ConstantPointerNull>(Init);
}
assert((GV || isa<ConstantPointerNull>(V)) &&
"TypeInfo must be a global variable or NULL");
return GV;
}
bool
llvm::hasInlineAsmMemConstraint(InlineAsm::ConstraintInfoVector &CInfos,
const TargetLowering &TLI) {
for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
InlineAsm::ConstraintInfo &CI = CInfos[i];
for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
if (CType == TargetLowering::C_Memory)
return true;
}
if (CI.isIndirect)
return true;
}
return false;
}
ISD::CondCode llvm::getFCmpCondCode(FCmpInst::Predicate Pred) {
switch (Pred) {
case FCmpInst::FCMP_FALSE: return ISD::SETFALSE;
case FCmpInst::FCMP_OEQ: return ISD::SETOEQ;
case FCmpInst::FCMP_OGT: return ISD::SETOGT;
case FCmpInst::FCMP_OGE: return ISD::SETOGE;
case FCmpInst::FCMP_OLT: return ISD::SETOLT;
case FCmpInst::FCMP_OLE: return ISD::SETOLE;
case FCmpInst::FCMP_ONE: return ISD::SETONE;
case FCmpInst::FCMP_ORD: return ISD::SETO;
case FCmpInst::FCMP_UNO: return ISD::SETUO;
case FCmpInst::FCMP_UEQ: return ISD::SETUEQ;
case FCmpInst::FCMP_UGT: return ISD::SETUGT;
case FCmpInst::FCMP_UGE: return ISD::SETUGE;
case FCmpInst::FCMP_ULT: return ISD::SETULT;
case FCmpInst::FCMP_ULE: return ISD::SETULE;
case FCmpInst::FCMP_UNE: return ISD::SETUNE;
case FCmpInst::FCMP_TRUE: return ISD::SETTRUE;
default: llvm_unreachable("Invalid FCmp predicate opcode!");
}
}
ISD::CondCode llvm::getFCmpCodeWithoutNaN(ISD::CondCode CC) {
switch (CC) {
case ISD::SETOEQ: case ISD::SETUEQ: return ISD::SETEQ;
case ISD::SETONE: case ISD::SETUNE: return ISD::SETNE;
case ISD::SETOLT: case ISD::SETULT: return ISD::SETLT;
case ISD::SETOLE: case ISD::SETULE: return ISD::SETLE;
case ISD::SETOGT: case ISD::SETUGT: return ISD::SETGT;
case ISD::SETOGE: case ISD::SETUGE: return ISD::SETGE;
default: return CC;
}
}
ISD::CondCode llvm::getICmpCondCode(ICmpInst::Predicate Pred) {
switch (Pred) {
case ICmpInst::ICMP_EQ: return ISD::SETEQ;
case ICmpInst::ICMP_NE: return ISD::SETNE;
case ICmpInst::ICMP_SLE: return ISD::SETLE;
case ICmpInst::ICMP_ULE: return ISD::SETULE;
case ICmpInst::ICMP_SGE: return ISD::SETGE;
case ICmpInst::ICMP_UGE: return ISD::SETUGE;
case ICmpInst::ICMP_SLT: return ISD::SETLT;
case ICmpInst::ICMP_ULT: return ISD::SETULT;
case ICmpInst::ICMP_SGT: return ISD::SETGT;
case ICmpInst::ICMP_UGT: return ISD::SETUGT;
default:
llvm_unreachable("Invalid ICmp predicate opcode!");
}
}
static bool isNoopBitcast(Type *T1, Type *T2,
const TargetLoweringBase& TLI) {
return T1 == T2 || (T1->isPointerTy() && T2->isPointerTy()) ||
(isa<VectorType>(T1) && isa<VectorType>(T2) &&
TLI.isTypeLegal(EVT::getEVT(T1)) && TLI.isTypeLegal(EVT::getEVT(T2)));
}
static const Value *getNoopInput(const Value *V,
SmallVectorImpl<unsigned> &ValLoc,
unsigned &DataBits,
const TargetLoweringBase &TLI) {
while (true) {
const Instruction *I = dyn_cast<Instruction>(V);
if (!I || I->getNumOperands() == 0) return V;
const Value *NoopInput = nullptr;
Value *Op = I->getOperand(0);
if (isa<BitCastInst>(I)) {
if (isNoopBitcast(Op->getType(), I->getType(), TLI))
NoopInput = Op;
} else if (isa<GetElementPtrInst>(I)) {
if (cast<GetElementPtrInst>(I)->hasAllZeroIndices())
NoopInput = Op;
} else if (isa<IntToPtrInst>(I)) {
if (!isa<VectorType>(I->getType()) &&
TLI.getPointerTy().getSizeInBits() ==
cast<IntegerType>(Op->getType())->getBitWidth())
NoopInput = Op;
} else if (isa<PtrToIntInst>(I)) {
if (!isa<VectorType>(I->getType()) &&
TLI.getPointerTy().getSizeInBits() ==
cast<IntegerType>(I->getType())->getBitWidth())
NoopInput = Op;
} else if (isa<TruncInst>(I) &&
TLI.allowTruncateForTailCall(Op->getType(), I->getType())) {
DataBits = std::min(DataBits, I->getType()->getPrimitiveSizeInBits());
NoopInput = Op;
} else if (isa<CallInst>(I)) {
for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 1;
i != e; ++i) {
unsigned attrInd = i - I->op_begin() + 1;
if (cast<CallInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
NoopInput = *i;
break;
}
}
} else if (isa<InvokeInst>(I)) {
for (User::const_op_iterator i = I->op_begin(), e = I->op_end() - 3;
i != e; ++i) {
unsigned attrInd = i - I->op_begin() + 1;
if (cast<InvokeInst>(I)->paramHasAttr(attrInd, Attribute::Returned) &&
isNoopBitcast((*i)->getType(), I->getType(), TLI)) {
NoopInput = *i;
break;
}
}
} else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(V)) {
ArrayRef<unsigned> InsertLoc = IVI->getIndices();
if (ValLoc.size() >= InsertLoc.size() &&
std::equal(InsertLoc.begin(), InsertLoc.end(), ValLoc.rbegin())) {
ValLoc.resize(ValLoc.size() - InsertLoc.size());
NoopInput = IVI->getInsertedValueOperand();
} else {
NoopInput = Op;
}
} else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(V)) {
ArrayRef<unsigned> ExtractLoc = EVI->getIndices();
ValLoc.append(ExtractLoc.rbegin(), ExtractLoc.rend());
NoopInput = Op;
}
if (!NoopInput)
return V;
V = NoopInput;
}
}
static bool slotOnlyDiscardsData(const Value *RetVal, const Value *CallVal,
SmallVectorImpl<unsigned> &RetIndices,
SmallVectorImpl<unsigned> &CallIndices,
bool AllowDifferingSizes,
const TargetLoweringBase &TLI) {
unsigned BitsRequired = UINT_MAX;
RetVal = getNoopInput(RetVal, RetIndices, BitsRequired, TLI);
if (isa<UndefValue>(RetVal))
return true;
unsigned BitsProvided = UINT_MAX;
CallVal = getNoopInput(CallVal, CallIndices, BitsProvided, TLI);
if (CallVal != RetVal || CallIndices != RetIndices)
return false;
if (BitsProvided < BitsRequired ||
(!AllowDifferingSizes && BitsProvided != BitsRequired))
return false;
return true;
}
static bool indexReallyValid(CompositeType *T, unsigned Idx) {
if (ArrayType *AT = dyn_cast<ArrayType>(T))
return Idx < AT->getNumElements();
return Idx < cast<StructType>(T)->getNumElements();
}
static bool advanceToNextLeafType(SmallVectorImpl<CompositeType *> &SubTypes,
SmallVectorImpl<unsigned> &Path) {
while (!Path.empty() && !indexReallyValid(SubTypes.back(), Path.back() + 1)) {
Path.pop_back();
SubTypes.pop_back();
}
if (Path.empty())
return false;
++Path.back();
Type *DeeperType = SubTypes.back()->getTypeAtIndex(Path.back());
while (DeeperType->isAggregateType()) {
CompositeType *CT = cast<CompositeType>(DeeperType);
if (!indexReallyValid(CT, 0))
return true;
SubTypes.push_back(CT);
Path.push_back(0);
DeeperType = CT->getTypeAtIndex(0U);
}
return true;
}
static bool firstRealType(Type *Next,
SmallVectorImpl<CompositeType *> &SubTypes,
SmallVectorImpl<unsigned> &Path) {
while (Next->isAggregateType() &&
indexReallyValid(cast<CompositeType>(Next), 0)) {
SubTypes.push_back(cast<CompositeType>(Next));
Path.push_back(0);
Next = cast<CompositeType>(Next)->getTypeAtIndex(0U);
}
if (Path.empty())
return true;
while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType()) {
if (!advanceToNextLeafType(SubTypes, Path))
return false;
}
return true;
}
static bool nextRealType(SmallVectorImpl<CompositeType *> &SubTypes,
SmallVectorImpl<unsigned> &Path) {
do {
if (!advanceToNextLeafType(SubTypes, Path))
return false;
assert(!Path.empty() && "found a leaf but didn't set the path?");
} while (SubTypes.back()->getTypeAtIndex(Path.back())->isAggregateType());
return true;
}
bool llvm::isInTailCallPosition(ImmutableCallSite CS, const TargetMachine &TM) {
const Instruction *I = CS.getInstruction();
const BasicBlock *ExitBB = I->getParent();
const TerminatorInst *Term = ExitBB->getTerminator();
const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
if (!Ret &&
(!TM.Options.GuaranteedTailCallOpt || !isa<UnreachableInst>(Term)))
return false;
if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
!isSafeToSpeculativelyExecute(I))
for (BasicBlock::const_iterator BBI = std::prev(ExitBB->end(), 2);; --BBI) {
if (&*BBI == I)
break;
if (isa<DbgInfoIntrinsic>(BBI))
continue;
if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
!isSafeToSpeculativelyExecute(BBI))
return false;
}
const Function *F = ExitBB->getParent();
return returnTypeIsEligibleForTailCall(
F, I, Ret, *TM.getSubtargetImpl(*F)->getTargetLowering());
}
bool llvm::returnTypeIsEligibleForTailCall(const Function *F,
const Instruction *I,
const ReturnInst *Ret,
const TargetLoweringBase &TLI) {
if (!Ret || Ret->getNumOperands() == 0) return true;
if (isa<UndefValue>(Ret->getOperand(0))) return true;
AttrBuilder CallerAttrs(F->getAttributes(),
AttributeSet::ReturnIndex);
AttrBuilder CalleeAttrs(cast<CallInst>(I)->getAttributes(),
AttributeSet::ReturnIndex);
CallerAttrs = CallerAttrs.removeAttribute(Attribute::NoAlias);
CalleeAttrs = CalleeAttrs.removeAttribute(Attribute::NoAlias);
bool AllowDifferingSizes = true;
if (CallerAttrs.contains(Attribute::ZExt)) {
if (!CalleeAttrs.contains(Attribute::ZExt))
return false;
AllowDifferingSizes = false;
CallerAttrs.removeAttribute(Attribute::ZExt);
CalleeAttrs.removeAttribute(Attribute::ZExt);
} else if (CallerAttrs.contains(Attribute::SExt)) {
if (!CalleeAttrs.contains(Attribute::SExt))
return false;
AllowDifferingSizes = false;
CallerAttrs.removeAttribute(Attribute::SExt);
CalleeAttrs.removeAttribute(Attribute::SExt);
}
if (CallerAttrs != CalleeAttrs)
return false;
const Value *RetVal = Ret->getOperand(0), *CallVal = I;
SmallVector<unsigned, 4> RetPath, CallPath;
SmallVector<CompositeType *, 4> RetSubTypes, CallSubTypes;
bool RetEmpty = !firstRealType(RetVal->getType(), RetSubTypes, RetPath);
bool CallEmpty = !firstRealType(CallVal->getType(), CallSubTypes, CallPath);
if (RetEmpty)
return true;
do {
if (CallEmpty) {
Type *SlotType = RetSubTypes.back()->getTypeAtIndex(RetPath.back());
CallVal = UndefValue::get(SlotType);
}
SmallVector<unsigned, 4> TmpRetPath(RetPath.rbegin(), RetPath.rend());
SmallVector<unsigned, 4> TmpCallPath(CallPath.rbegin(), CallPath.rend());
if (!slotOnlyDiscardsData(RetVal, CallVal, TmpRetPath, TmpCallPath,
AllowDifferingSizes, TLI))
return false;
CallEmpty = !nextRealType(CallSubTypes, CallPath);
} while(nextRealType(RetSubTypes, RetPath));
return true;
}
bool llvm::canBeOmittedFromSymbolTable(const GlobalValue *GV) {
if (!GV->hasLinkOnceODRLinkage())
return false;
if (GV->hasUnnamedAddr())
return true;
if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
if (!Var->isConstant())
return false;
}
if (isa<GlobalAlias>(GV))
return false;
GlobalStatus GS;
if (GlobalStatus::analyzeGlobal(GV, GS))
return false;
return !GS.IsCompared;
}