Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/Module.cpp | //===-- Module.cpp - Implement the Module class ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Module class for the IR library.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Module.h"
#include "SymbolTableListTraitsImpl.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GVMaterializer.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/TypeFinder.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/RandomNumberGenerator.h"
#include <algorithm>
#include <cstdarg>
#include <cstdlib>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Methods to implement the globals and functions lists.
//
// Explicit instantiations of SymbolTableListTraits since some of the methods
// are not in the public header file.
template class llvm::SymbolTableListTraits<Function, Module>;
template class llvm::SymbolTableListTraits<GlobalVariable, Module>;
template class llvm::SymbolTableListTraits<GlobalAlias, Module>;
//===----------------------------------------------------------------------===//
// Primitive Module methods.
//
Module::Module(StringRef MID, LLVMContext &C)
: Context(C), Materializer(), ModuleID(MID), DL("") {
// HLSL Change - use unique_ptr to avoid leaks
std::unique_ptr<ValueSymbolTable> ValSymTabPtr(new ValueSymbolTable());
std::unique_ptr<StringMap<NamedMDNode *> > NamedMDSymTabPtr(new StringMap<NamedMDNode *>());
Context.addModule(this);
ValSymTab = ValSymTabPtr.release();
NamedMDSymTab = NamedMDSymTabPtr.release();
}
Module::~Module() {
// HLSL Change Starts
ResetHLModule();
ResetDxilModule();
// HLSL Change Ends
Context.removeModule(this);
dropAllReferences();
GlobalList.clear();
FunctionList.clear();
AliasList.clear();
NamedMDList.clear();
delete ValSymTab;
delete static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab);
}
RandomNumberGenerator *Module::createRNG(const Pass* P) const {
SmallString<32> Salt(P->getPassName());
// This RNG is guaranteed to produce the same random stream only
// when the Module ID and thus the input filename is the same. This
// might be problematic if the input filename extension changes
// (e.g. from .c to .bc or .ll).
//
// We could store this salt in NamedMetadata, but this would make
// the parameter non-const. This would unfortunately make this
// interface unusable by any Machine passes, since they only have a
// const reference to their IR Module. Alternatively we can always
// store salt metadata from the Module constructor.
Salt += sys::path::filename(getModuleIdentifier());
return new RandomNumberGenerator(Salt);
}
/// getNamedValue - Return the first global value in the module with
/// the specified name, of arbitrary type. This method returns null
/// if a global with the specified name is not found.
GlobalValue *Module::getNamedValue(StringRef Name) const {
return cast_or_null<GlobalValue>(getValueSymbolTable().lookup(Name));
}
/// getMDKindID - Return a unique non-zero ID for the specified metadata kind.
/// This ID is uniqued across modules in the current LLVMContext.
unsigned Module::getMDKindID(StringRef Name) const {
return Context.getMDKindID(Name);
}
/// getMDKindNames - Populate client supplied SmallVector with the name for
/// custom metadata IDs registered in this LLVMContext. ID #0 is not used,
/// so it is filled in as an empty string.
void Module::getMDKindNames(SmallVectorImpl<StringRef> &Result) const {
return Context.getMDKindNames(Result);
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the functions in the module.
//
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return
// it. This is nice because it allows most passes to get away with not handling
// the symbol table directly for this common task.
//
Constant *Module::getOrInsertFunction(StringRef Name,
FunctionType *Ty,
AttributeSet AttributeList) {
// See if we have a definition for the specified function already.
GlobalValue *F = getNamedValue(Name);
if (!F) {
// Nope, add it
Function *New = Function::Create(Ty, GlobalVariable::ExternalLinkage, Name);
if (!New->isIntrinsic()) // Intrinsics get attrs set on construction
New->setAttributes(AttributeList);
FunctionList.push_back(New);
return New; // Return the new prototype.
}
// If the function exists but has the wrong type, return a bitcast to the
// right type.
if (F->getType() != PointerType::getUnqual(Ty))
return ConstantExpr::getBitCast(F, PointerType::getUnqual(Ty));
// Otherwise, we just found the existing function or a prototype.
return F;
}
Constant *Module::getOrInsertFunction(StringRef Name,
FunctionType *Ty) {
return getOrInsertFunction(Name, Ty, AttributeSet());
}
// getOrInsertFunction - Look up the specified function in the module symbol
// table. If it does not exist, add a prototype for the function and return it.
// This version of the method takes a null terminated list of function
// arguments, which makes it easier for clients to use.
//
Constant *Module::getOrInsertFunction(StringRef Name,
AttributeSet AttributeList,
Type *RetTy, ...) {
va_list Args;
va_start(Args, RetTy);
// Build the list of argument types...
std::vector<Type*> ArgTys;
while (Type *ArgTy = va_arg(Args, Type*))
ArgTys.push_back(ArgTy);
va_end(Args);
// Build the function type and chain to the other getOrInsertFunction...
return getOrInsertFunction(Name,
FunctionType::get(RetTy, ArgTys, false),
AttributeList);
}
Constant *Module::getOrInsertFunction(StringRef Name,
Type *RetTy, ...) {
va_list Args;
va_start(Args, RetTy);
// Build the list of argument types...
std::vector<Type*> ArgTys;
while (Type *ArgTy = va_arg(Args, Type*))
ArgTys.push_back(ArgTy);
va_end(Args);
// Build the function type and chain to the other getOrInsertFunction...
return getOrInsertFunction(Name,
FunctionType::get(RetTy, ArgTys, false),
AttributeSet());
}
// getFunction - Look up the specified function in the module symbol table.
// If it does not exist, return null.
//
Function *Module::getFunction(StringRef Name) const {
return dyn_cast_or_null<Function>(getNamedValue(Name));
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the global variables in the module.
//
/// getGlobalVariable - Look up the specified global variable in the module
/// symbol table. If it does not exist, return null. The type argument
/// should be the underlying type of the global, i.e., it should not have
/// the top-level PointerType, which represents the address of the global.
/// If AllowLocal is set to true, this function will return types that
/// have an local. By default, these types are not returned.
///
GlobalVariable *Module::getGlobalVariable(StringRef Name, bool AllowLocal) {
if (GlobalVariable *Result =
dyn_cast_or_null<GlobalVariable>(getNamedValue(Name)))
if (AllowLocal || !Result->hasLocalLinkage())
return Result;
return nullptr;
}
/// getOrInsertGlobal - Look up the specified global in the module symbol table.
/// 1. If it does not exist, add a declaration of the global and return it.
/// 2. Else, the global exists but has the wrong type: return the function
/// with a constantexpr cast to the right type.
/// 3. Finally, if the existing global is the correct declaration, return the
/// existing global.
Constant *Module::getOrInsertGlobal(StringRef Name, Type *Ty) {
// See if we have a definition for the specified global already.
GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(getNamedValue(Name));
if (!GV) {
// Nope, add it
GlobalVariable *New =
new GlobalVariable(*this, Ty, false, GlobalVariable::ExternalLinkage,
nullptr, Name);
return New; // Return the new declaration.
}
// If the variable exists but has the wrong type, return a bitcast to the
// right type.
Type *GVTy = GV->getType();
PointerType *PTy = PointerType::get(Ty, GVTy->getPointerAddressSpace());
if (GVTy != PTy)
return ConstantExpr::getBitCast(GV, PTy);
// Otherwise, we just found the existing function or a prototype.
return GV;
}
//===----------------------------------------------------------------------===//
// Methods for easy access to the global variables in the module.
//
// getNamedAlias - Look up the specified global in the module symbol table.
// If it does not exist, return null.
//
GlobalAlias *Module::getNamedAlias(StringRef Name) const {
return dyn_cast_or_null<GlobalAlias>(getNamedValue(Name));
}
/// getNamedMetadata - Return the first NamedMDNode in the module with the
/// specified name. This method returns null if a NamedMDNode with the
/// specified name is not found.
NamedMDNode *Module::getNamedMetadata(const Twine &Name) const {
SmallString<256> NameData;
StringRef NameRef = Name.toStringRef(NameData);
return static_cast<StringMap<NamedMDNode*> *>(NamedMDSymTab)->lookup(NameRef);
}
/// getOrInsertNamedMetadata - Return the first named MDNode in the module
/// with the specified name. This method returns a new NamedMDNode if a
/// NamedMDNode with the specified name is not found.
NamedMDNode *Module::getOrInsertNamedMetadata(StringRef Name) {
NamedMDNode *&NMD =
(*static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab))[Name];
if (!NMD) {
NMD = new NamedMDNode(Name);
NMD->setParent(this);
NamedMDList.push_back(NMD);
}
return NMD;
}
/// eraseNamedMetadata - Remove the given NamedMDNode from this module and
/// delete it.
void Module::eraseNamedMetadata(NamedMDNode *NMD) {
static_cast<StringMap<NamedMDNode *> *>(NamedMDSymTab)->erase(NMD->getName());
NamedMDList.erase(NMD);
}
bool Module::isValidModFlagBehavior(Metadata *MD, ModFlagBehavior &MFB) {
if (ConstantInt *Behavior = mdconst::dyn_extract_or_null<ConstantInt>(MD)) {
uint64_t Val = Behavior->getLimitedValue();
if (Val >= ModFlagBehaviorFirstVal && Val <= ModFlagBehaviorLastVal) {
MFB = static_cast<ModFlagBehavior>(Val);
return true;
}
}
return false;
}
/// getModuleFlagsMetadata - Returns the module flags in the provided vector.
void Module::
getModuleFlagsMetadata(SmallVectorImpl<ModuleFlagEntry> &Flags) const {
const NamedMDNode *ModFlags = getModuleFlagsMetadata();
if (!ModFlags) return;
for (const MDNode *Flag : ModFlags->operands()) {
ModFlagBehavior MFB;
if (Flag->getNumOperands() >= 3 &&
isValidModFlagBehavior(Flag->getOperand(0), MFB) &&
dyn_cast_or_null<MDString>(Flag->getOperand(1))) {
// Check the operands of the MDNode before accessing the operands.
// The verifier will actually catch these failures.
MDString *Key = cast<MDString>(Flag->getOperand(1));
Metadata *Val = Flag->getOperand(2);
Flags.push_back(ModuleFlagEntry(MFB, Key, Val));
}
}
}
/// Return the corresponding value if Key appears in module flags, otherwise
/// return null.
Metadata *Module::getModuleFlag(StringRef Key) const {
SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
getModuleFlagsMetadata(ModuleFlags);
for (const ModuleFlagEntry &MFE : ModuleFlags) {
if (Key == MFE.Key->getString())
return MFE.Val;
}
return nullptr;
}
/// getModuleFlagsMetadata - Returns the NamedMDNode in the module that
/// represents module-level flags. This method returns null if there are no
/// module-level flags.
NamedMDNode *Module::getModuleFlagsMetadata() const {
return getNamedMetadata("llvm.module.flags");
}
/// getOrInsertModuleFlagsMetadata - Returns the NamedMDNode in the module that
/// represents module-level flags. If module-level flags aren't found, it
/// creates the named metadata that contains them.
NamedMDNode *Module::getOrInsertModuleFlagsMetadata() {
return getOrInsertNamedMetadata("llvm.module.flags");
}
/// addModuleFlag - Add a module-level flag to the module-level flags
/// metadata. It will create the module-level flags named metadata if it doesn't
/// already exist.
void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
Metadata *Val) {
Type *Int32Ty = Type::getInt32Ty(Context);
Metadata *Ops[3] = {
ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Behavior)),
MDString::get(Context, Key), Val};
getOrInsertModuleFlagsMetadata()->addOperand(MDNode::get(Context, Ops));
}
void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
Constant *Val) {
addModuleFlag(Behavior, Key, ConstantAsMetadata::get(Val));
}
void Module::addModuleFlag(ModFlagBehavior Behavior, StringRef Key,
uint32_t Val) {
Type *Int32Ty = Type::getInt32Ty(Context);
addModuleFlag(Behavior, Key, ConstantInt::get(Int32Ty, Val));
}
void Module::addModuleFlag(MDNode *Node) {
assert(Node->getNumOperands() == 3 &&
"Invalid number of operands for module flag!");
assert(mdconst::hasa<ConstantInt>(Node->getOperand(0)) &&
isa<MDString>(Node->getOperand(1)) &&
"Invalid operand types for module flag!");
getOrInsertModuleFlagsMetadata()->addOperand(Node);
}
void Module::setDataLayout(StringRef Desc) {
DL.reset(Desc);
}
void Module::setDataLayout(const DataLayout &Other) { DL = Other; }
const DataLayout &Module::getDataLayout() const { return DL; }
//===----------------------------------------------------------------------===//
// Methods to control the materialization of GlobalValues in the Module.
//
void Module::setMaterializer(GVMaterializer *GVM) {
assert(!Materializer &&
"Module already has a GVMaterializer. Call MaterializeAllPermanently"
" to clear it out before setting another one.");
Materializer.reset(GVM);
}
bool Module::isDematerializable(const GlobalValue *GV) const {
if (Materializer)
return Materializer->isDematerializable(GV);
return false;
}
std::error_code Module::materialize(GlobalValue *GV) {
if (!Materializer)
return std::error_code();
return Materializer->materialize(GV);
}
void Module::dematerialize(GlobalValue *GV) {
if (Materializer)
return Materializer->dematerialize(GV);
}
std::error_code Module::materializeAll() {
if (!Materializer)
return std::error_code();
return Materializer->materializeModule(this);
}
std::error_code Module::materializeAllPermanently() {
if (std::error_code EC = materializeAll())
return EC;
Materializer.reset();
return std::error_code();
}
std::error_code Module::materializeMetadata() {
if (!Materializer)
return std::error_code();
return Materializer->materializeMetadata();
}
std::error_code Module::materializeSelectNamedMetadata(ArrayRef<StringRef> NamedMetadata) {
if (!Materializer)
return std::error_code();
return Materializer->materializeSelectNamedMetadata(NamedMetadata);
}
//===----------------------------------------------------------------------===//
// Other module related stuff.
//
std::vector<StructType *> Module::getIdentifiedStructTypes() const {
// If we have a materializer, it is possible that some unread function
// uses a type that is currently not visible to a TypeFinder, so ask
// the materializer which types it created.
if (Materializer)
return Materializer->getIdentifiedStructTypes();
std::vector<StructType *> Ret;
TypeFinder SrcStructTypes;
SrcStructTypes.run(*this, true);
Ret.assign(SrcStructTypes.begin(), SrcStructTypes.end());
return Ret;
}
// dropAllReferences() - This function causes all the subelements to "let go"
// of all references that they are maintaining. This allows one to 'delete' a
// whole module at a time, even though there may be circular references... first
// all references are dropped, and all use counts go to zero. Then everything
// is deleted for real. Note that no operations are valid on an object that
// has "dropped all references", except operator delete.
//
void Module::dropAllReferences() {
for (Function &F : *this)
F.dropAllReferences();
for (GlobalVariable &GV : globals())
GV.dropAllReferences();
for (GlobalAlias &GA : aliases())
GA.dropAllReferences();
}
unsigned Module::getDwarfVersion() const {
auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("Dwarf Version"));
if (!Val)
return dwarf::DWARF_VERSION;
return cast<ConstantInt>(Val->getValue())->getZExtValue();
}
Comdat *Module::getOrInsertComdat(StringRef Name) {
auto &Entry = *ComdatSymTab.insert(std::make_pair(Name, Comdat())).first;
Entry.second.Name = &Entry;
return &Entry.second;
}
PICLevel::Level Module::getPICLevel() const {
auto *Val = cast_or_null<ConstantAsMetadata>(getModuleFlag("PIC Level"));
if (Val == NULL)
return PICLevel::Default;
return static_cast<PICLevel::Level>(
cast<ConstantInt>(Val->getValue())->getZExtValue());
}
void Module::setPICLevel(PICLevel::Level PL) {
addModuleFlag(ModFlagBehavior::Error, "PIC Level", PL);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/BasicBlock.cpp | //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the BasicBlock class for the IR library.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/BasicBlock.h"
#include "SymbolTableListTraitsImpl.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Type.h"
#include <algorithm>
using namespace llvm;
ValueSymbolTable *BasicBlock::getValueSymbolTable() {
if (Function *F = getParent())
return &F->getValueSymbolTable();
return nullptr;
}
LLVMContext &BasicBlock::getContext() const {
return getType()->getContext();
}
// Explicit instantiation of SymbolTableListTraits since some of the methods
// are not in the public header file...
template class llvm::SymbolTableListTraits<Instruction, BasicBlock>;
BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
BasicBlock *InsertBefore)
: Value(Type::getLabelTy(C), Value::BasicBlockVal),
// HLSL Change Starts
// Use a real instruction as the sentinel. Transfer ownership to InstList.
// The sentinel only needs to participate in the intrusive list of
// instructions. Any instruction kind will do, but UnreachableInst is
// small and simple.
InstList(std::unique_ptr<Instruction>(new UnreachableInst(C))),
// HLSL Change Ends
Parent(nullptr) {
// HLSL Change Begin
// Do everything that can throw before inserting into the
// linked list, which takes ownership of this object on success.
setName(Name);
// HLSL Change End
if (NewParent)
insertInto(NewParent, InsertBefore);
else
assert(!InsertBefore &&
"Cannot insert block before another block with no function!");
// setName(Name); // HLSL Change: moved above
}
void BasicBlock::insertInto(Function *NewParent, BasicBlock *InsertBefore) {
assert(NewParent && "Expected a parent");
assert(!Parent && "Already has a parent");
if (InsertBefore)
NewParent->getBasicBlockList().insert(InsertBefore, this);
else
NewParent->getBasicBlockList().push_back(this);
}
BasicBlock::~BasicBlock() {
// If the address of the block is taken and it is being deleted (e.g. because
// it is dead), this means that there is either a dangling constant expr
// hanging off the block, or an undefined use of the block (source code
// expecting the address of a label to keep the block alive even though there
// is no indirect branch). Handle these cases by zapping the BlockAddress
// nodes. There are no other possible uses at this point.
if (hasAddressTaken()) {
assert(!use_empty() && "There should be at least one blockaddress!");
Constant *Replacement =
ConstantInt::get(llvm::Type::getInt32Ty(getContext()), 1);
while (!use_empty()) {
BlockAddress *BA = cast<BlockAddress>(user_back());
BA->replaceAllUsesWith(ConstantExpr::getIntToPtr(Replacement,
BA->getType()));
BA->destroyConstant();
}
}
assert(getParent() == nullptr && "BasicBlock still linked into the program!");
dropAllReferences();
InstList.clear();
}
void BasicBlock::setParent(Function *parent) {
// Set Parent=parent, updating instruction symtab entries as appropriate.
InstList.setSymTabObject(&Parent, parent);
}
void BasicBlock::removeFromParent() {
getParent()->getBasicBlockList().remove(this);
}
iplist<BasicBlock>::iterator BasicBlock::eraseFromParent() {
return getParent()->getBasicBlockList().erase(this);
}
/// Unlink this basic block from its current function and
/// insert it into the function that MovePos lives in, right before MovePos.
void BasicBlock::moveBefore(BasicBlock *MovePos) {
MovePos->getParent()->getBasicBlockList().splice(MovePos,
getParent()->getBasicBlockList(), this);
}
/// Unlink this basic block from its current function and
/// insert it into the function that MovePos lives in, right after MovePos.
void BasicBlock::moveAfter(BasicBlock *MovePos) {
Function::iterator I = MovePos;
MovePos->getParent()->getBasicBlockList().splice(++I,
getParent()->getBasicBlockList(), this);
}
const Module *BasicBlock::getModule() const {
return getParent()->getParent();
}
Module *BasicBlock::getModule() {
return getParent()->getParent();
}
TerminatorInst *BasicBlock::getTerminator() {
if (InstList.empty()) return nullptr;
return dyn_cast<TerminatorInst>(&InstList.back());
}
const TerminatorInst *BasicBlock::getTerminator() const {
if (InstList.empty()) return nullptr;
return dyn_cast<TerminatorInst>(&InstList.back());
}
CallInst *BasicBlock::getTerminatingMustTailCall() {
if (InstList.empty())
return nullptr;
ReturnInst *RI = dyn_cast<ReturnInst>(&InstList.back());
if (!RI || RI == &InstList.front())
return nullptr;
Instruction *Prev = RI->getPrevNode();
if (!Prev)
return nullptr;
if (Value *RV = RI->getReturnValue()) {
if (RV != Prev)
return nullptr;
// Look through the optional bitcast.
if (auto *BI = dyn_cast<BitCastInst>(Prev)) {
RV = BI->getOperand(0);
Prev = BI->getPrevNode();
if (!Prev || RV != Prev)
return nullptr;
}
}
if (auto *CI = dyn_cast<CallInst>(Prev)) {
if (CI->isMustTailCall())
return CI;
}
return nullptr;
}
// HLSL Change - begin
size_t BasicBlock::compute_size_no_dbg() const {
size_t ret = 0;
for (auto it = InstList.begin(), E = InstList.end(); it != E; it++) {
if (isa<DbgInfoIntrinsic>(&*it))
continue;
ret++;
}
return ret;
}
// HLSL Change - end
Instruction* BasicBlock::getFirstNonPHI() {
for (Instruction &I : *this)
if (!isa<PHINode>(I))
return &I;
return nullptr;
}
Instruction* BasicBlock::getFirstNonPHIOrDbg() {
for (Instruction &I : *this)
if (!isa<PHINode>(I) && !isa<DbgInfoIntrinsic>(I))
return &I;
return nullptr;
}
Instruction* BasicBlock::getFirstNonPHIOrDbgOrLifetime() {
for (Instruction &I : *this) {
if (isa<PHINode>(I) || isa<DbgInfoIntrinsic>(I))
continue;
if (auto *II = dyn_cast<IntrinsicInst>(&I))
if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
II->getIntrinsicID() == Intrinsic::lifetime_end)
continue;
return &I;
}
return nullptr;
}
BasicBlock::iterator BasicBlock::getFirstInsertionPt() {
Instruction *FirstNonPHI = getFirstNonPHI();
if (!FirstNonPHI)
return end();
iterator InsertPt = FirstNonPHI;
if (isa<LandingPadInst>(InsertPt)) ++InsertPt;
return InsertPt;
}
void BasicBlock::dropAllReferences() {
for(iterator I = begin(), E = end(); I != E; ++I)
I->dropAllReferences();
}
/// If this basic block has a single predecessor block,
/// return the block, otherwise return a null pointer.
BasicBlock *BasicBlock::getSinglePredecessor() {
pred_iterator PI = pred_begin(this), E = pred_end(this);
if (PI == E) return nullptr; // No preds.
BasicBlock *ThePred = *PI;
++PI;
return (PI == E) ? ThePred : nullptr /*multiple preds*/;
}
/// If this basic block has a unique predecessor block,
/// return the block, otherwise return a null pointer.
/// Note that unique predecessor doesn't mean single edge, there can be
/// multiple edges from the unique predecessor to this block (for example
/// a switch statement with multiple cases having the same destination).
BasicBlock *BasicBlock::getUniquePredecessor() {
pred_iterator PI = pred_begin(this), E = pred_end(this);
if (PI == E) return nullptr; // No preds.
BasicBlock *PredBB = *PI;
++PI;
for (;PI != E; ++PI) {
if (*PI != PredBB)
return nullptr;
// The same predecessor appears multiple times in the predecessor list.
// This is OK.
}
return PredBB;
}
BasicBlock *BasicBlock::getSingleSuccessor() {
succ_iterator SI = succ_begin(this), E = succ_end(this);
if (SI == E) return nullptr; // no successors
BasicBlock *TheSucc = *SI;
++SI;
return (SI == E) ? TheSucc : nullptr /* multiple successors */;
}
BasicBlock *BasicBlock::getUniqueSuccessor() {
succ_iterator SI = succ_begin(this), E = succ_end(this);
if (SI == E) return NULL; // No successors
BasicBlock *SuccBB = *SI;
++SI;
for (;SI != E; ++SI) {
if (*SI != SuccBB)
return NULL;
// The same successor appears multiple times in the successor list.
// This is OK.
}
return SuccBB;
}
/// This method is used to notify a BasicBlock that the
/// specified Predecessor of the block is no longer able to reach it. This is
/// actually not used to update the Predecessor list, but is actually used to
/// update the PHI nodes that reside in the block. Note that this should be
/// called while the predecessor still refers to this block.
///
void BasicBlock::removePredecessor(BasicBlock *Pred,
bool DontDeleteUselessPHIs) {
assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
std::find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
"removePredecessor: BB is not a predecessor!");
if (InstList.empty()) return;
PHINode *APN = dyn_cast<PHINode>(&front());
if (!APN) return; // Quick exit.
// If there are exactly two predecessors, then we want to nuke the PHI nodes
// altogether. However, we cannot do this, if this in this case:
//
// Loop:
// %x = phi [X, Loop]
// %x2 = add %x, 1 ;; This would become %x2 = add %x2, 1
// br Loop ;; %x2 does not dominate all uses
//
// This is because the PHI node input is actually taken from the predecessor
// basic block. The only case this can happen is with a self loop, so we
// check for this case explicitly now.
//
unsigned max_idx = APN->getNumIncomingValues();
assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
if (max_idx == 2) {
BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
// Disable PHI elimination!
if (this == Other) max_idx = 3;
}
// <= Two predecessors BEFORE I remove one?
if (max_idx <= 2 && !DontDeleteUselessPHIs) {
// Yup, loop through and nuke the PHI nodes
while (PHINode *PN = dyn_cast<PHINode>(&front())) {
// Remove the predecessor first.
PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
// If the PHI _HAD_ two uses, replace PHI node with its now *single* value
if (max_idx == 2) {
if (PN->getIncomingValue(0) != PN)
PN->replaceAllUsesWith(PN->getIncomingValue(0));
else
// We are left with an infinite loop with no entries: kill the PHI.
PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
getInstList().pop_front(); // Remove the PHI node
}
// If the PHI node already only had one entry, it got deleted by
// removeIncomingValue.
}
} else {
// Okay, now we know that we need to remove predecessor #pred_idx from all
// PHI nodes. Iterate over each PHI node fixing them up
PHINode *PN;
for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
++II;
PN->removeIncomingValue(Pred, false);
// If all incoming values to the Phi are the same, we can replace the Phi
// with that value.
Value* PNV = nullptr;
if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
if (PNV != PN) {
PN->replaceAllUsesWith(PNV);
PN->eraseFromParent();
}
}
}
}
/// This splits a basic block into two at the specified
/// instruction. Note that all instructions BEFORE the specified iterator stay
/// as part of the original basic block, an unconditional branch is added to
/// the new BB, and the rest of the instructions in the BB are moved to the new
/// BB, including the old terminator. This invalidates the iterator.
///
/// Note that this only works on well formed basic blocks (must have a
/// terminator), and 'I' must not be the end of instruction list (which would
/// cause a degenerate basic block to be formed, having a terminator inside of
/// the basic block).
///
BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
assert(I != InstList.end() &&
"Trying to get me to create degenerate basic block!");
BasicBlock *InsertBefore = std::next(Function::iterator(this))
.getNodePtrUnchecked();
BasicBlock *New = BasicBlock::Create(getContext(), BBName,
getParent(), InsertBefore);
// Save DebugLoc of split point before invalidating iterator.
DebugLoc Loc = I->getDebugLoc();
// Move all of the specified instructions from the original basic block into
// the new basic block.
New->getInstList().splice(New->end(), this->getInstList(), I, end());
// Add a branch instruction to the newly formed basic block.
BranchInst *BI = BranchInst::Create(New, this);
BI->setDebugLoc(Loc);
// Now we must loop through all of the successors of the New block (which
// _were_ the successors of the 'this' block), and update any PHI nodes in
// successors. If there were PHI nodes in the successors, then they need to
// know that incoming branches will be from New, not from Old.
//
for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
// Loop over any phi nodes in the basic block, updating the BB field of
// incoming values...
BasicBlock *Successor = *I;
PHINode *PN;
for (BasicBlock::iterator II = Successor->begin();
(PN = dyn_cast<PHINode>(II)); ++II) {
int IDX = PN->getBasicBlockIndex(this);
while (IDX != -1) {
PN->setIncomingBlock((unsigned)IDX, New);
IDX = PN->getBasicBlockIndex(this);
}
}
}
return New;
}
void BasicBlock::replaceSuccessorsPhiUsesWith(BasicBlock *New) {
TerminatorInst *TI = getTerminator();
if (!TI)
// Cope with being called on a BasicBlock that doesn't have a terminator
// yet. Clang's CodeGenFunction::EmitReturnBlock() likes to do this.
return;
for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
BasicBlock *Succ = TI->getSuccessor(i);
// N.B. Succ might not be a complete BasicBlock, so don't assume
// that it ends with a non-phi instruction.
for (iterator II = Succ->begin(), IE = Succ->end(); II != IE; ++II) {
PHINode *PN = dyn_cast<PHINode>(II);
if (!PN)
break;
int i;
while ((i = PN->getBasicBlockIndex(this)) >= 0)
PN->setIncomingBlock(i, New);
}
}
}
/// Return true if this basic block is a landing pad. I.e., it's
/// the destination of the 'unwind' edge of an invoke instruction.
bool BasicBlock::isLandingPad() const {
return isa<LandingPadInst>(getFirstNonPHI());
}
/// Return the landingpad instruction associated with the landing pad.
LandingPadInst *BasicBlock::getLandingPadInst() {
return dyn_cast<LandingPadInst>(getFirstNonPHI());
}
const LandingPadInst *BasicBlock::getLandingPadInst() const {
return dyn_cast<LandingPadInst>(getFirstNonPHI());
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/IRBuilder.cpp | //===---- IRBuilder.cpp - Builder for LLVM Instrs -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the IRBuilder class, which is used as a convenient way
// to create LLVM instructions with a consistent and simplified interface.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Statepoint.h"
using namespace llvm;
/// CreateGlobalString - Make a new global variable with an initializer that
/// has array of i8 type filled in with the nul terminated string value
/// specified. If Name is specified, it is the name of the global variable
/// created.
GlobalVariable *IRBuilderBase::CreateGlobalString(StringRef Str,
const Twine &Name,
unsigned AddressSpace) {
Constant *StrConstant = ConstantDataArray::getString(Context, Str);
Module &M = *BB->getParent()->getParent();
GlobalVariable *GV = new GlobalVariable(M, StrConstant->getType(),
true, GlobalValue::PrivateLinkage,
StrConstant, Name, nullptr,
GlobalVariable::NotThreadLocal,
AddressSpace);
GV->setUnnamedAddr(true);
return GV;
}
Type *IRBuilderBase::getCurrentFunctionReturnType() const {
assert(BB && BB->getParent() && "No current function!");
return BB->getParent()->getReturnType();
}
Value *IRBuilderBase::getCastedInt8PtrValue(Value *Ptr) {
PointerType *PT = cast<PointerType>(Ptr->getType());
if (PT->getElementType()->isIntegerTy(8))
return Ptr;
// Otherwise, we need to insert a bitcast.
PT = getInt8PtrTy(PT->getAddressSpace());
BitCastInst *BCI = new BitCastInst(Ptr, PT, "");
BB->getInstList().insert(InsertPt, BCI);
SetInstDebugLocation(BCI);
return BCI;
}
static CallInst *createCallHelper(Value *Callee, ArrayRef<Value *> Ops,
IRBuilderBase *Builder,
const Twine& Name="") {
CallInst *CI = CallInst::Create(Callee, Ops, Name);
Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),CI);
Builder->SetInstDebugLocation(CI);
return CI;
}
static InvokeInst *createInvokeHelper(Value *Invokee, BasicBlock *NormalDest,
BasicBlock *UnwindDest,
ArrayRef<Value *> Ops,
IRBuilderBase *Builder,
const Twine &Name = "") {
InvokeInst *II =
InvokeInst::Create(Invokee, NormalDest, UnwindDest, Ops, Name);
Builder->GetInsertBlock()->getInstList().insert(Builder->GetInsertPoint(),
II);
Builder->SetInstDebugLocation(II);
return II;
}
CallInst *IRBuilderBase::
CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag,
MDNode *NoAliasTag) {
Ptr = getCastedInt8PtrValue(Ptr);
Value *Ops[] = { Ptr, Val, Size, getInt32(Align), getInt1(isVolatile) };
Type *Tys[] = { Ptr->getType(), Size->getType() };
Module *M = BB->getParent()->getParent();
Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys);
CallInst *CI = createCallHelper(TheFn, Ops, this);
// Set the TBAA info if present.
if (TBAATag)
CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
if (ScopeTag)
CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
if (NoAliasTag)
CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
return CI;
}
CallInst *IRBuilderBase::
CreateMemCpy(Value *Dst, Value *Src, Value *Size, unsigned Align,
bool isVolatile, MDNode *TBAATag, MDNode *TBAAStructTag,
MDNode *ScopeTag, MDNode *NoAliasTag) {
Dst = getCastedInt8PtrValue(Dst);
Src = getCastedInt8PtrValue(Src);
Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) };
Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
Module *M = BB->getParent()->getParent();
Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memcpy, Tys);
CallInst *CI = createCallHelper(TheFn, Ops, this);
// Set the TBAA info if present.
if (TBAATag)
CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
// Set the TBAA Struct info if present.
if (TBAAStructTag)
CI->setMetadata(LLVMContext::MD_tbaa_struct, TBAAStructTag);
if (ScopeTag)
CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
if (NoAliasTag)
CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
return CI;
}
CallInst *IRBuilderBase::
CreateMemMove(Value *Dst, Value *Src, Value *Size, unsigned Align,
bool isVolatile, MDNode *TBAATag, MDNode *ScopeTag,
MDNode *NoAliasTag) {
Dst = getCastedInt8PtrValue(Dst);
Src = getCastedInt8PtrValue(Src);
Value *Ops[] = { Dst, Src, Size, getInt32(Align), getInt1(isVolatile) };
Type *Tys[] = { Dst->getType(), Src->getType(), Size->getType() };
Module *M = BB->getParent()->getParent();
Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::memmove, Tys);
CallInst *CI = createCallHelper(TheFn, Ops, this);
// Set the TBAA info if present.
if (TBAATag)
CI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
if (ScopeTag)
CI->setMetadata(LLVMContext::MD_alias_scope, ScopeTag);
if (NoAliasTag)
CI->setMetadata(LLVMContext::MD_noalias, NoAliasTag);
return CI;
}
CallInst *IRBuilderBase::CreateLifetimeStart(Value *Ptr, ConstantInt *Size) {
assert(isa<PointerType>(Ptr->getType()) &&
"lifetime.start only applies to pointers.");
Ptr = getCastedInt8PtrValue(Ptr);
if (!Size)
Size = getInt64(-1);
else
assert(Size->getType() == getInt64Ty() &&
"lifetime.start requires the size to be an i64");
Value *Ops[] = { Size, Ptr };
Module *M = BB->getParent()->getParent();
Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_start);
return createCallHelper(TheFn, Ops, this);
}
CallInst *IRBuilderBase::CreateLifetimeEnd(Value *Ptr, ConstantInt *Size) {
assert(isa<PointerType>(Ptr->getType()) &&
"lifetime.end only applies to pointers.");
Ptr = getCastedInt8PtrValue(Ptr);
if (!Size)
Size = getInt64(-1);
else
assert(Size->getType() == getInt64Ty() &&
"lifetime.end requires the size to be an i64");
Value *Ops[] = { Size, Ptr };
Module *M = BB->getParent()->getParent();
Value *TheFn = Intrinsic::getDeclaration(M, Intrinsic::lifetime_end);
return createCallHelper(TheFn, Ops, this);
}
CallInst *IRBuilderBase::CreateAssumption(Value *Cond) {
assert(Cond->getType() == getInt1Ty() &&
"an assumption condition must be of type i1");
Value *Ops[] = { Cond };
Module *M = BB->getParent()->getParent();
Value *FnAssume = Intrinsic::getDeclaration(M, Intrinsic::assume);
return createCallHelper(FnAssume, Ops, this);
}
/// Create a call to a Masked Load intrinsic.
/// Ptr - the base pointer for the load
/// Align - alignment of the source location
/// Mask - an vector of booleans which indicates what vector lanes should
/// be accessed in memory
/// PassThru - a pass-through value that is used to fill the masked-off lanes
/// of the result
/// Name - name of the result variable
CallInst *IRBuilderBase::CreateMaskedLoad(Value *Ptr, unsigned Align,
Value *Mask, Value *PassThru,
const Twine &Name) {
assert(Ptr->getType()->isPointerTy() && "Ptr must be of pointer type");
// DataTy is the overloaded type
Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
assert(DataTy->isVectorTy() && "Ptr should point to a vector");
if (!PassThru)
PassThru = UndefValue::get(DataTy);
Value *Ops[] = { Ptr, getInt32(Align), Mask, PassThru};
return CreateMaskedIntrinsic(Intrinsic::masked_load, Ops, DataTy, Name);
}
/// Create a call to a Masked Store intrinsic.
/// Val - the data to be stored,
/// Ptr - the base pointer for the store
/// Align - alignment of the destination location
/// Mask - an vector of booleans which indicates what vector lanes should
/// be accessed in memory
CallInst *IRBuilderBase::CreateMaskedStore(Value *Val, Value *Ptr,
unsigned Align, Value *Mask) {
Value *Ops[] = { Val, Ptr, getInt32(Align), Mask };
// Type of the data to be stored - the only one overloaded type
return CreateMaskedIntrinsic(Intrinsic::masked_store, Ops, Val->getType());
}
/// Create a call to a Masked intrinsic, with given intrinsic Id,
/// an array of operands - Ops, and one overloaded type - DataTy
CallInst *IRBuilderBase::CreateMaskedIntrinsic(Intrinsic::ID Id,
ArrayRef<Value *> Ops,
Type *DataTy,
const Twine &Name) {
Module *M = BB->getParent()->getParent();
Type *OverloadedTypes[] = { DataTy };
Value *TheFn = Intrinsic::getDeclaration(M, Id, OverloadedTypes);
return createCallHelper(TheFn, Ops, this, Name);
}
static std::vector<Value *>
getStatepointArgs(IRBuilderBase &B, uint64_t ID, uint32_t NumPatchBytes,
Value *ActualCallee, ArrayRef<Value *> CallArgs,
ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs) {
std::vector<Value *> Args;
Args.push_back(B.getInt64(ID));
Args.push_back(B.getInt32(NumPatchBytes));
Args.push_back(ActualCallee);
Args.push_back(B.getInt32(CallArgs.size()));
Args.push_back(B.getInt32((unsigned)StatepointFlags::None));
Args.insert(Args.end(), CallArgs.begin(), CallArgs.end());
Args.push_back(B.getInt32(0 /* no transition args */));
Args.push_back(B.getInt32(DeoptArgs.size()));
Args.insert(Args.end(), DeoptArgs.begin(), DeoptArgs.end());
Args.insert(Args.end(), GCArgs.begin(), GCArgs.end());
return Args;
}
CallInst *IRBuilderBase::CreateGCStatepointCall(
uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
ArrayRef<Value *> CallArgs, ArrayRef<Value *> DeoptArgs,
ArrayRef<Value *> GCArgs, const Twine &Name) {
// Extract out the type of the callee.
PointerType *FuncPtrType = cast<PointerType>(ActualCallee->getType());
assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
"actual callee must be a callable value");
Module *M = BB->getParent()->getParent();
// Fill in the one generic type'd argument (the function is also vararg)
Type *ArgTypes[] = { FuncPtrType };
Function *FnStatepoint =
Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_statepoint,
ArgTypes);
std::vector<llvm::Value *> Args = getStatepointArgs(
*this, ID, NumPatchBytes, ActualCallee, CallArgs, DeoptArgs, GCArgs);
return createCallHelper(FnStatepoint, Args, this, Name);
}
CallInst *IRBuilderBase::CreateGCStatepointCall(
uint64_t ID, uint32_t NumPatchBytes, Value *ActualCallee,
ArrayRef<Use> CallArgs, ArrayRef<Value *> DeoptArgs,
ArrayRef<Value *> GCArgs, const Twine &Name) {
std::vector<Value *> VCallArgs;
for (auto &U : CallArgs)
VCallArgs.push_back(U.get());
return CreateGCStatepointCall(ID, NumPatchBytes, ActualCallee, VCallArgs,
DeoptArgs, GCArgs, Name);
}
InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
BasicBlock *NormalDest, BasicBlock *UnwindDest,
ArrayRef<Value *> InvokeArgs, ArrayRef<Value *> DeoptArgs,
ArrayRef<Value *> GCArgs, const Twine &Name) {
// Extract out the type of the callee.
PointerType *FuncPtrType = cast<PointerType>(ActualInvokee->getType());
assert(isa<FunctionType>(FuncPtrType->getElementType()) &&
"actual callee must be a callable value");
Module *M = BB->getParent()->getParent();
// Fill in the one generic type'd argument (the function is also vararg)
Function *FnStatepoint = Intrinsic::getDeclaration(
M, Intrinsic::experimental_gc_statepoint, {FuncPtrType});
std::vector<llvm::Value *> Args = getStatepointArgs(
*this, ID, NumPatchBytes, ActualInvokee, InvokeArgs, DeoptArgs, GCArgs);
return createInvokeHelper(FnStatepoint, NormalDest, UnwindDest, Args, this,
Name);
}
InvokeInst *IRBuilderBase::CreateGCStatepointInvoke(
uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
ArrayRef<Value *> DeoptArgs, ArrayRef<Value *> GCArgs, const Twine &Name) {
std::vector<Value *> VCallArgs;
for (auto &U : InvokeArgs)
VCallArgs.push_back(U.get());
return CreateGCStatepointInvoke(ID, NumPatchBytes, ActualInvokee, NormalDest,
UnwindDest, VCallArgs, DeoptArgs, GCArgs,
Name);
}
CallInst *IRBuilderBase::CreateGCResult(Instruction *Statepoint,
Type *ResultType,
const Twine &Name) {
Intrinsic::ID ID = Intrinsic::experimental_gc_result;
Module *M = BB->getParent()->getParent();
Type *Types[] = {ResultType};
Value *FnGCResult = Intrinsic::getDeclaration(M, ID, Types);
Value *Args[] = {Statepoint};
return createCallHelper(FnGCResult, Args, this, Name);
}
CallInst *IRBuilderBase::CreateGCRelocate(Instruction *Statepoint,
int BaseOffset,
int DerivedOffset,
Type *ResultType,
const Twine &Name) {
Module *M = BB->getParent()->getParent();
Type *Types[] = {ResultType};
Value *FnGCRelocate =
Intrinsic::getDeclaration(M, Intrinsic::experimental_gc_relocate, Types);
Value *Args[] = {Statepoint,
getInt32(BaseOffset),
getInt32(DerivedOffset)};
return createCallHelper(FnGCRelocate, Args, this, Name);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/LLVMContextImpl.cpp | //===-- LLVMContextImpl.cpp - Implement LLVMContextImpl -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the opaque LLVMContextImpl.
//
//===----------------------------------------------------------------------===//
#include "LLVMContextImpl.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/Module.h"
#include <algorithm>
using namespace llvm;
LLVMContextImpl::LLVMContextImpl(LLVMContext &C)
: TheTrueVal(nullptr), TheFalseVal(nullptr),
VoidTy(C, Type::VoidTyID),
LabelTy(C, Type::LabelTyID),
HalfTy(C, Type::HalfTyID),
FloatTy(C, Type::FloatTyID),
DoubleTy(C, Type::DoubleTyID),
MetadataTy(C, Type::MetadataTyID),
X86_FP80Ty(C, Type::X86_FP80TyID),
FP128Ty(C, Type::FP128TyID),
PPC_FP128Ty(C, Type::PPC_FP128TyID),
X86_MMXTy(C, Type::X86_MMXTyID),
Int1Ty(C, 1),
Int8Ty(C, 8),
Int16Ty(C, 16),
Int32Ty(C, 32),
Int64Ty(C, 64),
Int128Ty(C, 128) {
InlineAsmDiagHandler = nullptr;
InlineAsmDiagContext = nullptr;
DiagnosticHandler = nullptr;
DiagnosticContext = nullptr;
RespectDiagnosticFilters = false;
YieldCallback = nullptr;
YieldOpaqueHandle = nullptr;
NamedStructTypesUniqueID = 0;
}
namespace {
struct DropReferences {
// Takes the value_type of a ConstantUniqueMap's internal map, whose 'second'
// is a Constant*.
template <typename PairT> void operator()(const PairT &P) {
P.second->dropAllReferences();
}
};
// Temporary - drops pair.first instead of second.
struct DropFirst {
// Takes the value_type of a ConstantUniqueMap's internal map, whose 'second'
// is a Constant*.
template<typename PairT>
void operator()(const PairT &P) {
P.first->dropAllReferences();
}
};
}
LLVMContextImpl::~LLVMContextImpl() {
// NOTE: We need to delete the contents of OwnedModules, but Module's dtor
// will call LLVMContextImpl::removeModule, thus invalidating iterators into
// the container. Avoid iterators during this operation:
while (!OwnedModules.empty())
delete *OwnedModules.begin();
// Drop references for MDNodes. Do this before Values get deleted to avoid
// unnecessary RAUW when nodes are still unresolved.
for (auto *I : DistinctMDNodes)
I->dropAllReferences();
#define HANDLE_MDNODE_LEAF(CLASS) \
for (auto *I : CLASS##s) \
I->dropAllReferences();
#include "llvm/IR/Metadata.def"
// Also drop references that come from the Value bridges.
for (auto &Pair : ValuesAsMetadata)
if (Pair.second) Pair.second->dropUsers(); // HLSL Change - if alloc failed, entry might not be populated
for (auto &Pair : MetadataAsValues)
if (Pair.second) Pair.second->dropUse(); // HLSL Change - if alloc failed, entry might not be populated
// Destroy MDNodes.
for (MDNode *I : DistinctMDNodes)
I->deleteAsSubclass();
#define HANDLE_MDNODE_LEAF(CLASS) \
for (CLASS *I : CLASS##s) \
delete I;
#include "llvm/IR/Metadata.def"
// Free the constants.
std::for_each(ExprConstants.map_begin(), ExprConstants.map_end(),
DropFirst());
std::for_each(ArrayConstants.map_begin(), ArrayConstants.map_end(),
DropFirst());
std::for_each(StructConstants.map_begin(), StructConstants.map_end(),
DropFirst());
std::for_each(VectorConstants.map_begin(), VectorConstants.map_end(),
DropFirst());
ExprConstants.freeConstants();
ArrayConstants.freeConstants();
StructConstants.freeConstants();
VectorConstants.freeConstants();
DeleteContainerSeconds(CAZConstants);
DeleteContainerSeconds(CPNConstants);
DeleteContainerSeconds(UVConstants);
InlineAsms.freeConstants();
DeleteContainerSeconds(IntConstants);
DeleteContainerSeconds(FPConstants);
for (StringMap<ConstantDataSequential*>::iterator I = CDSConstants.begin(),
E = CDSConstants.end(); I != E; ++I)
delete I->second;
CDSConstants.clear();
// Destroy attributes.
for (FoldingSetIterator<AttributeImpl> I = AttrsSet.begin(),
E = AttrsSet.end(); I != E; ) {
FoldingSetIterator<AttributeImpl> Elem = I++;
delete &*Elem;
}
// Destroy attribute lists.
for (FoldingSetIterator<AttributeSetImpl> I = AttrsLists.begin(),
E = AttrsLists.end(); I != E; ) {
FoldingSetIterator<AttributeSetImpl> Elem = I++;
delete &*Elem;
}
// Destroy attribute node lists.
for (FoldingSetIterator<AttributeSetNode> I = AttrsSetNodes.begin(),
E = AttrsSetNodes.end(); I != E; ) {
FoldingSetIterator<AttributeSetNode> Elem = I++;
delete &*Elem;
}
// Destroy MetadataAsValues.
{
SmallVector<MetadataAsValue *, 8> MDVs;
MDVs.reserve(MetadataAsValues.size());
for (auto &Pair : MetadataAsValues)
MDVs.push_back(Pair.second);
MetadataAsValues.clear();
for (auto *V : MDVs)
delete V;
}
// Destroy ValuesAsMetadata.
for (auto &Pair : ValuesAsMetadata)
delete Pair.second;
// Destroy MDStrings.
MDStringCache.clear();
}
void LLVMContextImpl::dropTriviallyDeadConstantArrays() {
bool Changed;
do {
Changed = false;
for (auto I = ArrayConstants.map_begin(), E = ArrayConstants.map_end();
I != E; ) {
auto *C = I->first;
I++;
if (C->use_empty()) {
Changed = true;
C->destroyConstant();
}
}
} while (Changed);
}
void Module::dropTriviallyDeadConstantArrays() {
Context.pImpl->dropTriviallyDeadConstantArrays();
}
namespace llvm {
/// \brief Make MDOperand transparent for hashing.
///
/// This overload of an implementation detail of the hashing library makes
/// MDOperand hash to the same value as a \a Metadata pointer.
///
/// Note that overloading \a hash_value() as follows:
///
/// \code
/// size_t hash_value(const MDOperand &X) { return hash_value(X.get()); }
/// \endcode
///
/// does not cause MDOperand to be transparent. In particular, a bare pointer
/// doesn't get hashed before it's combined, whereas \a MDOperand would.
static const Metadata *get_hashable_data(const MDOperand &X) { return X.get(); }
}
unsigned MDNodeOpsKey::calculateHash(MDNode *N, unsigned Offset) {
unsigned Hash = hash_combine_range(N->op_begin() + Offset, N->op_end());
#ifndef NDEBUG
{
SmallVector<Metadata *, 8> MDs(N->op_begin() + Offset, N->op_end());
unsigned RawHash = calculateHash(MDs);
assert(Hash == RawHash &&
"Expected hash of MDOperand to equal hash of Metadata*");
}
#endif
return Hash;
}
unsigned MDNodeOpsKey::calculateHash(ArrayRef<Metadata *> Ops) {
return hash_combine_range(Ops.begin(), Ops.end());
}
// ConstantsContext anchors
void UnaryConstantExpr::anchor() { }
void BinaryConstantExpr::anchor() { }
void SelectConstantExpr::anchor() { }
void ExtractElementConstantExpr::anchor() { }
void InsertElementConstantExpr::anchor() { }
void ShuffleVectorConstantExpr::anchor() { }
void ExtractValueConstantExpr::anchor() { }
void InsertValueConstantExpr::anchor() { }
void GetElementPtrConstantExpr::anchor() { }
void CompareConstantExpr::anchor() { }
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/CMakeLists.txt | add_llvm_library(LLVMCore
AsmWriter.cpp
Attributes.cpp
AutoUpgrade.cpp
BasicBlock.cpp
Comdat.cpp
ConstantFold.cpp
ConstantRange.cpp
Constants.cpp
Core.cpp
DIBuilder.cpp
DataLayout.cpp
DebugInfo.cpp
DebugInfoMetadata.cpp
DebugLoc.cpp
DiagnosticInfo.cpp
DiagnosticPrinter.cpp
Dominators.cpp
Function.cpp
GCOV.cpp
GVMaterializer.cpp
Globals.cpp
IRBuilder.cpp
IRPrintingPasses.cpp
InlineAsm.cpp
Instruction.cpp
Instructions.cpp
IntrinsicInst.cpp
LLVMContext.cpp
LLVMContextImpl.cpp
LegacyPassManager.cpp
MDBuilder.cpp
Mangler.cpp
Metadata.cpp
MetadataTracking.cpp
Module.cpp
Operator.cpp
Pass.cpp
PassManager.cpp
PassRegistry.cpp
Statepoint.cpp
Type.cpp
TypeFinder.cpp
Use.cpp
User.cpp
Value.cpp
ValueSymbolTable.cpp
ValueTypes.cpp
Verifier.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/IR
)
add_dependencies(LLVMCore intrinsics_gen)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/LLVMBuild.txt | ;===- ./lib/IR/LLVMBuild.txt -----------------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = Core
parent = Libraries
required_libraries = Support
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/DebugLoc.cpp | //===-- DebugLoc.cpp - Implement DebugLoc class ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DebugLoc.h"
#include "LLVMContextImpl.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/IR/DebugInfo.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// DebugLoc Implementation
//===----------------------------------------------------------------------===//
DebugLoc::DebugLoc(const DILocation *L) : Loc(const_cast<DILocation *>(L)) {}
DebugLoc::DebugLoc(const MDNode *L) : Loc(const_cast<MDNode *>(L)) {}
DILocation *DebugLoc::get() const {
return cast_or_null<DILocation>(Loc.get());
}
unsigned DebugLoc::getLine() const {
assert(get() && "Expected valid DebugLoc");
return get()->getLine();
}
unsigned DebugLoc::getCol() const {
assert(get() && "Expected valid DebugLoc");
return get()->getColumn();
}
MDNode *DebugLoc::getScope() const {
assert(get() && "Expected valid DebugLoc");
return get()->getScope();
}
DILocation *DebugLoc::getInlinedAt() const {
assert(get() && "Expected valid DebugLoc");
return get()->getInlinedAt();
}
MDNode *DebugLoc::getInlinedAtScope() const {
return cast<DILocation>(Loc)->getInlinedAtScope();
}
DebugLoc DebugLoc::getFnDebugLoc() const {
// FIXME: Add a method on \a DILocation that does this work.
const MDNode *Scope = getInlinedAtScope();
if (auto *SP = getDISubprogram(Scope))
return DebugLoc::get(SP->getScopeLine(), 0, SP);
return DebugLoc();
}
DebugLoc DebugLoc::get(unsigned Line, unsigned Col, const MDNode *Scope,
const MDNode *InlinedAt) {
// If no scope is available, this is an unknown location.
if (!Scope)
return DebugLoc();
return DILocation::get(Scope->getContext(), Line, Col,
const_cast<MDNode *>(Scope),
const_cast<MDNode *>(InlinedAt));
}
void DebugLoc::dump() const {
#ifndef NDEBUG
if (!Loc)
return;
dbgs() << getLine();
if (getCol() != 0)
dbgs() << ',' << getCol();
if (DebugLoc InlinedAtDL = DebugLoc(getInlinedAt())) {
dbgs() << " @ ";
InlinedAtDL.dump();
} else
dbgs() << "\n";
#endif
}
void DebugLoc::print(raw_ostream &OS) const {
if (!Loc)
return;
// Print source line info.
auto *Scope = cast<DIScope>(getScope());
OS << Scope->getFilename();
OS << ':' << getLine();
if (getCol() != 0)
OS << ':' << getCol();
if (DebugLoc InlinedAtDL = getInlinedAt()) {
OS << " @[ ";
InlinedAtDL.print(OS);
OS << " ]";
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/Type.cpp | //===-- Type.cpp - Implement the Type class -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Type class for the IR library.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Type.h"
#include "LLVMContextImpl.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/Module.h"
#include <algorithm>
#include <cstdarg>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Type Class Implementation
//===----------------------------------------------------------------------===//
Type *Type::getPrimitiveType(LLVMContext &C, TypeID IDNumber) {
switch (IDNumber) {
case VoidTyID : return getVoidTy(C);
case HalfTyID : return getHalfTy(C);
case FloatTyID : return getFloatTy(C);
case DoubleTyID : return getDoubleTy(C);
case X86_FP80TyID : return getX86_FP80Ty(C);
case FP128TyID : return getFP128Ty(C);
case PPC_FP128TyID : return getPPC_FP128Ty(C);
case LabelTyID : return getLabelTy(C);
case MetadataTyID : return getMetadataTy(C);
case X86_MMXTyID : return getX86_MMXTy(C);
default:
return nullptr;
}
}
/// getScalarType - If this is a vector type, return the element type,
/// otherwise return this.
Type *Type::getScalarType() {
if (VectorType *VTy = dyn_cast<VectorType>(this))
return VTy->getElementType();
return this;
}
const Type *Type::getScalarType() const {
if (const VectorType *VTy = dyn_cast<VectorType>(this))
return VTy->getElementType();
return this;
}
/// isIntegerTy - Return true if this is an IntegerType of the specified width.
bool Type::isIntegerTy(unsigned Bitwidth) const {
return isIntegerTy() && cast<IntegerType>(this)->getBitWidth() == Bitwidth;
}
// canLosslesslyBitCastTo - Return true if this type can be converted to
// 'Ty' without any reinterpretation of bits. For example, i8* to i32*.
//
bool Type::canLosslesslyBitCastTo(Type *Ty) const {
// Identity cast means no change so return true
if (this == Ty)
return true;
// They are not convertible unless they are at least first class types
if (!this->isFirstClassType() || !Ty->isFirstClassType())
return false;
// Vector -> Vector conversions are always lossless if the two vector types
// have the same size, otherwise not. Also, 64-bit vector types can be
// converted to x86mmx.
if (const VectorType *thisPTy = dyn_cast<VectorType>(this)) {
if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
return thisPTy->getBitWidth() == thatPTy->getBitWidth();
if (Ty->getTypeID() == Type::X86_MMXTyID &&
thisPTy->getBitWidth() == 64)
return true;
}
if (this->getTypeID() == Type::X86_MMXTyID)
if (const VectorType *thatPTy = dyn_cast<VectorType>(Ty))
if (thatPTy->getBitWidth() == 64)
return true;
// At this point we have only various mismatches of the first class types
// remaining and ptr->ptr. Just select the lossless conversions. Everything
// else is not lossless. Conservatively assume we can't losslessly convert
// between pointers with different address spaces.
if (const PointerType *PTy = dyn_cast<PointerType>(this)) {
if (const PointerType *OtherPTy = dyn_cast<PointerType>(Ty))
return PTy->getAddressSpace() == OtherPTy->getAddressSpace();
return false;
}
return false; // Other types have no identity values
}
bool Type::isEmptyTy() const {
const ArrayType *ATy = dyn_cast<ArrayType>(this);
if (ATy) {
unsigned NumElements = ATy->getNumElements();
return NumElements == 0 || ATy->getElementType()->isEmptyTy();
}
const StructType *STy = dyn_cast<StructType>(this);
if (STy) {
unsigned NumElements = STy->getNumElements();
for (unsigned i = 0; i < NumElements; ++i)
if (!STy->getElementType(i)->isEmptyTy())
return false;
return true;
}
return false;
}
unsigned Type::getPrimitiveSizeInBits() const {
switch (getTypeID()) {
case Type::HalfTyID: return 16;
case Type::FloatTyID: return 32;
case Type::DoubleTyID: return 64;
case Type::X86_FP80TyID: return 80;
case Type::FP128TyID: return 128;
case Type::PPC_FP128TyID: return 128;
case Type::X86_MMXTyID: return 64;
case Type::IntegerTyID: return cast<IntegerType>(this)->getBitWidth();
case Type::VectorTyID: return cast<VectorType>(this)->getBitWidth();
default: return 0;
}
}
/// getScalarSizeInBits - If this is a vector type, return the
/// getPrimitiveSizeInBits value for the element type. Otherwise return the
/// getPrimitiveSizeInBits value for this type.
unsigned Type::getScalarSizeInBits() const {
return getScalarType()->getPrimitiveSizeInBits();
}
/// getFPMantissaWidth - Return the width of the mantissa of this type. This
/// is only valid on floating point types. If the FP type does not
/// have a stable mantissa (e.g. ppc long double), this method returns -1.
int Type::getFPMantissaWidth() const {
if (const VectorType *VTy = dyn_cast<VectorType>(this))
return VTy->getElementType()->getFPMantissaWidth();
assert(isFloatingPointTy() && "Not a floating point type!");
if (getTypeID() == HalfTyID) return 11;
if (getTypeID() == FloatTyID) return 24;
if (getTypeID() == DoubleTyID) return 53;
if (getTypeID() == X86_FP80TyID) return 64;
if (getTypeID() == FP128TyID) return 113;
assert(getTypeID() == PPC_FP128TyID && "unknown fp type");
return -1;
}
/// isSizedDerivedType - Derived types like structures and arrays are sized
/// iff all of the members of the type are sized as well. Since asking for
/// their size is relatively uncommon, move this operation out of line.
bool Type::isSizedDerivedType(SmallPtrSetImpl<const Type*> *Visited) const {
if (const ArrayType *ATy = dyn_cast<ArrayType>(this))
return ATy->getElementType()->isSized(Visited);
if (const VectorType *VTy = dyn_cast<VectorType>(this))
return VTy->getElementType()->isSized(Visited);
return cast<StructType>(this)->isSized(Visited);
}
//===----------------------------------------------------------------------===//
// Subclass Helper Methods
//===----------------------------------------------------------------------===//
unsigned Type::getIntegerBitWidth() const {
return cast<IntegerType>(this)->getBitWidth();
}
bool Type::isFunctionVarArg() const {
return cast<FunctionType>(this)->isVarArg();
}
Type *Type::getFunctionParamType(unsigned i) const {
return cast<FunctionType>(this)->getParamType(i);
}
unsigned Type::getFunctionNumParams() const {
return cast<FunctionType>(this)->getNumParams();
}
StringRef Type::getStructName() const {
return cast<StructType>(this)->getName();
}
unsigned Type::getStructNumElements() const {
return cast<StructType>(this)->getNumElements();
}
Type *Type::getStructElementType(unsigned N) const {
return cast<StructType>(this)->getElementType(N);
}
Type *Type::getSequentialElementType() const {
return cast<SequentialType>(this)->getElementType();
}
uint64_t Type::getArrayNumElements() const {
return cast<ArrayType>(this)->getNumElements();
}
unsigned Type::getVectorNumElements() const {
return cast<VectorType>(this)->getNumElements();
}
unsigned Type::getPointerAddressSpace() const {
return cast<PointerType>(getScalarType())->getAddressSpace();
}
//===----------------------------------------------------------------------===//
// Primitive 'Type' data
//===----------------------------------------------------------------------===//
Type *Type::getVoidTy(LLVMContext &C) { return &C.pImpl->VoidTy; }
Type *Type::getLabelTy(LLVMContext &C) { return &C.pImpl->LabelTy; }
Type *Type::getHalfTy(LLVMContext &C) { return &C.pImpl->HalfTy; }
Type *Type::getFloatTy(LLVMContext &C) { return &C.pImpl->FloatTy; }
Type *Type::getDoubleTy(LLVMContext &C) { return &C.pImpl->DoubleTy; }
Type *Type::getMetadataTy(LLVMContext &C) { return &C.pImpl->MetadataTy; }
Type *Type::getX86_FP80Ty(LLVMContext &C) { return &C.pImpl->X86_FP80Ty; }
Type *Type::getFP128Ty(LLVMContext &C) { return &C.pImpl->FP128Ty; }
Type *Type::getPPC_FP128Ty(LLVMContext &C) { return &C.pImpl->PPC_FP128Ty; }
Type *Type::getX86_MMXTy(LLVMContext &C) { return &C.pImpl->X86_MMXTy; }
IntegerType *Type::getInt1Ty(LLVMContext &C) { return &C.pImpl->Int1Ty; }
IntegerType *Type::getInt8Ty(LLVMContext &C) { return &C.pImpl->Int8Ty; }
IntegerType *Type::getInt16Ty(LLVMContext &C) { return &C.pImpl->Int16Ty; }
IntegerType *Type::getInt32Ty(LLVMContext &C) { return &C.pImpl->Int32Ty; }
IntegerType *Type::getInt64Ty(LLVMContext &C) { return &C.pImpl->Int64Ty; }
IntegerType *Type::getInt128Ty(LLVMContext &C) { return &C.pImpl->Int128Ty; }
IntegerType *Type::getIntNTy(LLVMContext &C, unsigned N) {
return IntegerType::get(C, N);
}
PointerType *Type::getHalfPtrTy(LLVMContext &C, unsigned AS) {
return getHalfTy(C)->getPointerTo(AS);
}
PointerType *Type::getFloatPtrTy(LLVMContext &C, unsigned AS) {
return getFloatTy(C)->getPointerTo(AS);
}
PointerType *Type::getDoublePtrTy(LLVMContext &C, unsigned AS) {
return getDoubleTy(C)->getPointerTo(AS);
}
PointerType *Type::getX86_FP80PtrTy(LLVMContext &C, unsigned AS) {
return getX86_FP80Ty(C)->getPointerTo(AS);
}
PointerType *Type::getFP128PtrTy(LLVMContext &C, unsigned AS) {
return getFP128Ty(C)->getPointerTo(AS);
}
PointerType *Type::getPPC_FP128PtrTy(LLVMContext &C, unsigned AS) {
return getPPC_FP128Ty(C)->getPointerTo(AS);
}
PointerType *Type::getX86_MMXPtrTy(LLVMContext &C, unsigned AS) {
return getX86_MMXTy(C)->getPointerTo(AS);
}
PointerType *Type::getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS) {
return getIntNTy(C, N)->getPointerTo(AS);
}
PointerType *Type::getInt1PtrTy(LLVMContext &C, unsigned AS) {
return getInt1Ty(C)->getPointerTo(AS);
}
PointerType *Type::getInt8PtrTy(LLVMContext &C, unsigned AS) {
return getInt8Ty(C)->getPointerTo(AS);
}
PointerType *Type::getInt16PtrTy(LLVMContext &C, unsigned AS) {
return getInt16Ty(C)->getPointerTo(AS);
}
PointerType *Type::getInt32PtrTy(LLVMContext &C, unsigned AS) {
return getInt32Ty(C)->getPointerTo(AS);
}
PointerType *Type::getInt64PtrTy(LLVMContext &C, unsigned AS) {
return getInt64Ty(C)->getPointerTo(AS);
}
//===----------------------------------------------------------------------===//
// IntegerType Implementation
//===----------------------------------------------------------------------===//
IntegerType *IntegerType::get(LLVMContext &C, unsigned NumBits) {
assert(NumBits >= MIN_INT_BITS && "bitwidth too small");
assert(NumBits <= MAX_INT_BITS && "bitwidth too large");
// Check for the built-in integer types
switch (NumBits) {
case 1: return cast<IntegerType>(Type::getInt1Ty(C));
case 8: return cast<IntegerType>(Type::getInt8Ty(C));
case 16: return cast<IntegerType>(Type::getInt16Ty(C));
case 32: return cast<IntegerType>(Type::getInt32Ty(C));
case 64: return cast<IntegerType>(Type::getInt64Ty(C));
case 128: return cast<IntegerType>(Type::getInt128Ty(C));
default:
break;
}
IntegerType *&Entry = C.pImpl->IntegerTypes[NumBits];
if (!Entry)
Entry = new (C.pImpl->TypeAllocator) IntegerType(C, NumBits);
return Entry;
}
bool IntegerType::isPowerOf2ByteWidth() const {
unsigned BitWidth = getBitWidth();
return (BitWidth > 7) && isPowerOf2_32(BitWidth);
}
APInt IntegerType::getMask() const {
return APInt::getAllOnesValue(getBitWidth());
}
//===----------------------------------------------------------------------===//
// FunctionType Implementation
//===----------------------------------------------------------------------===//
FunctionType::FunctionType(Type *Result, ArrayRef<Type*> Params,
bool IsVarArgs)
: Type(Result->getContext(), FunctionTyID) {
Type **SubTys = reinterpret_cast<Type**>(this+1);
assert(isValidReturnType(Result) && "invalid return type for function");
setSubclassData(IsVarArgs);
SubTys[0] = const_cast<Type*>(Result);
for (unsigned i = 0, e = Params.size(); i != e; ++i) {
assert(isValidArgumentType(Params[i]) &&
"Not a valid type for function argument!");
SubTys[i+1] = Params[i];
}
ContainedTys = SubTys;
NumContainedTys = Params.size() + 1; // + 1 for result type
}
// FunctionType::get - The factory function for the FunctionType class.
FunctionType *FunctionType::get(Type *ReturnType,
ArrayRef<Type*> Params, bool isVarArg) {
LLVMContextImpl *pImpl = ReturnType->getContext().pImpl;
FunctionTypeKeyInfo::KeyTy Key(ReturnType, Params, isVarArg);
auto I = pImpl->FunctionTypes.find_as(Key);
FunctionType *FT;
if (I == pImpl->FunctionTypes.end()) {
FT = (FunctionType*) pImpl->TypeAllocator.
Allocate(sizeof(FunctionType) + sizeof(Type*) * (Params.size() + 1),
AlignOf<FunctionType>::Alignment);
new (FT) FunctionType(ReturnType, Params, isVarArg);
pImpl->FunctionTypes.insert(FT);
} else {
FT = *I;
}
return FT;
}
FunctionType *FunctionType::get(Type *Result, bool isVarArg) {
return get(Result, None, isVarArg);
}
/// isValidReturnType - Return true if the specified type is valid as a return
/// type.
bool FunctionType::isValidReturnType(Type *RetTy) {
return !RetTy->isFunctionTy() && !RetTy->isLabelTy() &&
!RetTy->isMetadataTy();
}
/// isValidArgumentType - Return true if the specified type is valid as an
/// argument type.
bool FunctionType::isValidArgumentType(Type *ArgTy) {
return ArgTy->isFirstClassType();
}
//===----------------------------------------------------------------------===//
// StructType Implementation
//===----------------------------------------------------------------------===//
// Primitive Constructors.
StructType *StructType::get(LLVMContext &Context, ArrayRef<Type*> ETypes,
bool isPacked) {
LLVMContextImpl *pImpl = Context.pImpl;
AnonStructTypeKeyInfo::KeyTy Key(ETypes, isPacked);
auto I = pImpl->AnonStructTypes.find_as(Key);
StructType *ST;
if (I == pImpl->AnonStructTypes.end()) {
// Value not found. Create a new type!
ST = new (Context.pImpl->TypeAllocator) StructType(Context);
ST->setSubclassData(SCDB_IsLiteral); // Literal struct.
ST->setBody(ETypes, isPacked);
Context.pImpl->AnonStructTypes.insert(ST);
} else {
ST = *I;
}
return ST;
}
void StructType::setBody(ArrayRef<Type*> Elements, bool isPacked) {
assert(isOpaque() && "Struct body already set!");
setSubclassData(getSubclassData() | SCDB_HasBody);
if (isPacked)
setSubclassData(getSubclassData() | SCDB_Packed);
unsigned NumElements = Elements.size();
Type **Elts = getContext().pImpl->TypeAllocator.Allocate<Type*>(NumElements);
memcpy(Elts, Elements.data(), sizeof(Elements[0]) * NumElements);
ContainedTys = Elts;
NumContainedTys = NumElements;
}
void StructType::setName(StringRef Name) {
if (Name == getName()) return;
StringMap<StructType *> &SymbolTable = getContext().pImpl->NamedStructTypes;
typedef StringMap<StructType *>::MapEntryTy EntryTy;
// If this struct already had a name, remove its symbol table entry. Don't
// delete the data yet because it may be part of the new name.
if (SymbolTableEntry)
SymbolTable.remove((EntryTy *)SymbolTableEntry);
// If this is just removing the name, we're done.
if (Name.empty()) {
if (SymbolTableEntry) {
// Delete the old string data.
((EntryTy *)SymbolTableEntry)->Destroy(SymbolTable.getAllocator());
SymbolTableEntry = nullptr;
}
return;
}
// Look up the entry for the name.
auto IterBool =
getContext().pImpl->NamedStructTypes.insert(std::make_pair(Name, this));
// While we have a name collision, try a random rename.
if (!IterBool.second) {
SmallString<64> TempStr(Name);
TempStr.push_back('.');
raw_svector_ostream TmpStream(TempStr);
unsigned NameSize = Name.size();
do {
TempStr.resize(NameSize + 1);
TmpStream.resync();
TmpStream << getContext().pImpl->NamedStructTypesUniqueID++;
IterBool = getContext().pImpl->NamedStructTypes.insert(
std::make_pair(TmpStream.str(), this));
} while (!IterBool.second);
}
// Delete the old string data.
if (SymbolTableEntry)
((EntryTy *)SymbolTableEntry)->Destroy(SymbolTable.getAllocator());
SymbolTableEntry = &*IterBool.first;
}
//===----------------------------------------------------------------------===//
// StructType Helper functions.
StructType *StructType::create(LLVMContext &Context, StringRef Name) {
StructType *ST = new (Context.pImpl->TypeAllocator) StructType(Context);
if (!Name.empty())
ST->setName(Name);
return ST;
}
StructType *StructType::get(LLVMContext &Context, bool isPacked) {
return get(Context, None, isPacked);
}
StructType *StructType::get(Type *type, ...) {
assert(type && "Cannot create a struct type with no elements with this");
LLVMContext &Ctx = type->getContext();
va_list ap;
SmallVector<llvm::Type*, 8> StructFields;
va_start(ap, type);
while (type) {
StructFields.push_back(type);
type = va_arg(ap, llvm::Type*);
}
auto *Ret = llvm::StructType::get(Ctx, StructFields);
va_end(ap);
return Ret;
}
StructType *StructType::create(LLVMContext &Context, ArrayRef<Type*> Elements,
StringRef Name, bool isPacked) {
StructType *ST = create(Context, Name);
ST->setBody(Elements, isPacked);
return ST;
}
StructType *StructType::create(LLVMContext &Context, ArrayRef<Type*> Elements) {
return create(Context, Elements, StringRef());
}
StructType *StructType::create(LLVMContext &Context) {
return create(Context, StringRef());
}
StructType *StructType::create(ArrayRef<Type*> Elements, StringRef Name,
bool isPacked) {
assert(!Elements.empty() &&
"This method may not be invoked with an empty list");
return create(Elements[0]->getContext(), Elements, Name, isPacked);
}
StructType *StructType::create(ArrayRef<Type*> Elements) {
assert(!Elements.empty() &&
"This method may not be invoked with an empty list");
return create(Elements[0]->getContext(), Elements, StringRef());
}
StructType *StructType::create(StringRef Name, Type *type, ...) {
assert(type && "Cannot create a struct type with no elements with this");
LLVMContext &Ctx = type->getContext();
va_list ap;
SmallVector<llvm::Type*, 8> StructFields;
va_start(ap, type);
while (type) {
StructFields.push_back(type);
type = va_arg(ap, llvm::Type*);
}
auto *Ret = llvm::StructType::create(Ctx, StructFields, Name);
va_end(ap);
return Ret;
}
bool StructType::isSized(SmallPtrSetImpl<const Type*> *Visited) const {
if ((getSubclassData() & SCDB_IsSized) != 0)
return true;
if (isOpaque())
return false;
if (Visited && !Visited->insert(this).second)
return false;
// Okay, our struct is sized if all of the elements are, but if one of the
// elements is opaque, the struct isn't sized *yet*, but may become sized in
// the future, so just bail out without caching.
for (element_iterator I = element_begin(), E = element_end(); I != E; ++I)
if (!(*I)->isSized(Visited))
return false;
// Here we cheat a bit and cast away const-ness. The goal is to memoize when
// we find a sized type, as types can only move from opaque to sized, not the
// other way.
const_cast<StructType*>(this)->setSubclassData(
getSubclassData() | SCDB_IsSized);
return true;
}
StringRef StructType::getName() const {
assert(!isLiteral() && "Literal structs never have names");
if (!SymbolTableEntry) return StringRef();
return ((StringMapEntry<StructType*> *)SymbolTableEntry)->getKey();
}
void StructType::setBody(Type *type, ...) {
assert(type && "Cannot create a struct type with no elements with this");
va_list ap;
SmallVector<llvm::Type*, 8> StructFields;
va_start(ap, type);
while (type) {
StructFields.push_back(type);
type = va_arg(ap, llvm::Type*);
}
setBody(StructFields);
va_end(ap);
}
bool StructType::isValidElementType(Type *ElemTy) {
return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
!ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
}
/// isLayoutIdentical - Return true if this is layout identical to the
/// specified struct.
bool StructType::isLayoutIdentical(StructType *Other) const {
if (this == Other) return true;
if (isPacked() != Other->isPacked() ||
getNumElements() != Other->getNumElements())
return false;
if (!getNumElements())
return true;
return std::equal(element_begin(), element_end(), Other->element_begin());
}
/// getTypeByName - Return the type with the specified name, or null if there
/// is none by that name.
StructType *Module::getTypeByName(StringRef Name) const {
return getContext().pImpl->NamedStructTypes.lookup(Name);
}
//===----------------------------------------------------------------------===//
// CompositeType Implementation
//===----------------------------------------------------------------------===//
Type *CompositeType::getTypeAtIndex(const Value *V) {
if (StructType *STy = dyn_cast<StructType>(this)) {
unsigned Idx =
(unsigned)cast<Constant>(V)->getUniqueInteger().getZExtValue();
assert(indexValid(Idx) && "Invalid structure index!");
return STy->getElementType(Idx);
}
return cast<SequentialType>(this)->getElementType();
}
Type *CompositeType::getTypeAtIndex(unsigned Idx) {
if (StructType *STy = dyn_cast<StructType>(this)) {
assert(indexValid(Idx) && "Invalid structure index!");
return STy->getElementType(Idx);
}
return cast<SequentialType>(this)->getElementType();
}
bool CompositeType::indexValid(const Value *V) const {
if (const StructType *STy = dyn_cast<StructType>(this)) {
// Structure indexes require (vectors of) 32-bit integer constants. In the
// vector case all of the indices must be equal.
if (!V->getType()->getScalarType()->isIntegerTy(32))
return false;
const Constant *C = dyn_cast<Constant>(V);
if (C && V->getType()->isVectorTy())
C = C->getSplatValue();
const ConstantInt *CU = dyn_cast_or_null<ConstantInt>(C);
return CU && CU->getZExtValue() < STy->getNumElements();
}
// Sequential types can be indexed by any integer.
return V->getType()->isIntOrIntVectorTy();
}
bool CompositeType::indexValid(unsigned Idx) const {
if (const StructType *STy = dyn_cast<StructType>(this))
return Idx < STy->getNumElements();
// Sequential types can be indexed by any integer.
return true;
}
//===----------------------------------------------------------------------===//
// ArrayType Implementation
//===----------------------------------------------------------------------===//
ArrayType::ArrayType(Type *ElType, uint64_t NumEl)
: SequentialType(ArrayTyID, ElType) {
NumElements = NumEl;
}
ArrayType *ArrayType::get(Type *elementType, uint64_t NumElements) {
Type *ElementType = const_cast<Type*>(elementType);
assert(isValidElementType(ElementType) && "Invalid type for array element!");
LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
ArrayType *&Entry =
pImpl->ArrayTypes[std::make_pair(ElementType, NumElements)];
if (!Entry)
Entry = new (pImpl->TypeAllocator) ArrayType(ElementType, NumElements);
return Entry;
}
bool ArrayType::isValidElementType(Type *ElemTy) {
return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
!ElemTy->isMetadataTy() && !ElemTy->isFunctionTy();
}
//===----------------------------------------------------------------------===//
// VectorType Implementation
//===----------------------------------------------------------------------===//
VectorType::VectorType(Type *ElType, unsigned NumEl)
: SequentialType(VectorTyID, ElType) {
NumElements = NumEl;
}
VectorType *VectorType::get(Type *elementType, unsigned NumElements) {
Type *ElementType = const_cast<Type*>(elementType);
assert(NumElements > 0 && "#Elements of a VectorType must be greater than 0");
assert(isValidElementType(ElementType) && "Element type of a VectorType must "
"be an integer, floating point, or "
"pointer type.");
LLVMContextImpl *pImpl = ElementType->getContext().pImpl;
VectorType *&Entry = ElementType->getContext().pImpl
->VectorTypes[std::make_pair(ElementType, NumElements)];
if (!Entry)
Entry = new (pImpl->TypeAllocator) VectorType(ElementType, NumElements);
return Entry;
}
bool VectorType::isValidElementType(Type *ElemTy) {
return ElemTy->isIntegerTy() || ElemTy->isFloatingPointTy() ||
ElemTy->isPointerTy();
}
//===----------------------------------------------------------------------===//
// PointerType Implementation
//===----------------------------------------------------------------------===//
PointerType *PointerType::get(Type *EltTy, unsigned AddressSpace) {
assert(EltTy && "Can't get a pointer to <null> type!");
assert(isValidElementType(EltTy) && "Invalid type for pointer element!");
LLVMContextImpl *CImpl = EltTy->getContext().pImpl;
// Since AddressSpace #0 is the common case, we special case it.
PointerType *&Entry = AddressSpace == 0 ? CImpl->PointerTypes[EltTy]
: CImpl->ASPointerTypes[std::make_pair(EltTy, AddressSpace)];
if (!Entry)
Entry = new (CImpl->TypeAllocator) PointerType(EltTy, AddressSpace);
return Entry;
}
PointerType::PointerType(Type *E, unsigned AddrSpace)
: SequentialType(PointerTyID, E) {
#ifndef NDEBUG
const unsigned oldNCT = NumContainedTys;
#endif
setSubclassData(AddrSpace);
// Check for miscompile. PR11652.
assert(oldNCT == NumContainedTys && "bitfield written out of bounds?");
}
PointerType *Type::getPointerTo(unsigned addrs) {
return PointerType::get(this, addrs);
}
bool PointerType::isValidElementType(Type *ElemTy) {
return !ElemTy->isVoidTy() && !ElemTy->isLabelTy() &&
!ElemTy->isMetadataTy();
}
bool PointerType::isLoadableOrStorableType(Type *ElemTy) {
return isValidElementType(ElemTy) && !ElemTy->isFunctionTy();
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/DebugInfoMetadata.cpp | //===- DebugInfoMetadata.cpp - Implement debug info metadata --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the debug info Metadata classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/DebugInfoMetadata.h"
#include "LLVMContextImpl.h"
#include "MetadataImpl.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/IR/Function.h"
using namespace llvm;
DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
unsigned Column, ArrayRef<Metadata *> MDs)
: MDNode(C, DILocationKind, Storage, MDs) {
assert((MDs.size() == 1 || MDs.size() == 2) &&
"Expected a scope and optional inlined-at");
// Set line and column.
assert(Column < (1u << 16) && "Expected 16-bit column");
SubclassData32 = Line;
SubclassData16 = Column;
}
static void adjustColumn(unsigned &Column) {
// Set to unknown on overflow. We only have 16 bits to play with here.
if (Column >= (1u << 16))
Column = 0;
}
DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
unsigned Column, Metadata *Scope,
Metadata *InlinedAt, StorageType Storage,
bool ShouldCreate) {
// Fixup column.
adjustColumn(Column);
assert(Scope && "Expected scope");
if (Storage == Uniqued) {
if (auto *N =
getUniqued(Context.pImpl->DILocations,
DILocationInfo::KeyTy(Line, Column, Scope, InlinedAt)))
return N;
if (!ShouldCreate)
return nullptr;
} else {
assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
}
SmallVector<Metadata *, 2> Ops;
Ops.push_back(Scope);
if (InlinedAt)
Ops.push_back(InlinedAt);
return storeImpl(new (Ops.size())
DILocation(Context, Storage, Line, Column, Ops),
Storage, Context.pImpl->DILocations);
}
unsigned DILocation::computeNewDiscriminator() const {
// FIXME: This seems completely wrong.
//
// 1. If two modules are generated in the same context, then the second
// Module will get different discriminators than it would have if it were
// generated in its own context.
// 2. If this function is called after round-tripping to bitcode instead of
// before, it will give a different (and potentially incorrect!) return.
//
// The discriminator should instead be calculated from local information
// where it's actually needed. This logic should be moved to
// AddDiscriminators::runOnFunction(), where it doesn't pollute the
// LLVMContext.
std::pair<const char *, unsigned> Key(getFilename().data(), getLine());
return ++getContext().pImpl->DiscriminatorTable[Key];
}
unsigned DINode::getFlag(StringRef Flag) {
return StringSwitch<unsigned>(Flag)
#define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
#include "llvm/IR/DebugInfoFlags.def"
.Default(0);
}
const char *DINode::getFlagString(unsigned Flag) {
switch (Flag) {
default:
return "";
#define HANDLE_DI_FLAG(ID, NAME) \
case Flag##NAME: \
return "DIFlag" #NAME;
#include "llvm/IR/DebugInfoFlags.def"
}
}
unsigned DINode::splitFlags(unsigned Flags,
SmallVectorImpl<unsigned> &SplitFlags) {
// Accessibility flags need to be specially handled, since they're packed
// together.
if (unsigned A = Flags & FlagAccessibility) {
if (A == FlagPrivate)
SplitFlags.push_back(FlagPrivate);
else if (A == FlagProtected)
SplitFlags.push_back(FlagProtected);
else
SplitFlags.push_back(FlagPublic);
Flags &= ~A;
}
#define HANDLE_DI_FLAG(ID, NAME) \
if (unsigned Bit = Flags & ID) { \
SplitFlags.push_back(Bit); \
Flags &= ~Bit; \
}
#include "llvm/IR/DebugInfoFlags.def"
return Flags;
}
DIScopeRef DIScope::getScope() const {
if (auto *T = dyn_cast<DIType>(this))
return T->getScope();
if (auto *SP = dyn_cast<DISubprogram>(this))
return SP->getScope();
if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
return DIScopeRef(LB->getScope());
if (auto *NS = dyn_cast<DINamespace>(this))
return DIScopeRef(NS->getScope());
if (auto *M = dyn_cast<DIModule>(this))
return DIScopeRef(M->getScope());
assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
"Unhandled type of scope.");
return nullptr;
}
StringRef DIScope::getName() const {
if (auto *T = dyn_cast<DIType>(this))
return T->getName();
if (auto *SP = dyn_cast<DISubprogram>(this))
return SP->getName();
if (auto *NS = dyn_cast<DINamespace>(this))
return NS->getName();
if (auto *M = dyn_cast<DIModule>(this))
return M->getName();
assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
isa<DICompileUnit>(this)) &&
"Unhandled type of scope.");
return "";
}
static StringRef getString(const MDString *S) {
if (S)
return S->getString();
return StringRef();
}
#ifndef NDEBUG
static bool isCanonical(const MDString *S) {
return !S || !S->getString().empty();
}
#endif
GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
MDString *Header,
ArrayRef<Metadata *> DwarfOps,
StorageType Storage, bool ShouldCreate) {
unsigned Hash = 0;
if (Storage == Uniqued) {
GenericDINodeInfo::KeyTy Key(Tag, getString(Header), DwarfOps);
if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
return N;
if (!ShouldCreate)
return nullptr;
Hash = Key.getHash();
} else {
assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
}
// Use a nullptr for empty headers.
assert(isCanonical(Header) && "Expected canonical MDString");
Metadata *PreOps[] = {Header};
return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
Context, Storage, Hash, Tag, PreOps, DwarfOps),
Storage, Context.pImpl->GenericDINodes);
}
void GenericDINode::recalculateHash() {
setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
}
#define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
#define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
#define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS) \
do { \
if (Storage == Uniqued) { \
if (auto *N = getUniqued(Context.pImpl->CLASS##s, \
CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS)))) \
return N; \
if (!ShouldCreate) \
return nullptr; \
} else { \
assert(ShouldCreate && \
"Expected non-uniqued nodes to always be created"); \
} \
} while (false)
#define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS) \
return storeImpl(new (ArrayRef<Metadata *>(OPS).size()) \
CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \
Storage, Context.pImpl->CLASS##s)
#define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS) \
return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)), \
Storage, Context.pImpl->CLASS##s)
#define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS) \
return storeImpl(new (ArrayRef<Metadata *>(OPS).size()) \
CLASS(Context, Storage, OPS), \
Storage, Context.pImpl->CLASS##s)
DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
StorageType Storage, bool ShouldCreate) {
DEFINE_GETIMPL_LOOKUP(DISubrange, (Count, Lo));
DEFINE_GETIMPL_STORE_NO_OPS(DISubrange, (Count, Lo));
}
DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, int64_t Value,
MDString *Name, StorageType Storage,
bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, getString(Name)));
Metadata *Ops[] = {Name};
DEFINE_GETIMPL_STORE(DIEnumerator, (Value), Ops);
}
DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
MDString *Name, uint64_t SizeInBits,
uint64_t AlignInBits, unsigned Encoding,
StorageType Storage, bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(
DIBasicType, (Tag, getString(Name), SizeInBits, AlignInBits, Encoding));
Metadata *Ops[] = {nullptr, nullptr, Name};
DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding),
Ops);
}
DIDerivedType *DIDerivedType::getImpl(
LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
Metadata *ExtraData, StorageType Storage, bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DIDerivedType, (Tag, getString(Name), File, Line, Scope,
BaseType, SizeInBits, AlignInBits,
OffsetInBits, Flags, ExtraData));
Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData};
DEFINE_GETIMPL_STORE(
DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits, Flags),
Ops);
}
DICompositeType *DICompositeType::getImpl(
LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
Metadata *TemplateParams, MDString *Identifier, StorageType Storage,
bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DICompositeType,
(Tag, getString(Name), File, Line, Scope, BaseType,
SizeInBits, AlignInBits, OffsetInBits, Flags, Elements,
RuntimeLang, VTableHolder, TemplateParams,
getString(Identifier)));
Metadata *Ops[] = {File, Scope, Name, BaseType,
Elements, VTableHolder, TemplateParams, Identifier};
DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
AlignInBits, OffsetInBits, Flags),
Ops);
}
DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context,
unsigned Flags, Metadata *TypeArray,
StorageType Storage,
bool ShouldCreate) {
DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, TypeArray));
Metadata *Ops[] = {nullptr, nullptr, nullptr, nullptr,
TypeArray, nullptr, nullptr, nullptr};
DEFINE_GETIMPL_STORE(DISubroutineType, (Flags), Ops);
}
DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
MDString *Directory, StorageType Storage,
bool ShouldCreate) {
assert(isCanonical(Filename) && "Expected canonical MDString");
assert(isCanonical(Directory) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DIFile, (getString(Filename), getString(Directory)));
Metadata *Ops[] = {Filename, Directory};
DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIFile, Ops);
}
DICompileUnit *DICompileUnit::getImpl(
LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
MDString *Producer, bool IsOptimized, MDString *Flags,
unsigned RuntimeVersion, MDString *SplitDebugFilename,
unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
Metadata *Subprograms, Metadata *GlobalVariables,
Metadata *ImportedEntities, uint64_t DWOId,
StorageType Storage, bool ShouldCreate) {
assert(isCanonical(Producer) && "Expected canonical MDString");
assert(isCanonical(Flags) && "Expected canonical MDString");
assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(
DICompileUnit,
(SourceLanguage, File, getString(Producer), IsOptimized, getString(Flags),
RuntimeVersion, getString(SplitDebugFilename), EmissionKind, EnumTypes,
RetainedTypes, Subprograms, GlobalVariables, ImportedEntities, DWOId));
Metadata *Ops[] = {File, Producer, Flags, SplitDebugFilename, EnumTypes,
RetainedTypes, Subprograms, GlobalVariables,
ImportedEntities};
DEFINE_GETIMPL_STORE(
DICompileUnit,
(SourceLanguage, IsOptimized, RuntimeVersion, EmissionKind, DWOId), Ops);
}
DISubprogram *DILocalScope::getSubprogram() const {
if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
return Block->getScope()->getSubprogram();
return const_cast<DISubprogram *>(cast<DISubprogram>(this));
}
DISubprogram *DISubprogram::getImpl(
LLVMContext &Context, Metadata *Scope, MDString *Name,
MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
unsigned Flags, bool IsOptimized, Metadata *Function,
Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
StorageType Storage, bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
assert(isCanonical(LinkageName) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DISubprogram,
(Scope, getString(Name), getString(LinkageName), File,
Line, Type, IsLocalToUnit, IsDefinition, ScopeLine,
ContainingType, Virtuality, VirtualIndex, Flags,
IsOptimized, Function, TemplateParams, Declaration,
Variables));
Metadata *Ops[] = {File, Scope, Name, Name,
LinkageName, Type, ContainingType, Function,
TemplateParams, Declaration, Variables};
DEFINE_GETIMPL_STORE(DISubprogram,
(Line, ScopeLine, Virtuality, VirtualIndex, Flags,
IsLocalToUnit, IsDefinition, IsOptimized),
Ops);
}
Function *DISubprogram::getFunction() const {
// FIXME: Should this be looking through bitcasts?
return dyn_cast_or_null<Function>(getFunctionConstant());
}
bool DISubprogram::describes(const Function *F) const {
assert(F && "Invalid function");
if (F == getFunction())
return true;
StringRef Name = getLinkageName();
if (Name.empty())
Name = getName();
return F->getName() == Name;
}
void DISubprogram::replaceFunction(Function *F) {
replaceFunction(F ? ConstantAsMetadata::get(F)
: static_cast<ConstantAsMetadata *>(nullptr));
}
DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
Metadata *File, unsigned Line,
unsigned Column, StorageType Storage,
bool ShouldCreate) {
assert(Scope && "Expected scope");
DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
Metadata *Ops[] = {File, Scope};
DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
}
DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
Metadata *Scope, Metadata *File,
unsigned Discriminator,
StorageType Storage,
bool ShouldCreate) {
assert(Scope && "Expected scope");
DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
Metadata *Ops[] = {File, Scope};
DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
}
DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
Metadata *File, MDString *Name, unsigned Line,
StorageType Storage, bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, File, getString(Name), Line));
Metadata *Ops[] = {File, Scope, Name};
DEFINE_GETIMPL_STORE(DINamespace, (Line), Ops);
}
DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *Scope,
MDString *Name, MDString *ConfigurationMacros,
MDString *IncludePath, MDString *ISysRoot,
StorageType Storage, bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DIModule,
(Scope, getString(Name), getString(ConfigurationMacros),
getString(IncludePath), getString(ISysRoot)));
Metadata *Ops[] = {Scope, Name, ConfigurationMacros, IncludePath, ISysRoot};
DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIModule, Ops);
}
DITemplateTypeParameter *DITemplateTypeParameter::getImpl(LLVMContext &Context,
MDString *Name,
Metadata *Type,
StorageType Storage,
bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (getString(Name), Type));
Metadata *Ops[] = {Name, Type};
DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DITemplateTypeParameter, Ops);
}
DITemplateValueParameter *DITemplateValueParameter::getImpl(
LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
Metadata *Value, StorageType Storage, bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
(Tag, getString(Name), Type, Value));
Metadata *Ops[] = {Name, Type, Value};
DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag), Ops);
}
DIGlobalVariable *
DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
MDString *LinkageName, Metadata *File, unsigned Line,
Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
Metadata *Variable,
Metadata *StaticDataMemberDeclaration,
StorageType Storage, bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
assert(isCanonical(LinkageName) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DIGlobalVariable,
(Scope, getString(Name), getString(LinkageName), File,
Line, Type, IsLocalToUnit, IsDefinition, Variable,
StaticDataMemberDeclaration));
Metadata *Ops[] = {Scope, Name, File, Type,
Name, LinkageName, Variable, StaticDataMemberDeclaration};
DEFINE_GETIMPL_STORE(DIGlobalVariable, (Line, IsLocalToUnit, IsDefinition),
Ops);
}
DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, unsigned Tag,
Metadata *Scope, MDString *Name,
Metadata *File, unsigned Line,
Metadata *Type, unsigned Arg,
unsigned Flags, StorageType Storage,
bool ShouldCreate) {
// 64K ought to be enough for any frontend.
assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
assert(Scope && "Expected scope");
assert(isCanonical(Name) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DILocalVariable, (Tag, Scope, getString(Name), File,
Line, Type, Arg, Flags));
Metadata *Ops[] = {Scope, Name, File, Type};
DEFINE_GETIMPL_STORE(DILocalVariable, (Tag, Line, Arg, Flags), Ops);
}
DIExpression *DIExpression::getImpl(LLVMContext &Context,
ArrayRef<uint64_t> Elements,
StorageType Storage, bool ShouldCreate) {
DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
}
unsigned DIExpression::ExprOperand::getSize() const {
switch (getOp()) {
case dwarf::DW_OP_bit_piece:
return 3;
case dwarf::DW_OP_plus:
return 2;
default:
return 1;
}
}
bool DIExpression::isValid() const {
for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
// Check that there's space for the operand.
if (I->get() + I->getSize() > E->get())
return false;
// Check that the operand is valid.
switch (I->getOp()) {
default:
return false;
case dwarf::DW_OP_bit_piece:
// Piece expressions must be at the end.
return I->get() + I->getSize() == E->get();
case dwarf::DW_OP_plus:
case dwarf::DW_OP_deref:
break;
}
}
return true;
}
bool DIExpression::isBitPiece() const {
assert(isValid() && "Expected valid expression");
if (unsigned N = getNumElements())
if (N >= 3)
return getElement(N - 3) == dwarf::DW_OP_bit_piece;
return false;
}
uint64_t DIExpression::getBitPieceOffset() const {
assert(isBitPiece() && "Expected bit piece");
return getElement(getNumElements() - 2);
}
uint64_t DIExpression::getBitPieceSize() const {
assert(isBitPiece() && "Expected bit piece");
return getElement(getNumElements() - 1);
}
DIObjCProperty *DIObjCProperty::getImpl(
LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
MDString *GetterName, MDString *SetterName, unsigned Attributes,
Metadata *Type, StorageType Storage, bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
assert(isCanonical(GetterName) && "Expected canonical MDString");
assert(isCanonical(SetterName) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DIObjCProperty,
(getString(Name), File, Line, getString(GetterName),
getString(SetterName), Attributes, Type));
Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
}
DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
Metadata *Scope, Metadata *Entity,
unsigned Line, MDString *Name,
StorageType Storage,
bool ShouldCreate) {
assert(isCanonical(Name) && "Expected canonical MDString");
DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
(Tag, Scope, Entity, Line, getString(Name)));
Metadata *Ops[] = {Scope, Entity, Name};
DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/IntrinsicInst.cpp | //===-- InstrinsicInst.cpp - Intrinsic Instruction Wrappers ---------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements methods that make it really easy to deal with intrinsic
// functions.
//
// All intrinsic function calls are instances of the call instruction, so these
// are all subclasses of the CallInst class. Note that none of these classes
// has state or virtual methods, which is an important part of this gross/neat
// hack working.
//
// In some cases, arguments to intrinsics need to be generic and are defined as
// type pointer to empty struct { }*. To access the real item of interest the
// cast instruction needs to be stripped away.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Metadata.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
/// DbgInfoIntrinsic - This is the common base class for debug info intrinsics
///
static Value *CastOperand(Value *C) {
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
if (CE->isCast())
return CE->getOperand(0);
return nullptr;
}
Value *DbgInfoIntrinsic::StripCast(Value *C) {
if (Value *CO = CastOperand(C)) {
C = StripCast(CO);
} else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
if (GV->hasInitializer())
if (Value *CO = CastOperand(GV->getInitializer()))
C = StripCast(CO);
}
return dyn_cast<GlobalVariable>(C);
}
static Value *getValueImpl(Value *Op) {
auto *MD = cast<MetadataAsValue>(Op)->getMetadata();
if (auto *V = dyn_cast<ValueAsMetadata>(MD))
return V->getValue();
// When the value goes to null, it gets replaced by an empty MDNode.
assert(!cast<MDNode>(MD)->getNumOperands() && "Expected an empty MDNode");
return nullptr;
}
//===----------------------------------------------------------------------===//
/// DbgDeclareInst - This represents the llvm.dbg.declare instruction.
///
Value *DbgDeclareInst::getAddress() const {
if (!getArgOperand(0))
return nullptr;
return getValueImpl(getArgOperand(0));
}
//===----------------------------------------------------------------------===//
/// DbgValueInst - This represents the llvm.dbg.value instruction.
///
const Value *DbgValueInst::getValue() const {
return const_cast<DbgValueInst *>(this)->getValue();
}
Value *DbgValueInst::getValue() { return getValueImpl(getArgOperand(0)); }
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/module.modulemap | module IR { requires cplusplus umbrella "." module * { export * } }
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/GCOV.cpp | //===- GCOV.cpp - LLVM coverage tool --------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// GCOV implements the interface to read and write coverage files that use
// 'gcov' format.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/GCOV.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/MemoryObject.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <system_error>
using namespace llvm;
//===----------------------------------------------------------------------===//
// GCOVFile implementation.
/// readGCNO - Read GCNO buffer.
bool GCOVFile::readGCNO(GCOVBuffer &Buffer) {
if (!Buffer.readGCNOFormat())
return false;
if (!Buffer.readGCOVVersion(Version))
return false;
if (!Buffer.readInt(Checksum))
return false;
while (true) {
if (!Buffer.readFunctionTag())
break;
auto GFun = make_unique<GCOVFunction>(*this);
if (!GFun->readGCNO(Buffer, Version))
return false;
Functions.push_back(std::move(GFun));
}
GCNOInitialized = true;
return true;
}
/// readGCDA - Read GCDA buffer. It is required that readGCDA() can only be
/// called after readGCNO().
bool GCOVFile::readGCDA(GCOVBuffer &Buffer) {
assert(GCNOInitialized && "readGCDA() can only be called after readGCNO()");
if (!Buffer.readGCDAFormat())
return false;
GCOV::GCOVVersion GCDAVersion;
if (!Buffer.readGCOVVersion(GCDAVersion))
return false;
if (Version != GCDAVersion) {
errs() << "GCOV versions do not match.\n";
return false;
}
uint32_t GCDAChecksum;
if (!Buffer.readInt(GCDAChecksum))
return false;
if (Checksum != GCDAChecksum) {
errs() << "File checksums do not match: " << Checksum
<< " != " << GCDAChecksum << ".\n";
return false;
}
for (size_t i = 0, e = Functions.size(); i < e; ++i) {
if (!Buffer.readFunctionTag()) {
errs() << "Unexpected number of functions.\n";
return false;
}
if (!Functions[i]->readGCDA(Buffer, Version))
return false;
}
if (Buffer.readObjectTag()) {
uint32_t Length;
uint32_t Dummy;
if (!Buffer.readInt(Length))
return false;
if (!Buffer.readInt(Dummy))
return false; // checksum
if (!Buffer.readInt(Dummy))
return false; // num
if (!Buffer.readInt(RunCount))
return false;
Buffer.advanceCursor(Length - 3);
}
while (Buffer.readProgramTag()) {
uint32_t Length;
if (!Buffer.readInt(Length))
return false;
Buffer.advanceCursor(Length);
++ProgramCount;
}
return true;
}
/// dump - Dump GCOVFile content to dbgs() for debugging purposes.
void GCOVFile::dump() const {
for (const auto &FPtr : Functions)
FPtr->dump();
}
/// collectLineCounts - Collect line counts. This must be used after
/// reading .gcno and .gcda files.
void GCOVFile::collectLineCounts(FileInfo &FI) {
for (const auto &FPtr : Functions)
FPtr->collectLineCounts(FI);
FI.setRunCount(RunCount);
FI.setProgramCount(ProgramCount);
}
//===----------------------------------------------------------------------===//
// GCOVFunction implementation.
/// readGCNO - Read a function from the GCNO buffer. Return false if an error
/// occurs.
bool GCOVFunction::readGCNO(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
uint32_t Dummy;
if (!Buff.readInt(Dummy))
return false; // Function header length
if (!Buff.readInt(Ident))
return false;
if (!Buff.readInt(Checksum))
return false;
if (Version != GCOV::V402) {
uint32_t CfgChecksum;
if (!Buff.readInt(CfgChecksum))
return false;
if (Parent.getChecksum() != CfgChecksum) {
errs() << "File checksums do not match: " << Parent.getChecksum()
<< " != " << CfgChecksum << " in (" << Name << ").\n";
return false;
}
}
if (!Buff.readString(Name))
return false;
if (!Buff.readString(Filename))
return false;
if (!Buff.readInt(LineNumber))
return false;
// read blocks.
if (!Buff.readBlockTag()) {
errs() << "Block tag not found.\n";
return false;
}
uint32_t BlockCount;
if (!Buff.readInt(BlockCount))
return false;
for (uint32_t i = 0, e = BlockCount; i != e; ++i) {
if (!Buff.readInt(Dummy))
return false; // Block flags;
Blocks.push_back(make_unique<GCOVBlock>(*this, i));
}
// read edges.
while (Buff.readEdgeTag()) {
uint32_t EdgeCount;
if (!Buff.readInt(EdgeCount))
return false;
EdgeCount = (EdgeCount - 1) / 2;
uint32_t BlockNo;
if (!Buff.readInt(BlockNo))
return false;
if (BlockNo >= BlockCount) {
errs() << "Unexpected block number: " << BlockNo << " (in " << Name
<< ").\n";
return false;
}
for (uint32_t i = 0, e = EdgeCount; i != e; ++i) {
uint32_t Dst;
if (!Buff.readInt(Dst))
return false;
Edges.push_back(make_unique<GCOVEdge>(*Blocks[BlockNo], *Blocks[Dst]));
GCOVEdge *Edge = Edges.back().get();
Blocks[BlockNo]->addDstEdge(Edge);
Blocks[Dst]->addSrcEdge(Edge);
if (!Buff.readInt(Dummy))
return false; // Edge flag
}
}
// read line table.
while (Buff.readLineTag()) {
uint32_t LineTableLength;
// Read the length of this line table.
if (!Buff.readInt(LineTableLength))
return false;
uint32_t EndPos = Buff.getCursor() + LineTableLength * 4;
uint32_t BlockNo;
// Read the block number this table is associated with.
if (!Buff.readInt(BlockNo))
return false;
if (BlockNo >= BlockCount) {
errs() << "Unexpected block number: " << BlockNo << " (in " << Name
<< ").\n";
return false;
}
GCOVBlock &Block = *Blocks[BlockNo];
// Read the word that pads the beginning of the line table. This may be a
// flag of some sort, but seems to always be zero.
if (!Buff.readInt(Dummy))
return false;
// Line information starts here and continues up until the last word.
if (Buff.getCursor() != (EndPos - sizeof(uint32_t))) {
StringRef F;
// Read the source file name.
if (!Buff.readString(F))
return false;
if (Filename != F) {
errs() << "Multiple sources for a single basic block: " << Filename
<< " != " << F << " (in " << Name << ").\n";
return false;
}
// Read lines up to, but not including, the null terminator.
while (Buff.getCursor() < (EndPos - 2 * sizeof(uint32_t))) {
uint32_t Line;
if (!Buff.readInt(Line))
return false;
// Line 0 means this instruction was injected by the compiler. Skip it.
if (!Line)
continue;
Block.addLine(Line);
}
// Read the null terminator.
if (!Buff.readInt(Dummy))
return false;
}
// The last word is either a flag or padding, it isn't clear which. Skip
// over it.
if (!Buff.readInt(Dummy))
return false;
}
return true;
}
/// readGCDA - Read a function from the GCDA buffer. Return false if an error
/// occurs.
bool GCOVFunction::readGCDA(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
uint32_t Dummy;
if (!Buff.readInt(Dummy))
return false; // Function header length
uint32_t GCDAIdent;
if (!Buff.readInt(GCDAIdent))
return false;
if (Ident != GCDAIdent) {
errs() << "Function identifiers do not match: " << Ident
<< " != " << GCDAIdent << " (in " << Name << ").\n";
return false;
}
uint32_t GCDAChecksum;
if (!Buff.readInt(GCDAChecksum))
return false;
if (Checksum != GCDAChecksum) {
errs() << "Function checksums do not match: " << Checksum
<< " != " << GCDAChecksum << " (in " << Name << ").\n";
return false;
}
uint32_t CfgChecksum;
if (Version != GCOV::V402) {
if (!Buff.readInt(CfgChecksum))
return false;
if (Parent.getChecksum() != CfgChecksum) {
errs() << "File checksums do not match: " << Parent.getChecksum()
<< " != " << CfgChecksum << " (in " << Name << ").\n";
return false;
}
}
StringRef GCDAName;
if (!Buff.readString(GCDAName))
return false;
if (Name != GCDAName) {
errs() << "Function names do not match: " << Name << " != " << GCDAName
<< ".\n";
return false;
}
if (!Buff.readArcTag()) {
errs() << "Arc tag not found (in " << Name << ").\n";
return false;
}
uint32_t Count;
if (!Buff.readInt(Count))
return false;
Count /= 2;
// This for loop adds the counts for each block. A second nested loop is
// required to combine the edge counts that are contained in the GCDA file.
for (uint32_t BlockNo = 0; Count > 0; ++BlockNo) {
// The last block is always reserved for exit block
if (BlockNo >= Blocks.size()) {
errs() << "Unexpected number of edges (in " << Name << ").\n";
return false;
}
if (BlockNo == Blocks.size() - 1)
errs() << "(" << Name << ") has arcs from exit block.\n";
GCOVBlock &Block = *Blocks[BlockNo];
for (size_t EdgeNo = 0, End = Block.getNumDstEdges(); EdgeNo < End;
++EdgeNo) {
if (Count == 0) {
errs() << "Unexpected number of edges (in " << Name << ").\n";
return false;
}
uint64_t ArcCount;
if (!Buff.readInt64(ArcCount))
return false;
Block.addCount(EdgeNo, ArcCount);
--Count;
}
Block.sortDstEdges();
}
return true;
}
/// getEntryCount - Get the number of times the function was called by
/// retrieving the entry block's count.
uint64_t GCOVFunction::getEntryCount() const {
return Blocks.front()->getCount();
}
/// getExitCount - Get the number of times the function returned by retrieving
/// the exit block's count.
uint64_t GCOVFunction::getExitCount() const {
return Blocks.back()->getCount();
}
/// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
void GCOVFunction::dump() const {
dbgs() << "===== " << Name << " (" << Ident << ") @ " << Filename << ":"
<< LineNumber << "\n";
for (const auto &Block : Blocks)
Block->dump();
}
/// collectLineCounts - Collect line counts. This must be used after
/// reading .gcno and .gcda files.
void GCOVFunction::collectLineCounts(FileInfo &FI) {
// If the line number is zero, this is a function that doesn't actually appear
// in the source file, so there isn't anything we can do with it.
if (LineNumber == 0)
return;
for (const auto &Block : Blocks)
Block->collectLineCounts(FI);
FI.addFunctionLine(Filename, LineNumber, this);
}
//===----------------------------------------------------------------------===//
// GCOVBlock implementation.
/// ~GCOVBlock - Delete GCOVBlock and its content.
GCOVBlock::~GCOVBlock() {
SrcEdges.clear();
DstEdges.clear();
Lines.clear();
}
/// addCount - Add to block counter while storing the edge count. If the
/// destination has no outgoing edges, also update that block's count too.
void GCOVBlock::addCount(size_t DstEdgeNo, uint64_t N) {
assert(DstEdgeNo < DstEdges.size()); // up to caller to ensure EdgeNo is valid
DstEdges[DstEdgeNo]->Count = N;
Counter += N;
if (!DstEdges[DstEdgeNo]->Dst.getNumDstEdges())
DstEdges[DstEdgeNo]->Dst.Counter += N;
}
/// sortDstEdges - Sort destination edges by block number, nop if already
/// sorted. This is required for printing branch info in the correct order.
void GCOVBlock::sortDstEdges() {
if (!DstEdgesAreSorted) {
SortDstEdgesFunctor SortEdges;
std::stable_sort(DstEdges.begin(), DstEdges.end(), SortEdges);
}
}
/// collectLineCounts - Collect line counts. This must be used after
/// reading .gcno and .gcda files.
void GCOVBlock::collectLineCounts(FileInfo &FI) {
for (uint32_t N : Lines)
FI.addBlockLine(Parent.getFilename(), N, this);
}
/// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
void GCOVBlock::dump() const {
dbgs() << "Block : " << Number << " Counter : " << Counter << "\n";
if (!SrcEdges.empty()) {
dbgs() << "\tSource Edges : ";
for (const GCOVEdge *Edge : SrcEdges)
dbgs() << Edge->Src.Number << " (" << Edge->Count << "), ";
dbgs() << "\n";
}
if (!DstEdges.empty()) {
dbgs() << "\tDestination Edges : ";
for (const GCOVEdge *Edge : DstEdges)
dbgs() << Edge->Dst.Number << " (" << Edge->Count << "), ";
dbgs() << "\n";
}
if (!Lines.empty()) {
dbgs() << "\tLines : ";
for (uint32_t N : Lines)
dbgs() << (N) << ",";
dbgs() << "\n";
}
}
//===----------------------------------------------------------------------===//
// FileInfo implementation.
// Safe integer division, returns 0 if numerator is 0.
static uint32_t safeDiv(uint64_t Numerator, uint64_t Divisor) {
if (!Numerator)
return 0;
return Numerator / Divisor;
}
// This custom division function mimics gcov's branch ouputs:
// - Round to closest whole number
// - Only output 0% or 100% if it's exactly that value
static uint32_t branchDiv(uint64_t Numerator, uint64_t Divisor) {
if (!Numerator)
return 0;
if (Numerator == Divisor)
return 100;
uint8_t Res = (Numerator * 100 + Divisor / 2) / Divisor;
if (Res == 0)
return 1;
if (Res == 100)
return 99;
return Res;
}
namespace {
struct formatBranchInfo {
formatBranchInfo(const GCOVOptions &Options, uint64_t Count, uint64_t Total)
: Options(Options), Count(Count), Total(Total) {}
void print(raw_ostream &OS) const {
if (!Total)
OS << "never executed";
else if (Options.BranchCount)
OS << "taken " << Count;
else
OS << "taken " << branchDiv(Count, Total) << "%";
}
const GCOVOptions &Options;
uint64_t Count;
uint64_t Total;
};
static raw_ostream &operator<<(raw_ostream &OS, const formatBranchInfo &FBI) {
FBI.print(OS);
return OS;
}
class LineConsumer {
std::unique_ptr<MemoryBuffer> Buffer;
StringRef Remaining;
public:
LineConsumer(StringRef Filename) {
ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
MemoryBuffer::getFileOrSTDIN(Filename);
if (std::error_code EC = BufferOrErr.getError()) {
errs() << Filename << ": " << EC.message() << "\n";
Remaining = "";
} else {
Buffer = std::move(BufferOrErr.get());
Remaining = Buffer->getBuffer();
}
}
bool empty() { return Remaining.empty(); }
void printNext(raw_ostream &OS, uint32_t LineNum) {
StringRef Line;
if (empty())
Line = "/*EOF*/";
else
std::tie(Line, Remaining) = Remaining.split("\n");
OS << format("%5u:", LineNum) << Line << "\n";
}
};
}
/// Convert a path to a gcov filename. If PreservePaths is true, this
/// translates "/" to "#", ".." to "^", and drops ".", to match gcov.
static std::string mangleCoveragePath(StringRef Filename, bool PreservePaths) {
if (!PreservePaths)
return sys::path::filename(Filename).str();
// This behaviour is defined by gcov in terms of text replacements, so it's
// not likely to do anything useful on filesystems with different textual
// conventions.
llvm::SmallString<256> Result("");
StringRef::iterator I, S, E;
for (I = S = Filename.begin(), E = Filename.end(); I != E; ++I) {
if (*I != '/')
continue;
if (I - S == 1 && *S == '.') {
// ".", the current directory, is skipped.
} else if (I - S == 2 && *S == '.' && *(S + 1) == '.') {
// "..", the parent directory, is replaced with "^".
Result.append("^#");
} else {
if (S < I)
// Leave other components intact,
Result.append(S, I);
// And separate with "#".
Result.push_back('#');
}
S = I + 1;
}
if (S < I)
Result.append(S, I);
return Result.str();
}
std::string FileInfo::getCoveragePath(StringRef Filename,
StringRef MainFilename) {
if (Options.NoOutput)
// This is probably a bug in gcov, but when -n is specified, paths aren't
// mangled at all, and the -l and -p options are ignored. Here, we do the
// same.
return Filename;
std::string CoveragePath;
if (Options.LongFileNames && !Filename.equals(MainFilename))
CoveragePath =
mangleCoveragePath(MainFilename, Options.PreservePaths) + "##";
CoveragePath += mangleCoveragePath(Filename, Options.PreservePaths) + ".gcov";
return CoveragePath;
}
std::unique_ptr<raw_ostream>
FileInfo::openCoveragePath(StringRef CoveragePath) {
if (Options.NoOutput)
return llvm::make_unique<raw_null_ostream>();
std::error_code EC;
auto OS = llvm::make_unique<raw_fd_ostream>(CoveragePath, EC,
sys::fs::F_Text);
if (EC) {
errs() << EC.message() << "\n";
return llvm::make_unique<raw_null_ostream>();
}
return std::move(OS);
}
/// print - Print source files with collected line count information.
void FileInfo::print(raw_ostream &InfoOS, StringRef MainFilename,
StringRef GCNOFile, StringRef GCDAFile) {
for (const auto &LI : LineInfo) {
StringRef Filename = LI.first();
auto AllLines = LineConsumer(Filename);
std::string CoveragePath = getCoveragePath(Filename, MainFilename);
std::unique_ptr<raw_ostream> CovStream = openCoveragePath(CoveragePath);
raw_ostream &CovOS = *CovStream;
CovOS << " -: 0:Source:" << Filename << "\n";
CovOS << " -: 0:Graph:" << GCNOFile << "\n";
CovOS << " -: 0:Data:" << GCDAFile << "\n";
CovOS << " -: 0:Runs:" << RunCount << "\n";
CovOS << " -: 0:Programs:" << ProgramCount << "\n";
const LineData &Line = LI.second;
GCOVCoverage FileCoverage(Filename);
for (uint32_t LineIndex = 0; LineIndex < Line.LastLine || !AllLines.empty();
++LineIndex) {
if (Options.BranchInfo) {
FunctionLines::const_iterator FuncsIt = Line.Functions.find(LineIndex);
if (FuncsIt != Line.Functions.end())
printFunctionSummary(CovOS, FuncsIt->second);
}
BlockLines::const_iterator BlocksIt = Line.Blocks.find(LineIndex);
if (BlocksIt == Line.Blocks.end()) {
// No basic blocks are on this line. Not an executable line of code.
CovOS << " -:";
AllLines.printNext(CovOS, LineIndex + 1);
} else {
const BlockVector &Blocks = BlocksIt->second;
// Add up the block counts to form line counts.
DenseMap<const GCOVFunction *, bool> LineExecs;
uint64_t LineCount = 0;
for (const GCOVBlock *Block : Blocks) {
if (Options.AllBlocks) {
// Only take the highest block count for that line.
uint64_t BlockCount = Block->getCount();
LineCount = LineCount > BlockCount ? LineCount : BlockCount;
} else {
// Sum up all of the block counts.
LineCount += Block->getCount();
}
if (Options.FuncCoverage) {
// This is a slightly convoluted way to most accurately gather line
// statistics for functions. Basically what is happening is that we
// don't want to count a single line with multiple blocks more than
// once. However, we also don't simply want to give the total line
// count to every function that starts on the line. Thus, what is
// happening here are two things:
// 1) Ensure that the number of logical lines is only incremented
// once per function.
// 2) If there are multiple blocks on the same line, ensure that the
// number of lines executed is incremented as long as at least
// one of the blocks are executed.
const GCOVFunction *Function = &Block->getParent();
if (FuncCoverages.find(Function) == FuncCoverages.end()) {
std::pair<const GCOVFunction *, GCOVCoverage> KeyValue(
Function, GCOVCoverage(Function->getName()));
FuncCoverages.insert(KeyValue);
}
GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
if (LineExecs.find(Function) == LineExecs.end()) {
if (Block->getCount()) {
++FuncCoverage.LinesExec;
LineExecs[Function] = true;
} else {
LineExecs[Function] = false;
}
++FuncCoverage.LogicalLines;
} else if (!LineExecs[Function] && Block->getCount()) {
++FuncCoverage.LinesExec;
LineExecs[Function] = true;
}
}
}
if (LineCount == 0)
CovOS << " #####:";
else {
CovOS << format("%9" PRIu64 ":", LineCount);
++FileCoverage.LinesExec;
}
++FileCoverage.LogicalLines;
AllLines.printNext(CovOS, LineIndex + 1);
uint32_t BlockNo = 0;
uint32_t EdgeNo = 0;
for (const GCOVBlock *Block : Blocks) {
// Only print block and branch information at the end of the block.
if (Block->getLastLine() != LineIndex + 1)
continue;
if (Options.AllBlocks)
printBlockInfo(CovOS, *Block, LineIndex, BlockNo);
if (Options.BranchInfo) {
size_t NumEdges = Block->getNumDstEdges();
if (NumEdges > 1)
printBranchInfo(CovOS, *Block, FileCoverage, EdgeNo);
else if (Options.UncondBranch && NumEdges == 1)
printUncondBranchInfo(CovOS, EdgeNo,
(*Block->dst_begin())->Count);
}
}
}
}
FileCoverages.push_back(std::make_pair(CoveragePath, FileCoverage));
}
// FIXME: There is no way to detect calls given current instrumentation.
if (Options.FuncCoverage)
printFuncCoverage(InfoOS);
printFileCoverage(InfoOS);
return;
}
/// printFunctionSummary - Print function and block summary.
void FileInfo::printFunctionSummary(raw_ostream &OS,
const FunctionVector &Funcs) const {
for (const GCOVFunction *Func : Funcs) {
uint64_t EntryCount = Func->getEntryCount();
uint32_t BlocksExec = 0;
for (const GCOVBlock &Block : Func->blocks())
if (Block.getNumDstEdges() && Block.getCount())
++BlocksExec;
OS << "function " << Func->getName() << " called " << EntryCount
<< " returned " << safeDiv(Func->getExitCount() * 100, EntryCount)
<< "% blocks executed "
<< safeDiv(BlocksExec * 100, Func->getNumBlocks() - 1) << "%\n";
}
}
/// printBlockInfo - Output counts for each block.
void FileInfo::printBlockInfo(raw_ostream &OS, const GCOVBlock &Block,
uint32_t LineIndex, uint32_t &BlockNo) const {
if (Block.getCount() == 0)
OS << " $$$$$:";
else
OS << format("%9" PRIu64 ":", Block.getCount());
OS << format("%5u-block %2u\n", LineIndex + 1, BlockNo++);
}
/// printBranchInfo - Print conditional branch probabilities.
void FileInfo::printBranchInfo(raw_ostream &OS, const GCOVBlock &Block,
GCOVCoverage &Coverage, uint32_t &EdgeNo) {
SmallVector<uint64_t, 16> BranchCounts;
uint64_t TotalCounts = 0;
for (const GCOVEdge *Edge : Block.dsts()) {
BranchCounts.push_back(Edge->Count);
TotalCounts += Edge->Count;
if (Block.getCount())
++Coverage.BranchesExec;
if (Edge->Count)
++Coverage.BranchesTaken;
++Coverage.Branches;
if (Options.FuncCoverage) {
const GCOVFunction *Function = &Block.getParent();
GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
if (Block.getCount())
++FuncCoverage.BranchesExec;
if (Edge->Count)
++FuncCoverage.BranchesTaken;
++FuncCoverage.Branches;
}
}
for (uint64_t N : BranchCounts)
OS << format("branch %2u ", EdgeNo++)
<< formatBranchInfo(Options, N, TotalCounts) << "\n";
}
/// printUncondBranchInfo - Print unconditional branch probabilities.
void FileInfo::printUncondBranchInfo(raw_ostream &OS, uint32_t &EdgeNo,
uint64_t Count) const {
OS << format("unconditional %2u ", EdgeNo++)
<< formatBranchInfo(Options, Count, Count) << "\n";
}
// printCoverage - Print generic coverage info used by both printFuncCoverage
// and printFileCoverage.
void FileInfo::printCoverage(raw_ostream &OS,
const GCOVCoverage &Coverage) const {
OS << format("Lines executed:%.2f%% of %u\n",
double(Coverage.LinesExec) * 100 / Coverage.LogicalLines,
Coverage.LogicalLines);
if (Options.BranchInfo) {
if (Coverage.Branches) {
OS << format("Branches executed:%.2f%% of %u\n",
double(Coverage.BranchesExec) * 100 / Coverage.Branches,
Coverage.Branches);
OS << format("Taken at least once:%.2f%% of %u\n",
double(Coverage.BranchesTaken) * 100 / Coverage.Branches,
Coverage.Branches);
} else {
OS << "No branches\n";
}
OS << "No calls\n"; // to be consistent with gcov
}
}
// printFuncCoverage - Print per-function coverage info.
void FileInfo::printFuncCoverage(raw_ostream &OS) const {
for (const auto &FC : FuncCoverages) {
const GCOVCoverage &Coverage = FC.second;
OS << "Function '" << Coverage.Name << "'\n";
printCoverage(OS, Coverage);
OS << "\n";
}
}
// printFileCoverage - Print per-file coverage info.
void FileInfo::printFileCoverage(raw_ostream &OS) const {
for (const auto &FC : FileCoverages) {
const std::string &Filename = FC.first;
const GCOVCoverage &Coverage = FC.second;
OS << "File '" << Coverage.Name << "'\n";
printCoverage(OS, Coverage);
if (!Options.NoOutput)
OS << Coverage.Name << ":creating '" << Filename << "'\n";
OS << "\n";
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/TypeFinder.cpp | //===-- TypeFinder.cpp - Implement the TypeFinder class -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the TypeFinder class for the IR library.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/TypeFinder.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
using namespace llvm;
void TypeFinder::run(const Module &M, bool onlyNamed) {
OnlyNamed = onlyNamed;
// Get types from global variables.
for (Module::const_global_iterator I = M.global_begin(),
E = M.global_end(); I != E; ++I) {
incorporateType(I->getType());
if (I->hasInitializer())
incorporateValue(I->getInitializer());
}
// Get types from aliases.
for (Module::const_alias_iterator I = M.alias_begin(),
E = M.alias_end(); I != E; ++I) {
incorporateType(I->getType());
if (const Value *Aliasee = I->getAliasee())
incorporateValue(Aliasee);
}
// Get types from functions.
SmallVector<std::pair<unsigned, MDNode *>, 4> MDForInst;
for (Module::const_iterator FI = M.begin(), E = M.end(); FI != E; ++FI) {
incorporateType(FI->getType());
if (FI->hasPrefixData())
incorporateValue(FI->getPrefixData());
if (FI->hasPrologueData())
incorporateValue(FI->getPrologueData());
if (FI->hasPersonalityFn())
incorporateValue(FI->getPersonalityFn());
// First incorporate the arguments.
for (Function::const_arg_iterator AI = FI->arg_begin(),
AE = FI->arg_end(); AI != AE; ++AI)
incorporateValue(AI);
for (Function::const_iterator BB = FI->begin(), E = FI->end();
BB != E;++BB)
for (BasicBlock::const_iterator II = BB->begin(),
E = BB->end(); II != E; ++II) {
const Instruction &I = *II;
// Incorporate the type of the instruction.
incorporateType(I.getType());
// Incorporate non-instruction operand types. (We are incorporating all
// instructions with this loop.)
for (User::const_op_iterator OI = I.op_begin(), OE = I.op_end();
OI != OE; ++OI)
if (*OI && !isa<Instruction>(OI))
incorporateValue(*OI);
// Incorporate types hiding in metadata.
I.getAllMetadataOtherThanDebugLoc(MDForInst);
for (unsigned i = 0, e = MDForInst.size(); i != e; ++i)
incorporateMDNode(MDForInst[i].second);
MDForInst.clear();
}
}
for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
E = M.named_metadata_end(); I != E; ++I) {
const NamedMDNode *NMD = I;
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i)
incorporateMDNode(NMD->getOperand(i));
}
}
void TypeFinder::clear() {
VisitedConstants.clear();
VisitedTypes.clear();
StructTypes.clear();
}
/// incorporateType - This method adds the type to the list of used structures
/// if it's not in there already.
void TypeFinder::incorporateType(Type *Ty) {
// Check to see if we've already visited this type.
if (!VisitedTypes.insert(Ty).second)
return;
SmallVector<Type *, 4> TypeWorklist;
TypeWorklist.push_back(Ty);
do {
Ty = TypeWorklist.pop_back_val();
// If this is a structure or opaque type, add a name for the type.
if (StructType *STy = dyn_cast<StructType>(Ty))
if (!OnlyNamed || STy->hasName())
StructTypes.push_back(STy);
// Add all unvisited subtypes to worklist for processing
for (Type::subtype_reverse_iterator I = Ty->subtype_rbegin(),
E = Ty->subtype_rend();
I != E; ++I)
if (VisitedTypes.insert(*I).second)
TypeWorklist.push_back(*I);
} while (!TypeWorklist.empty());
}
/// incorporateValue - This method is used to walk operand lists finding types
/// hiding in constant expressions and other operands that won't be walked in
/// other ways. GlobalValues, basic blocks, instructions, and inst operands are
/// all explicitly enumerated.
void TypeFinder::incorporateValue(const Value *V) {
if (const auto *M = dyn_cast<MetadataAsValue>(V)) {
if (const auto *N = dyn_cast<MDNode>(M->getMetadata()))
return incorporateMDNode(N);
if (const auto *MDV = dyn_cast<ValueAsMetadata>(M->getMetadata()))
return incorporateValue(MDV->getValue());
return;
}
if (!isa<Constant>(V) || isa<GlobalValue>(V)) return;
// Already visited?
if (!VisitedConstants.insert(V).second)
return;
// Check this type.
incorporateType(V->getType());
// If this is an instruction, we incorporate it separately.
if (isa<Instruction>(V))
return;
// Look in operands for types.
const User *U = cast<User>(V);
for (Constant::const_op_iterator I = U->op_begin(),
E = U->op_end(); I != E;++I)
incorporateValue(*I);
}
/// incorporateMDNode - This method is used to walk the operands of an MDNode to
/// find types hiding within.
void TypeFinder::incorporateMDNode(const MDNode *V) {
// Already visited?
if (!VisitedMetadata.insert(V).second)
return;
// Look in operands for types.
for (unsigned i = 0, e = V->getNumOperands(); i != e; ++i) {
Metadata *Op = V->getOperand(i);
if (!Op)
continue;
if (auto *N = dyn_cast<MDNode>(Op)) {
incorporateMDNode(N);
continue;
}
if (auto *C = dyn_cast<ConstantAsMetadata>(Op)) {
incorporateValue(C->getValue());
continue;
}
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/Dominators.cpp | //===- Dominators.cpp - Dominator Calculation -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements simple dominator construction algorithms for finding
// forward dominators. Postdominators are available in libanalysis, but are not
// included in libvmcore, because it's not needed. Forward dominators are
// needed to support the Verifier pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Dominators.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/PassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/GenericDomTreeConstruction.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;
// Always verify dominfo if expensive checking is enabled.
#ifdef XDEBUG
static bool VerifyDomInfo = true;
#else
static bool VerifyDomInfo = false;
#endif
#if 0 // HLSL Change Starts - option pending
static cl::opt<bool,true>
VerifyDomInfoX("verify-dom-info", cl::location(VerifyDomInfo),
cl::desc("Verify dominator info (time consuming)"));
#endif // HLSL Change Ends
bool BasicBlockEdge::isSingleEdge() const {
const TerminatorInst *TI = Start->getTerminator();
unsigned NumEdgesToEnd = 0;
for (unsigned int i = 0, n = TI->getNumSuccessors(); i < n; ++i) {
if (TI->getSuccessor(i) == End)
++NumEdgesToEnd;
if (NumEdgesToEnd >= 2)
return false;
}
assert(NumEdgesToEnd == 1);
return true;
}
//===----------------------------------------------------------------------===//
// DominatorTree Implementation
//===----------------------------------------------------------------------===//
//
// Provide public access to DominatorTree information. Implementation details
// can be found in Dominators.h, GenericDomTree.h, and
// GenericDomTreeConstruction.h.
//
//===----------------------------------------------------------------------===//
template class llvm::DomTreeNodeBase<BasicBlock>;
template class llvm::DominatorTreeBase<BasicBlock>;
template void llvm::Calculate<Function, BasicBlock *>(
DominatorTreeBase<GraphTraits<BasicBlock *>::NodeType> &DT, Function &F);
template void llvm::Calculate<Function, Inverse<BasicBlock *>>(
DominatorTreeBase<GraphTraits<Inverse<BasicBlock *>>::NodeType> &DT,
Function &F);
// dominates - Return true if Def dominates a use in User. This performs
// the special checks necessary if Def and User are in the same basic block.
// Note that Def doesn't dominate a use in Def itself!
bool DominatorTree::dominates(const Instruction *Def,
const Instruction *User) const {
const BasicBlock *UseBB = User->getParent();
const BasicBlock *DefBB = Def->getParent();
// Any unreachable use is dominated, even if Def == User.
if (!isReachableFromEntry(UseBB))
return true;
// Unreachable definitions don't dominate anything.
if (!isReachableFromEntry(DefBB))
return false;
// An instruction doesn't dominate a use in itself.
if (Def == User)
return false;
// The value defined by an invoke dominates an instruction only if
// it dominates every instruction in UseBB.
// A PHI is dominated only if the instruction dominates every possible use
// in the UseBB.
if (isa<InvokeInst>(Def) || isa<PHINode>(User))
return dominates(Def, UseBB);
if (DefBB != UseBB)
return dominates(DefBB, UseBB);
// Loop through the basic block until we find Def or User.
BasicBlock::const_iterator I = DefBB->begin();
for (; &*I != Def && &*I != User; ++I)
/*empty*/;
return &*I == Def;
}
// true if Def would dominate a use in any instruction in UseBB.
// note that dominates(Def, Def->getParent()) is false.
bool DominatorTree::dominates(const Instruction *Def,
const BasicBlock *UseBB) const {
const BasicBlock *DefBB = Def->getParent();
// Any unreachable use is dominated, even if DefBB == UseBB.
if (!isReachableFromEntry(UseBB))
return true;
// Unreachable definitions don't dominate anything.
if (!isReachableFromEntry(DefBB))
return false;
if (DefBB == UseBB)
return false;
const InvokeInst *II = dyn_cast<InvokeInst>(Def);
if (!II)
return dominates(DefBB, UseBB);
// Invoke results are only usable in the normal destination, not in the
// exceptional destination.
BasicBlock *NormalDest = II->getNormalDest();
BasicBlockEdge E(DefBB, NormalDest);
return dominates(E, UseBB);
}
bool DominatorTree::dominates(const BasicBlockEdge &BBE,
const BasicBlock *UseBB) const {
// Assert that we have a single edge. We could handle them by simply
// returning false, but since isSingleEdge is linear on the number of
// edges, the callers can normally handle them more efficiently.
assert(BBE.isSingleEdge());
// If the BB the edge ends in doesn't dominate the use BB, then the
// edge also doesn't.
const BasicBlock *Start = BBE.getStart();
const BasicBlock *End = BBE.getEnd();
if (!dominates(End, UseBB))
return false;
// Simple case: if the end BB has a single predecessor, the fact that it
// dominates the use block implies that the edge also does.
if (End->getSinglePredecessor())
return true;
// The normal edge from the invoke is critical. Conceptually, what we would
// like to do is split it and check if the new block dominates the use.
// With X being the new block, the graph would look like:
//
// DefBB
// /\ . .
// / \ . .
// / \ . .
// / \ | |
// A X B C
// | \ | /
// . \|/
// . NormalDest
// .
//
// Given the definition of dominance, NormalDest is dominated by X iff X
// dominates all of NormalDest's predecessors (X, B, C in the example). X
// trivially dominates itself, so we only have to find if it dominates the
// other predecessors. Since the only way out of X is via NormalDest, X can
// only properly dominate a node if NormalDest dominates that node too.
for (const_pred_iterator PI = pred_begin(End), E = pred_end(End);
PI != E; ++PI) {
const BasicBlock *BB = *PI;
if (BB == Start)
continue;
if (!dominates(End, BB))
return false;
}
return true;
}
bool DominatorTree::dominates(const BasicBlockEdge &BBE, const Use &U) const {
// Assert that we have a single edge. We could handle them by simply
// returning false, but since isSingleEdge is linear on the number of
// edges, the callers can normally handle them more efficiently.
assert(BBE.isSingleEdge());
Instruction *UserInst = cast<Instruction>(U.getUser());
// A PHI in the end of the edge is dominated by it.
PHINode *PN = dyn_cast<PHINode>(UserInst);
if (PN && PN->getParent() == BBE.getEnd() &&
PN->getIncomingBlock(U) == BBE.getStart())
return true;
// Otherwise use the edge-dominates-block query, which
// handles the crazy critical edge cases properly.
const BasicBlock *UseBB;
if (PN)
UseBB = PN->getIncomingBlock(U);
else
UseBB = UserInst->getParent();
return dominates(BBE, UseBB);
}
bool DominatorTree::dominates(const Instruction *Def, const Use &U) const {
Instruction *UserInst = cast<Instruction>(U.getUser());
const BasicBlock *DefBB = Def->getParent();
// Determine the block in which the use happens. PHI nodes use
// their operands on edges; simulate this by thinking of the use
// happening at the end of the predecessor block.
const BasicBlock *UseBB;
if (PHINode *PN = dyn_cast<PHINode>(UserInst))
UseBB = PN->getIncomingBlock(U);
else
UseBB = UserInst->getParent();
// Any unreachable use is dominated, even if Def == User.
if (!isReachableFromEntry(UseBB))
return true;
// Unreachable definitions don't dominate anything.
if (!isReachableFromEntry(DefBB))
return false;
// Invoke instructions define their return values on the edges
// to their normal successors, so we have to handle them specially.
// Among other things, this means they don't dominate anything in
// their own block, except possibly a phi, so we don't need to
// walk the block in any case.
if (const InvokeInst *II = dyn_cast<InvokeInst>(Def)) {
BasicBlock *NormalDest = II->getNormalDest();
BasicBlockEdge E(DefBB, NormalDest);
return dominates(E, U);
}
// If the def and use are in different blocks, do a simple CFG dominator
// tree query.
if (DefBB != UseBB)
return dominates(DefBB, UseBB);
// Ok, def and use are in the same block. If the def is an invoke, it
// doesn't dominate anything in the block. If it's a PHI, it dominates
// everything in the block.
if (isa<PHINode>(UserInst))
return true;
// Otherwise, just loop through the basic block until we find Def or User.
BasicBlock::const_iterator I = DefBB->begin();
for (; &*I != Def && &*I != UserInst; ++I)
/*empty*/;
return &*I != UserInst;
}
bool DominatorTree::isReachableFromEntry(const Use &U) const {
Instruction *I = dyn_cast<Instruction>(U.getUser());
// ConstantExprs aren't really reachable from the entry block, but they
// don't need to be treated like unreachable code either.
if (!I) return true;
// PHI nodes use their operands on their incoming edges.
if (PHINode *PN = dyn_cast<PHINode>(I))
return isReachableFromEntry(PN->getIncomingBlock(U));
// Everything else uses their operands in their own block.
return isReachableFromEntry(I->getParent());
}
void DominatorTree::verifyDomTree() const {
Function &F = *getRoot()->getParent();
DominatorTree OtherDT;
OtherDT.recalculate(F);
if (compare(OtherDT)) {
errs() << "DominatorTree is not up to date!\nComputed:\n";
print(errs());
errs() << "\nActual:\n";
OtherDT.print(errs());
abort();
}
}
//===----------------------------------------------------------------------===//
// DominatorTreeAnalysis and related pass implementations
//===----------------------------------------------------------------------===//
//
// This implements the DominatorTreeAnalysis which is used with the new pass
// manager. It also implements some methods from utility passes.
//
//===----------------------------------------------------------------------===//
DominatorTree DominatorTreeAnalysis::run(Function &F) {
DominatorTree DT;
DT.recalculate(F);
return DT;
}
char DominatorTreeAnalysis::PassID;
DominatorTreePrinterPass::DominatorTreePrinterPass(raw_ostream &OS) : OS(OS) {}
PreservedAnalyses DominatorTreePrinterPass::run(Function &F,
FunctionAnalysisManager *AM) {
OS << "DominatorTree for function: " << F.getName() << "\n";
AM->getResult<DominatorTreeAnalysis>(F).print(OS);
return PreservedAnalyses::all();
}
PreservedAnalyses DominatorTreeVerifierPass::run(Function &F,
FunctionAnalysisManager *AM) {
AM->getResult<DominatorTreeAnalysis>(F).verifyDomTree();
return PreservedAnalyses::all();
}
//===----------------------------------------------------------------------===//
// DominatorTreeWrapperPass Implementation
//===----------------------------------------------------------------------===//
//
// The implementation details of the wrapper pass that holds a DominatorTree
// suitable for use with the legacy pass manager.
//
//===----------------------------------------------------------------------===//
char DominatorTreeWrapperPass::ID = 0;
INITIALIZE_PASS(DominatorTreeWrapperPass, "domtree",
"Dominator Tree Construction", true, true)
bool DominatorTreeWrapperPass::runOnFunction(Function &F) {
DT.recalculate(F);
return false;
}
void DominatorTreeWrapperPass::verifyAnalysis() const {
if (VerifyDomInfo)
DT.verifyDomTree();
}
void DominatorTreeWrapperPass::print(raw_ostream &OS, const Module *) const {
DT.print(OS);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/Function.cpp | //===-- Function.cpp - Implement the Global object classes ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Function class for the IR library.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Function.h"
#include "LLVMContextImpl.h"
#include "SymbolTableListTraitsImpl.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/RWMutex.h"
#include "llvm/Support/StringPool.h"
#include "llvm/Support/Threading.h"
using namespace llvm;
// Explicit instantiations of SymbolTableListTraits since some of the methods
// are not in the public header file...
template class llvm::SymbolTableListTraits<Argument, Function>;
template class llvm::SymbolTableListTraits<BasicBlock, Function>;
//===----------------------------------------------------------------------===//
// Argument Implementation
//===----------------------------------------------------------------------===//
void Argument::anchor() { }
Argument::Argument(Type *Ty, const Twine &Name, Function *Par)
: Value(Ty, Value::ArgumentVal) {
Parent = nullptr;
if (Par)
Par->getArgumentList().push_back(this);
setName(Name);
}
void Argument::setParent(Function *parent) {
Parent = parent;
}
/// getArgNo - Return the index of this formal argument in its containing
/// function. For example in "void foo(int a, float b)" a is 0 and b is 1.
unsigned Argument::getArgNo() const {
const Function *F = getParent();
assert(F && "Argument is not in a function");
Function::const_arg_iterator AI = F->arg_begin();
unsigned ArgIdx = 0;
for (; &*AI != this; ++AI)
++ArgIdx;
return ArgIdx;
}
/// hasNonNullAttr - Return true if this argument has the nonnull attribute on
/// it in its containing function. Also returns true if at least one byte is
/// known to be dereferenceable and the pointer is in addrspace(0).
bool Argument::hasNonNullAttr() const {
if (!getType()->isPointerTy()) return false;
if (getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::NonNull))
return true;
else if (getDereferenceableBytes() > 0 &&
getType()->getPointerAddressSpace() == 0)
return true;
return false;
}
/// hasByValAttr - Return true if this argument has the byval attribute on it
/// in its containing function.
bool Argument::hasByValAttr() const {
if (!getType()->isPointerTy()) return false;
return getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::ByVal);
}
/// \brief Return true if this argument has the inalloca attribute on it in
/// its containing function.
bool Argument::hasInAllocaAttr() const {
if (!getType()->isPointerTy()) return false;
return getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::InAlloca);
}
bool Argument::hasByValOrInAllocaAttr() const {
if (!getType()->isPointerTy()) return false;
AttributeSet Attrs = getParent()->getAttributes();
return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) ||
Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca);
}
unsigned Argument::getParamAlignment() const {
assert(getType()->isPointerTy() && "Only pointers have alignments");
return getParent()->getParamAlignment(getArgNo()+1);
}
uint64_t Argument::getDereferenceableBytes() const {
assert(getType()->isPointerTy() &&
"Only pointers have dereferenceable bytes");
return getParent()->getDereferenceableBytes(getArgNo()+1);
}
uint64_t Argument::getDereferenceableOrNullBytes() const {
assert(getType()->isPointerTy() &&
"Only pointers have dereferenceable bytes");
return getParent()->getDereferenceableOrNullBytes(getArgNo()+1);
}
/// hasNestAttr - Return true if this argument has the nest attribute on
/// it in its containing function.
bool Argument::hasNestAttr() const {
if (!getType()->isPointerTy()) return false;
return getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::Nest);
}
/// hasNoAliasAttr - Return true if this argument has the noalias attribute on
/// it in its containing function.
bool Argument::hasNoAliasAttr() const {
if (!getType()->isPointerTy()) return false;
return getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::NoAlias);
}
/// hasNoCaptureAttr - Return true if this argument has the nocapture attribute
/// on it in its containing function.
bool Argument::hasNoCaptureAttr() const {
if (!getType()->isPointerTy()) return false;
return getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::NoCapture);
}
/// hasSRetAttr - Return true if this argument has the sret attribute on
/// it in its containing function.
bool Argument::hasStructRetAttr() const {
if (!getType()->isPointerTy()) return false;
return getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::StructRet);
}
/// hasReturnedAttr - Return true if this argument has the returned attribute on
/// it in its containing function.
bool Argument::hasReturnedAttr() const {
return getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::Returned);
}
/// hasZExtAttr - Return true if this argument has the zext attribute on it in
/// its containing function.
bool Argument::hasZExtAttr() const {
return getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::ZExt);
}
/// hasSExtAttr Return true if this argument has the sext attribute on it in its
/// containing function.
bool Argument::hasSExtAttr() const {
return getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::SExt);
}
/// Return true if this argument has the readonly or readnone attribute on it
/// in its containing function.
bool Argument::onlyReadsMemory() const {
return getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::ReadOnly) ||
getParent()->getAttributes().
hasAttribute(getArgNo()+1, Attribute::ReadNone);
}
/// addAttr - Add attributes to an argument.
void Argument::addAttr(AttributeSet AS) {
assert(AS.getNumSlots() <= 1 &&
"Trying to add more than one attribute set to an argument!");
AttrBuilder B(AS, AS.getSlotIndex(0));
getParent()->addAttributes(getArgNo() + 1,
AttributeSet::get(Parent->getContext(),
getArgNo() + 1, B));
}
/// removeAttr - Remove attributes from an argument.
void Argument::removeAttr(AttributeSet AS) {
assert(AS.getNumSlots() <= 1 &&
"Trying to remove more than one attribute set from an argument!");
AttrBuilder B(AS, AS.getSlotIndex(0));
getParent()->removeAttributes(getArgNo() + 1,
AttributeSet::get(Parent->getContext(),
getArgNo() + 1, B));
}
//===----------------------------------------------------------------------===//
// Helper Methods in Function
//===----------------------------------------------------------------------===//
bool Function::isMaterializable() const {
return getGlobalObjectSubClassData() & IsMaterializableBit;
}
void Function::setIsMaterializable(bool V) {
setGlobalObjectBit(IsMaterializableBit, V);
}
LLVMContext &Function::getContext() const {
return getType()->getContext();
}
FunctionType *Function::getFunctionType() const { return Ty; }
bool Function::isVarArg() const {
return getFunctionType()->isVarArg();
}
Type *Function::getReturnType() const {
return getFunctionType()->getReturnType();
}
void Function::removeFromParent() {
getParent()->CallRemoveGlobalHook(this); // HLSL Change
getParent()->getFunctionList().remove(this);
}
void Function::eraseFromParent() {
getParent()->CallRemoveGlobalHook(this); // HLSL Change
getParent()->getFunctionList().erase(this);
}
//===----------------------------------------------------------------------===//
// Function Implementation
//===----------------------------------------------------------------------===//
Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name,
Module *ParentModule)
: GlobalObject(PointerType::getUnqual(Ty), Value::FunctionVal,
OperandTraits<Function>::op_begin(this), 0, Linkage, name),
Ty(Ty) {
assert(FunctionType::isValidReturnType(getReturnType()) &&
"invalid return type");
setGlobalObjectSubClassData(0);
SymTab.reset(new ValueSymbolTable()); // HLSL Change: use unique_ptr
// If the function has arguments, mark them as lazily built.
if (Ty->getNumParams())
setValueSubclassData(1); // Set the "has lazy arguments" bit.
if (ParentModule)
ParentModule->getFunctionList().push_back(this);
// Ensure intrinsics have the right parameter attributes.
// Note, the IntID field will have been set in Value::setName if this function
// name is a valid intrinsic ID.
if (IntID)
setAttributes(Intrinsic::getAttributes(getContext(), IntID));
}
Function::~Function() {
dropAllReferences(); // After this it is safe to delete instructions.
// Delete all of the method arguments and unlink from symbol table...
ArgumentList.clear();
SymTab.reset(); // HLSL Change: use unique_ptr
// Remove the function from the on-the-side GC table.
clearGC();
// FIXME: needed by operator delete
setFunctionNumOperands(1);
}
void Function::BuildLazyArguments() const {
// Create the arguments vector, all arguments start out unnamed.
FunctionType *FT = getFunctionType();
for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
assert(!FT->getParamType(i)->isVoidTy() &&
"Cannot have void typed arguments!");
ArgumentList.push_back(new Argument(FT->getParamType(i)));
}
// Clear the lazy arguments bit.
unsigned SDC = getSubclassDataFromValue();
const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0));
}
size_t Function::arg_size() const {
return getFunctionType()->getNumParams();
}
bool Function::arg_empty() const {
return getFunctionType()->getNumParams() == 0;
}
void Function::setParent(Module *parent) {
Parent = parent;
}
// dropAllReferences() - This function causes all the subinstructions to "let
// go" of all references that they are maintaining. This allows one to
// 'delete' a whole class at a time, even though there may be circular
// references... first all references are dropped, and all use counts go to
// zero. Then everything is deleted for real. Note that no operations are
// valid on an object that has "dropped all references", except operator
// delete.
//
void Function::dropAllReferences() {
setIsMaterializable(false);
for (iterator I = begin(), E = end(); I != E; ++I)
I->dropAllReferences();
// Delete all basic blocks. They are now unused, except possibly by
// blockaddresses, but BasicBlock's destructor takes care of those.
while (!BasicBlocks.empty())
BasicBlocks.begin()->eraseFromParent();
// Prefix and prologue data are stored in a side table.
setPrefixData(nullptr);
setPrologueData(nullptr);
// Metadata is stored in a side-table.
clearMetadata();
setPersonalityFn(nullptr);
}
void Function::addAttribute(unsigned i, Attribute::AttrKind attr) {
AttributeSet PAL = getAttributes();
PAL = PAL.addAttribute(getContext(), i, attr);
setAttributes(PAL);
}
void Function::addAttributes(unsigned i, AttributeSet attrs) {
AttributeSet PAL = getAttributes();
PAL = PAL.addAttributes(getContext(), i, attrs);
setAttributes(PAL);
}
void Function::removeAttributes(unsigned i, AttributeSet attrs) {
AttributeSet PAL = getAttributes();
PAL = PAL.removeAttributes(getContext(), i, attrs);
setAttributes(PAL);
}
void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
AttributeSet PAL = getAttributes();
PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
setAttributes(PAL);
}
void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
AttributeSet PAL = getAttributes();
PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
setAttributes(PAL);
}
// Maintain the GC name for each function in an on-the-side table. This saves
// allocating an additional word in Function for programs which do not use GC
// (i.e., most programs) at the cost of increased overhead for clients which do
// use GC.
#if 0 // HLSL Change
static DenseMap<const Function*,PooledStringPtr> *GCNames;
static StringPool *GCNamePool;
static ManagedStatic<sys::SmartRWMutex<true> > GCLock;
#endif // HLSL Change
bool Function::hasGC() const {
#if 0 // HLSL Change
sys::SmartScopedReader<true> Reader(*GCLock);
return GCNames && GCNames->count(this);
#else
return false;
#endif // HLSL Change Ends
}
const char *Function::getGC() const {
#if 0 // HLSL Change
assert(hasGC() && "Function has no collector");
sys::SmartScopedReader<true> Reader(*GCLock);
return *(*GCNames)[this];
#else
return nullptr;
#endif // HLSL Change Ends
}
void Function::setGC(const char *Str) {
#if 0 // HLSL Change Starts
sys::SmartScopedWriter<true> Writer(*GCLock);
if (!GCNamePool)
GCNamePool = new StringPool();
if (!GCNames)
GCNames = new DenseMap<const Function*,PooledStringPtr>();
(*GCNames)[this] = GCNamePool->intern(Str);
#else
assert(false && "GC not supported");
#endif // HLSL Change Ends
}
void Function::clearGC() {
#if 0 // HLSL Change Starts
sys::SmartScopedWriter<true> Writer(*GCLock);
if (GCNames) {
GCNames->erase(this);
if (GCNames->empty()) {
delete GCNames;
GCNames = nullptr;
if (GCNamePool->empty()) {
delete GCNamePool;
GCNamePool = nullptr;
}
}
}
#endif // HLSL Change Ends
}
/// copyAttributesFrom - copy all additional attributes (those not needed to
/// create a Function) from the Function Src to this one.
void Function::copyAttributesFrom(const GlobalValue *Src) {
assert(isa<Function>(Src) && "Expected a Function!");
GlobalObject::copyAttributesFrom(Src);
const Function *SrcF = cast<Function>(Src);
setCallingConv(SrcF->getCallingConv());
setAttributes(SrcF->getAttributes());
if (SrcF->hasGC())
setGC(SrcF->getGC());
else
clearGC();
if (SrcF->hasPrefixData())
setPrefixData(SrcF->getPrefixData());
else
setPrefixData(nullptr);
if (SrcF->hasPrologueData())
setPrologueData(SrcF->getPrologueData());
else
setPrologueData(nullptr);
if (SrcF->hasPersonalityFn())
setPersonalityFn(SrcF->getPersonalityFn());
else
setPersonalityFn(nullptr);
}
/// \brief This does the actual lookup of an intrinsic ID which
/// matches the given function name.
static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) {
unsigned Len = ValName->getKeyLength();
const char *Name = ValName->getKeyData();
#define GET_FUNCTION_RECOGNIZER
#include "llvm/IR/Intrinsics.gen"
#undef GET_FUNCTION_RECOGNIZER
return Intrinsic::not_intrinsic;
}
void Function::recalculateIntrinsicID() {
const ValueName *ValName = this->getValueName();
if (!ValName || !isIntrinsic()) {
IntID = Intrinsic::not_intrinsic;
return;
}
IntID = lookupIntrinsicID(ValName);
}
/// Returns a stable mangling for the type specified for use in the name
/// mangling scheme used by 'any' types in intrinsic signatures. The mangling
/// of named types is simply their name. Manglings for unnamed types consist
/// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions)
/// combined with the mangling of their component types. A vararg function
/// type will have a suffix of 'vararg'. Since function types can contain
/// other function types, we close a function type mangling with suffix 'f'
/// which can't be confused with it's prefix. This ensures we don't have
/// collisions between two unrelated function types. Otherwise, you might
/// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.)
/// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most
/// cases) fall back to the MVT codepath, where they could be mangled to
/// 'x86mmx', for example; matching on derived types is not sufficient to mangle
/// everything.
static std::string getMangledTypeStr(Type* Ty) {
std::string Result;
if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) {
Result += "p" + llvm::utostr(PTyp->getAddressSpace()) +
getMangledTypeStr(PTyp->getElementType());
} else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) {
Result += "a" + llvm::utostr(ATyp->getNumElements()) +
getMangledTypeStr(ATyp->getElementType());
} else if (StructType* STyp = dyn_cast<StructType>(Ty)) {
assert(!STyp->isLiteral() && "TODO: implement literal types");
Result += STyp->getName();
} else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) {
Result += "f_" + getMangledTypeStr(FT->getReturnType());
for (size_t i = 0; i < FT->getNumParams(); i++)
Result += getMangledTypeStr(FT->getParamType(i));
if (FT->isVarArg())
Result += "vararg";
// Ensure nested function types are distinguishable.
Result += "f";
} else if (Ty)
Result += EVT::getEVT(Ty).getEVTString();
return Result;
}
std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) {
assert(id < num_intrinsics && "Invalid intrinsic ID!");
static const char * const Table[] = {
"not_intrinsic",
#define GET_INTRINSIC_NAME_TABLE
#include "llvm/IR/Intrinsics.gen"
#undef GET_INTRINSIC_NAME_TABLE
};
if (Tys.empty())
return Table[id];
std::string Result(Table[id]);
for (unsigned i = 0; i < Tys.size(); ++i) {
Result += "." + getMangledTypeStr(Tys[i]);
}
return Result;
}
/// IIT_Info - These are enumerators that describe the entries returned by the
/// getIntrinsicInfoTableEntries function.
///
/// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter!
enum IIT_Info {
// Common values should be encoded with 0-15.
IIT_Done = 0,
IIT_I1 = 1,
IIT_I8 = 2,
IIT_I16 = 3,
IIT_I32 = 4,
IIT_I64 = 5,
IIT_F16 = 6,
IIT_F32 = 7,
IIT_F64 = 8,
IIT_V2 = 9,
IIT_V4 = 10,
IIT_V8 = 11,
IIT_V16 = 12,
IIT_V32 = 13,
IIT_PTR = 14,
IIT_ARG = 15,
// Values from 16+ are only encodable with the inefficient encoding.
IIT_V64 = 16,
IIT_MMX = 17,
IIT_METADATA = 18,
IIT_EMPTYSTRUCT = 19,
IIT_STRUCT2 = 20,
IIT_STRUCT3 = 21,
IIT_STRUCT4 = 22,
IIT_STRUCT5 = 23,
IIT_EXTEND_ARG = 24,
IIT_TRUNC_ARG = 25,
IIT_ANYPTR = 26,
IIT_V1 = 27,
IIT_VARARG = 28,
IIT_HALF_VEC_ARG = 29,
IIT_SAME_VEC_WIDTH_ARG = 30,
IIT_PTR_TO_ARG = 31,
IIT_VEC_OF_PTRS_TO_ELT = 32,
IIT_I128 = 33
};
static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos,
SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) {
IIT_Info Info = IIT_Info(Infos[NextElt++]);
unsigned StructElts = 2;
using namespace Intrinsic;
switch (Info) {
case IIT_Done:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0));
return;
case IIT_VARARG:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0));
return;
case IIT_MMX:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0));
return;
case IIT_METADATA:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0));
return;
case IIT_F16:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0));
return;
case IIT_F32:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0));
return;
case IIT_F64:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0));
return;
case IIT_I1:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1));
return;
case IIT_I8:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8));
return;
case IIT_I16:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16));
return;
case IIT_I32:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32));
return;
case IIT_I64:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64));
return;
case IIT_I128:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128));
return;
case IIT_V1:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1));
DecodeIITType(NextElt, Infos, OutputTable);
return;
case IIT_V2:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2));
DecodeIITType(NextElt, Infos, OutputTable);
return;
case IIT_V4:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4));
DecodeIITType(NextElt, Infos, OutputTable);
return;
case IIT_V8:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8));
DecodeIITType(NextElt, Infos, OutputTable);
return;
case IIT_V16:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16));
DecodeIITType(NextElt, Infos, OutputTable);
return;
case IIT_V32:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32));
DecodeIITType(NextElt, Infos, OutputTable);
return;
case IIT_V64:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64));
DecodeIITType(NextElt, Infos, OutputTable);
return;
case IIT_PTR:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0));
DecodeIITType(NextElt, Infos, OutputTable);
return;
case IIT_ANYPTR: { // [ANYPTR addrspace, subtype]
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer,
Infos[NextElt++]));
DecodeIITType(NextElt, Infos, OutputTable);
return;
}
case IIT_ARG: {
unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo));
return;
}
case IIT_EXTEND_ARG: {
unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument,
ArgInfo));
return;
}
case IIT_TRUNC_ARG: {
unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument,
ArgInfo));
return;
}
case IIT_HALF_VEC_ARG: {
unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument,
ArgInfo));
return;
}
case IIT_SAME_VEC_WIDTH_ARG: {
unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument,
ArgInfo));
return;
}
case IIT_PTR_TO_ARG: {
unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument,
ArgInfo));
return;
}
case IIT_VEC_OF_PTRS_TO_ELT: {
unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]);
OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt,
ArgInfo));
return;
}
case IIT_EMPTYSTRUCT:
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0));
return;
case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH; // HLSL Change
case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH; // HLSL Change
case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH; // HLSL Change
case IIT_STRUCT2: {
OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts));
for (unsigned i = 0; i != StructElts; ++i)
DecodeIITType(NextElt, Infos, OutputTable);
return;
}
}
llvm_unreachable("unhandled");
}
#define GET_INTRINSIC_GENERATOR_GLOBAL
#include "llvm/IR/Intrinsics.gen"
#undef GET_INTRINSIC_GENERATOR_GLOBAL
void Intrinsic::getIntrinsicInfoTableEntries(ID id,
SmallVectorImpl<IITDescriptor> &T){
// Check to see if the intrinsic's type was expressible by the table.
unsigned TableVal = IIT_Table[id-1];
// Decode the TableVal into an array of IITValues.
SmallVector<unsigned char, 8> IITValues;
ArrayRef<unsigned char> IITEntries;
unsigned NextElt = 0;
if ((TableVal >> 31) != 0) {
// This is an offset into the IIT_LongEncodingTable.
IITEntries = IIT_LongEncodingTable;
// Strip sentinel bit.
NextElt = (TableVal << 1) >> 1;
} else {
// Decode the TableVal into an array of IITValues. If the entry was encoded
// into a single word in the table itself, decode it now.
do {
IITValues.push_back(TableVal & 0xF);
TableVal >>= 4;
} while (TableVal);
IITEntries = IITValues;
NextElt = 0;
}
// Okay, decode the table into the output vector of IITDescriptors.
DecodeIITType(NextElt, IITEntries, T);
while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0)
DecodeIITType(NextElt, IITEntries, T);
}
static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos,
ArrayRef<Type*> Tys, LLVMContext &Context) {
using namespace Intrinsic;
IITDescriptor D = Infos.front();
Infos = Infos.slice(1);
switch (D.Kind) {
case IITDescriptor::Void: return Type::getVoidTy(Context);
case IITDescriptor::VarArg: return Type::getVoidTy(Context);
case IITDescriptor::MMX: return Type::getX86_MMXTy(Context);
case IITDescriptor::Metadata: return Type::getMetadataTy(Context);
case IITDescriptor::Half: return Type::getHalfTy(Context);
case IITDescriptor::Float: return Type::getFloatTy(Context);
case IITDescriptor::Double: return Type::getDoubleTy(Context);
case IITDescriptor::Integer:
return IntegerType::get(Context, D.Integer_Width);
case IITDescriptor::Vector:
return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width);
case IITDescriptor::Pointer:
return PointerType::get(DecodeFixedType(Infos, Tys, Context),
D.Pointer_AddressSpace);
case IITDescriptor::Struct: {
Type *Elts[5];
assert(D.Struct_NumElements <= 5 && "Can't handle this yet");
for (unsigned i = 0, e = D.Struct_NumElements; i != e && i < _countof(Elts); ++i) // HLSL Change - add extra check to help SAL
Elts[i] = DecodeFixedType(Infos, Tys, Context);
return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements));
}
case IITDescriptor::Argument:
return Tys[D.getArgumentNumber()];
case IITDescriptor::ExtendArgument: {
Type *Ty = Tys[D.getArgumentNumber()];
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return VectorType::getExtendedElementVectorType(VTy);
return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth());
}
case IITDescriptor::TruncArgument: {
Type *Ty = Tys[D.getArgumentNumber()];
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return VectorType::getTruncatedElementVectorType(VTy);
IntegerType *ITy = cast<IntegerType>(Ty);
assert(ITy->getBitWidth() % 2 == 0);
return IntegerType::get(Context, ITy->getBitWidth() / 2);
}
case IITDescriptor::HalfVecArgument:
return VectorType::getHalfElementsVectorType(cast<VectorType>(
Tys[D.getArgumentNumber()]));
case IITDescriptor::SameVecWidthArgument: {
Type *EltTy = DecodeFixedType(Infos, Tys, Context);
Type *Ty = Tys[D.getArgumentNumber()];
if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
return VectorType::get(EltTy, VTy->getNumElements());
}
llvm_unreachable("unhandled");
}
case IITDescriptor::PtrToArgument: {
Type *Ty = Tys[D.getArgumentNumber()];
return PointerType::getUnqual(Ty);
}
case IITDescriptor::VecOfPtrsToElt: {
Type *Ty = Tys[D.getArgumentNumber()];
VectorType *VTy = dyn_cast<VectorType>(Ty);
if (!VTy)
llvm_unreachable("Expected an argument of Vector Type");
Type *EltTy = VTy->getVectorElementType();
return VectorType::get(PointerType::getUnqual(EltTy),
VTy->getNumElements());
}
}
llvm_unreachable("unhandled");
}
FunctionType *Intrinsic::getType(LLVMContext &Context,
ID id, ArrayRef<Type*> Tys) {
SmallVector<IITDescriptor, 8> Table;
getIntrinsicInfoTableEntries(id, Table);
ArrayRef<IITDescriptor> TableRef = Table;
Type *ResultTy = DecodeFixedType(TableRef, Tys, Context);
SmallVector<Type*, 8> ArgTys;
while (!TableRef.empty())
ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context));
// DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg
// If we see void type as the type of the last argument, it is vararg intrinsic
if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) {
ArgTys.pop_back();
return FunctionType::get(ResultTy, ArgTys, true);
}
return FunctionType::get(ResultTy, ArgTys, false);
}
bool Intrinsic::isOverloaded(ID id) {
#define GET_INTRINSIC_OVERLOAD_TABLE
#include "llvm/IR/Intrinsics.gen"
#undef GET_INTRINSIC_OVERLOAD_TABLE
}
bool Intrinsic::isLeaf(ID id) {
switch (id) {
default:
return true;
case Intrinsic::experimental_gc_statepoint:
case Intrinsic::experimental_patchpoint_void:
case Intrinsic::experimental_patchpoint_i64:
return false;
}
}
/// This defines the "Intrinsic::getAttributes(ID id)" method.
#define GET_INTRINSIC_ATTRIBUTES
#include "llvm/IR/Intrinsics.gen"
#undef GET_INTRINSIC_ATTRIBUTES
Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) {
// There can never be multiple globals with the same name of different types,
// because intrinsics must be a specific type.
return
cast<Function>(M->getOrInsertFunction(getName(id, Tys),
getType(M->getContext(), id, Tys)));
}
// This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method.
//#pragma optimize("", off) // HLSL Change - comment out pragma optimize directive
#define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
#include "llvm/IR/Intrinsics.gen"
#undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN
//#pragma optimize("", on) // HLSL Change - comment out pragma optimize directive
// This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method.
#define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
#include "llvm/IR/Intrinsics.gen"
#undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN
/// hasAddressTaken - returns true if there are any uses of this function
/// other than direct calls or invokes to it.
bool Function::hasAddressTaken(const User* *PutOffender) const {
for (const Use &U : uses()) {
const User *FU = U.getUser();
if (isa<BlockAddress>(FU))
continue;
if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU))
return PutOffender ? (*PutOffender = FU, true) : true;
ImmutableCallSite CS(cast<Instruction>(FU));
if (!CS.isCallee(&U))
return PutOffender ? (*PutOffender = FU, true) : true;
}
return false;
}
bool Function::isDefTriviallyDead() const {
// Check the linkage
if (!hasLinkOnceLinkage() && !hasLocalLinkage() &&
!hasAvailableExternallyLinkage())
return false;
// Check if the function is used by anything other than a blockaddress.
for (const User *U : users())
if (!isa<BlockAddress>(U))
return false;
return true;
}
/// callsFunctionThatReturnsTwice - Return true if the function has a call to
/// setjmp or other function that gcc recognizes as "returning twice".
bool Function::callsFunctionThatReturnsTwice() const {
for (const_inst_iterator
I = inst_begin(this), E = inst_end(this); I != E; ++I) {
ImmutableCallSite CS(&*I);
if (CS && CS.hasFnAttr(Attribute::ReturnsTwice))
return true;
}
return false;
}
Constant *Function::getPrefixData() const {
assert(hasPrefixData());
const LLVMContextImpl::PrefixDataMapTy &PDMap =
getContext().pImpl->PrefixDataMap;
assert(PDMap.find(this) != PDMap.end());
return cast<Constant>(PDMap.find(this)->second->getReturnValue());
}
void Function::setPrefixData(Constant *PrefixData) {
if (!PrefixData && !hasPrefixData())
return;
unsigned SCData = getSubclassDataFromValue();
LLVMContextImpl::PrefixDataMapTy &PDMap = getContext().pImpl->PrefixDataMap;
ReturnInst *&PDHolder = PDMap[this];
if (PrefixData) {
if (PDHolder)
PDHolder->setOperand(0, PrefixData);
else
PDHolder = ReturnInst::Create(getContext(), PrefixData);
SCData |= (1<<1);
} else {
delete PDHolder;
PDMap.erase(this);
SCData &= ~(1<<1);
}
setValueSubclassData(SCData);
}
Constant *Function::getPrologueData() const {
assert(hasPrologueData());
const LLVMContextImpl::PrologueDataMapTy &SOMap =
getContext().pImpl->PrologueDataMap;
assert(SOMap.find(this) != SOMap.end());
return cast<Constant>(SOMap.find(this)->second->getReturnValue());
}
void Function::setPrologueData(Constant *PrologueData) {
if (!PrologueData && !hasPrologueData())
return;
unsigned PDData = getSubclassDataFromValue();
LLVMContextImpl::PrologueDataMapTy &PDMap = getContext().pImpl->PrologueDataMap;
ReturnInst *&PDHolder = PDMap[this];
if (PrologueData) {
if (PDHolder)
PDHolder->setOperand(0, PrologueData);
else
PDHolder = ReturnInst::Create(getContext(), PrologueData);
PDData |= (1<<2);
} else {
delete PDHolder;
PDMap.erase(this);
PDData &= ~(1<<2);
}
setValueSubclassData(PDData);
}
void Function::setEntryCount(uint64_t Count) {
MDBuilder MDB(getContext());
setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count));
}
Optional<uint64_t> Function::getEntryCount() const {
MDNode *MD = getMetadata(LLVMContext::MD_prof);
if (MD && MD->getOperand(0))
if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0)))
if (MDS->getString().equals("function_entry_count")) {
ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1));
return CI->getValue().getZExtValue();
}
return None;
}
void Function::setPersonalityFn(Constant *C) {
if (!C) {
if (hasPersonalityFn()) {
// Note, the num operands is used to compute the offset of the operand, so
// the order here matters. Clearing the operand then clearing the num
// operands ensures we have the correct offset to the operand.
Op<0>().set(nullptr);
setFunctionNumOperands(0);
}
} else {
// Note, the num operands is used to compute the offset of the operand, so
// the order here matters. We need to set num operands to 1 first so that
// we get the correct offset to the first operand when we set it.
if (!hasPersonalityFn())
setFunctionNumOperands(1);
Op<0>().set(C);
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/User.cpp | //===-- User.cpp - Implement the User class -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/User.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Operator.h"
namespace llvm {
class BasicBlock;
//===----------------------------------------------------------------------===//
// User Class
//===----------------------------------------------------------------------===//
void User::anchor() {}
void User::replaceUsesOfWith(Value *From, Value *To) {
if (From == To) return; // Duh what?
assert((!isa<Constant>(this) || isa<GlobalValue>(this)) &&
"Cannot call User::replaceUsesOfWith on a constant!");
for (unsigned i = 0, E = getNumOperands(); i != E; ++i)
if (getOperand(i) == From) { // Is This operand is pointing to oldval?
// The side effects of this setOperand call include linking to
// "To", adding "this" to the uses list of To, and
// most importantly, removing "this" from the use list of "From".
setOperand(i, To); // Fix it now...
}
}
//===----------------------------------------------------------------------===//
// User allocHungoffUses Implementation
//===----------------------------------------------------------------------===//
void User::allocHungoffUses(unsigned N, bool IsPhi) {
assert(HasHungOffUses && "alloc must have hung off uses");
static_assert(AlignOf<Use>::Alignment >= AlignOf<Use::UserRef>::Alignment,
"Alignment is insufficient for 'hung-off-uses' pieces");
static_assert(AlignOf<Use::UserRef>::Alignment >=
AlignOf<BasicBlock *>::Alignment,
"Alignment is insufficient for 'hung-off-uses' pieces");
// Allocate the array of Uses, followed by a pointer (with bottom bit set) to
// the User.
size_t size = N * sizeof(Use) + sizeof(Use::UserRef);
if (IsPhi)
size += N * sizeof(BasicBlock *);
Use *Begin = static_cast<Use*>(::operator new(size));
Use *End = Begin + N;
(void) new(End) Use::UserRef(const_cast<User*>(this), 1);
setOperandList(Use::initTags(Begin, End));
}
void User::growHungoffUses(unsigned NewNumUses, bool IsPhi) {
assert(HasHungOffUses && "realloc must have hung off uses");
unsigned OldNumUses = getNumOperands();
// We don't support shrinking the number of uses. We wouldn't have enough
// space to copy the old uses in to the new space.
assert(NewNumUses > OldNumUses && "realloc must grow num uses");
Use *OldOps = getOperandList();
allocHungoffUses(NewNumUses, IsPhi);
Use *NewOps = getOperandList();
// Now copy from the old operands list to the new one.
std::copy(OldOps, OldOps + OldNumUses, NewOps);
// If this is a Phi, then we need to copy the BB pointers too.
if (IsPhi) {
auto *OldPtr =
reinterpret_cast<char *>(OldOps + OldNumUses) + sizeof(Use::UserRef);
auto *NewPtr =
reinterpret_cast<char *>(NewOps + NewNumUses) + sizeof(Use::UserRef);
std::copy(OldPtr, OldPtr + (OldNumUses * sizeof(BasicBlock *)), NewPtr);
}
Use::zap(OldOps, OldOps + OldNumUses, true);
}
//===----------------------------------------------------------------------===//
// User operator new Implementations
//===----------------------------------------------------------------------===//
void *User::operator new(size_t Size, unsigned Us) {
assert(Us < (1u << NumUserOperandsBits) && "Too many operands");
void *Storage = ::operator new(Size + sizeof(Use) * Us);
Use *Start = static_cast<Use*>(Storage);
Use *End = Start + Us;
User *Obj = reinterpret_cast<User*>(End);
Obj->NumUserOperands = Us;
Obj->HasHungOffUses = false;
Use::initTags(Start, End);
return Obj;
}
void *User::operator new(size_t Size) {
// Allocate space for a single Use*
void *Storage = ::operator new(Size + sizeof(Use *));
Use **HungOffOperandList = static_cast<Use **>(Storage);
User *Obj = reinterpret_cast<User *>(HungOffOperandList + 1);
Obj->NumUserOperands = 0;
Obj->HasHungOffUses = true;
*HungOffOperandList = nullptr;
return Obj;
}
//===----------------------------------------------------------------------===//
// User operator delete Implementation
//===----------------------------------------------------------------------===//
void User::operator delete(void *Usr) {
// Hung off uses use a single Use* before the User, while other subclasses
// use a Use[] allocated prior to the user.
User *Obj = static_cast<User *>(Usr);
if (Obj->HasHungOffUses) {
Use **HungOffOperandList = static_cast<Use **>(Usr) - 1;
// drop the hung off uses.
Use::zap(*HungOffOperandList, *HungOffOperandList + Obj->NumUserOperands,
/* Delete */ true);
::operator delete(HungOffOperandList);
} else {
Use *Storage = static_cast<Use *>(Usr) - Obj->NumUserOperands;
Use::zap(Storage, Storage + Obj->NumUserOperands,
/* Delete */ false);
::operator delete(Storage);
}
}
// HLSL Change Starts
void User::operator delete(void *Usr, unsigned NumUserOperands) {
// Fun fact: during construction Obj->NumUserOperands is overwritten
Use *Storage = static_cast<Use *>(Usr) - NumUserOperands;
Use::zap(Storage, Storage + NumUserOperands, /* Delete */ false);
::operator delete(Storage);
}
// HLSL Change Ends
//===----------------------------------------------------------------------===//
// Operator Class
//===----------------------------------------------------------------------===//
Operator::~Operator() {
llvm_unreachable("should never destroy an Operator");
}
} // End llvm namespace
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/Instruction.cpp | //===-- Instruction.cpp - Implement the Instruction class -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Instruction class for the IR library.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Instruction.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Type.h"
using namespace llvm;
Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
Instruction *InsertBefore)
: User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
// If requested, insert this instruction into a basic block...
if (InsertBefore) {
BasicBlock *BB = InsertBefore->getParent();
assert(BB && "Instruction to insert before is not in a basic block!");
BB->getInstList().insert(InsertBefore, this);
}
}
Instruction::Instruction(Type *ty, unsigned it, Use *Ops, unsigned NumOps,
BasicBlock *InsertAtEnd)
: User(ty, Value::InstructionVal + it, Ops, NumOps), Parent(nullptr) {
// append this instruction into the basic block
assert(InsertAtEnd && "Basic block to append to may not be NULL!");
InsertAtEnd->getInstList().push_back(this);
}
// Out of line virtual method, so the vtable, etc has a home.
Instruction::~Instruction() {
assert(!Parent && "Instruction still linked in the program!");
if (hasMetadataHashEntry())
clearMetadataHashEntries();
}
void Instruction::setParent(BasicBlock *P) {
Parent = P;
}
const Module *Instruction::getModule() const {
return getParent()->getModule();
}
Module *Instruction::getModule() {
return getParent()->getModule();
}
void Instruction::removeFromParent() {
getParent()->getInstList().remove(this);
}
iplist<Instruction>::iterator Instruction::eraseFromParent() {
return getParent()->getInstList().erase(this);
}
/// insertBefore - Insert an unlinked instructions into a basic block
/// immediately before the specified instruction.
void Instruction::insertBefore(Instruction *InsertPos) {
InsertPos->getParent()->getInstList().insert(InsertPos, this);
}
/// insertAfter - Insert an unlinked instructions into a basic block
/// immediately after the specified instruction.
void Instruction::insertAfter(Instruction *InsertPos) {
InsertPos->getParent()->getInstList().insertAfter(InsertPos, this);
}
/// moveBefore - Unlink this instruction from its current basic block and
/// insert it into the basic block that MovePos lives in, right before
/// MovePos.
void Instruction::moveBefore(Instruction *MovePos) {
MovePos->getParent()->getInstList().splice(MovePos,getParent()->getInstList(),
this);
}
/// Set or clear the unsafe-algebra flag on this instruction, which must be an
/// operator which supports this flag. See LangRef.html for the meaning of this
/// flag.
void Instruction::setHasUnsafeAlgebra(bool B) {
assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
cast<FPMathOperator>(this)->setHasUnsafeAlgebra(B);
}
/// Set or clear the NoNaNs flag on this instruction, which must be an operator
/// which supports this flag. See LangRef.html for the meaning of this flag.
void Instruction::setHasNoNaNs(bool B) {
assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
cast<FPMathOperator>(this)->setHasNoNaNs(B);
}
/// Set or clear the no-infs flag on this instruction, which must be an operator
/// which supports this flag. See LangRef.html for the meaning of this flag.
void Instruction::setHasNoInfs(bool B) {
assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
cast<FPMathOperator>(this)->setHasNoInfs(B);
}
/// Set or clear the no-signed-zeros flag on this instruction, which must be an
/// operator which supports this flag. See LangRef.html for the meaning of this
/// flag.
void Instruction::setHasNoSignedZeros(bool B) {
assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
cast<FPMathOperator>(this)->setHasNoSignedZeros(B);
}
/// Set or clear the allow-reciprocal flag on this instruction, which must be an
/// operator which supports this flag. See LangRef.html for the meaning of this
/// flag.
void Instruction::setHasAllowReciprocal(bool B) {
assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
cast<FPMathOperator>(this)->setHasAllowReciprocal(B);
}
/// Convenience function for setting all the fast-math flags on this
/// instruction, which must be an operator which supports these flags. See
/// LangRef.html for the meaning of these flats.
void Instruction::setFastMathFlags(FastMathFlags FMF) {
assert(isa<FPMathOperator>(this) && "setting fast-math flag on invalid op");
cast<FPMathOperator>(this)->setFastMathFlags(FMF);
}
void Instruction::copyFastMathFlags(FastMathFlags FMF) {
assert(isa<FPMathOperator>(this) && "copying fast-math flag on invalid op");
cast<FPMathOperator>(this)->copyFastMathFlags(FMF);
}
/// Determine whether the unsafe-algebra flag is set.
bool Instruction::hasUnsafeAlgebra() const {
assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
}
/// Determine whether the no-NaNs flag is set.
bool Instruction::hasNoNaNs() const {
assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
return cast<FPMathOperator>(this)->hasNoNaNs();
}
/// Determine whether the no-infs flag is set.
bool Instruction::hasNoInfs() const {
assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
return cast<FPMathOperator>(this)->hasNoInfs();
}
/// Determine whether the no-signed-zeros flag is set.
bool Instruction::hasNoSignedZeros() const {
assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
return cast<FPMathOperator>(this)->hasNoSignedZeros();
}
/// Determine whether the allow-reciprocal flag is set.
bool Instruction::hasAllowReciprocal() const {
assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
return cast<FPMathOperator>(this)->hasAllowReciprocal();
}
/// Convenience function for getting all the fast-math flags, which must be an
/// operator which supports these flags. See LangRef.html for the meaning of
/// these flags.
FastMathFlags Instruction::getFastMathFlags() const {
assert(isa<FPMathOperator>(this) && "getting fast-math flag on invalid op");
return cast<FPMathOperator>(this)->getFastMathFlags();
}
/// Copy I's fast-math flags
void Instruction::copyFastMathFlags(const Instruction *I) {
copyFastMathFlags(I->getFastMathFlags());
}
const char *Instruction::getOpcodeName(unsigned OpCode) {
switch (OpCode) {
// Terminators
case Ret: return "ret";
case Br: return "br";
case Switch: return "switch";
case IndirectBr: return "indirectbr";
case Invoke: return "invoke";
case Resume: return "resume";
case Unreachable: return "unreachable";
// Standard binary operators...
case Add: return "add";
case FAdd: return "fadd";
case Sub: return "sub";
case FSub: return "fsub";
case Mul: return "mul";
case FMul: return "fmul";
case UDiv: return "udiv";
case SDiv: return "sdiv";
case FDiv: return "fdiv";
case URem: return "urem";
case SRem: return "srem";
case FRem: return "frem";
// Logical operators...
case And: return "and";
case Or : return "or";
case Xor: return "xor";
// Memory instructions...
case Alloca: return "alloca";
case Load: return "load";
case Store: return "store";
case AtomicCmpXchg: return "cmpxchg";
case AtomicRMW: return "atomicrmw";
case Fence: return "fence";
case GetElementPtr: return "getelementptr";
// Convert instructions...
case Trunc: return "trunc";
case ZExt: return "zext";
case SExt: return "sext";
case FPTrunc: return "fptrunc";
case FPExt: return "fpext";
case FPToUI: return "fptoui";
case FPToSI: return "fptosi";
case UIToFP: return "uitofp";
case SIToFP: return "sitofp";
case IntToPtr: return "inttoptr";
case PtrToInt: return "ptrtoint";
case BitCast: return "bitcast";
case AddrSpaceCast: return "addrspacecast";
// Other instructions...
case ICmp: return "icmp";
case FCmp: return "fcmp";
case PHI: return "phi";
case Select: return "select";
case Call: return "call";
case Shl: return "shl";
case LShr: return "lshr";
case AShr: return "ashr";
case VAArg: return "va_arg";
case ExtractElement: return "extractelement";
case InsertElement: return "insertelement";
case ShuffleVector: return "shufflevector";
case ExtractValue: return "extractvalue";
case InsertValue: return "insertvalue";
case LandingPad: return "landingpad";
default: return "<Invalid operator> ";
}
}
/// Return true if both instructions have the same special state
/// This must be kept in sync with lib/Transforms/IPO/MergeFunctions.cpp.
static bool haveSameSpecialState(const Instruction *I1, const Instruction *I2,
bool IgnoreAlignment = false) {
assert(I1->getOpcode() == I2->getOpcode() &&
"Can not compare special state of different instructions");
if (const LoadInst *LI = dyn_cast<LoadInst>(I1))
return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() &&
(LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() ||
IgnoreAlignment) &&
LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() &&
LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope();
if (const StoreInst *SI = dyn_cast<StoreInst>(I1))
return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() &&
(SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() ||
IgnoreAlignment) &&
SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() &&
SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope();
if (const CmpInst *CI = dyn_cast<CmpInst>(I1))
return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate();
if (const CallInst *CI = dyn_cast<CallInst>(I1))
return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() &&
CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() &&
CI->getAttributes() == cast<CallInst>(I2)->getAttributes();
if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1))
return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() &&
CI->getAttributes() ==
cast<InvokeInst>(I2)->getAttributes();
if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1))
return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices();
if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1))
return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices();
if (const FenceInst *FI = dyn_cast<FenceInst>(I1))
return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() &&
FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope();
if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1))
return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() &&
CXI->isWeak() == cast<AtomicCmpXchgInst>(I2)->isWeak() &&
CXI->getSuccessOrdering() ==
cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() &&
CXI->getFailureOrdering() ==
cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() &&
CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope();
if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1))
return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() &&
RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() &&
RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() &&
RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope();
return true;
}
/// isIdenticalTo - Return true if the specified instruction is exactly
/// identical to the current one. This means that all operands match and any
/// extra information (e.g. load is volatile) agree.
bool Instruction::isIdenticalTo(const Instruction *I) const {
return isIdenticalToWhenDefined(I) &&
SubclassOptionalData == I->SubclassOptionalData;
}
/// isIdenticalToWhenDefined - This is like isIdenticalTo, except that it
/// ignores the SubclassOptionalData flags, which specify conditions
/// under which the instruction's result is undefined.
bool Instruction::isIdenticalToWhenDefined(const Instruction *I) const {
if (getOpcode() != I->getOpcode() ||
getNumOperands() != I->getNumOperands() ||
getType() != I->getType())
return false;
// If both instructions have no operands, they are identical.
if (getNumOperands() == 0 && I->getNumOperands() == 0)
return haveSameSpecialState(this, I);
// We have two instructions of identical opcode and #operands. Check to see
// if all operands are the same.
if (!std::equal(op_begin(), op_end(), I->op_begin()))
return false;
if (const PHINode *thisPHI = dyn_cast<PHINode>(this)) {
const PHINode *otherPHI = cast<PHINode>(I);
return std::equal(thisPHI->block_begin(), thisPHI->block_end(),
otherPHI->block_begin());
}
return haveSameSpecialState(this, I);
}
// isSameOperationAs
// This should be kept in sync with isEquivalentOperation in
// lib/Transforms/IPO/MergeFunctions.cpp.
bool Instruction::isSameOperationAs(const Instruction *I,
unsigned flags) const {
bool IgnoreAlignment = flags & CompareIgnoringAlignment;
bool UseScalarTypes = flags & CompareUsingScalarTypes;
if (getOpcode() != I->getOpcode() ||
getNumOperands() != I->getNumOperands() ||
(UseScalarTypes ?
getType()->getScalarType() != I->getType()->getScalarType() :
getType() != I->getType()))
return false;
// We have two instructions of identical opcode and #operands. Check to see
// if all operands are the same type
for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
if (UseScalarTypes ?
getOperand(i)->getType()->getScalarType() !=
I->getOperand(i)->getType()->getScalarType() :
getOperand(i)->getType() != I->getOperand(i)->getType())
return false;
return haveSameSpecialState(this, I, IgnoreAlignment);
}
/// isUsedOutsideOfBlock - Return true if there are any uses of I outside of the
/// specified block. Note that PHI nodes are considered to evaluate their
/// operands in the corresponding predecessor block.
bool Instruction::isUsedOutsideOfBlock(const BasicBlock *BB) const {
for (const Use &U : uses()) {
// PHI nodes uses values in the corresponding predecessor block. For other
// instructions, just check to see whether the parent of the use matches up.
const Instruction *I = cast<Instruction>(U.getUser());
const PHINode *PN = dyn_cast<PHINode>(I);
if (!PN) {
if (I->getParent() != BB)
return true;
continue;
}
if (PN->getIncomingBlock(U) != BB)
return true;
}
return false;
}
/// mayReadFromMemory - Return true if this instruction may read memory.
///
bool Instruction::mayReadFromMemory() const {
switch (getOpcode()) {
default: return false;
case Instruction::VAArg:
case Instruction::Load:
case Instruction::Fence: // FIXME: refine definition of mayReadFromMemory
case Instruction::AtomicCmpXchg:
case Instruction::AtomicRMW:
return true;
case Instruction::Call:
return !cast<CallInst>(this)->doesNotAccessMemory();
case Instruction::Invoke:
return !cast<InvokeInst>(this)->doesNotAccessMemory();
case Instruction::Store:
return !cast<StoreInst>(this)->isUnordered();
}
}
/// mayWriteToMemory - Return true if this instruction may modify memory.
///
bool Instruction::mayWriteToMemory() const {
switch (getOpcode()) {
default: return false;
case Instruction::Fence: // FIXME: refine definition of mayWriteToMemory
case Instruction::Store:
case Instruction::VAArg:
case Instruction::AtomicCmpXchg:
case Instruction::AtomicRMW:
return true;
case Instruction::Call:
return !cast<CallInst>(this)->onlyReadsMemory();
case Instruction::Invoke:
return !cast<InvokeInst>(this)->onlyReadsMemory();
case Instruction::Load:
return !cast<LoadInst>(this)->isUnordered();
}
}
bool Instruction::isAtomic() const {
switch (getOpcode()) {
default:
return false;
case Instruction::AtomicCmpXchg:
case Instruction::AtomicRMW:
case Instruction::Fence:
return true;
case Instruction::Load:
return cast<LoadInst>(this)->getOrdering() != NotAtomic;
case Instruction::Store:
return cast<StoreInst>(this)->getOrdering() != NotAtomic;
}
}
bool Instruction::mayThrow() const {
if (const CallInst *CI = dyn_cast<CallInst>(this))
return !CI->doesNotThrow();
return isa<ResumeInst>(this);
}
bool Instruction::mayReturn() const {
if (const CallInst *CI = dyn_cast<CallInst>(this))
return !CI->doesNotReturn();
return true;
}
/// isAssociative - Return true if the instruction is associative:
///
/// Associative operators satisfy: x op (y op z) === (x op y) op z
///
/// In LLVM, the Add, Mul, And, Or, and Xor operators are associative.
///
bool Instruction::isAssociative(unsigned Opcode) {
return Opcode == And || Opcode == Or || Opcode == Xor ||
Opcode == Add || Opcode == Mul;
}
bool Instruction::isAssociative() const {
unsigned Opcode = getOpcode();
if (isAssociative(Opcode))
return true;
switch (Opcode) {
case FMul:
case FAdd:
return cast<FPMathOperator>(this)->hasUnsafeAlgebra();
default:
return false;
}
}
/// isCommutative - Return true if the instruction is commutative:
///
/// Commutative operators satisfy: (x op y) === (y op x)
///
/// In LLVM, these are the associative operators, plus SetEQ and SetNE, when
/// applied to any type.
///
bool Instruction::isCommutative(unsigned op) {
switch (op) {
case Add:
case FAdd:
case Mul:
case FMul:
case And:
case Or:
case Xor:
return true;
default:
return false;
}
}
/// isIdempotent - Return true if the instruction is idempotent:
///
/// Idempotent operators satisfy: x op x === x
///
/// In LLVM, the And and Or operators are idempotent.
///
bool Instruction::isIdempotent(unsigned Opcode) {
return Opcode == And || Opcode == Or;
}
/// isNilpotent - Return true if the instruction is nilpotent:
///
/// Nilpotent operators satisfy: x op x === Id,
///
/// where Id is the identity for the operator, i.e. a constant such that
/// x op Id === x and Id op x === x for all x.
///
/// In LLVM, the Xor operator is nilpotent.
///
bool Instruction::isNilpotent(unsigned Opcode) {
return Opcode == Xor;
}
Instruction *Instruction::cloneImpl() const {
llvm_unreachable("Subclass of Instruction failed to implement cloneImpl");
}
Instruction *Instruction::clone() const {
Instruction *New = nullptr;
switch (getOpcode()) {
default:
llvm_unreachable("Unhandled Opcode.");
#define HANDLE_INST(num, opc, clas) \
case Instruction::opc: \
New = cast<clas>(this)->cloneImpl(); \
break;
#include "llvm/IR/Instruction.def"
#undef HANDLE_INST
}
New->SubclassOptionalData = SubclassOptionalData;
if (!hasMetadata())
return New;
// Otherwise, enumerate and copy over metadata from the old instruction to the
// new one.
SmallVector<std::pair<unsigned, MDNode *>, 4> TheMDs;
getAllMetadataOtherThanDebugLoc(TheMDs);
for (const auto &MD : TheMDs)
New->setMetadata(MD.first, MD.second);
New->setDebugLoc(getDebugLoc());
return New;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/Mangler.cpp | //===-- Mangler.cpp - Self-contained c/asm llvm name mangler --------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Unified name mangler for assembly backends.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Mangler.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
enum ManglerPrefixTy {
Default, ///< Emit default string before each symbol.
Private, ///< Emit "private" prefix before each symbol.
LinkerPrivate ///< Emit "linker private" prefix before each symbol.
};
}
static void getNameWithPrefixImpl(raw_ostream &OS, const Twine &GVName,
ManglerPrefixTy PrefixTy,
const DataLayout &DL, char Prefix) {
SmallString<256> TmpData;
StringRef Name = GVName.toStringRef(TmpData);
assert(!Name.empty() && "getNameWithPrefix requires non-empty name");
// No need to do anything special if the global has the special "do not
// mangle" flag in the name.
if (Name[0] == '\1') {
OS << Name.substr(1);
return;
}
if (PrefixTy == Private)
OS << DL.getPrivateGlobalPrefix();
else if (PrefixTy == LinkerPrivate)
OS << DL.getLinkerPrivateGlobalPrefix();
if (Prefix != '\0')
OS << Prefix;
// If this is a simple string that doesn't need escaping, just append it.
OS << Name;
}
static void getNameWithPrefixImpl(raw_ostream &OS, const Twine &GVName,
const DataLayout &DL,
ManglerPrefixTy PrefixTy) {
char Prefix = DL.getGlobalPrefix();
return getNameWithPrefixImpl(OS, GVName, PrefixTy, DL, Prefix);
}
void Mangler::getNameWithPrefix(raw_ostream &OS, const Twine &GVName,
const DataLayout &DL) {
return getNameWithPrefixImpl(OS, GVName, DL, Default);
}
void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
const Twine &GVName, const DataLayout &DL) {
raw_svector_ostream OS(OutName);
char Prefix = DL.getGlobalPrefix();
return getNameWithPrefixImpl(OS, GVName, Default, DL, Prefix);
}
static bool hasByteCountSuffix(CallingConv::ID CC) {
switch (CC) {
case CallingConv::X86_FastCall:
case CallingConv::X86_StdCall:
case CallingConv::X86_VectorCall:
return true;
default:
return false;
}
}
/// Microsoft fastcall and stdcall functions require a suffix on their name
/// indicating the number of words of arguments they take.
static void addByteCountSuffix(raw_ostream &OS, const Function *F,
const DataLayout &DL) {
// Calculate arguments size total.
unsigned ArgWords = 0;
for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
AI != AE; ++AI) {
Type *Ty = AI->getType();
// 'Dereference' type in case of byval or inalloca parameter attribute.
if (AI->hasByValOrInAllocaAttr())
Ty = cast<PointerType>(Ty)->getElementType();
// Size should be aligned to pointer size.
unsigned PtrSize = DL.getPointerSize();
ArgWords += RoundUpToAlignment(DL.getTypeAllocSize(Ty), PtrSize);
}
OS << '@' << ArgWords;
}
void Mangler::getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV,
bool CannotUsePrivateLabel) const {
ManglerPrefixTy PrefixTy = Default;
if (GV->hasPrivateLinkage()) {
if (CannotUsePrivateLabel)
PrefixTy = LinkerPrivate;
else
PrefixTy = Private;
}
const DataLayout &DL = GV->getParent()->getDataLayout();
if (!GV->hasName()) {
// Get the ID for the global, assigning a new one if we haven't got one
// already.
unsigned &ID = AnonGlobalIDs[GV];
if (ID == 0)
ID = NextAnonGlobalID++;
// Must mangle the global into a unique ID.
getNameWithPrefixImpl(OS, "__unnamed_" + Twine(ID), DL, PrefixTy);
return;
}
StringRef Name = GV->getName();
char Prefix = DL.getGlobalPrefix();
// Mangle functions with Microsoft calling conventions specially. Only do
// this mangling for x86_64 vectorcall and 32-bit x86.
const Function *MSFunc = dyn_cast<Function>(GV);
if (Name.startswith("\01"))
MSFunc = nullptr; // Don't mangle when \01 is present.
CallingConv::ID CC =
MSFunc ? MSFunc->getCallingConv() : (unsigned)CallingConv::C;
if (!DL.hasMicrosoftFastStdCallMangling() &&
CC != CallingConv::X86_VectorCall)
MSFunc = nullptr;
if (MSFunc) {
if (CC == CallingConv::X86_FastCall)
Prefix = '@'; // fastcall functions have an @ prefix instead of _.
else if (CC == CallingConv::X86_VectorCall)
Prefix = '\0'; // vectorcall functions have no prefix.
}
getNameWithPrefixImpl(OS, Name, PrefixTy, DL, Prefix);
if (!MSFunc)
return;
// If we are supposed to add a microsoft-style suffix for stdcall, fastcall,
// or vectorcall, add it. These functions have a suffix of @N where N is the
// cumulative byte size of all of the parameters to the function in decimal.
if (CC == CallingConv::X86_VectorCall)
OS << '@'; // vectorcall functions use a double @ suffix.
FunctionType *FT = MSFunc->getFunctionType();
if (hasByteCountSuffix(CC) &&
// "Pure" variadic functions do not receive @0 suffix.
(!FT->isVarArg() || FT->getNumParams() == 0 ||
(FT->getNumParams() == 1 && MSFunc->hasStructRetAttr())))
addByteCountSuffix(OS, MSFunc, DL);
}
void Mangler::getNameWithPrefix(SmallVectorImpl<char> &OutName,
const GlobalValue *GV,
bool CannotUsePrivateLabel) const {
raw_svector_ostream OS(OutName);
getNameWithPrefix(OS, GV, CannotUsePrivateLabel);
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/LLVMContext.cpp | //===-- LLVMContext.cpp - Implement LLVMContext ---------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements LLVMContext, as a wrapper around the opaque
// class LLVMContextImpl.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/LLVMContext.h"
#include "LLVMContextImpl.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Metadata.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/SourceMgr.h"
#include <cctype>
using namespace llvm;
static ManagedStatic<LLVMContext> GlobalContext;
LLVMContext& llvm::getGlobalContext() {
return *GlobalContext;
}
LLVMContext::LLVMContext() : pImpl(new LLVMContextImpl(*this)) {
std::unique_ptr<LLVMContextImpl> implPtrGuard(pImpl); // HLSL Change: Don't leak if constructor throws.
// Create the fixed metadata kinds. This is done in the same order as the
// MD_* enum values so that they correspond.
// Create the 'dbg' metadata kind.
unsigned DbgID = getMDKindID("dbg");
assert(DbgID == MD_dbg && "dbg kind id drifted"); (void)DbgID;
// Create the 'tbaa' metadata kind.
unsigned TBAAID = getMDKindID("tbaa");
assert(TBAAID == MD_tbaa && "tbaa kind id drifted"); (void)TBAAID;
// Create the 'prof' metadata kind.
unsigned ProfID = getMDKindID("prof");
assert(ProfID == MD_prof && "prof kind id drifted"); (void)ProfID;
// Create the 'fpmath' metadata kind.
unsigned FPAccuracyID = getMDKindID("fpmath");
assert(FPAccuracyID == MD_fpmath && "fpmath kind id drifted");
(void)FPAccuracyID;
// Create the 'range' metadata kind.
unsigned RangeID = getMDKindID("range");
assert(RangeID == MD_range && "range kind id drifted");
(void)RangeID;
// Create the 'tbaa.struct' metadata kind.
unsigned TBAAStructID = getMDKindID("tbaa.struct");
assert(TBAAStructID == MD_tbaa_struct && "tbaa.struct kind id drifted");
(void)TBAAStructID;
// Create the 'invariant.load' metadata kind.
unsigned InvariantLdId = getMDKindID("invariant.load");
assert(InvariantLdId == MD_invariant_load && "invariant.load kind id drifted");
(void)InvariantLdId;
// Create the 'alias.scope' metadata kind.
unsigned AliasScopeID = getMDKindID("alias.scope");
assert(AliasScopeID == MD_alias_scope && "alias.scope kind id drifted");
(void)AliasScopeID;
// Create the 'noalias' metadata kind.
unsigned NoAliasID = getMDKindID("noalias");
assert(NoAliasID == MD_noalias && "noalias kind id drifted");
(void)NoAliasID;
// Create the 'nontemporal' metadata kind.
unsigned NonTemporalID = getMDKindID("nontemporal");
assert(NonTemporalID == MD_nontemporal && "nontemporal kind id drifted");
(void)NonTemporalID;
// Create the 'llvm.mem.parallel_loop_access' metadata kind.
unsigned MemParallelLoopAccessID = getMDKindID("llvm.mem.parallel_loop_access");
assert(MemParallelLoopAccessID == MD_mem_parallel_loop_access &&
"mem_parallel_loop_access kind id drifted");
(void)MemParallelLoopAccessID;
// Create the 'nonnull' metadata kind.
unsigned NonNullID = getMDKindID("nonnull");
assert(NonNullID == MD_nonnull && "nonnull kind id drifted");
(void)NonNullID;
// Create the 'dereferenceable' metadata kind.
unsigned DereferenceableID = getMDKindID("dereferenceable");
assert(DereferenceableID == MD_dereferenceable &&
"dereferenceable kind id drifted");
(void)DereferenceableID;
// Create the 'dereferenceable_or_null' metadata kind.
unsigned DereferenceableOrNullID = getMDKindID("dereferenceable_or_null");
assert(DereferenceableOrNullID == MD_dereferenceable_or_null &&
"dereferenceable_or_null kind id drifted");
(void)DereferenceableOrNullID;
implPtrGuard.release(); // HLSL Change: Destructor now on the hook for destruction
}
LLVMContext::~LLVMContext() { delete pImpl; }
void LLVMContext::addModule(Module *M) {
pImpl->OwnedModules.insert(M);
}
void LLVMContext::removeModule(Module *M) {
pImpl->OwnedModules.erase(M);
}
//===----------------------------------------------------------------------===//
// Recoverable Backend Errors
//===----------------------------------------------------------------------===//
void LLVMContext::
setInlineAsmDiagnosticHandler(InlineAsmDiagHandlerTy DiagHandler,
void *DiagContext) {
pImpl->InlineAsmDiagHandler = DiagHandler;
pImpl->InlineAsmDiagContext = DiagContext;
}
/// getInlineAsmDiagnosticHandler - Return the diagnostic handler set by
/// setInlineAsmDiagnosticHandler.
LLVMContext::InlineAsmDiagHandlerTy
LLVMContext::getInlineAsmDiagnosticHandler() const {
return pImpl->InlineAsmDiagHandler;
}
/// getInlineAsmDiagnosticContext - Return the diagnostic context set by
/// setInlineAsmDiagnosticHandler.
void *LLVMContext::getInlineAsmDiagnosticContext() const {
return pImpl->InlineAsmDiagContext;
}
void LLVMContext::setDiagnosticHandler(DiagnosticHandlerTy DiagnosticHandler,
void *DiagnosticContext,
bool RespectFilters) {
pImpl->DiagnosticHandler = DiagnosticHandler;
pImpl->DiagnosticContext = DiagnosticContext;
pImpl->RespectDiagnosticFilters = RespectFilters;
}
LLVMContext::DiagnosticHandlerTy LLVMContext::getDiagnosticHandler() const {
return pImpl->DiagnosticHandler;
}
void *LLVMContext::getDiagnosticContext() const {
return pImpl->DiagnosticContext;
}
void LLVMContext::setYieldCallback(YieldCallbackTy Callback, void *OpaqueHandle)
{
pImpl->YieldCallback = Callback;
pImpl->YieldOpaqueHandle = OpaqueHandle;
}
void LLVMContext::yield() {
if (pImpl->YieldCallback)
pImpl->YieldCallback(this, pImpl->YieldOpaqueHandle);
}
void LLVMContext::emitError(const Twine &ErrorStr) {
diagnose(DiagnosticInfoInlineAsm(ErrorStr));
}
// HLSL Change Start
void LLVMContext::emitWarning(const Twine &WarningStr) {
diagnose(DiagnosticInfoInlineAsm(WarningStr, DiagnosticSeverity::DS_Warning));
}
// HLSL Change End
void LLVMContext::emitError(const Instruction *I, const Twine &ErrorStr) {
assert (I && "Invalid instruction");
diagnose(DiagnosticInfoInlineAsm(*I, ErrorStr));
}
static bool isDiagnosticEnabled(const DiagnosticInfo &DI) {
// Optimization remarks are selective. They need to check whether the regexp
// pattern, passed via one of the -pass-remarks* flags, matches the name of
// the pass that is emitting the diagnostic. If there is no match, ignore the
// diagnostic and return.
switch (DI.getKind()) {
case llvm::DK_OptimizationRemark:
if (!cast<DiagnosticInfoOptimizationRemark>(DI).isEnabled())
return false;
break;
case llvm::DK_OptimizationRemarkMissed:
if (!cast<DiagnosticInfoOptimizationRemarkMissed>(DI).isEnabled())
return false;
break;
case llvm::DK_OptimizationRemarkAnalysis:
if (!cast<DiagnosticInfoOptimizationRemarkAnalysis>(DI).isEnabled())
return false;
break;
default:
break;
}
return true;
}
static const char *getDiagnosticMessagePrefix(DiagnosticSeverity Severity) {
switch (Severity) {
case DS_Error:
return "error";
case DS_Warning:
return "warning";
case DS_Remark:
return "remark";
case DS_Note:
return "note";
}
llvm_unreachable("Unknown DiagnosticSeverity");
}
void LLVMContext::diagnose(const DiagnosticInfo &DI) {
// If there is a report handler, use it.
if (pImpl->DiagnosticHandler) {
if (!pImpl->RespectDiagnosticFilters || isDiagnosticEnabled(DI))
pImpl->DiagnosticHandler(DI, pImpl->DiagnosticContext);
return;
}
if (!isDiagnosticEnabled(DI))
return;
// Otherwise, print the message with a prefix based on the severity.
DiagnosticPrinterRawOStream DP(errs());
errs() << getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
DI.print(DP);
errs() << "\n";
if (DI.getSeverity() == DS_Error)
// exit(1); // HLSL Change - unwind if necessary, but don't terminate the process
throw std::exception();
}
void LLVMContext::emitError(unsigned LocCookie, const Twine &ErrorStr) {
diagnose(DiagnosticInfoInlineAsm(LocCookie, ErrorStr));
}
//===----------------------------------------------------------------------===//
// Metadata Kind Uniquing
//===----------------------------------------------------------------------===//
// HLSL Change - Begin
/// Return a unique non-zero ID for the specified metadata kind if it exists.
bool LLVMContext::findMDKindID(StringRef Name, unsigned *ID) const {
auto it = pImpl->CustomMDKindNames.find(Name);
if (it != pImpl->CustomMDKindNames.end()) {
*ID = it->second;
return true;
}
return false;
}
// HLSL Change - End
/// Return a unique non-zero ID for the specified metadata kind.
unsigned LLVMContext::getMDKindID(StringRef Name) const {
// If this is new, assign it its ID.
return pImpl->CustomMDKindNames.insert(
std::make_pair(
Name, pImpl->CustomMDKindNames.size()))
.first->second;
}
/// getHandlerNames - Populate client supplied smallvector using custome
/// metadata name and ID.
void LLVMContext::getMDKindNames(SmallVectorImpl<StringRef> &Names) const {
Names.resize(pImpl->CustomMDKindNames.size());
for (StringMap<unsigned>::const_iterator I = pImpl->CustomMDKindNames.begin(),
E = pImpl->CustomMDKindNames.end(); I != E; ++I)
Names[I->second] = I->first();
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/ValueTypes.cpp | //===----------- ValueTypes.cpp - Implementation of EVT methods -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements methods in the CodeGen/ValueTypes.h header.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
EVT EVT::changeExtendedVectorElementTypeToInteger() const {
LLVMContext &Context = LLVMTy->getContext();
EVT IntTy = getIntegerVT(Context, getVectorElementType().getSizeInBits());
return getVectorVT(Context, IntTy, getVectorNumElements());
}
EVT EVT::getExtendedIntegerVT(LLVMContext &Context, unsigned BitWidth) {
EVT VT;
VT.LLVMTy = IntegerType::get(Context, BitWidth);
assert(VT.isExtended() && "Type is not extended!");
return VT;
}
EVT EVT::getExtendedVectorVT(LLVMContext &Context, EVT VT,
unsigned NumElements) {
EVT ResultVT;
ResultVT.LLVMTy = VectorType::get(VT.getTypeForEVT(Context), NumElements);
assert(ResultVT.isExtended() && "Type is not extended!");
return ResultVT;
}
bool EVT::isExtendedFloatingPoint() const {
assert(isExtended() && "Type is not extended!");
return LLVMTy->isFPOrFPVectorTy();
}
bool EVT::isExtendedInteger() const {
assert(isExtended() && "Type is not extended!");
return LLVMTy->isIntOrIntVectorTy();
}
bool EVT::isExtendedVector() const {
assert(isExtended() && "Type is not extended!");
return LLVMTy->isVectorTy();
}
bool EVT::isExtended16BitVector() const {
return isExtendedVector() && getExtendedSizeInBits() == 16;
}
bool EVT::isExtended32BitVector() const {
return isExtendedVector() && getExtendedSizeInBits() == 32;
}
bool EVT::isExtended64BitVector() const {
return isExtendedVector() && getExtendedSizeInBits() == 64;
}
bool EVT::isExtended128BitVector() const {
return isExtendedVector() && getExtendedSizeInBits() == 128;
}
bool EVT::isExtended256BitVector() const {
return isExtendedVector() && getExtendedSizeInBits() == 256;
}
bool EVT::isExtended512BitVector() const {
return isExtendedVector() && getExtendedSizeInBits() == 512;
}
bool EVT::isExtended1024BitVector() const {
return isExtendedVector() && getExtendedSizeInBits() == 1024;
}
EVT EVT::getExtendedVectorElementType() const {
assert(isExtended() && "Type is not extended!");
return EVT::getEVT(cast<VectorType>(LLVMTy)->getElementType());
}
unsigned EVT::getExtendedVectorNumElements() const {
assert(isExtended() && "Type is not extended!");
return cast<VectorType>(LLVMTy)->getNumElements();
}
unsigned EVT::getExtendedSizeInBits() const {
assert(isExtended() && "Type is not extended!");
if (IntegerType *ITy = dyn_cast<IntegerType>(LLVMTy))
return ITy->getBitWidth();
if (VectorType *VTy = dyn_cast<VectorType>(LLVMTy))
return VTy->getBitWidth();
llvm_unreachable("Unrecognized extended type!");
}
/// getEVTString - This function returns value type as a string, e.g. "i32".
std::string EVT::getEVTString() const {
switch (V.SimpleTy) {
default:
if (isVector())
return "v" + utostr(getVectorNumElements()) +
getVectorElementType().getEVTString();
if (isInteger())
return "i" + utostr(getSizeInBits());
llvm_unreachable("Invalid EVT!");
case MVT::i1: return "i1";
case MVT::i8: return "i8";
case MVT::i16: return "i16";
case MVT::i32: return "i32";
case MVT::i64: return "i64";
case MVT::i128: return "i128";
case MVT::f16: return "f16";
case MVT::f32: return "f32";
case MVT::f64: return "f64";
case MVT::f80: return "f80";
case MVT::f128: return "f128";
case MVT::ppcf128: return "ppcf128";
case MVT::isVoid: return "isVoid";
case MVT::Other: return "ch";
case MVT::Glue: return "glue";
case MVT::x86mmx: return "x86mmx";
case MVT::v2i1: return "v2i1";
case MVT::v4i1: return "v4i1";
case MVT::v8i1: return "v8i1";
case MVT::v16i1: return "v16i1";
case MVT::v32i1: return "v32i1";
case MVT::v64i1: return "v64i1";
case MVT::v1i8: return "v1i8";
case MVT::v2i8: return "v2i8";
case MVT::v4i8: return "v4i8";
case MVT::v8i8: return "v8i8";
case MVT::v16i8: return "v16i8";
case MVT::v32i8: return "v32i8";
case MVT::v64i8: return "v64i8";
case MVT::v1i16: return "v1i16";
case MVT::v2i16: return "v2i16";
case MVT::v4i16: return "v4i16";
case MVT::v8i16: return "v8i16";
case MVT::v16i16: return "v16i16";
case MVT::v32i16: return "v32i16";
case MVT::v1i32: return "v1i32";
case MVT::v2i32: return "v2i32";
case MVT::v4i32: return "v4i32";
case MVT::v8i32: return "v8i32";
case MVT::v16i32: return "v16i32";
case MVT::v1i64: return "v1i64";
case MVT::v2i64: return "v2i64";
case MVT::v4i64: return "v4i64";
case MVT::v8i64: return "v8i64";
case MVT::v16i64: return "v16i64";
case MVT::v1i128: return "v1i128";
case MVT::v1f32: return "v1f32";
case MVT::v2f32: return "v2f32";
case MVT::v2f16: return "v2f16";
case MVT::v4f16: return "v4f16";
case MVT::v8f16: return "v8f16";
case MVT::v4f32: return "v4f32";
case MVT::v8f32: return "v8f32";
case MVT::v16f32: return "v16f32";
case MVT::v1f64: return "v1f64";
case MVT::v2f64: return "v2f64";
case MVT::v4f64: return "v4f64";
case MVT::v8f64: return "v8f64";
case MVT::Metadata:return "Metadata";
case MVT::Untyped: return "Untyped";
}
}
/// getTypeForEVT - This method returns an LLVM type corresponding to the
/// specified EVT. For integer types, this returns an unsigned type. Note
/// that this will abort for types that cannot be represented.
Type *EVT::getTypeForEVT(LLVMContext &Context) const {
switch (V.SimpleTy) {
default:
assert(isExtended() && "Type is not extended!");
return LLVMTy;
case MVT::isVoid: return Type::getVoidTy(Context);
case MVT::i1: return Type::getInt1Ty(Context);
case MVT::i8: return Type::getInt8Ty(Context);
case MVT::i16: return Type::getInt16Ty(Context);
case MVT::i32: return Type::getInt32Ty(Context);
case MVT::i64: return Type::getInt64Ty(Context);
case MVT::i128: return IntegerType::get(Context, 128);
case MVT::f16: return Type::getHalfTy(Context);
case MVT::f32: return Type::getFloatTy(Context);
case MVT::f64: return Type::getDoubleTy(Context);
case MVT::f80: return Type::getX86_FP80Ty(Context);
case MVT::f128: return Type::getFP128Ty(Context);
case MVT::ppcf128: return Type::getPPC_FP128Ty(Context);
case MVT::x86mmx: return Type::getX86_MMXTy(Context);
case MVT::v2i1: return VectorType::get(Type::getInt1Ty(Context), 2);
case MVT::v4i1: return VectorType::get(Type::getInt1Ty(Context), 4);
case MVT::v8i1: return VectorType::get(Type::getInt1Ty(Context), 8);
case MVT::v16i1: return VectorType::get(Type::getInt1Ty(Context), 16);
case MVT::v32i1: return VectorType::get(Type::getInt1Ty(Context), 32);
case MVT::v64i1: return VectorType::get(Type::getInt1Ty(Context), 64);
case MVT::v1i8: return VectorType::get(Type::getInt8Ty(Context), 1);
case MVT::v2i8: return VectorType::get(Type::getInt8Ty(Context), 2);
case MVT::v4i8: return VectorType::get(Type::getInt8Ty(Context), 4);
case MVT::v8i8: return VectorType::get(Type::getInt8Ty(Context), 8);
case MVT::v16i8: return VectorType::get(Type::getInt8Ty(Context), 16);
case MVT::v32i8: return VectorType::get(Type::getInt8Ty(Context), 32);
case MVT::v64i8: return VectorType::get(Type::getInt8Ty(Context), 64);
case MVT::v1i16: return VectorType::get(Type::getInt16Ty(Context), 1);
case MVT::v2i16: return VectorType::get(Type::getInt16Ty(Context), 2);
case MVT::v4i16: return VectorType::get(Type::getInt16Ty(Context), 4);
case MVT::v8i16: return VectorType::get(Type::getInt16Ty(Context), 8);
case MVT::v16i16: return VectorType::get(Type::getInt16Ty(Context), 16);
case MVT::v32i16: return VectorType::get(Type::getInt16Ty(Context), 32);
case MVT::v1i32: return VectorType::get(Type::getInt32Ty(Context), 1);
case MVT::v2i32: return VectorType::get(Type::getInt32Ty(Context), 2);
case MVT::v4i32: return VectorType::get(Type::getInt32Ty(Context), 4);
case MVT::v8i32: return VectorType::get(Type::getInt32Ty(Context), 8);
case MVT::v16i32: return VectorType::get(Type::getInt32Ty(Context), 16);
case MVT::v1i64: return VectorType::get(Type::getInt64Ty(Context), 1);
case MVT::v2i64: return VectorType::get(Type::getInt64Ty(Context), 2);
case MVT::v4i64: return VectorType::get(Type::getInt64Ty(Context), 4);
case MVT::v8i64: return VectorType::get(Type::getInt64Ty(Context), 8);
case MVT::v16i64: return VectorType::get(Type::getInt64Ty(Context), 16);
case MVT::v1i128: return VectorType::get(Type::getInt128Ty(Context), 1);
case MVT::v2f16: return VectorType::get(Type::getHalfTy(Context), 2);
case MVT::v4f16: return VectorType::get(Type::getHalfTy(Context), 4);
case MVT::v8f16: return VectorType::get(Type::getHalfTy(Context), 8);
case MVT::v1f32: return VectorType::get(Type::getFloatTy(Context), 1);
case MVT::v2f32: return VectorType::get(Type::getFloatTy(Context), 2);
case MVT::v4f32: return VectorType::get(Type::getFloatTy(Context), 4);
case MVT::v8f32: return VectorType::get(Type::getFloatTy(Context), 8);
case MVT::v16f32: return VectorType::get(Type::getFloatTy(Context), 16);
case MVT::v1f64: return VectorType::get(Type::getDoubleTy(Context), 1);
case MVT::v2f64: return VectorType::get(Type::getDoubleTy(Context), 2);
case MVT::v4f64: return VectorType::get(Type::getDoubleTy(Context), 4);
case MVT::v8f64: return VectorType::get(Type::getDoubleTy(Context), 8);
case MVT::Metadata: return Type::getMetadataTy(Context);
}
}
/// Return the value type corresponding to the specified type. This returns all
/// pointers as MVT::iPTR. If HandleUnknown is true, unknown types are returned
/// as Other, otherwise they are invalid.
MVT MVT::getVT(Type *Ty, bool HandleUnknown){
switch (Ty->getTypeID()) {
default:
if (HandleUnknown) return MVT(MVT::Other);
llvm_unreachable("Unknown type!");
case Type::VoidTyID:
return MVT::isVoid;
case Type::IntegerTyID:
return getIntegerVT(cast<IntegerType>(Ty)->getBitWidth());
case Type::HalfTyID: return MVT(MVT::f16);
case Type::FloatTyID: return MVT(MVT::f32);
case Type::DoubleTyID: return MVT(MVT::f64);
case Type::X86_FP80TyID: return MVT(MVT::f80);
case Type::X86_MMXTyID: return MVT(MVT::x86mmx);
case Type::FP128TyID: return MVT(MVT::f128);
case Type::PPC_FP128TyID: return MVT(MVT::ppcf128);
case Type::PointerTyID: return MVT(MVT::iPTR);
case Type::VectorTyID: {
VectorType *VTy = cast<VectorType>(Ty);
return getVectorVT(
getVT(VTy->getElementType(), false), VTy->getNumElements());
}
}
}
/// getEVT - Return the value type corresponding to the specified type. This
/// returns all pointers as MVT::iPTR. If HandleUnknown is true, unknown types
/// are returned as Other, otherwise they are invalid.
EVT EVT::getEVT(Type *Ty, bool HandleUnknown){
switch (Ty->getTypeID()) {
default:
return MVT::getVT(Ty, HandleUnknown);
case Type::IntegerTyID:
return getIntegerVT(Ty->getContext(), cast<IntegerType>(Ty)->getBitWidth());
case Type::VectorTyID: {
VectorType *VTy = cast<VectorType>(Ty);
return getVectorVT(Ty->getContext(), getEVT(VTy->getElementType(), false),
VTy->getNumElements());
}
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/DiagnosticPrinter.cpp | //===- llvm/Support/DiagnosticInfo.cpp - Diagnostic Definitions -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a diagnostic printer relying on raw_ostream.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Twine.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
using namespace llvm;
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(char C) {
Stream << C;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(unsigned char C) {
Stream << C;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(signed char C) {
Stream << C;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(StringRef Str) {
Stream << Str;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(const char *Str) {
Stream << Str;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(
const std::string &Str) {
Stream << Str;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(unsigned long N) {
Stream << N;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(long N) {
Stream << N;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(
unsigned long long N) {
Stream << N;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(long long N) {
Stream << N;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(const void *P) {
Stream << P;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(unsigned int N) {
Stream << N;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(int N) {
Stream << N;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(double N) {
Stream << N;
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(const Twine &Str) {
Str.print(Stream);
return *this;
}
// HLSL Change Starts
DiagnosticPrinter &DiagnosticPrinterRawOStream::
operator<<(std::ios_base &(*iomanip)(std::ios_base &)) {
Stream << iomanip;
return *this;
}
// HLSL Change Ends.
// IR related types.
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(const Value &V) {
Stream << V.getName();
return *this;
}
DiagnosticPrinter &DiagnosticPrinterRawOStream::operator<<(const Module &M) {
Stream << M.getModuleIdentifier();
return *this;
}
// Other types.
DiagnosticPrinter &DiagnosticPrinterRawOStream::
operator<<(const SMDiagnostic &Diag) {
// We don't have to print the SMDiagnostic kind, as the diagnostic severity
// is printed by the diagnostic handler.
Diag.print("", Stream, /*ShowColors=*/true, /*ShowKindLabel=*/false);
return *this;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/MDBuilder.cpp | //===---- llvm/MDBuilder.cpp - Builder for LLVM metadata ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the MDBuilder class, which is used as a convenient way to
// create LLVM metadata with a consistent and simplified interface.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Metadata.h"
using namespace llvm;
MDString *MDBuilder::createString(StringRef Str) {
return MDString::get(Context, Str);
}
ConstantAsMetadata *MDBuilder::createConstant(Constant *C) {
return ConstantAsMetadata::get(C);
}
MDNode *MDBuilder::createFPMath(float Accuracy) {
if (Accuracy == 0.0)
return nullptr;
assert(Accuracy > 0.0 && "Invalid fpmath accuracy!");
auto *Op =
createConstant(ConstantFP::get(Type::getFloatTy(Context), Accuracy));
return MDNode::get(Context, Op);
}
MDNode *MDBuilder::createBranchWeights(uint32_t TrueWeight,
uint32_t FalseWeight) {
uint32_t Weights[] = {TrueWeight, FalseWeight};
return createBranchWeights(Weights);
}
MDNode *MDBuilder::createBranchWeights(ArrayRef<uint32_t> Weights) {
assert(Weights.size() >= 2 && "Need at least two branch weights!");
SmallVector<Metadata *, 4> Vals(Weights.size() + 1);
Vals[0] = createString("branch_weights");
Type *Int32Ty = Type::getInt32Ty(Context);
for (unsigned i = 0, e = Weights.size(); i != e; ++i)
Vals[i + 1] = createConstant(ConstantInt::get(Int32Ty, Weights[i]));
return MDNode::get(Context, Vals);
}
MDNode *MDBuilder::createFunctionEntryCount(uint64_t Count) {
SmallVector<Metadata *, 2> Vals(2);
Vals[0] = createString("function_entry_count");
Type *Int64Ty = Type::getInt64Ty(Context);
Vals[1] = createConstant(ConstantInt::get(Int64Ty, Count));
return MDNode::get(Context, Vals);
}
MDNode *MDBuilder::createRange(const APInt &Lo, const APInt &Hi) {
assert(Lo.getBitWidth() == Hi.getBitWidth() && "Mismatched bitwidths!");
Type *Ty = IntegerType::get(Context, Lo.getBitWidth());
return createRange(ConstantInt::get(Ty, Lo), ConstantInt::get(Ty, Hi));
}
MDNode *MDBuilder::createRange(Constant *Lo, Constant *Hi) {
// If the range is everything then it is useless.
if (Hi == Lo)
return nullptr;
// Return the range [Lo, Hi).
Metadata *Range[2] = {createConstant(Lo), createConstant(Hi)};
return MDNode::get(Context, Range);
}
MDNode *MDBuilder::createAnonymousAARoot(StringRef Name, MDNode *Extra) {
// To ensure uniqueness the root node is self-referential.
auto Dummy = MDNode::getTemporary(Context, None);
SmallVector<Metadata *, 3> Args(1, Dummy.get());
if (Extra)
Args.push_back(Extra);
if (!Name.empty())
Args.push_back(createString(Name));
MDNode *Root = MDNode::get(Context, Args);
// At this point we have
// !0 = metadata !{} <- dummy
// !1 = metadata !{metadata !0} <- root
// Replace the dummy operand with the root node itself and delete the dummy.
Root->replaceOperandWith(0, Root);
// We now have
// !1 = metadata !{metadata !1} <- self-referential root
return Root;
}
MDNode *MDBuilder::createTBAARoot(StringRef Name) {
return MDNode::get(Context, createString(Name));
}
/// \brief Return metadata for a non-root TBAA node with the given name,
/// parent in the TBAA tree, and value for 'pointsToConstantMemory'.
MDNode *MDBuilder::createTBAANode(StringRef Name, MDNode *Parent,
bool isConstant) {
if (isConstant) {
Constant *Flags = ConstantInt::get(Type::getInt64Ty(Context), 1);
Metadata *Ops[3] = {createString(Name), Parent, createConstant(Flags)};
return MDNode::get(Context, Ops);
} else {
Metadata *Ops[2] = {createString(Name), Parent};
return MDNode::get(Context, Ops);
}
}
MDNode *MDBuilder::createAliasScopeDomain(StringRef Name) {
return MDNode::get(Context, createString(Name));
}
MDNode *MDBuilder::createAliasScope(StringRef Name, MDNode *Domain) {
Metadata *Ops[2] = {createString(Name), Domain};
return MDNode::get(Context, Ops);
}
/// \brief Return metadata for a tbaa.struct node with the given
/// struct field descriptions.
MDNode *MDBuilder::createTBAAStructNode(ArrayRef<TBAAStructField> Fields) {
SmallVector<Metadata *, 4> Vals(Fields.size() * 3);
Type *Int64 = Type::getInt64Ty(Context);
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
Vals[i * 3 + 0] = createConstant(ConstantInt::get(Int64, Fields[i].Offset));
Vals[i * 3 + 1] = createConstant(ConstantInt::get(Int64, Fields[i].Size));
Vals[i * 3 + 2] = Fields[i].TBAA;
}
return MDNode::get(Context, Vals);
}
/// \brief Return metadata for a TBAA struct node in the type DAG
/// with the given name, a list of pairs (offset, field type in the type DAG).
MDNode *MDBuilder::createTBAAStructTypeNode(
StringRef Name, ArrayRef<std::pair<MDNode *, uint64_t>> Fields) {
SmallVector<Metadata *, 4> Ops(Fields.size() * 2 + 1);
Type *Int64 = Type::getInt64Ty(Context);
Ops[0] = createString(Name);
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
Ops[i * 2 + 1] = Fields[i].first;
Ops[i * 2 + 2] = createConstant(ConstantInt::get(Int64, Fields[i].second));
}
return MDNode::get(Context, Ops);
}
/// \brief Return metadata for a TBAA scalar type node with the
/// given name, an offset and a parent in the TBAA type DAG.
MDNode *MDBuilder::createTBAAScalarTypeNode(StringRef Name, MDNode *Parent,
uint64_t Offset) {
ConstantInt *Off = ConstantInt::get(Type::getInt64Ty(Context), Offset);
Metadata *Ops[3] = {createString(Name), Parent, createConstant(Off)};
return MDNode::get(Context, Ops);
}
/// \brief Return metadata for a TBAA tag node with the given
/// base type, access type and offset relative to the base type.
MDNode *MDBuilder::createTBAAStructTagNode(MDNode *BaseType, MDNode *AccessType,
uint64_t Offset, bool IsConstant) {
Type *Int64 = Type::getInt64Ty(Context);
if (IsConstant) {
Metadata *Ops[4] = {BaseType, AccessType,
createConstant(ConstantInt::get(Int64, Offset)),
createConstant(ConstantInt::get(Int64, 1))};
return MDNode::get(Context, Ops);
} else {
Metadata *Ops[3] = {BaseType, AccessType,
createConstant(ConstantInt::get(Int64, Offset))};
return MDNode::get(Context, Ops);
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/AsmWriter.cpp | //===-- AsmWriter.cpp - Printing LLVM as an assembly file -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This library implements the functionality defined in llvm/IR/Writer.h
//
// Note that these routines must be extremely tolerant of various errors in the
// LLVM code, because it can be used for debugging transformations.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/AssemblyAnnotationWriter.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ModuleSlotTracker.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Statepoint.h"
#include "llvm/IR/TypeFinder.h"
#include "llvm/IR/UseListOrder.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cctype>
using namespace llvm;
// Make virtual table appear in this compilation unit.
AssemblyAnnotationWriter::~AssemblyAnnotationWriter() {}
//===----------------------------------------------------------------------===//
// Helper Functions
//===----------------------------------------------------------------------===//
namespace {
struct OrderMap {
DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
unsigned size() const { return IDs.size(); }
std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
std::pair<unsigned, bool> lookup(const Value *V) const {
return IDs.lookup(V);
}
void index(const Value *V) {
// Explicitly sequence get-size and insert-value operations to avoid UB.
unsigned ID = IDs.size() + 1;
IDs[V].first = ID;
}
};
}
static void orderValue(const Value *V, OrderMap &OM) {
if (OM.lookup(V).first)
return;
if (const Constant *C = dyn_cast<Constant>(V))
if (C->getNumOperands() && !isa<GlobalValue>(C))
for (const Value *Op : C->operands())
if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
orderValue(Op, OM);
// Note: we cannot cache this lookup above, since inserting into the map
// changes the map's size, and thus affects the other IDs.
OM.index(V);
}
static OrderMap orderModule(const Module *M) {
// This needs to match the order used by ValueEnumerator::ValueEnumerator()
// and ValueEnumerator::incorporateFunction().
OrderMap OM;
for (const GlobalVariable &G : M->globals()) {
if (G.hasInitializer())
if (!isa<GlobalValue>(G.getInitializer()))
orderValue(G.getInitializer(), OM);
orderValue(&G, OM);
}
for (const GlobalAlias &A : M->aliases()) {
if (!isa<GlobalValue>(A.getAliasee()))
orderValue(A.getAliasee(), OM);
orderValue(&A, OM);
}
for (const Function &F : *M) {
if (F.hasPrefixData())
if (!isa<GlobalValue>(F.getPrefixData()))
orderValue(F.getPrefixData(), OM);
if (F.hasPrologueData())
if (!isa<GlobalValue>(F.getPrologueData()))
orderValue(F.getPrologueData(), OM);
if (F.hasPersonalityFn())
if (!isa<GlobalValue>(F.getPersonalityFn()))
orderValue(F.getPersonalityFn(), OM);
orderValue(&F, OM);
if (F.isDeclaration())
continue;
for (const Argument &A : F.args())
orderValue(&A, OM);
for (const BasicBlock &BB : F) {
orderValue(&BB, OM);
for (const Instruction &I : BB) {
for (const Value *Op : I.operands())
if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
isa<InlineAsm>(*Op))
orderValue(Op, OM);
orderValue(&I, OM);
}
}
}
return OM;
}
static void predictValueUseListOrderImpl(const Value *V, const Function *F,
unsigned ID, const OrderMap &OM,
UseListOrderStack &Stack) {
// Predict use-list order for this one.
typedef std::pair<const Use *, unsigned> Entry;
SmallVector<Entry, 64> List;
for (const Use &U : V->uses())
// Check if this user will be serialized.
if (OM.lookup(U.getUser()).first)
List.push_back(std::make_pair(&U, List.size()));
if (List.size() < 2)
// We may have lost some users.
return;
bool GetsReversed =
!isa<GlobalVariable>(V) && !isa<Function>(V) && !isa<BasicBlock>(V);
if (auto *BA = dyn_cast<BlockAddress>(V))
ID = OM.lookup(BA->getBasicBlock()).first;
std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
const Use *LU = L.first;
const Use *RU = R.first;
if (LU == RU)
return false;
auto LID = OM.lookup(LU->getUser()).first;
auto RID = OM.lookup(RU->getUser()).first;
// If ID is 4, then expect: 7 6 5 1 2 3.
if (LID < RID) {
if (GetsReversed)
if (RID <= ID)
return true;
return false;
}
if (RID < LID) {
if (GetsReversed)
if (LID <= ID)
return false;
return true;
}
// LID and RID are equal, so we have different operands of the same user.
// Assume operands are added in order for all instructions.
if (GetsReversed)
if (LID <= ID)
return LU->getOperandNo() < RU->getOperandNo();
return LU->getOperandNo() > RU->getOperandNo();
});
if (std::is_sorted(
List.begin(), List.end(),
[](const Entry &L, const Entry &R) { return L.second < R.second; }))
// Order is already correct.
return;
// Store the shuffle.
Stack.emplace_back(V, F, List.size());
assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
for (size_t I = 0, E = List.size(); I != E; ++I)
Stack.back().Shuffle[I] = List[I].second;
}
static void predictValueUseListOrder(const Value *V, const Function *F,
OrderMap &OM, UseListOrderStack &Stack) {
auto &IDPair = OM[V];
assert(IDPair.first && "Unmapped value");
if (IDPair.second)
// Already predicted.
return;
// Do the actual prediction.
IDPair.second = true;
if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
// Recursive descent into constants.
if (const Constant *C = dyn_cast<Constant>(V))
if (C->getNumOperands()) // Visit GlobalValues.
for (const Value *Op : C->operands())
if (isa<Constant>(Op)) // Visit GlobalValues.
predictValueUseListOrder(Op, F, OM, Stack);
}
static UseListOrderStack predictUseListOrder(const Module *M) {
OrderMap OM = orderModule(M);
// Use-list orders need to be serialized after all the users have been added
// to a value, or else the shuffles will be incomplete. Store them per
// function in a stack.
//
// Aside from function order, the order of values doesn't matter much here.
UseListOrderStack Stack;
// We want to visit the functions backward now so we can list function-local
// constants in the last Function they're used in. Module-level constants
// have already been visited above.
for (auto I = M->rbegin(), E = M->rend(); I != E; ++I) {
const Function &F = *I;
if (F.isDeclaration())
continue;
for (const BasicBlock &BB : F)
predictValueUseListOrder(&BB, &F, OM, Stack);
for (const Argument &A : F.args())
predictValueUseListOrder(&A, &F, OM, Stack);
for (const BasicBlock &BB : F)
for (const Instruction &I : BB)
for (const Value *Op : I.operands())
if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
predictValueUseListOrder(Op, &F, OM, Stack);
for (const BasicBlock &BB : F)
for (const Instruction &I : BB)
predictValueUseListOrder(&I, &F, OM, Stack);
}
// Visit globals last.
for (const GlobalVariable &G : M->globals())
predictValueUseListOrder(&G, nullptr, OM, Stack);
for (const Function &F : *M)
predictValueUseListOrder(&F, nullptr, OM, Stack);
for (const GlobalAlias &A : M->aliases())
predictValueUseListOrder(&A, nullptr, OM, Stack);
for (const GlobalVariable &G : M->globals())
if (G.hasInitializer())
predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
for (const GlobalAlias &A : M->aliases())
predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
for (const Function &F : *M)
if (F.hasPrefixData())
predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
return Stack;
}
static const Module *getModuleFromVal(const Value *V) {
if (const Argument *MA = dyn_cast<Argument>(V))
return MA->getParent() ? MA->getParent()->getParent() : nullptr;
if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
return BB->getParent() ? BB->getParent()->getParent() : nullptr;
if (const Instruction *I = dyn_cast<Instruction>(V)) {
const Function *M = I->getParent() ? I->getParent()->getParent() : nullptr;
return M ? M->getParent() : nullptr;
}
if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
return GV->getParent();
if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) {
for (const User *U : MAV->users())
if (isa<Instruction>(U))
if (const Module *M = getModuleFromVal(U))
return M;
return nullptr;
}
return nullptr;
}
static void PrintCallingConv(unsigned cc, raw_ostream &Out) {
switch (cc) {
default: Out << "cc" << cc; break;
case CallingConv::Fast: Out << "fastcc"; break;
case CallingConv::Cold: Out << "coldcc"; break;
case CallingConv::WebKit_JS: Out << "webkit_jscc"; break;
case CallingConv::AnyReg: Out << "anyregcc"; break;
case CallingConv::PreserveMost: Out << "preserve_mostcc"; break;
case CallingConv::PreserveAll: Out << "preserve_allcc"; break;
case CallingConv::GHC: Out << "ghccc"; break;
case CallingConv::X86_StdCall: Out << "x86_stdcallcc"; break;
case CallingConv::X86_FastCall: Out << "x86_fastcallcc"; break;
case CallingConv::X86_ThisCall: Out << "x86_thiscallcc"; break;
case CallingConv::X86_VectorCall:Out << "x86_vectorcallcc"; break;
case CallingConv::Intel_OCL_BI: Out << "intel_ocl_bicc"; break;
case CallingConv::ARM_APCS: Out << "arm_apcscc"; break;
case CallingConv::ARM_AAPCS: Out << "arm_aapcscc"; break;
case CallingConv::ARM_AAPCS_VFP: Out << "arm_aapcs_vfpcc"; break;
case CallingConv::MSP430_INTR: Out << "msp430_intrcc"; break;
case CallingConv::PTX_Kernel: Out << "ptx_kernel"; break;
case CallingConv::PTX_Device: Out << "ptx_device"; break;
case CallingConv::X86_64_SysV: Out << "x86_64_sysvcc"; break;
case CallingConv::X86_64_Win64: Out << "x86_64_win64cc"; break;
case CallingConv::SPIR_FUNC: Out << "spir_func"; break;
case CallingConv::SPIR_KERNEL: Out << "spir_kernel"; break;
}
}
// PrintEscapedString - Print each character of the specified string, escaping
// it if it is not printable or if it is an escape char.
static void PrintEscapedString(StringRef Name, raw_ostream &Out) {
for (unsigned i = 0, e = Name.size(); i != e; ++i) {
unsigned char C = Name[i];
if (isprint(C) && C != '\\' && C != '"')
Out << C;
else
Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
}
}
enum PrefixType {
GlobalPrefix,
ComdatPrefix,
LabelPrefix,
LocalPrefix,
NoPrefix
};
/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
/// prefixed with % (if the string only contains simple characters) or is
/// surrounded with ""'s (if it has special chars in it). Print it out.
static void PrintLLVMName(raw_ostream &OS, StringRef Name, PrefixType Prefix) {
assert(!Name.empty() && "Cannot get empty name!");
switch (Prefix) {
case NoPrefix: break;
case GlobalPrefix: OS << '@'; break;
case ComdatPrefix: OS << '$'; break;
case LabelPrefix: break;
case LocalPrefix: OS << '%'; break;
}
// Scan the name to see if it needs quotes first.
bool NeedsQuotes = isdigit(static_cast<unsigned char>(Name[0]));
if (!NeedsQuotes) {
for (unsigned i = 0, e = Name.size(); i != e; ++i) {
// By making this unsigned, the value passed in to isalnum will always be
// in the range 0-255. This is important when building with MSVC because
// its implementation will assert. This situation can arise when dealing
// with UTF-8 multibyte characters.
unsigned char C = Name[i];
if (!isalnum(static_cast<unsigned char>(C)) && C != '-' && C != '.' &&
C != '_') {
NeedsQuotes = true;
break;
}
}
}
// If we didn't need any quotes, just write out the name in one blast.
if (!NeedsQuotes) {
OS << Name;
return;
}
// Okay, we need quotes. Output the quotes and escape any scary characters as
// needed.
OS << '"';
PrintEscapedString(Name, OS);
OS << '"';
}
/// PrintLLVMName - Turn the specified name into an 'LLVM name', which is either
/// prefixed with % (if the string only contains simple characters) or is
/// surrounded with ""'s (if it has special chars in it). Print it out.
static void PrintLLVMName(raw_ostream &OS, const Value *V) {
PrintLLVMName(OS, V->getName(),
isa<GlobalValue>(V) ? GlobalPrefix : LocalPrefix);
}
namespace {
class TypePrinting {
TypePrinting(const TypePrinting &) = delete;
void operator=(const TypePrinting&) = delete;
public:
/// NamedTypes - The named types that are used by the current module.
TypeFinder NamedTypes;
/// NumberedTypes - The numbered types, along with their value.
DenseMap<StructType*, unsigned> NumberedTypes;
TypePrinting() = default;
void incorporateTypes(const Module &M);
void print(Type *Ty, raw_ostream &OS);
void printStructBody(StructType *Ty, raw_ostream &OS);
};
} // namespace
void TypePrinting::incorporateTypes(const Module &M) {
NamedTypes.run(M, false);
// The list of struct types we got back includes all the struct types, split
// the unnamed ones out to a numbering and remove the anonymous structs.
unsigned NextNumber = 0;
std::vector<StructType*>::iterator NextToUse = NamedTypes.begin(), I, E;
for (I = NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I) {
StructType *STy = *I;
// Ignore anonymous types.
if (STy->isLiteral())
continue;
if (STy->getName().empty())
NumberedTypes[STy] = NextNumber++;
else
*NextToUse++ = STy;
}
NamedTypes.erase(NextToUse, NamedTypes.end());
}
/// CalcTypeName - Write the specified type to the specified raw_ostream, making
/// use of type names or up references to shorten the type name where possible.
void TypePrinting::print(Type *Ty, raw_ostream &OS) {
switch (Ty->getTypeID()) {
case Type::VoidTyID: OS << "void"; return;
case Type::HalfTyID: OS << "half"; return;
case Type::FloatTyID: OS << "float"; return;
case Type::DoubleTyID: OS << "double"; return;
case Type::X86_FP80TyID: OS << "x86_fp80"; return;
case Type::FP128TyID: OS << "fp128"; return;
case Type::PPC_FP128TyID: OS << "ppc_fp128"; return;
case Type::LabelTyID: OS << "label"; return;
case Type::MetadataTyID: OS << "metadata"; return;
case Type::X86_MMXTyID: OS << "x86_mmx"; return;
case Type::IntegerTyID:
OS << 'i' << cast<IntegerType>(Ty)->getBitWidth();
return;
case Type::FunctionTyID: {
FunctionType *FTy = cast<FunctionType>(Ty);
print(FTy->getReturnType(), OS);
OS << " (";
for (FunctionType::param_iterator I = FTy->param_begin(),
E = FTy->param_end(); I != E; ++I) {
if (I != FTy->param_begin())
OS << ", ";
print(*I, OS);
}
if (FTy->isVarArg()) {
if (FTy->getNumParams()) OS << ", ";
OS << "...";
}
OS << ')';
return;
}
case Type::StructTyID: {
StructType *STy = cast<StructType>(Ty);
if (STy->isLiteral())
return printStructBody(STy, OS);
if (!STy->getName().empty())
return PrintLLVMName(OS, STy->getName(), LocalPrefix);
DenseMap<StructType*, unsigned>::iterator I = NumberedTypes.find(STy);
if (I != NumberedTypes.end())
OS << '%' << I->second;
else // Not enumerated, print the hex address.
OS << "%\"type " << STy << '\"';
return;
}
case Type::PointerTyID: {
PointerType *PTy = cast<PointerType>(Ty);
print(PTy->getElementType(), OS);
if (unsigned AddressSpace = PTy->getAddressSpace())
OS << " addrspace(" << AddressSpace << ')';
OS << '*';
return;
}
case Type::ArrayTyID: {
ArrayType *ATy = cast<ArrayType>(Ty);
OS << '[' << ATy->getNumElements() << " x ";
print(ATy->getElementType(), OS);
OS << ']';
return;
}
case Type::VectorTyID: {
VectorType *PTy = cast<VectorType>(Ty);
OS << "<" << PTy->getNumElements() << " x ";
print(PTy->getElementType(), OS);
OS << '>';
return;
}
}
llvm_unreachable("Invalid TypeID");
}
void TypePrinting::printStructBody(StructType *STy, raw_ostream &OS) {
if (STy->isOpaque()) {
OS << "opaque";
return;
}
if (STy->isPacked())
OS << '<';
if (STy->getNumElements() == 0) {
OS << "{}";
} else {
StructType::element_iterator I = STy->element_begin();
OS << "{ ";
print(*I++, OS);
for (StructType::element_iterator E = STy->element_end(); I != E; ++I) {
OS << ", ";
print(*I, OS);
}
OS << " }";
}
if (STy->isPacked())
OS << '>';
}
namespace llvm {
//===----------------------------------------------------------------------===//
// SlotTracker Class: Enumerate slot numbers for unnamed values
//===----------------------------------------------------------------------===//
/// This class provides computation of slot numbers for LLVM Assembly writing.
///
class SlotTracker {
public:
/// ValueMap - A mapping of Values to slot numbers.
typedef DenseMap<const Value*, unsigned> ValueMap;
private:
/// TheModule - The module for which we are holding slot numbers.
const Module* TheModule;
/// TheFunction - The function for which we are holding slot numbers.
const Function* TheFunction;
bool FunctionProcessed;
bool ShouldInitializeAllMetadata;
/// mMap - The slot map for the module level data.
ValueMap mMap;
unsigned mNext;
/// fMap - The slot map for the function level data.
ValueMap fMap;
unsigned fNext;
/// mdnMap - Map for MDNodes.
DenseMap<const MDNode*, unsigned> mdnMap;
unsigned mdnNext;
/// asMap - The slot map for attribute sets.
DenseMap<AttributeSet, unsigned> asMap;
unsigned asNext;
public:
/// Construct from a module.
///
/// If \c ShouldInitializeAllMetadata, initializes all metadata in all
/// functions, giving correct numbering for metadata referenced only from
/// within a function (even if no functions have been initialized).
explicit SlotTracker(const Module *M,
bool ShouldInitializeAllMetadata = false);
/// Construct from a function, starting out in incorp state.
///
/// If \c ShouldInitializeAllMetadata, initializes all metadata in all
/// functions, giving correct numbering for metadata referenced only from
/// within a function (even if no functions have been initialized).
explicit SlotTracker(const Function *F,
bool ShouldInitializeAllMetadata = false);
/// Return the slot number of the specified value in it's type
/// plane. If something is not in the SlotTracker, return -1.
int getLocalSlot(const Value *V);
int getGlobalSlot(const GlobalValue *V);
int getMetadataSlot(const MDNode *N);
int getAttributeGroupSlot(AttributeSet AS);
/// If you'd like to deal with a function instead of just a module, use
/// this method to get its data into the SlotTracker.
void incorporateFunction(const Function *F) {
TheFunction = F;
FunctionProcessed = false;
}
const Function *getFunction() const { return TheFunction; }
/// After calling incorporateFunction, use this method to remove the
/// most recently incorporated function from the SlotTracker. This
/// will reset the state of the machine back to just the module contents.
void purgeFunction();
/// MDNode map iterators.
typedef DenseMap<const MDNode*, unsigned>::iterator mdn_iterator;
mdn_iterator mdn_begin() { return mdnMap.begin(); }
mdn_iterator mdn_end() { return mdnMap.end(); }
unsigned mdn_size() const { return mdnMap.size(); }
bool mdn_empty() const { return mdnMap.empty(); }
/// AttributeSet map iterators.
typedef DenseMap<AttributeSet, unsigned>::iterator as_iterator;
as_iterator as_begin() { return asMap.begin(); }
as_iterator as_end() { return asMap.end(); }
unsigned as_size() const { return asMap.size(); }
bool as_empty() const { return asMap.empty(); }
/// This function does the actual initialization.
inline void initialize();
// Implementation Details
private:
/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
void CreateModuleSlot(const GlobalValue *V);
/// CreateMetadataSlot - Insert the specified MDNode* into the slot table.
void CreateMetadataSlot(const MDNode *N);
/// CreateFunctionSlot - Insert the specified Value* into the slot table.
void CreateFunctionSlot(const Value *V);
/// \brief Insert the specified AttributeSet into the slot table.
void CreateAttributeSetSlot(AttributeSet AS);
/// Add all of the module level global variables (and their initializers)
/// and function declarations, but not the contents of those functions.
void processModule();
/// Add all of the functions arguments, basic blocks, and instructions.
void processFunction();
/// Add all of the metadata from a function.
void processFunctionMetadata(const Function &F);
/// Add all of the metadata from an instruction.
void processInstructionMetadata(const Instruction &I);
SlotTracker(const SlotTracker &) = delete;
void operator=(const SlotTracker &) = delete;
};
} // namespace llvm
ModuleSlotTracker::ModuleSlotTracker(SlotTracker &Machine, const Module *M,
const Function *F)
: M(M), F(F), Machine(&Machine) {}
ModuleSlotTracker::ModuleSlotTracker(const Module *M,
bool ShouldInitializeAllMetadata)
: MachineStorage(M ? new SlotTracker(M, ShouldInitializeAllMetadata)
: nullptr),
M(M), Machine(MachineStorage.get()) {}
ModuleSlotTracker::~ModuleSlotTracker() {}
void ModuleSlotTracker::incorporateFunction(const Function &F) {
if (!Machine)
return;
// Nothing to do if this is the right function already.
if (this->F == &F)
return;
if (this->F)
Machine->purgeFunction();
Machine->incorporateFunction(&F);
this->F = &F;
}
#if 0 // HLSL Change - Unused
static SlotTracker *createSlotTracker(const Module *M) {
return new SlotTracker(M);
}
#endif
static SlotTracker *createSlotTracker(const Value *V) {
if (const Argument *FA = dyn_cast<Argument>(V))
return new SlotTracker(FA->getParent());
if (const Instruction *I = dyn_cast<Instruction>(V))
if (I->getParent())
return new SlotTracker(I->getParent()->getParent());
if (const BasicBlock *BB = dyn_cast<BasicBlock>(V))
return new SlotTracker(BB->getParent());
if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
return new SlotTracker(GV->getParent());
if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
return new SlotTracker(GA->getParent());
if (const Function *Func = dyn_cast<Function>(V))
return new SlotTracker(Func);
return nullptr;
}
#if 0
#define ST_DEBUG(X) dbgs() << X
#else
#define ST_DEBUG(X)
#endif
// Module level constructor. Causes the contents of the Module (sans functions)
// to be added to the slot table.
SlotTracker::SlotTracker(const Module *M, bool ShouldInitializeAllMetadata)
: TheModule(M), TheFunction(nullptr), FunctionProcessed(false),
ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
fNext(0), mdnNext(0), asNext(0) {}
// Function level constructor. Causes the contents of the Module and the one
// function provided to be added to the slot table.
SlotTracker::SlotTracker(const Function *F, bool ShouldInitializeAllMetadata)
: TheModule(F ? F->getParent() : nullptr), TheFunction(F),
FunctionProcessed(false),
ShouldInitializeAllMetadata(ShouldInitializeAllMetadata), mNext(0),
fNext(0), mdnNext(0), asNext(0) {}
inline void SlotTracker::initialize() {
if (TheModule) {
processModule();
TheModule = nullptr; ///< Prevent re-processing next time we're called.
}
if (TheFunction && !FunctionProcessed)
processFunction();
}
// Iterate through all the global variables, functions, and global
// variable initializers and create slots for them.
void SlotTracker::processModule() {
ST_DEBUG("begin processModule!\n");
// Add all of the unnamed global variables to the value table.
for (const GlobalVariable &Var : TheModule->globals()) {
if (!Var.hasName())
CreateModuleSlot(&Var);
}
for (const GlobalAlias &A : TheModule->aliases()) {
if (!A.hasName())
CreateModuleSlot(&A);
}
// Add metadata used by named metadata.
for (const NamedMDNode &NMD : TheModule->named_metadata()) {
for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
CreateMetadataSlot(NMD.getOperand(i));
}
for (const Function &F : *TheModule) {
if (!F.hasName())
// Add all the unnamed functions to the table.
CreateModuleSlot(&F);
if (ShouldInitializeAllMetadata)
processFunctionMetadata(F);
// Add all the function attributes to the table.
// FIXME: Add attributes of other objects?
AttributeSet FnAttrs = F.getAttributes().getFnAttributes();
if (FnAttrs.hasAttributes(AttributeSet::FunctionIndex))
CreateAttributeSetSlot(FnAttrs);
}
ST_DEBUG("end processModule!\n");
}
// Process the arguments, basic blocks, and instructions of a function.
void SlotTracker::processFunction() {
ST_DEBUG("begin processFunction!\n");
fNext = 0;
// Add all the function arguments with no names.
for(Function::const_arg_iterator AI = TheFunction->arg_begin(),
AE = TheFunction->arg_end(); AI != AE; ++AI)
if (!AI->hasName())
CreateFunctionSlot(AI);
ST_DEBUG("Inserting Instructions:\n");
// Process function metadata if it wasn't hit at the module-level.
if (!ShouldInitializeAllMetadata)
processFunctionMetadata(*TheFunction);
// Add all of the basic blocks and instructions with no names.
for (auto &BB : *TheFunction) {
if (!BB.hasName())
CreateFunctionSlot(&BB);
for (auto &I : BB) {
if (!I.getType()->isVoidTy() && !I.hasName())
CreateFunctionSlot(&I);
// We allow direct calls to any llvm.foo function here, because the
// target may not be linked into the optimizer.
if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
// Add all the call attributes to the table.
AttributeSet Attrs = CI->getAttributes().getFnAttributes();
if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
CreateAttributeSetSlot(Attrs);
} else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
// Add all the call attributes to the table.
AttributeSet Attrs = II->getAttributes().getFnAttributes();
if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
CreateAttributeSetSlot(Attrs);
}
}
}
FunctionProcessed = true;
ST_DEBUG("end processFunction!\n");
}
void SlotTracker::processFunctionMetadata(const Function &F) {
SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
F.getAllMetadata(MDs);
for (auto &MD : MDs)
CreateMetadataSlot(MD.second);
for (auto &BB : F) {
for (auto &I : BB)
processInstructionMetadata(I);
}
}
void SlotTracker::processInstructionMetadata(const Instruction &I) {
// Process metadata used directly by intrinsics.
if (const CallInst *CI = dyn_cast<CallInst>(&I))
if (Function *F = CI->getCalledFunction())
if (F->isIntrinsic())
for (auto &Op : I.operands())
if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
if (MDNode *N = dyn_cast<MDNode>(V->getMetadata()))
CreateMetadataSlot(N);
// Process metadata attached to this instruction.
SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
I.getAllMetadata(MDs);
for (auto &MD : MDs)
CreateMetadataSlot(MD.second);
}
/// Clean up after incorporating a function. This is the only way to get out of
/// the function incorporation state that affects get*Slot/Create*Slot. Function
/// incorporation state is indicated by TheFunction != 0.
void SlotTracker::purgeFunction() {
ST_DEBUG("begin purgeFunction!\n");
fMap.clear(); // Simply discard the function level map
TheFunction = nullptr;
FunctionProcessed = false;
ST_DEBUG("end purgeFunction!\n");
}
/// getGlobalSlot - Get the slot number of a global value.
int SlotTracker::getGlobalSlot(const GlobalValue *V) {
// Check for uninitialized state and do lazy initialization.
initialize();
// Find the value in the module map
ValueMap::iterator MI = mMap.find(V);
return MI == mMap.end() ? -1 : (int)MI->second;
}
/// getMetadataSlot - Get the slot number of a MDNode.
int SlotTracker::getMetadataSlot(const MDNode *N) {
// Check for uninitialized state and do lazy initialization.
initialize();
// Find the MDNode in the module map
mdn_iterator MI = mdnMap.find(N);
return MI == mdnMap.end() ? -1 : (int)MI->second;
}
/// getLocalSlot - Get the slot number for a value that is local to a function.
int SlotTracker::getLocalSlot(const Value *V) {
assert(!isa<Constant>(V) && "Can't get a constant or global slot with this!");
// Check for uninitialized state and do lazy initialization.
initialize();
ValueMap::iterator FI = fMap.find(V);
return FI == fMap.end() ? -1 : (int)FI->second;
}
int SlotTracker::getAttributeGroupSlot(AttributeSet AS) {
// Check for uninitialized state and do lazy initialization.
initialize();
// Find the AttributeSet in the module map.
as_iterator AI = asMap.find(AS);
return AI == asMap.end() ? -1 : (int)AI->second;
}
/// CreateModuleSlot - Insert the specified GlobalValue* into the slot table.
void SlotTracker::CreateModuleSlot(const GlobalValue *V) {
assert(V && "Can't insert a null Value into SlotTracker!");
assert(!V->getType()->isVoidTy() && "Doesn't need a slot!");
assert(!V->hasName() && "Doesn't need a slot!");
unsigned DestSlot = mNext++;
mMap[V] = DestSlot;
ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
DestSlot << " [");
// G = Global, F = Function, A = Alias, o = other
ST_DEBUG((isa<GlobalVariable>(V) ? 'G' :
(isa<Function>(V) ? 'F' :
(isa<GlobalAlias>(V) ? 'A' : 'o'))) << "]\n");
}
/// CreateSlot - Create a new slot for the specified value if it has no name.
void SlotTracker::CreateFunctionSlot(const Value *V) {
assert(!V->getType()->isVoidTy() && !V->hasName() && "Doesn't need a slot!");
unsigned DestSlot = fNext++;
fMap[V] = DestSlot;
// G = Global, F = Function, o = other
ST_DEBUG(" Inserting value [" << V->getType() << "] = " << V << " slot=" <<
DestSlot << " [o]\n");
}
/// CreateModuleSlot - Insert the specified MDNode* into the slot table.
void SlotTracker::CreateMetadataSlot(const MDNode *N) {
assert(N && "Can't insert a null Value into SlotTracker!");
unsigned DestSlot = mdnNext;
if (!mdnMap.insert(std::make_pair(N, DestSlot)).second)
return;
++mdnNext;
// Recursively add any MDNodes referenced by operands.
for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
if (const MDNode *Op = dyn_cast_or_null<MDNode>(N->getOperand(i)))
CreateMetadataSlot(Op);
}
void SlotTracker::CreateAttributeSetSlot(AttributeSet AS) {
assert(AS.hasAttributes(AttributeSet::FunctionIndex) &&
"Doesn't need a slot!");
as_iterator I = asMap.find(AS);
if (I != asMap.end())
return;
unsigned DestSlot = asNext++;
asMap[AS] = DestSlot;
}
//===----------------------------------------------------------------------===//
// AsmWriter Implementation
//===----------------------------------------------------------------------===//
static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
TypePrinting *TypePrinter,
SlotTracker *Machine,
const Module *Context);
static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
TypePrinting *TypePrinter,
SlotTracker *Machine, const Module *Context,
bool FromValue = false);
static const char *getPredicateText(unsigned predicate) {
const char * pred = "unknown";
switch (predicate) {
case FCmpInst::FCMP_FALSE: pred = "false"; break;
case FCmpInst::FCMP_OEQ: pred = "oeq"; break;
case FCmpInst::FCMP_OGT: pred = "ogt"; break;
case FCmpInst::FCMP_OGE: pred = "oge"; break;
case FCmpInst::FCMP_OLT: pred = "olt"; break;
case FCmpInst::FCMP_OLE: pred = "ole"; break;
case FCmpInst::FCMP_ONE: pred = "one"; break;
case FCmpInst::FCMP_ORD: pred = "ord"; break;
case FCmpInst::FCMP_UNO: pred = "uno"; break;
case FCmpInst::FCMP_UEQ: pred = "ueq"; break;
case FCmpInst::FCMP_UGT: pred = "ugt"; break;
case FCmpInst::FCMP_UGE: pred = "uge"; break;
case FCmpInst::FCMP_ULT: pred = "ult"; break;
case FCmpInst::FCMP_ULE: pred = "ule"; break;
case FCmpInst::FCMP_UNE: pred = "une"; break;
case FCmpInst::FCMP_TRUE: pred = "true"; break;
case ICmpInst::ICMP_EQ: pred = "eq"; break;
case ICmpInst::ICMP_NE: pred = "ne"; break;
case ICmpInst::ICMP_SGT: pred = "sgt"; break;
case ICmpInst::ICMP_SGE: pred = "sge"; break;
case ICmpInst::ICMP_SLT: pred = "slt"; break;
case ICmpInst::ICMP_SLE: pred = "sle"; break;
case ICmpInst::ICMP_UGT: pred = "ugt"; break;
case ICmpInst::ICMP_UGE: pred = "uge"; break;
case ICmpInst::ICMP_ULT: pred = "ult"; break;
case ICmpInst::ICMP_ULE: pred = "ule"; break;
}
return pred;
}
static void writeAtomicRMWOperation(raw_ostream &Out,
AtomicRMWInst::BinOp Op) {
switch (Op) {
default: Out << " <unknown operation " << Op << ">"; break;
case AtomicRMWInst::Xchg: Out << " xchg"; break;
case AtomicRMWInst::Add: Out << " add"; break;
case AtomicRMWInst::Sub: Out << " sub"; break;
case AtomicRMWInst::And: Out << " and"; break;
case AtomicRMWInst::Nand: Out << " nand"; break;
case AtomicRMWInst::Or: Out << " or"; break;
case AtomicRMWInst::Xor: Out << " xor"; break;
case AtomicRMWInst::Max: Out << " max"; break;
case AtomicRMWInst::Min: Out << " min"; break;
case AtomicRMWInst::UMax: Out << " umax"; break;
case AtomicRMWInst::UMin: Out << " umin"; break;
}
}
static void WriteOptimizationInfo(raw_ostream &Out, const User *U) {
if (const FPMathOperator *FPOp = dyn_cast<const FPMathOperator>(U)) {
// Unsafe algebra implies all the others, no need to write them all out
if (FPOp->hasUnsafeAlgebra())
Out << " fast";
else {
if (FPOp->hasNoNaNs())
Out << " nnan";
if (FPOp->hasNoInfs())
Out << " ninf";
if (FPOp->hasNoSignedZeros())
Out << " nsz";
if (FPOp->hasAllowReciprocal())
Out << " arcp";
}
}
if (const OverflowingBinaryOperator *OBO =
dyn_cast<OverflowingBinaryOperator>(U)) {
if (OBO->hasNoUnsignedWrap())
Out << " nuw";
if (OBO->hasNoSignedWrap())
Out << " nsw";
} else if (const PossiblyExactOperator *Div =
dyn_cast<PossiblyExactOperator>(U)) {
if (Div->isExact())
Out << " exact";
} else if (const GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
if (GEP->isInBounds())
Out << " inbounds";
}
}
static void WriteConstantInternal(raw_ostream &Out, const Constant *CV,
TypePrinting &TypePrinter,
SlotTracker *Machine,
const Module *Context) {
if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
if (CI->getType()->isIntegerTy(1)) {
Out << (CI->getZExtValue() ? "true" : "false");
return;
}
Out << CI->getValue();
return;
}
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEsingle ||
&CFP->getValueAPF().getSemantics() == &APFloat::IEEEdouble) {
// We would like to output the FP constant value in exponential notation,
// but we cannot do this if doing so will lose precision. Check here to
// make sure that we only output it in exponential format if we can parse
// the value back and get the same value.
//
bool ignored;
bool isHalf = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEhalf;
bool isDouble = &CFP->getValueAPF().getSemantics()==&APFloat::IEEEdouble;
bool isInf = CFP->getValueAPF().isInfinity();
bool isNaN = CFP->getValueAPF().isNaN();
if (!isHalf && !isInf && !isNaN) {
double Val = isDouble ? CFP->getValueAPF().convertToDouble() :
CFP->getValueAPF().convertToFloat();
SmallString<128> StrVal;
raw_svector_ostream(StrVal) << Val;
// Check to make sure that the stringized number is not some string like
// "Inf" or NaN, that atof will accept, but the lexer will not. Check
// that the string matches the "[-+]?[0-9]" regex.
//
if ((StrVal[0] >= '0' && StrVal[0] <= '9') ||
((StrVal[0] == '-' || StrVal[0] == '+') &&
(StrVal[1] >= '0' && StrVal[1] <= '9'))) {
// Reparse stringized version!
if (APFloat(APFloat::IEEEdouble, StrVal).convertToDouble() == Val) {
Out << StrVal;
return;
}
}
}
// Otherwise we could not reparse it to exactly the same value, so we must
// output the string in hexadecimal format! Note that loading and storing
// floating point types changes the bits of NaNs on some hosts, notably
// x86, so we must not use these types.
static_assert(sizeof(double) == sizeof(uint64_t),
"assuming that double is 64 bits!");
char Buffer[40];
APFloat apf = CFP->getValueAPF();
// Halves and floats are represented in ASCII IR as double, convert.
if (!isDouble)
apf.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
&ignored);
Out << "0x" <<
utohex_buffer(uint64_t(apf.bitcastToAPInt().getZExtValue()),
Buffer+40);
return;
}
// Either half, or some form of long double.
// These appear as a magic letter identifying the type, then a
// fixed number of hex digits.
Out << "0x";
// Bit position, in the current word, of the next nibble to print.
int shiftcount;
if (&CFP->getValueAPF().getSemantics() == &APFloat::x87DoubleExtended) {
Out << 'K';
// api needed to prevent premature destruction
APInt api = CFP->getValueAPF().bitcastToAPInt();
const uint64_t* p = api.getRawData();
uint64_t word = p[1];
shiftcount = 12;
int width = api.getBitWidth();
for (int j=0; j<width; j+=4, shiftcount-=4) {
unsigned int nibble = (word>>shiftcount) & 15;
if (nibble < 10)
Out << (unsigned char)(nibble + '0');
else
Out << (unsigned char)(nibble - 10 + 'A');
if (shiftcount == 0 && j+4 < width) {
word = *p;
shiftcount = 64;
if (width-j-4 < 64)
shiftcount = width-j-4;
}
}
return;
} else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEquad) {
shiftcount = 60;
Out << 'L';
} else if (&CFP->getValueAPF().getSemantics() == &APFloat::PPCDoubleDouble) {
shiftcount = 60;
Out << 'M';
} else if (&CFP->getValueAPF().getSemantics() == &APFloat::IEEEhalf) {
shiftcount = 12;
Out << 'H';
} else
llvm_unreachable("Unsupported floating point type");
// api needed to prevent premature destruction
APInt api = CFP->getValueAPF().bitcastToAPInt();
const uint64_t* p = api.getRawData();
uint64_t word = *p;
int width = api.getBitWidth();
for (int j=0; j<width; j+=4, shiftcount-=4) {
unsigned int nibble = (word>>shiftcount) & 15;
if (nibble < 10)
Out << (unsigned char)(nibble + '0');
else
Out << (unsigned char)(nibble - 10 + 'A');
if (shiftcount == 0 && j+4 < width) {
word = *(++p);
shiftcount = 64;
if (width-j-4 < 64)
shiftcount = width-j-4;
}
}
return;
}
if (isa<ConstantAggregateZero>(CV)) {
Out << "zeroinitializer";
return;
}
if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) {
Out << "blockaddress(";
WriteAsOperandInternal(Out, BA->getFunction(), &TypePrinter, Machine,
Context);
Out << ", ";
WriteAsOperandInternal(Out, BA->getBasicBlock(), &TypePrinter, Machine,
Context);
Out << ")";
return;
}
if (const ConstantArray *CA = dyn_cast<ConstantArray>(CV)) {
Type *ETy = CA->getType()->getElementType();
Out << '[';
TypePrinter.print(ETy, Out);
Out << ' ';
WriteAsOperandInternal(Out, CA->getOperand(0),
&TypePrinter, Machine,
Context);
for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
Out << ", ";
TypePrinter.print(ETy, Out);
Out << ' ';
WriteAsOperandInternal(Out, CA->getOperand(i), &TypePrinter, Machine,
Context);
}
Out << ']';
return;
}
if (const ConstantDataArray *CA = dyn_cast<ConstantDataArray>(CV)) {
// As a special case, print the array as a string if it is an array of
// i8 with ConstantInt values.
if (CA->isString()) {
Out << "c\"";
PrintEscapedString(CA->getAsString(), Out);
Out << '"';
return;
}
Type *ETy = CA->getType()->getElementType();
Out << '[';
TypePrinter.print(ETy, Out);
Out << ' ';
WriteAsOperandInternal(Out, CA->getElementAsConstant(0),
&TypePrinter, Machine,
Context);
for (unsigned i = 1, e = CA->getNumElements(); i != e; ++i) {
Out << ", ";
TypePrinter.print(ETy, Out);
Out << ' ';
WriteAsOperandInternal(Out, CA->getElementAsConstant(i), &TypePrinter,
Machine, Context);
}
Out << ']';
return;
}
if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(CV)) {
if (CS->getType()->isPacked())
Out << '<';
Out << '{';
unsigned N = CS->getNumOperands();
if (N) {
Out << ' ';
TypePrinter.print(CS->getOperand(0)->getType(), Out);
Out << ' ';
WriteAsOperandInternal(Out, CS->getOperand(0), &TypePrinter, Machine,
Context);
for (unsigned i = 1; i < N; i++) {
Out << ", ";
TypePrinter.print(CS->getOperand(i)->getType(), Out);
Out << ' ';
WriteAsOperandInternal(Out, CS->getOperand(i), &TypePrinter, Machine,
Context);
}
Out << ' ';
}
Out << '}';
if (CS->getType()->isPacked())
Out << '>';
return;
}
if (isa<ConstantVector>(CV) || isa<ConstantDataVector>(CV)) {
Type *ETy = CV->getType()->getVectorElementType();
Out << '<';
TypePrinter.print(ETy, Out);
Out << ' ';
WriteAsOperandInternal(Out, CV->getAggregateElement(0U), &TypePrinter,
Machine, Context);
for (unsigned i = 1, e = CV->getType()->getVectorNumElements(); i != e;++i){
Out << ", ";
TypePrinter.print(ETy, Out);
Out << ' ';
WriteAsOperandInternal(Out, CV->getAggregateElement(i), &TypePrinter,
Machine, Context);
}
Out << '>';
return;
}
if (isa<ConstantPointerNull>(CV)) {
Out << "null";
return;
}
if (isa<UndefValue>(CV)) {
Out << "undef";
return;
}
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Out << CE->getOpcodeName();
WriteOptimizationInfo(Out, CE);
if (CE->isCompare())
Out << ' ' << getPredicateText(CE->getPredicate());
Out << " (";
if (const GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
TypePrinter.print(
cast<PointerType>(GEP->getPointerOperandType()->getScalarType())
->getElementType(),
Out);
Out << ", ";
}
for (User::const_op_iterator OI=CE->op_begin(); OI != CE->op_end(); ++OI) {
TypePrinter.print((*OI)->getType(), Out);
Out << ' ';
WriteAsOperandInternal(Out, *OI, &TypePrinter, Machine, Context);
if (OI+1 != CE->op_end())
Out << ", ";
}
if (CE->hasIndices()) {
ArrayRef<unsigned> Indices = CE->getIndices();
for (unsigned i = 0, e = Indices.size(); i != e; ++i)
Out << ", " << Indices[i];
}
if (CE->isCast()) {
Out << " to ";
TypePrinter.print(CE->getType(), Out);
}
Out << ')';
return;
}
Out << "<placeholder or erroneous Constant>";
}
static void writeMDTuple(raw_ostream &Out, const MDTuple *Node,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!{";
for (unsigned mi = 0, me = Node->getNumOperands(); mi != me; ++mi) {
const Metadata *MD = Node->getOperand(mi);
if (!MD)
Out << "null";
else if (auto *MDV = dyn_cast<ValueAsMetadata>(MD)) {
Value *V = MDV->getValue();
TypePrinter->print(V->getType(), Out);
Out << ' ';
WriteAsOperandInternal(Out, V, TypePrinter, Machine, Context);
} else {
WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
}
if (mi + 1 != me)
Out << ", ";
}
Out << "}";
}
namespace {
struct FieldSeparator {
bool Skip;
const char *Sep;
FieldSeparator(const char *Sep = ", ") : Skip(true), Sep(Sep) {}
};
raw_ostream &operator<<(raw_ostream &OS, FieldSeparator &FS) {
if (FS.Skip) {
FS.Skip = false;
return OS;
}
return OS << FS.Sep;
}
struct MDFieldPrinter {
raw_ostream &Out;
FieldSeparator FS;
TypePrinting *TypePrinter;
SlotTracker *Machine;
const Module *Context;
explicit MDFieldPrinter(raw_ostream &Out)
: Out(Out), TypePrinter(nullptr), Machine(nullptr), Context(nullptr) {}
MDFieldPrinter(raw_ostream &Out, TypePrinting *TypePrinter,
SlotTracker *Machine, const Module *Context)
: Out(Out), TypePrinter(TypePrinter), Machine(Machine), Context(Context) {
}
void printTag(const DINode *N);
void printString(StringRef Name, StringRef Value,
bool ShouldSkipEmpty = true);
void printMetadata(StringRef Name, const Metadata *MD,
bool ShouldSkipNull = true);
template <class IntTy>
void printInt(StringRef Name, IntTy Int, bool ShouldSkipZero = true);
void printBool(StringRef Name, bool Value);
void printDIFlags(StringRef Name, unsigned Flags);
template <class IntTy, class Stringifier>
void printDwarfEnum(StringRef Name, IntTy Value, Stringifier toString,
bool ShouldSkipZero = true);
};
} // end namespace
void MDFieldPrinter::printTag(const DINode *N) {
Out << FS << "tag: ";
if (const char *Tag = dwarf::TagString(N->getTag()))
Out << Tag;
else
Out << N->getTag();
}
void MDFieldPrinter::printString(StringRef Name, StringRef Value,
bool ShouldSkipEmpty) {
if (ShouldSkipEmpty && Value.empty())
return;
Out << FS << Name << ": \"";
PrintEscapedString(Value, Out);
Out << "\"";
}
static void writeMetadataAsOperand(raw_ostream &Out, const Metadata *MD,
TypePrinting *TypePrinter,
SlotTracker *Machine,
const Module *Context) {
if (!MD) {
Out << "null";
return;
}
WriteAsOperandInternal(Out, MD, TypePrinter, Machine, Context);
}
void MDFieldPrinter::printMetadata(StringRef Name, const Metadata *MD,
bool ShouldSkipNull) {
if (ShouldSkipNull && !MD)
return;
Out << FS << Name << ": ";
writeMetadataAsOperand(Out, MD, TypePrinter, Machine, Context);
}
template <class IntTy>
void MDFieldPrinter::printInt(StringRef Name, IntTy Int, bool ShouldSkipZero) {
if (ShouldSkipZero && !Int)
return;
Out << FS << Name << ": " << Int;
}
void MDFieldPrinter::printBool(StringRef Name, bool Value) {
Out << FS << Name << ": " << (Value ? "true" : "false");
}
void MDFieldPrinter::printDIFlags(StringRef Name, unsigned Flags) {
if (!Flags)
return;
Out << FS << Name << ": ";
SmallVector<unsigned, 8> SplitFlags;
unsigned Extra = DINode::splitFlags(Flags, SplitFlags);
FieldSeparator FlagsFS(" | ");
for (unsigned F : SplitFlags) {
const char *StringF = DINode::getFlagString(F);
assert(StringF && "Expected valid flag");
Out << FlagsFS << StringF;
}
if (Extra || SplitFlags.empty())
Out << FlagsFS << Extra;
}
template <class IntTy, class Stringifier>
void MDFieldPrinter::printDwarfEnum(StringRef Name, IntTy Value,
Stringifier toString, bool ShouldSkipZero) {
if (!Value)
return;
Out << FS << Name << ": ";
if (const char *S = toString(Value))
Out << S;
else
Out << Value;
}
static void writeGenericDINode(raw_ostream &Out, const GenericDINode *N,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!GenericDINode(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printTag(N);
Printer.printString("header", N->getHeader());
if (N->getNumDwarfOperands()) {
Out << Printer.FS << "operands: {";
FieldSeparator IFS;
for (auto &I : N->dwarf_operands()) {
Out << IFS;
writeMetadataAsOperand(Out, I, TypePrinter, Machine, Context);
}
Out << "}";
}
Out << ")";
}
static void writeDILocation(raw_ostream &Out, const DILocation *DL,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!DILocation(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
// Always output the line, since 0 is a relevant and important value for it.
Printer.printInt("line", DL->getLine(), /* ShouldSkipZero */ false);
Printer.printInt("column", DL->getColumn());
Printer.printMetadata("scope", DL->getRawScope(), /* ShouldSkipNull */ false);
Printer.printMetadata("inlinedAt", DL->getRawInlinedAt());
Out << ")";
}
static void writeDISubrange(raw_ostream &Out, const DISubrange *N,
TypePrinting *, SlotTracker *, const Module *) {
Out << "!DISubrange(";
MDFieldPrinter Printer(Out);
Printer.printInt("count", N->getCount(), /* ShouldSkipZero */ false);
Printer.printInt("lowerBound", N->getLowerBound());
Out << ")";
}
static void writeDIEnumerator(raw_ostream &Out, const DIEnumerator *N,
TypePrinting *, SlotTracker *, const Module *) {
Out << "!DIEnumerator(";
MDFieldPrinter Printer(Out);
Printer.printString("name", N->getName(), /* ShouldSkipEmpty */ false);
Printer.printInt("value", N->getValue(), /* ShouldSkipZero */ false);
Out << ")";
}
static void writeDIBasicType(raw_ostream &Out, const DIBasicType *N,
TypePrinting *, SlotTracker *, const Module *) {
Out << "!DIBasicType(";
MDFieldPrinter Printer(Out);
if (N->getTag() != dwarf::DW_TAG_base_type)
Printer.printTag(N);
Printer.printString("name", N->getName());
Printer.printInt("size", N->getSizeInBits());
Printer.printInt("align", N->getAlignInBits());
Printer.printDwarfEnum("encoding", N->getEncoding(),
dwarf::AttributeEncodingString);
Out << ")";
}
static void writeDIDerivedType(raw_ostream &Out, const DIDerivedType *N,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!DIDerivedType(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printTag(N);
Printer.printString("name", N->getName());
Printer.printMetadata("scope", N->getRawScope());
Printer.printMetadata("file", N->getRawFile());
Printer.printInt("line", N->getLine());
Printer.printMetadata("baseType", N->getRawBaseType(),
/* ShouldSkipNull */ false);
Printer.printInt("size", N->getSizeInBits());
Printer.printInt("align", N->getAlignInBits());
Printer.printInt("offset", N->getOffsetInBits());
Printer.printDIFlags("flags", N->getFlags());
Printer.printMetadata("extraData", N->getRawExtraData());
Out << ")";
}
static void writeDICompositeType(raw_ostream &Out, const DICompositeType *N,
TypePrinting *TypePrinter,
SlotTracker *Machine, const Module *Context) {
Out << "!DICompositeType(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printTag(N);
Printer.printString("name", N->getName());
Printer.printMetadata("scope", N->getRawScope());
Printer.printMetadata("file", N->getRawFile());
Printer.printInt("line", N->getLine());
Printer.printMetadata("baseType", N->getRawBaseType());
Printer.printInt("size", N->getSizeInBits());
Printer.printInt("align", N->getAlignInBits());
Printer.printInt("offset", N->getOffsetInBits());
Printer.printDIFlags("flags", N->getFlags());
Printer.printMetadata("elements", N->getRawElements());
Printer.printDwarfEnum("runtimeLang", N->getRuntimeLang(),
dwarf::LanguageString);
Printer.printMetadata("vtableHolder", N->getRawVTableHolder());
Printer.printMetadata("templateParams", N->getRawTemplateParams());
Printer.printString("identifier", N->getIdentifier());
Out << ")";
}
static void writeDISubroutineType(raw_ostream &Out, const DISubroutineType *N,
TypePrinting *TypePrinter,
SlotTracker *Machine, const Module *Context) {
Out << "!DISubroutineType(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printDIFlags("flags", N->getFlags());
Printer.printMetadata("types", N->getRawTypeArray(),
/* ShouldSkipNull */ false);
Out << ")";
}
static void writeDIFile(raw_ostream &Out, const DIFile *N, TypePrinting *,
SlotTracker *, const Module *) {
Out << "!DIFile(";
MDFieldPrinter Printer(Out);
Printer.printString("filename", N->getFilename(),
/* ShouldSkipEmpty */ false);
Printer.printString("directory", N->getDirectory(),
/* ShouldSkipEmpty */ false);
Out << ")";
}
static void writeDICompileUnit(raw_ostream &Out, const DICompileUnit *N,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!DICompileUnit(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printDwarfEnum("language", N->getSourceLanguage(),
dwarf::LanguageString, /* ShouldSkipZero */ false);
Printer.printMetadata("file", N->getRawFile(), /* ShouldSkipNull */ false);
Printer.printString("producer", N->getProducer());
Printer.printBool("isOptimized", N->isOptimized());
Printer.printString("flags", N->getFlags());
Printer.printInt("runtimeVersion", N->getRuntimeVersion(),
/* ShouldSkipZero */ false);
Printer.printString("splitDebugFilename", N->getSplitDebugFilename());
Printer.printInt("emissionKind", N->getEmissionKind(),
/* ShouldSkipZero */ false);
Printer.printMetadata("enums", N->getRawEnumTypes());
Printer.printMetadata("retainedTypes", N->getRawRetainedTypes());
Printer.printMetadata("subprograms", N->getRawSubprograms());
Printer.printMetadata("globals", N->getRawGlobalVariables());
Printer.printMetadata("imports", N->getRawImportedEntities());
Printer.printInt("dwoId", N->getDWOId());
Out << ")";
}
static void writeDISubprogram(raw_ostream &Out, const DISubprogram *N,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!DISubprogram(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printString("name", N->getName());
Printer.printString("linkageName", N->getLinkageName());
Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
Printer.printMetadata("file", N->getRawFile());
Printer.printInt("line", N->getLine());
Printer.printMetadata("type", N->getRawType());
Printer.printBool("isLocal", N->isLocalToUnit());
Printer.printBool("isDefinition", N->isDefinition());
Printer.printInt("scopeLine", N->getScopeLine());
Printer.printMetadata("containingType", N->getRawContainingType());
Printer.printDwarfEnum("virtuality", N->getVirtuality(),
dwarf::VirtualityString);
Printer.printInt("virtualIndex", N->getVirtualIndex());
Printer.printDIFlags("flags", N->getFlags());
Printer.printBool("isOptimized", N->isOptimized());
Printer.printMetadata("function", N->getRawFunction());
Printer.printMetadata("templateParams", N->getRawTemplateParams());
Printer.printMetadata("declaration", N->getRawDeclaration());
Printer.printMetadata("variables", N->getRawVariables());
Out << ")";
}
static void writeDILexicalBlock(raw_ostream &Out, const DILexicalBlock *N,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!DILexicalBlock(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
Printer.printMetadata("file", N->getRawFile());
Printer.printInt("line", N->getLine());
Printer.printInt("column", N->getColumn());
Out << ")";
}
static void writeDILexicalBlockFile(raw_ostream &Out,
const DILexicalBlockFile *N,
TypePrinting *TypePrinter,
SlotTracker *Machine,
const Module *Context) {
Out << "!DILexicalBlockFile(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
Printer.printMetadata("file", N->getRawFile());
Printer.printInt("discriminator", N->getDiscriminator(),
/* ShouldSkipZero */ false);
Out << ")";
}
static void writeDINamespace(raw_ostream &Out, const DINamespace *N,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!DINamespace(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printString("name", N->getName());
Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
Printer.printMetadata("file", N->getRawFile());
Printer.printInt("line", N->getLine());
Out << ")";
}
static void writeDIModule(raw_ostream &Out, const DIModule *N,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!DIModule(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
Printer.printString("name", N->getName());
Printer.printString("configMacros", N->getConfigurationMacros());
Printer.printString("includePath", N->getIncludePath());
Printer.printString("isysroot", N->getISysRoot());
Out << ")";
}
static void writeDITemplateTypeParameter(raw_ostream &Out,
const DITemplateTypeParameter *N,
TypePrinting *TypePrinter,
SlotTracker *Machine,
const Module *Context) {
Out << "!DITemplateTypeParameter(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printString("name", N->getName());
Printer.printMetadata("type", N->getRawType(), /* ShouldSkipNull */ false);
Out << ")";
}
static void writeDITemplateValueParameter(raw_ostream &Out,
const DITemplateValueParameter *N,
TypePrinting *TypePrinter,
SlotTracker *Machine,
const Module *Context) {
Out << "!DITemplateValueParameter(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
if (N->getTag() != dwarf::DW_TAG_template_value_parameter)
Printer.printTag(N);
Printer.printString("name", N->getName());
Printer.printMetadata("type", N->getRawType());
Printer.printMetadata("value", N->getValue(), /* ShouldSkipNull */ false);
Out << ")";
}
static void writeDIGlobalVariable(raw_ostream &Out, const DIGlobalVariable *N,
TypePrinting *TypePrinter,
SlotTracker *Machine, const Module *Context) {
Out << "!DIGlobalVariable(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printString("name", N->getName());
Printer.printString("linkageName", N->getLinkageName());
Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
Printer.printMetadata("file", N->getRawFile());
Printer.printInt("line", N->getLine());
Printer.printMetadata("type", N->getRawType());
Printer.printBool("isLocal", N->isLocalToUnit());
Printer.printBool("isDefinition", N->isDefinition());
Printer.printMetadata("variable", N->getRawVariable());
Printer.printMetadata("declaration", N->getRawStaticDataMemberDeclaration());
Out << ")";
}
static void writeDILocalVariable(raw_ostream &Out, const DILocalVariable *N,
TypePrinting *TypePrinter,
SlotTracker *Machine, const Module *Context) {
Out << "!DILocalVariable(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printTag(N);
Printer.printString("name", N->getName());
Printer.printInt("arg", N->getArg(),
/* ShouldSkipZero */
N->getTag() == dwarf::DW_TAG_auto_variable);
Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
Printer.printMetadata("file", N->getRawFile());
Printer.printInt("line", N->getLine());
Printer.printMetadata("type", N->getRawType());
Printer.printDIFlags("flags", N->getFlags());
Out << ")";
}
static void writeDIExpression(raw_ostream &Out, const DIExpression *N,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!DIExpression(";
FieldSeparator FS;
if (N->isValid()) {
for (auto I = N->expr_op_begin(), E = N->expr_op_end(); I != E; ++I) {
const char *OpStr = dwarf::OperationEncodingString(I->getOp());
assert(OpStr && "Expected valid opcode");
Out << FS << OpStr;
for (unsigned A = 0, AE = I->getNumArgs(); A != AE; ++A)
Out << FS << I->getArg(A);
}
} else {
for (const auto &I : N->getElements())
Out << FS << I;
}
Out << ")";
}
static void writeDIObjCProperty(raw_ostream &Out, const DIObjCProperty *N,
TypePrinting *TypePrinter, SlotTracker *Machine,
const Module *Context) {
Out << "!DIObjCProperty(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printString("name", N->getName());
Printer.printMetadata("file", N->getRawFile());
Printer.printInt("line", N->getLine());
Printer.printString("setter", N->getSetterName());
Printer.printString("getter", N->getGetterName());
Printer.printInt("attributes", N->getAttributes());
Printer.printMetadata("type", N->getRawType());
Out << ")";
}
static void writeDIImportedEntity(raw_ostream &Out, const DIImportedEntity *N,
TypePrinting *TypePrinter,
SlotTracker *Machine, const Module *Context) {
Out << "!DIImportedEntity(";
MDFieldPrinter Printer(Out, TypePrinter, Machine, Context);
Printer.printTag(N);
Printer.printString("name", N->getName());
Printer.printMetadata("scope", N->getRawScope(), /* ShouldSkipNull */ false);
Printer.printMetadata("entity", N->getRawEntity());
Printer.printInt("line", N->getLine());
Out << ")";
}
static void WriteMDNodeBodyInternal(raw_ostream &Out, const MDNode *Node,
TypePrinting *TypePrinter,
SlotTracker *Machine,
const Module *Context) {
if (Node->isDistinct())
Out << "distinct ";
else if (Node->isTemporary())
Out << "<temporary!> "; // Handle broken code.
switch (Node->getMetadataID()) {
default:
llvm_unreachable("Expected uniquable MDNode");
#define HANDLE_MDNODE_LEAF(CLASS) \
case Metadata::CLASS##Kind: \
write##CLASS(Out, cast<CLASS>(Node), TypePrinter, Machine, Context); \
break;
#include "llvm/IR/Metadata.def"
}
}
// Full implementation of printing a Value as an operand with support for
// TypePrinting, etc.
static void WriteAsOperandInternal(raw_ostream &Out, const Value *V,
TypePrinting *TypePrinter,
SlotTracker *Machine,
const Module *Context) {
if (V->hasName()) {
PrintLLVMName(Out, V);
return;
}
const Constant *CV = dyn_cast<Constant>(V);
if (CV && !isa<GlobalValue>(CV)) {
assert(TypePrinter && "Constants require TypePrinting!");
WriteConstantInternal(Out, CV, *TypePrinter, Machine, Context);
return;
}
if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
Out << "asm ";
if (IA->hasSideEffects())
Out << "sideeffect ";
if (IA->isAlignStack())
Out << "alignstack ";
// We don't emit the AD_ATT dialect as it's the assumed default.
if (IA->getDialect() == InlineAsm::AD_Intel)
Out << "inteldialect ";
Out << '"';
PrintEscapedString(IA->getAsmString(), Out);
Out << "\", \"";
PrintEscapedString(IA->getConstraintString(), Out);
Out << '"';
return;
}
if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
WriteAsOperandInternal(Out, MD->getMetadata(), TypePrinter, Machine,
Context, /* FromValue */ true);
return;
}
char Prefix = '%';
int Slot;
// If we have a SlotTracker, use it.
if (Machine) {
if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
Slot = Machine->getGlobalSlot(GV);
Prefix = '@';
} else {
Slot = Machine->getLocalSlot(V);
// If the local value didn't succeed, then we may be referring to a value
// from a different function. Translate it, as this can happen when using
// address of blocks.
if (Slot == -1)
if ((Machine = createSlotTracker(V))) {
Slot = Machine->getLocalSlot(V);
delete Machine;
}
}
} else if ((Machine = createSlotTracker(V))) {
// Otherwise, create one to get the # and then destroy it.
if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
Slot = Machine->getGlobalSlot(GV);
Prefix = '@';
} else {
Slot = Machine->getLocalSlot(V);
}
delete Machine;
Machine = nullptr;
} else {
Slot = -1;
}
if (Slot != -1)
Out << Prefix << Slot;
else
Out << "<badref>";
}
static void WriteAsOperandInternal(raw_ostream &Out, const Metadata *MD,
TypePrinting *TypePrinter,
SlotTracker *Machine, const Module *Context,
bool FromValue) {
if (const MDNode *N = dyn_cast<MDNode>(MD)) {
std::unique_ptr<SlotTracker> MachineStorage;
if (!Machine) {
MachineStorage = make_unique<SlotTracker>(Context);
Machine = MachineStorage.get();
}
int Slot = Machine->getMetadataSlot(N);
if (Slot == -1)
// Give the pointer value instead of "badref", since this comes up all
// the time when debugging.
Out << "<" << N << ">";
else
Out << '!' << Slot;
return;
}
if (const MDString *MDS = dyn_cast<MDString>(MD)) {
Out << "!\"";
PrintEscapedString(MDS->getString(), Out);
Out << '"';
return;
}
auto *V = cast<ValueAsMetadata>(MD);
assert(TypePrinter && "TypePrinter required for metadata values");
assert((FromValue || !isa<LocalAsMetadata>(V)) &&
"Unexpected function-local metadata outside of value argument");
TypePrinter->print(V->getValue()->getType(), Out);
Out << ' ';
WriteAsOperandInternal(Out, V->getValue(), TypePrinter, Machine, Context);
}
namespace {
class AssemblyWriter {
formatted_raw_ostream &Out;
const Module *TheModule;
std::unique_ptr<SlotTracker> SlotTrackerStorage;
SlotTracker &Machine;
TypePrinting TypePrinter;
AssemblyAnnotationWriter *AnnotationWriter;
SetVector<const Comdat *> Comdats;
bool ShouldPreserveUseListOrder;
UseListOrderStack UseListOrders;
SmallVector<StringRef, 8> MDNames;
public:
/// Construct an AssemblyWriter with an external SlotTracker
AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac, const Module *M,
AssemblyAnnotationWriter *AAW,
bool ShouldPreserveUseListOrder = false);
/// Construct an AssemblyWriter with an internally allocated SlotTracker
AssemblyWriter(formatted_raw_ostream &o, const Module *M,
AssemblyAnnotationWriter *AAW,
bool ShouldPreserveUseListOrder = false);
void printMDNodeBody(const MDNode *MD);
void printNamedMDNode(const NamedMDNode *NMD);
void printModule(const Module *M);
void writeOperand(const Value *Op, bool PrintType);
void writeParamOperand(const Value *Operand, AttributeSet Attrs,unsigned Idx);
void writeAtomic(AtomicOrdering Ordering, SynchronizationScope SynchScope);
void writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
AtomicOrdering FailureOrdering,
SynchronizationScope SynchScope);
void writeAllMDNodes();
void writeMDNode(unsigned Slot, const MDNode *Node);
void writeAllAttributeGroups();
void printTypeIdentities();
void printGlobal(const GlobalVariable *GV);
void printAlias(const GlobalAlias *GV);
void printComdat(const Comdat *C);
void printFunction(const Function *F);
void printArgument(const Argument *FA, AttributeSet Attrs, unsigned Idx);
void printBasicBlock(const BasicBlock *BB);
void printInstructionLine(const Instruction &I);
void printInstruction(const Instruction &I);
void printUseListOrder(const UseListOrder &Order);
void printUseLists(const Function *F);
private:
void init();
/// \brief Print out metadata attachments.
void printMetadataAttachments(
const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
StringRef Separator);
// printInfoComment - Print a little comment after the instruction indicating
// which slot it occupies.
void printInfoComment(const Value &V);
// printGCRelocateComment - print comment after call to the gc.relocate
// intrinsic indicating base and derived pointer names.
void printGCRelocateComment(const Value &V);
};
} // namespace
void AssemblyWriter::init() {
if (!TheModule)
return;
TypePrinter.incorporateTypes(*TheModule);
for (const Function &F : *TheModule)
if (const Comdat *C = F.getComdat())
Comdats.insert(C);
for (const GlobalVariable &GV : TheModule->globals())
if (const Comdat *C = GV.getComdat())
Comdats.insert(C);
}
AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, SlotTracker &Mac,
const Module *M, AssemblyAnnotationWriter *AAW,
bool ShouldPreserveUseListOrder)
: Out(o), TheModule(M), Machine(Mac), AnnotationWriter(AAW),
ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
init();
}
#if 0 // HLSL Change - Unused
AssemblyWriter::AssemblyWriter(formatted_raw_ostream &o, const Module *M,
AssemblyAnnotationWriter *AAW,
bool ShouldPreserveUseListOrder)
: Out(o), TheModule(M), SlotTrackerStorage(createSlotTracker(M)),
Machine(*SlotTrackerStorage), AnnotationWriter(AAW),
ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
init();
}
#endif
void AssemblyWriter::writeOperand(const Value *Operand, bool PrintType) {
if (!Operand) {
Out << "<null operand!>";
return;
}
if (PrintType) {
TypePrinter.print(Operand->getType(), Out);
Out << ' ';
}
WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
}
void AssemblyWriter::writeAtomic(AtomicOrdering Ordering,
SynchronizationScope SynchScope) {
if (Ordering == NotAtomic)
return;
switch (SynchScope) {
case SingleThread: Out << " singlethread"; break;
case CrossThread: break;
}
switch (Ordering) {
default: Out << " <bad ordering " << int(Ordering) << ">"; break;
case Unordered: Out << " unordered"; break;
case Monotonic: Out << " monotonic"; break;
case Acquire: Out << " acquire"; break;
case Release: Out << " release"; break;
case AcquireRelease: Out << " acq_rel"; break;
case SequentiallyConsistent: Out << " seq_cst"; break;
}
}
void AssemblyWriter::writeAtomicCmpXchg(AtomicOrdering SuccessOrdering,
AtomicOrdering FailureOrdering,
SynchronizationScope SynchScope) {
assert(SuccessOrdering != NotAtomic && FailureOrdering != NotAtomic);
switch (SynchScope) {
case SingleThread: Out << " singlethread"; break;
case CrossThread: break;
}
switch (SuccessOrdering) {
default: Out << " <bad ordering " << int(SuccessOrdering) << ">"; break;
case Unordered: Out << " unordered"; break;
case Monotonic: Out << " monotonic"; break;
case Acquire: Out << " acquire"; break;
case Release: Out << " release"; break;
case AcquireRelease: Out << " acq_rel"; break;
case SequentiallyConsistent: Out << " seq_cst"; break;
}
switch (FailureOrdering) {
default: Out << " <bad ordering " << int(FailureOrdering) << ">"; break;
case Unordered: Out << " unordered"; break;
case Monotonic: Out << " monotonic"; break;
case Acquire: Out << " acquire"; break;
case Release: Out << " release"; break;
case AcquireRelease: Out << " acq_rel"; break;
case SequentiallyConsistent: Out << " seq_cst"; break;
}
}
void AssemblyWriter::writeParamOperand(const Value *Operand,
AttributeSet Attrs, unsigned Idx) {
if (!Operand) {
Out << "<null operand!>";
return;
}
// Print the type
TypePrinter.print(Operand->getType(), Out);
// Print parameter attributes list
if (Attrs.hasAttributes(Idx))
Out << ' ' << Attrs.getAsString(Idx);
Out << ' ';
// Print the operand
WriteAsOperandInternal(Out, Operand, &TypePrinter, &Machine, TheModule);
}
void AssemblyWriter::printModule(const Module *M) {
Machine.initialize();
if (ShouldPreserveUseListOrder)
UseListOrders = predictUseListOrder(M);
if (!M->getModuleIdentifier().empty() &&
// Don't print the ID if it will start a new line (which would
// require a comment char before it).
M->getModuleIdentifier().find('\n') == std::string::npos)
Out << "; ModuleID = '" << M->getModuleIdentifier() << "'\n";
const std::string &DL = M->getDataLayoutStr();
if (!DL.empty())
Out << "target datalayout = \"" << DL << "\"\n";
if (!M->getTargetTriple().empty())
Out << "target triple = \"" << M->getTargetTriple() << "\"\n";
if (!M->getModuleInlineAsm().empty()) {
Out << '\n';
// Split the string into lines, to make it easier to read the .ll file.
StringRef Asm = M->getModuleInlineAsm();
do {
StringRef Front;
std::tie(Front, Asm) = Asm.split('\n');
// We found a newline, print the portion of the asm string from the
// last newline up to this newline.
Out << "module asm \"";
PrintEscapedString(Front, Out);
Out << "\"\n";
} while (!Asm.empty());
}
printTypeIdentities();
// Output all comdats.
if (!Comdats.empty())
Out << '\n';
for (const Comdat *C : Comdats) {
printComdat(C);
if (C != Comdats.back())
Out << '\n';
}
// Output all globals.
if (!M->global_empty()) Out << '\n';
for (const GlobalVariable &GV : M->globals()) {
printGlobal(&GV); Out << '\n';
}
// Output all aliases.
if (!M->alias_empty()) Out << "\n";
for (const GlobalAlias &GA : M->aliases())
printAlias(&GA);
// Output global use-lists.
printUseLists(nullptr);
// Output all of the functions.
for (const Function &F : *M)
printFunction(&F);
assert(UseListOrders.empty() && "All use-lists should have been consumed");
// Output all attribute groups.
if (!Machine.as_empty()) {
Out << '\n';
writeAllAttributeGroups();
}
// Output named metadata.
if (!M->named_metadata_empty()) Out << '\n';
for (const NamedMDNode &Node : M->named_metadata())
printNamedMDNode(&Node);
// Output metadata.
if (!Machine.mdn_empty()) {
Out << '\n';
writeAllMDNodes();
}
}
static void printMetadataIdentifier(StringRef Name,
formatted_raw_ostream &Out) {
if (Name.empty()) {
Out << "<empty name> ";
} else {
if (isalpha(static_cast<unsigned char>(Name[0])) || Name[0] == '-' ||
Name[0] == '$' || Name[0] == '.' || Name[0] == '_')
Out << Name[0];
else
Out << '\\' << hexdigit(Name[0] >> 4) << hexdigit(Name[0] & 0x0F);
for (unsigned i = 1, e = Name.size(); i != e; ++i) {
unsigned char C = Name[i];
if (isalnum(static_cast<unsigned char>(C)) || C == '-' || C == '$' ||
C == '.' || C == '_')
Out << C;
else
Out << '\\' << hexdigit(C >> 4) << hexdigit(C & 0x0F);
}
}
}
void AssemblyWriter::printNamedMDNode(const NamedMDNode *NMD) {
Out << '!';
printMetadataIdentifier(NMD->getName(), Out);
Out << " = !{";
for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
if (i)
Out << ", ";
int Slot = Machine.getMetadataSlot(NMD->getOperand(i));
if (Slot == -1)
Out << "<badref>";
else
Out << '!' << Slot;
}
Out << "}\n";
}
static void PrintLinkage(GlobalValue::LinkageTypes LT,
formatted_raw_ostream &Out) {
switch (LT) {
case GlobalValue::ExternalLinkage: break;
case GlobalValue::PrivateLinkage: Out << "private "; break;
case GlobalValue::InternalLinkage: Out << "internal "; break;
case GlobalValue::LinkOnceAnyLinkage: Out << "linkonce "; break;
case GlobalValue::LinkOnceODRLinkage: Out << "linkonce_odr "; break;
case GlobalValue::WeakAnyLinkage: Out << "weak "; break;
case GlobalValue::WeakODRLinkage: Out << "weak_odr "; break;
case GlobalValue::CommonLinkage: Out << "common "; break;
case GlobalValue::AppendingLinkage: Out << "appending "; break;
case GlobalValue::ExternalWeakLinkage: Out << "extern_weak "; break;
case GlobalValue::AvailableExternallyLinkage:
Out << "available_externally ";
break;
}
}
static void PrintVisibility(GlobalValue::VisibilityTypes Vis,
formatted_raw_ostream &Out) {
switch (Vis) {
case GlobalValue::DefaultVisibility: break;
case GlobalValue::HiddenVisibility: Out << "hidden "; break;
case GlobalValue::ProtectedVisibility: Out << "protected "; break;
}
}
static void PrintDLLStorageClass(GlobalValue::DLLStorageClassTypes SCT,
formatted_raw_ostream &Out) {
switch (SCT) {
case GlobalValue::DefaultStorageClass: break;
case GlobalValue::DLLImportStorageClass: Out << "dllimport "; break;
case GlobalValue::DLLExportStorageClass: Out << "dllexport "; break;
}
}
static void PrintThreadLocalModel(GlobalVariable::ThreadLocalMode TLM,
formatted_raw_ostream &Out) {
switch (TLM) {
case GlobalVariable::NotThreadLocal:
break;
case GlobalVariable::GeneralDynamicTLSModel:
Out << "thread_local ";
break;
case GlobalVariable::LocalDynamicTLSModel:
Out << "thread_local(localdynamic) ";
break;
case GlobalVariable::InitialExecTLSModel:
Out << "thread_local(initialexec) ";
break;
case GlobalVariable::LocalExecTLSModel:
Out << "thread_local(localexec) ";
break;
}
}
static void maybePrintComdat(formatted_raw_ostream &Out,
const GlobalObject &GO) {
const Comdat *C = GO.getComdat();
if (!C)
return;
if (isa<GlobalVariable>(GO))
Out << ',';
Out << " comdat";
if (GO.getName() == C->getName())
return;
Out << '(';
PrintLLVMName(Out, C->getName(), ComdatPrefix);
Out << ')';
}
void AssemblyWriter::printGlobal(const GlobalVariable *GV) {
if (GV->isMaterializable())
Out << "; Materializable\n";
WriteAsOperandInternal(Out, GV, &TypePrinter, &Machine, GV->getParent());
Out << " = ";
if (!GV->hasInitializer() && GV->hasExternalLinkage())
Out << "external ";
PrintLinkage(GV->getLinkage(), Out);
PrintVisibility(GV->getVisibility(), Out);
PrintDLLStorageClass(GV->getDLLStorageClass(), Out);
PrintThreadLocalModel(GV->getThreadLocalMode(), Out);
if (GV->hasUnnamedAddr())
Out << "unnamed_addr ";
if (unsigned AddressSpace = GV->getType()->getAddressSpace())
Out << "addrspace(" << AddressSpace << ") ";
if (GV->isExternallyInitialized()) Out << "externally_initialized ";
Out << (GV->isConstant() ? "constant " : "global ");
TypePrinter.print(GV->getType()->getElementType(), Out);
if (GV->hasInitializer()) {
Out << ' ';
writeOperand(GV->getInitializer(), false);
}
if (GV->hasSection()) {
Out << ", section \"";
PrintEscapedString(GV->getSection(), Out);
Out << '"';
}
maybePrintComdat(Out, *GV);
if (GV->getAlignment())
Out << ", align " << GV->getAlignment();
printInfoComment(*GV);
}
void AssemblyWriter::printAlias(const GlobalAlias *GA) {
if (GA->isMaterializable())
Out << "; Materializable\n";
WriteAsOperandInternal(Out, GA, &TypePrinter, &Machine, GA->getParent());
Out << " = ";
PrintLinkage(GA->getLinkage(), Out);
PrintVisibility(GA->getVisibility(), Out);
PrintDLLStorageClass(GA->getDLLStorageClass(), Out);
PrintThreadLocalModel(GA->getThreadLocalMode(), Out);
if (GA->hasUnnamedAddr())
Out << "unnamed_addr ";
Out << "alias ";
const Constant *Aliasee = GA->getAliasee();
if (!Aliasee) {
TypePrinter.print(GA->getType(), Out);
Out << " <<NULL ALIASEE>>";
} else {
writeOperand(Aliasee, !isa<ConstantExpr>(Aliasee));
}
printInfoComment(*GA);
Out << '\n';
}
void AssemblyWriter::printComdat(const Comdat *C) {
C->print(Out);
}
void AssemblyWriter::printTypeIdentities() {
if (TypePrinter.NumberedTypes.empty() &&
TypePrinter.NamedTypes.empty())
return;
Out << '\n';
// We know all the numbers that each type is used and we know that it is a
// dense assignment. Convert the map to an index table.
std::vector<StructType*> NumberedTypes(TypePrinter.NumberedTypes.size());
for (DenseMap<StructType*, unsigned>::iterator I =
TypePrinter.NumberedTypes.begin(), E = TypePrinter.NumberedTypes.end();
I != E; ++I) {
assert(I->second < NumberedTypes.size() && "Didn't get a dense numbering?");
NumberedTypes[I->second] = I->first;
}
// Emit all numbered types.
for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i) {
Out << '%' << i << " = type ";
// Make sure we print out at least one level of the type structure, so
// that we do not get %2 = type %2
TypePrinter.printStructBody(NumberedTypes[i], Out);
Out << '\n';
}
for (unsigned i = 0, e = TypePrinter.NamedTypes.size(); i != e; ++i) {
PrintLLVMName(Out, TypePrinter.NamedTypes[i]->getName(), LocalPrefix);
Out << " = type ";
// Make sure we print out at least one level of the type structure, so
// that we do not get %FILE = type %FILE
TypePrinter.printStructBody(TypePrinter.NamedTypes[i], Out);
Out << '\n';
}
}
/// printFunction - Print all aspects of a function.
///
void AssemblyWriter::printFunction(const Function *F) {
// Print out the return type and name.
Out << '\n';
if (AnnotationWriter) AnnotationWriter->emitFunctionAnnot(F, Out);
if (F->isMaterializable())
Out << "; Materializable\n";
const AttributeSet &Attrs = F->getAttributes();
if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) {
AttributeSet AS = Attrs.getFnAttributes();
std::string AttrStr;
unsigned Idx = 0;
for (unsigned E = AS.getNumSlots(); Idx != E; ++Idx)
if (AS.getSlotIndex(Idx) == AttributeSet::FunctionIndex)
break;
for (AttributeSet::iterator I = AS.begin(Idx), E = AS.end(Idx);
I != E; ++I) {
Attribute Attr = *I;
if (!Attr.isStringAttribute()) {
if (!AttrStr.empty()) AttrStr += ' ';
AttrStr += Attr.getAsString();
}
}
if (!AttrStr.empty())
Out << "; Function Attrs: " << AttrStr << '\n';
}
if (F->isDeclaration())
Out << "declare ";
else
Out << "define ";
PrintLinkage(F->getLinkage(), Out);
PrintVisibility(F->getVisibility(), Out);
PrintDLLStorageClass(F->getDLLStorageClass(), Out);
// Print the calling convention.
if (F->getCallingConv() != CallingConv::C) {
PrintCallingConv(F->getCallingConv(), Out);
Out << " ";
}
FunctionType *FT = F->getFunctionType();
if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Out << Attrs.getAsString(AttributeSet::ReturnIndex) << ' ';
TypePrinter.print(F->getReturnType(), Out);
Out << ' ';
WriteAsOperandInternal(Out, F, &TypePrinter, &Machine, F->getParent());
Out << '(';
Machine.incorporateFunction(F);
// Loop over the arguments, printing them...
unsigned Idx = 1;
if (!F->isDeclaration()) {
// If this isn't a declaration, print the argument names as well.
for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
I != E; ++I) {
// Insert commas as we go... the first arg doesn't get a comma
if (I != F->arg_begin()) Out << ", ";
printArgument(I, Attrs, Idx);
Idx++;
}
} else {
// Otherwise, print the types from the function type.
for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
// Insert commas as we go... the first arg doesn't get a comma
if (i) Out << ", ";
// Output type...
TypePrinter.print(FT->getParamType(i), Out);
if (Attrs.hasAttributes(i+1))
Out << ' ' << Attrs.getAsString(i+1);
}
}
// Finish printing arguments...
if (FT->isVarArg()) {
if (FT->getNumParams()) Out << ", ";
Out << "..."; // Output varargs portion of signature!
}
Out << ')';
if (F->hasUnnamedAddr())
Out << " unnamed_addr";
if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Out << " #" << Machine.getAttributeGroupSlot(Attrs.getFnAttributes());
if (F->hasSection()) {
Out << " section \"";
PrintEscapedString(F->getSection(), Out);
Out << '"';
}
maybePrintComdat(Out, *F);
if (F->getAlignment())
Out << " align " << F->getAlignment();
if (F->hasGC())
Out << " gc \"" << F->getGC() << '"';
if (F->hasPrefixData()) {
Out << " prefix ";
writeOperand(F->getPrefixData(), true);
}
if (F->hasPrologueData()) {
Out << " prologue ";
writeOperand(F->getPrologueData(), true);
}
if (F->hasPersonalityFn()) {
Out << " personality ";
writeOperand(F->getPersonalityFn(), /*PrintType=*/true);
}
SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
F->getAllMetadata(MDs);
printMetadataAttachments(MDs, " ");
if (F->isDeclaration()) {
Out << '\n';
} else {
Out << " {";
// Output all of the function's basic blocks.
for (Function::const_iterator I = F->begin(), E = F->end(); I != E; ++I)
printBasicBlock(I);
// Output the function's use-lists.
printUseLists(F);
Out << "}\n";
}
Machine.purgeFunction();
}
/// printArgument - This member is called for every argument that is passed into
/// the function. Simply print it out
///
void AssemblyWriter::printArgument(const Argument *Arg,
AttributeSet Attrs, unsigned Idx) {
// Output type...
TypePrinter.print(Arg->getType(), Out);
// Output parameter attributes list
if (Attrs.hasAttributes(Idx))
Out << ' ' << Attrs.getAsString(Idx);
// Output name, if available...
if (Arg->hasName()) {
Out << ' ';
PrintLLVMName(Out, Arg);
}
}
/// printBasicBlock - This member is called for each basic block in a method.
///
void AssemblyWriter::printBasicBlock(const BasicBlock *BB) {
if (BB->hasName()) { // Print out the label if it exists...
Out << "\n";
PrintLLVMName(Out, BB->getName(), LabelPrefix);
Out << ':';
} else if (!BB->use_empty()) { // Don't print block # of no uses...
Out << "\n; <label>:";
int Slot = Machine.getLocalSlot(BB);
if (Slot != -1)
Out << Slot;
else
Out << "<badref>";
}
if (!BB->getParent()) {
Out.PadToColumn(50);
Out << "; Error: Block without parent!";
} else if (BB != &BB->getParent()->getEntryBlock()) { // Not the entry block?
// Output predecessors for the block.
Out.PadToColumn(50);
Out << ";";
const_pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
if (PI == PE) {
Out << " No predecessors!";
} else {
Out << " preds = ";
writeOperand(*PI, false);
for (++PI; PI != PE; ++PI) {
Out << ", ";
writeOperand(*PI, false);
}
}
}
Out << "\n";
if (AnnotationWriter) AnnotationWriter->emitBasicBlockStartAnnot(BB, Out);
// Output all of the instructions in the basic block...
for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
printInstructionLine(*I);
}
if (AnnotationWriter) AnnotationWriter->emitBasicBlockEndAnnot(BB, Out);
}
/// printInstructionLine - Print an instruction and a newline character.
void AssemblyWriter::printInstructionLine(const Instruction &I) {
printInstruction(I);
Out << '\n';
}
/// printGCRelocateComment - print comment after call to the gc.relocate
/// intrinsic indicating base and derived pointer names.
void AssemblyWriter::printGCRelocateComment(const Value &V) {
assert(isGCRelocate(&V));
GCRelocateOperands GCOps(cast<Instruction>(&V));
Out << " ; (";
writeOperand(GCOps.getBasePtr(), false);
Out << ", ";
writeOperand(GCOps.getDerivedPtr(), false);
Out << ")";
}
/// printInfoComment - Print a little comment after the instruction indicating
/// which slot it occupies.
///
void AssemblyWriter::printInfoComment(const Value &V) {
if (isGCRelocate(&V))
printGCRelocateComment(V);
if (AnnotationWriter)
AnnotationWriter->printInfoComment(V, Out);
}
// This member is called for each Instruction in a function..
void AssemblyWriter::printInstruction(const Instruction &I) {
if (AnnotationWriter) AnnotationWriter->emitInstructionAnnot(&I, Out);
// Print out indentation for an instruction.
Out << " ";
// Print out name if it exists...
if (I.hasName()) {
PrintLLVMName(Out, &I);
Out << " = ";
} else if (!I.getType()->isVoidTy()) {
// Print out the def slot taken.
int SlotNum = Machine.getLocalSlot(&I);
if (SlotNum == -1)
Out << "<badref> = ";
else
Out << '%' << SlotNum << " = ";
}
if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
if (CI->isMustTailCall())
Out << "musttail ";
else if (CI->isTailCall())
Out << "tail ";
}
// Print out the opcode...
Out << I.getOpcodeName();
// If this is an atomic load or store, print out the atomic marker.
if ((isa<LoadInst>(I) && cast<LoadInst>(I).isAtomic()) ||
(isa<StoreInst>(I) && cast<StoreInst>(I).isAtomic()))
Out << " atomic";
if (isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isWeak())
Out << " weak";
// If this is a volatile operation, print out the volatile marker.
if ((isa<LoadInst>(I) && cast<LoadInst>(I).isVolatile()) ||
(isa<StoreInst>(I) && cast<StoreInst>(I).isVolatile()) ||
(isa<AtomicCmpXchgInst>(I) && cast<AtomicCmpXchgInst>(I).isVolatile()) ||
(isa<AtomicRMWInst>(I) && cast<AtomicRMWInst>(I).isVolatile()))
Out << " volatile";
// Print out optimization information.
WriteOptimizationInfo(Out, &I);
// Print out the compare instruction predicates
if (const CmpInst *CI = dyn_cast<CmpInst>(&I))
Out << ' ' << getPredicateText(CI->getPredicate());
// Print out the atomicrmw operation
if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I))
writeAtomicRMWOperation(Out, RMWI->getOperation());
// Print out the type of the operands...
const Value *Operand = I.getNumOperands() ? I.getOperand(0) : nullptr;
// Special case conditional branches to swizzle the condition out to the front
if (isa<BranchInst>(I) && cast<BranchInst>(I).isConditional()) {
const BranchInst &BI(cast<BranchInst>(I));
Out << ' ';
writeOperand(BI.getCondition(), true);
Out << ", ";
writeOperand(BI.getSuccessor(0), true);
Out << ", ";
writeOperand(BI.getSuccessor(1), true);
} else if (isa<SwitchInst>(I)) {
const SwitchInst& SI(cast<SwitchInst>(I));
// Special case switch instruction to get formatting nice and correct.
Out << ' ';
writeOperand(SI.getCondition(), true);
Out << ", ";
writeOperand(SI.getDefaultDest(), true);
Out << " [";
for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
i != e; ++i) {
Out << "\n ";
writeOperand(i.getCaseValue(), true);
Out << ", ";
writeOperand(i.getCaseSuccessor(), true);
}
Out << "\n ]";
} else if (isa<IndirectBrInst>(I)) {
// Special case indirectbr instruction to get formatting nice and correct.
Out << ' ';
writeOperand(Operand, true);
Out << ", [";
for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
if (i != 1)
Out << ", ";
writeOperand(I.getOperand(i), true);
}
Out << ']';
} else if (const PHINode *PN = dyn_cast<PHINode>(&I)) {
Out << ' ';
TypePrinter.print(I.getType(), Out);
Out << ' ';
for (unsigned op = 0, Eop = PN->getNumIncomingValues(); op < Eop; ++op) {
if (op) Out << ", ";
Out << "[ ";
writeOperand(PN->getIncomingValue(op), false); Out << ", ";
writeOperand(PN->getIncomingBlock(op), false); Out << " ]";
}
} else if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&I)) {
Out << ' ';
writeOperand(I.getOperand(0), true);
for (const unsigned *i = EVI->idx_begin(), *e = EVI->idx_end(); i != e; ++i)
Out << ", " << *i;
} else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&I)) {
Out << ' ';
writeOperand(I.getOperand(0), true); Out << ", ";
writeOperand(I.getOperand(1), true);
for (const unsigned *i = IVI->idx_begin(), *e = IVI->idx_end(); i != e; ++i)
Out << ", " << *i;
} else if (const LandingPadInst *LPI = dyn_cast<LandingPadInst>(&I)) {
Out << ' ';
TypePrinter.print(I.getType(), Out);
if (LPI->isCleanup() || LPI->getNumClauses() != 0)
Out << '\n';
if (LPI->isCleanup())
Out << " cleanup";
for (unsigned i = 0, e = LPI->getNumClauses(); i != e; ++i) {
if (i != 0 || LPI->isCleanup()) Out << "\n";
if (LPI->isCatch(i))
Out << " catch ";
else
Out << " filter ";
writeOperand(LPI->getClause(i), true);
}
} else if (isa<ReturnInst>(I) && !Operand) {
Out << " void";
} else if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
// Print the calling convention being used.
if (CI->getCallingConv() != CallingConv::C) {
Out << " ";
PrintCallingConv(CI->getCallingConv(), Out);
}
Operand = CI->getCalledValue();
FunctionType *FTy = cast<FunctionType>(CI->getFunctionType());
Type *RetTy = FTy->getReturnType();
const AttributeSet &PAL = CI->getAttributes();
if (PAL.hasAttributes(AttributeSet::ReturnIndex))
Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
// If possible, print out the short form of the call instruction. We can
// only do this if the first argument is a pointer to a nonvararg function,
// and if the return type is not a pointer to a function.
//
Out << ' ';
TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
Out << ' ';
writeOperand(Operand, false);
Out << '(';
for (unsigned op = 0, Eop = CI->getNumArgOperands(); op < Eop; ++op) {
if (op > 0)
Out << ", ";
writeParamOperand(CI->getArgOperand(op), PAL, op + 1);
}
// Emit an ellipsis if this is a musttail call in a vararg function. This
// is only to aid readability, musttail calls forward varargs by default.
if (CI->isMustTailCall() && CI->getParent() &&
CI->getParent()->getParent() &&
CI->getParent()->getParent()->isVarArg())
Out << ", ...";
Out << ')';
if (PAL.hasAttributes(AttributeSet::FunctionIndex))
Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
} else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I)) {
Operand = II->getCalledValue();
FunctionType *FTy = cast<FunctionType>(II->getFunctionType());
Type *RetTy = FTy->getReturnType();
const AttributeSet &PAL = II->getAttributes();
// Print the calling convention being used.
if (II->getCallingConv() != CallingConv::C) {
Out << " ";
PrintCallingConv(II->getCallingConv(), Out);
}
if (PAL.hasAttributes(AttributeSet::ReturnIndex))
Out << ' ' << PAL.getAsString(AttributeSet::ReturnIndex);
// If possible, print out the short form of the invoke instruction. We can
// only do this if the first argument is a pointer to a nonvararg function,
// and if the return type is not a pointer to a function.
//
Out << ' ';
TypePrinter.print(FTy->isVarArg() ? FTy : RetTy, Out);
Out << ' ';
writeOperand(Operand, false);
Out << '(';
for (unsigned op = 0, Eop = II->getNumArgOperands(); op < Eop; ++op) {
if (op)
Out << ", ";
writeParamOperand(II->getArgOperand(op), PAL, op + 1);
}
Out << ')';
if (PAL.hasAttributes(AttributeSet::FunctionIndex))
Out << " #" << Machine.getAttributeGroupSlot(PAL.getFnAttributes());
Out << "\n to ";
writeOperand(II->getNormalDest(), true);
Out << " unwind ";
writeOperand(II->getUnwindDest(), true);
} else if (const AllocaInst *AI = dyn_cast<AllocaInst>(&I)) {
Out << ' ';
if (AI->isUsedWithInAlloca())
Out << "inalloca ";
TypePrinter.print(AI->getAllocatedType(), Out);
// Explicitly write the array size if the code is broken, if it's an array
// allocation, or if the type is not canonical for scalar allocations. The
// latter case prevents the type from mutating when round-tripping through
// assembly.
if (!AI->getArraySize() || AI->isArrayAllocation() ||
!AI->getArraySize()->getType()->isIntegerTy(32)) {
Out << ", ";
writeOperand(AI->getArraySize(), true);
}
if (AI->getAlignment()) {
Out << ", align " << AI->getAlignment();
}
} else if (isa<CastInst>(I)) {
if (Operand) {
Out << ' ';
writeOperand(Operand, true); // Work with broken code
}
Out << " to ";
TypePrinter.print(I.getType(), Out);
} else if (isa<VAArgInst>(I)) {
if (Operand) {
Out << ' ';
writeOperand(Operand, true); // Work with broken code
}
Out << ", ";
TypePrinter.print(I.getType(), Out);
} else if (Operand) { // Print the normal way.
if (const auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
Out << ' ';
TypePrinter.print(GEP->getSourceElementType(), Out);
Out << ',';
} else if (const auto *LI = dyn_cast<LoadInst>(&I)) {
Out << ' ';
TypePrinter.print(LI->getType(), Out);
Out << ',';
}
// PrintAllTypes - Instructions who have operands of all the same type
// omit the type from all but the first operand. If the instruction has
// different type operands (for example br), then they are all printed.
bool PrintAllTypes = false;
Type *TheType = Operand->getType();
// Select, Store and ShuffleVector always print all types.
if (isa<SelectInst>(I) || isa<StoreInst>(I) || isa<ShuffleVectorInst>(I)
|| isa<ReturnInst>(I)) {
PrintAllTypes = true;
} else {
for (unsigned i = 1, E = I.getNumOperands(); i != E; ++i) {
Operand = I.getOperand(i);
// note that Operand shouldn't be null, but the test helps make dump()
// more tolerant of malformed IR
if (Operand && Operand->getType() != TheType) {
PrintAllTypes = true; // We have differing types! Print them all!
break;
}
}
}
if (!PrintAllTypes) {
Out << ' ';
TypePrinter.print(TheType, Out);
}
Out << ' ';
for (unsigned i = 0, E = I.getNumOperands(); i != E; ++i) {
if (i) Out << ", ";
writeOperand(I.getOperand(i), PrintAllTypes);
}
}
// Print atomic ordering/alignment for memory operations
if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) {
if (LI->isAtomic())
writeAtomic(LI->getOrdering(), LI->getSynchScope());
if (LI->getAlignment())
Out << ", align " << LI->getAlignment();
} else if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) {
if (SI->isAtomic())
writeAtomic(SI->getOrdering(), SI->getSynchScope());
if (SI->getAlignment())
Out << ", align " << SI->getAlignment();
} else if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(&I)) {
writeAtomicCmpXchg(CXI->getSuccessOrdering(), CXI->getFailureOrdering(),
CXI->getSynchScope());
} else if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(&I)) {
writeAtomic(RMWI->getOrdering(), RMWI->getSynchScope());
} else if (const FenceInst *FI = dyn_cast<FenceInst>(&I)) {
writeAtomic(FI->getOrdering(), FI->getSynchScope());
}
// Print Metadata info.
SmallVector<std::pair<unsigned, MDNode *>, 4> InstMD;
I.getAllMetadata(InstMD);
printMetadataAttachments(InstMD, ", ");
// Print a nice comment.
printInfoComment(I);
}
void AssemblyWriter::printMetadataAttachments(
const SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs,
StringRef Separator) {
if (MDs.empty())
return;
if (MDNames.empty())
TheModule->getMDKindNames(MDNames);
for (const auto &I : MDs) {
unsigned Kind = I.first;
Out << Separator;
if (Kind < MDNames.size()) {
Out << "!";
printMetadataIdentifier(MDNames[Kind], Out);
} else
Out << "!<unknown kind #" << Kind << ">";
Out << ' ';
WriteAsOperandInternal(Out, I.second, &TypePrinter, &Machine, TheModule);
}
}
void AssemblyWriter::writeMDNode(unsigned Slot, const MDNode *Node) {
Out << '!' << Slot << " = ";
printMDNodeBody(Node);
Out << "\n";
}
void AssemblyWriter::writeAllMDNodes() {
SmallVector<const MDNode *, 16> Nodes;
Nodes.resize(Machine.mdn_size());
for (SlotTracker::mdn_iterator I = Machine.mdn_begin(), E = Machine.mdn_end();
I != E; ++I)
Nodes[I->second] = cast<MDNode>(I->first);
for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
writeMDNode(i, Nodes[i]);
}
}
void AssemblyWriter::printMDNodeBody(const MDNode *Node) {
WriteMDNodeBodyInternal(Out, Node, &TypePrinter, &Machine, TheModule);
}
void AssemblyWriter::writeAllAttributeGroups() {
std::vector<std::pair<AttributeSet, unsigned> > asVec;
asVec.resize(Machine.as_size());
for (SlotTracker::as_iterator I = Machine.as_begin(), E = Machine.as_end();
I != E; ++I)
asVec[I->second] = *I;
for (std::vector<std::pair<AttributeSet, unsigned> >::iterator
I = asVec.begin(), E = asVec.end(); I != E; ++I)
Out << "attributes #" << I->second << " = { "
<< I->first.getAsString(AttributeSet::FunctionIndex, true) << " }\n";
}
void AssemblyWriter::printUseListOrder(const UseListOrder &Order) {
bool IsInFunction = Machine.getFunction();
if (IsInFunction)
Out << " ";
Out << "uselistorder";
if (const BasicBlock *BB =
IsInFunction ? nullptr : dyn_cast<BasicBlock>(Order.V)) {
Out << "_bb ";
writeOperand(BB->getParent(), false);
Out << ", ";
writeOperand(BB, false);
} else {
Out << " ";
writeOperand(Order.V, true);
}
Out << ", { ";
assert(Order.Shuffle.size() >= 2 && "Shuffle too small");
Out << Order.Shuffle[0];
for (unsigned I = 1, E = Order.Shuffle.size(); I != E; ++I)
Out << ", " << Order.Shuffle[I];
Out << " }\n";
}
void AssemblyWriter::printUseLists(const Function *F) {
auto hasMore =
[&]() { return !UseListOrders.empty() && UseListOrders.back().F == F; };
if (!hasMore())
// Nothing to do.
return;
Out << "\n; uselistorder directives\n";
while (hasMore()) {
printUseListOrder(UseListOrders.back());
UseListOrders.pop_back();
}
}
//===----------------------------------------------------------------------===//
// External Interface declarations
//===----------------------------------------------------------------------===//
void Function::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW) const {
SlotTracker SlotTable(this->getParent());
formatted_raw_ostream OS(ROS);
AssemblyWriter W(OS, SlotTable, this->getParent(), AAW);
W.printFunction(this);
}
void Module::print(raw_ostream &ROS, AssemblyAnnotationWriter *AAW,
bool ShouldPreserveUseListOrder) const {
SlotTracker SlotTable(this);
formatted_raw_ostream OS(ROS);
AssemblyWriter W(OS, SlotTable, this, AAW, ShouldPreserveUseListOrder);
W.printModule(this);
}
void NamedMDNode::print(raw_ostream &ROS) const {
SlotTracker SlotTable(getParent());
formatted_raw_ostream OS(ROS);
AssemblyWriter W(OS, SlotTable, getParent(), nullptr);
W.printNamedMDNode(this);
}
void Comdat::print(raw_ostream &ROS) const {
PrintLLVMName(ROS, getName(), ComdatPrefix);
ROS << " = comdat ";
switch (getSelectionKind()) {
case Comdat::Any:
ROS << "any";
break;
case Comdat::ExactMatch:
ROS << "exactmatch";
break;
case Comdat::Largest:
ROS << "largest";
break;
case Comdat::NoDuplicates:
ROS << "noduplicates";
break;
case Comdat::SameSize:
ROS << "samesize";
break;
}
ROS << '\n';
}
void Type::print(raw_ostream &OS) const {
TypePrinting TP;
TP.print(const_cast<Type*>(this), OS);
// If the type is a named struct type, print the body as well.
if (StructType *STy = dyn_cast<StructType>(const_cast<Type*>(this)))
if (!STy->isLiteral()) {
OS << " = type ";
TP.printStructBody(STy, OS);
}
}
static bool isReferencingMDNode(const Instruction &I) {
if (const auto *CI = dyn_cast<CallInst>(&I))
if (Function *F = CI->getCalledFunction())
if (F->isIntrinsic())
for (auto &Op : I.operands())
if (auto *V = dyn_cast_or_null<MetadataAsValue>(Op))
if (isa<MDNode>(V->getMetadata()))
return true;
return false;
}
void Value::print(raw_ostream &ROS) const {
bool ShouldInitializeAllMetadata = false;
if (auto *I = dyn_cast<Instruction>(this))
ShouldInitializeAllMetadata = isReferencingMDNode(*I);
else if (isa<Function>(this) || isa<MetadataAsValue>(this))
ShouldInitializeAllMetadata = true;
ModuleSlotTracker MST(getModuleFromVal(this), ShouldInitializeAllMetadata);
print(ROS, MST);
}
void Value::print(raw_ostream &ROS, ModuleSlotTracker &MST) const {
formatted_raw_ostream OS(ROS);
SlotTracker EmptySlotTable(static_cast<const Module *>(nullptr));
SlotTracker &SlotTable =
MST.getMachine() ? *MST.getMachine() : EmptySlotTable;
auto incorporateFunction = [&](const Function *F) {
if (F)
MST.incorporateFunction(*F);
};
if (const Instruction *I = dyn_cast<Instruction>(this)) {
incorporateFunction(I->getParent() ? I->getParent()->getParent() : nullptr);
AssemblyWriter W(OS, SlotTable, getModuleFromVal(I), nullptr);
W.printInstruction(*I);
} else if (const BasicBlock *BB = dyn_cast<BasicBlock>(this)) {
incorporateFunction(BB->getParent());
AssemblyWriter W(OS, SlotTable, getModuleFromVal(BB), nullptr);
W.printBasicBlock(BB);
} else if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
AssemblyWriter W(OS, SlotTable, GV->getParent(), nullptr);
if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
W.printGlobal(V);
else if (const Function *F = dyn_cast<Function>(GV))
W.printFunction(F);
else
W.printAlias(cast<GlobalAlias>(GV));
} else if (const MetadataAsValue *V = dyn_cast<MetadataAsValue>(this)) {
V->getMetadata()->print(ROS, MST, getModuleFromVal(V));
} else if (const Constant *C = dyn_cast<Constant>(this)) {
TypePrinting TypePrinter;
TypePrinter.print(C->getType(), OS);
OS << ' ';
WriteConstantInternal(OS, C, TypePrinter, MST.getMachine(), nullptr);
} else if (isa<InlineAsm>(this) || isa<Argument>(this)) {
this->printAsOperand(OS, /* PrintType */ true, MST);
} else {
llvm_unreachable("Unknown value to print out!");
}
}
/// Print without a type, skipping the TypePrinting object.
///
/// \return \c true iff printing was succesful.
static bool printWithoutType(const Value &V, raw_ostream &O,
SlotTracker *Machine, const Module *M) {
if (V.hasName() || isa<GlobalValue>(V) ||
(!isa<Constant>(V) && !isa<MetadataAsValue>(V))) {
WriteAsOperandInternal(O, &V, nullptr, Machine, M);
return true;
}
return false;
}
static void printAsOperandImpl(const Value &V, raw_ostream &O, bool PrintType,
ModuleSlotTracker &MST) {
TypePrinting TypePrinter;
if (const Module *M = MST.getModule())
TypePrinter.incorporateTypes(*M);
if (PrintType) {
TypePrinter.print(V.getType(), O);
O << ' ';
}
WriteAsOperandInternal(O, &V, &TypePrinter, MST.getMachine(),
MST.getModule());
}
void Value::printAsOperand(raw_ostream &O, bool PrintType,
const Module *M) const {
if (!M)
M = getModuleFromVal(this);
if (!PrintType)
if (printWithoutType(*this, O, nullptr, M))
return;
SlotTracker Machine(
M, /* ShouldInitializeAllMetadata */ isa<MetadataAsValue>(this));
ModuleSlotTracker MST(Machine, M);
printAsOperandImpl(*this, O, PrintType, MST);
}
void Value::printAsOperand(raw_ostream &O, bool PrintType,
ModuleSlotTracker &MST) const {
if (!PrintType)
if (printWithoutType(*this, O, MST.getMachine(), MST.getModule()))
return;
printAsOperandImpl(*this, O, PrintType, MST);
}
static void printMetadataImpl(raw_ostream &ROS, const Metadata &MD,
ModuleSlotTracker &MST, const Module *M,
bool OnlyAsOperand) {
formatted_raw_ostream OS(ROS);
TypePrinting TypePrinter;
if (M)
TypePrinter.incorporateTypes(*M);
WriteAsOperandInternal(OS, &MD, &TypePrinter, MST.getMachine(), M,
/* FromValue */ true);
auto *N = dyn_cast<MDNode>(&MD);
if (OnlyAsOperand || !N)
return;
OS << " = ";
WriteMDNodeBodyInternal(OS, N, &TypePrinter, MST.getMachine(), M);
}
void Metadata::printAsOperand(raw_ostream &OS, const Module *M) const {
ModuleSlotTracker MST(M, isa<MDNode>(this));
printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
}
void Metadata::printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
const Module *M) const {
printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ true);
}
void Metadata::print(raw_ostream &OS, const Module *M) const {
ModuleSlotTracker MST(M, isa<MDNode>(this));
printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
}
void Metadata::print(raw_ostream &OS, ModuleSlotTracker &MST,
const Module *M) const {
printMetadataImpl(OS, *this, MST, M, /* OnlyAsOperand */ false);
}
// HLSL Change Begin
void MDNode::printAsBody(raw_ostream &OS, const Module *M) const {
ModuleSlotTracker MST(M, true);
printAsBody(OS, MST, M);
}
void MDNode::printAsBody(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M) const {
TypePrinting TypePrinter;
if (M)
TypePrinter.incorporateTypes(*M);
WriteMDNodeBodyInternal(OS, this, &TypePrinter, MST.getMachine(), M);
}
// HLSL Change end
// Value::dump - allow easy printing of Values from the debugger.
LLVM_DUMP_METHOD
void Value::dump() const { print(dbgs()); dbgs() << '\n'; }
// Type::dump - allow easy printing of Types from the debugger.
LLVM_DUMP_METHOD
void Type::dump() const { print(dbgs()); dbgs() << '\n'; }
// Module::dump() - Allow printing of Modules from the debugger.
LLVM_DUMP_METHOD
void Module::dump() const { print(dbgs(), nullptr); }
// \brief Allow printing of Comdats from the debugger.
LLVM_DUMP_METHOD
void Comdat::dump() const { print(dbgs()); }
// NamedMDNode::dump() - Allow printing of NamedMDNodes from the debugger.
LLVM_DUMP_METHOD
void NamedMDNode::dump() const { print(dbgs()); }
LLVM_DUMP_METHOD
void Metadata::dump() const { dump(nullptr); }
LLVM_DUMP_METHOD
void Metadata::dump(const Module *M) const {
print(dbgs(), M);
dbgs() << '\n';
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/ConstantsContext.h | //===-- ConstantsContext.h - Constants-related Context Interals -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines various helper methods and classes used by
// LLVMContextImpl for creating and managing constants.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_IR_CONSTANTSCONTEXT_H
#define LLVM_LIB_IR_CONSTANTSCONTEXT_H
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <map>
#include <tuple>
#define DEBUG_TYPE "ir"
namespace llvm {
/// UnaryConstantExpr - This class is private to Constants.cpp, and is used
/// behind the scenes to implement unary constant exprs.
class UnaryConstantExpr : public ConstantExpr {
void anchor() override;
void *operator new(size_t, unsigned) = delete;
public:
// allocate space for exactly one operand
void *operator new(size_t s) {
return User::operator new(s, 1);
}
UnaryConstantExpr(unsigned Opcode, Constant *C, Type *Ty)
: ConstantExpr(Ty, Opcode, &Op<0>(), 1) {
Op<0>() = C;
}
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
/// BinaryConstantExpr - This class is private to Constants.cpp, and is used
/// behind the scenes to implement binary constant exprs.
class BinaryConstantExpr : public ConstantExpr {
void anchor() override;
void *operator new(size_t, unsigned) = delete;
public:
// allocate space for exactly two operands
void *operator new(size_t s) {
return User::operator new(s, 2);
}
BinaryConstantExpr(unsigned Opcode, Constant *C1, Constant *C2,
unsigned Flags)
: ConstantExpr(C1->getType(), Opcode, &Op<0>(), 2) {
Op<0>() = C1;
Op<1>() = C2;
SubclassOptionalData = Flags;
}
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
/// SelectConstantExpr - This class is private to Constants.cpp, and is used
/// behind the scenes to implement select constant exprs.
class SelectConstantExpr : public ConstantExpr {
void anchor() override;
void *operator new(size_t, unsigned) = delete;
public:
// allocate space for exactly three operands
void *operator new(size_t s) {
return User::operator new(s, 3);
}
SelectConstantExpr(Constant *C1, Constant *C2, Constant *C3)
: ConstantExpr(C2->getType(), Instruction::Select, &Op<0>(), 3) {
Op<0>() = C1;
Op<1>() = C2;
Op<2>() = C3;
}
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
/// ExtractElementConstantExpr - This class is private to
/// Constants.cpp, and is used behind the scenes to implement
/// extractelement constant exprs.
class ExtractElementConstantExpr : public ConstantExpr {
void anchor() override;
void *operator new(size_t, unsigned) = delete;
public:
// allocate space for exactly two operands
void *operator new(size_t s) {
return User::operator new(s, 2);
}
ExtractElementConstantExpr(Constant *C1, Constant *C2)
: ConstantExpr(cast<VectorType>(C1->getType())->getElementType(),
Instruction::ExtractElement, &Op<0>(), 2) {
Op<0>() = C1;
Op<1>() = C2;
}
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
/// InsertElementConstantExpr - This class is private to
/// Constants.cpp, and is used behind the scenes to implement
/// insertelement constant exprs.
class InsertElementConstantExpr : public ConstantExpr {
void anchor() override;
void *operator new(size_t, unsigned) = delete;
public:
// allocate space for exactly three operands
void *operator new(size_t s) {
return User::operator new(s, 3);
}
InsertElementConstantExpr(Constant *C1, Constant *C2, Constant *C3)
: ConstantExpr(C1->getType(), Instruction::InsertElement,
&Op<0>(), 3) {
Op<0>() = C1;
Op<1>() = C2;
Op<2>() = C3;
}
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
/// ShuffleVectorConstantExpr - This class is private to
/// Constants.cpp, and is used behind the scenes to implement
/// shufflevector constant exprs.
class ShuffleVectorConstantExpr : public ConstantExpr {
void anchor() override;
void *operator new(size_t, unsigned) = delete;
public:
// allocate space for exactly three operands
void *operator new(size_t s) {
return User::operator new(s, 3);
}
ShuffleVectorConstantExpr(Constant *C1, Constant *C2, Constant *C3)
: ConstantExpr(VectorType::get(
cast<VectorType>(C1->getType())->getElementType(),
cast<VectorType>(C3->getType())->getNumElements()),
Instruction::ShuffleVector,
&Op<0>(), 3) {
Op<0>() = C1;
Op<1>() = C2;
Op<2>() = C3;
}
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
/// ExtractValueConstantExpr - This class is private to
/// Constants.cpp, and is used behind the scenes to implement
/// extractvalue constant exprs.
class ExtractValueConstantExpr : public ConstantExpr {
void anchor() override;
void *operator new(size_t, unsigned) = delete;
public:
// allocate space for exactly one operand
void *operator new(size_t s) {
return User::operator new(s, 1);
}
ExtractValueConstantExpr(Constant *Agg, ArrayRef<unsigned> IdxList,
Type *DestTy)
: ConstantExpr(DestTy, Instruction::ExtractValue, &Op<0>(), 1),
Indices(IdxList.begin(), IdxList.end()) {
Op<0>() = Agg;
}
/// Indices - These identify which value to extract.
const SmallVector<unsigned, 4> Indices;
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
/// InsertValueConstantExpr - This class is private to
/// Constants.cpp, and is used behind the scenes to implement
/// insertvalue constant exprs.
class InsertValueConstantExpr : public ConstantExpr {
void anchor() override;
void *operator new(size_t, unsigned) = delete;
public:
// allocate space for exactly one operand
void *operator new(size_t s) {
return User::operator new(s, 2);
}
InsertValueConstantExpr(Constant *Agg, Constant *Val,
ArrayRef<unsigned> IdxList, Type *DestTy)
: ConstantExpr(DestTy, Instruction::InsertValue, &Op<0>(), 2),
Indices(IdxList.begin(), IdxList.end()) {
Op<0>() = Agg;
Op<1>() = Val;
}
/// Indices - These identify the position for the insertion.
const SmallVector<unsigned, 4> Indices;
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
/// GetElementPtrConstantExpr - This class is private to Constants.cpp, and is
/// used behind the scenes to implement getelementpr constant exprs.
class GetElementPtrConstantExpr : public ConstantExpr {
Type *SrcElementTy;
void anchor() override;
GetElementPtrConstantExpr(Type *SrcElementTy, Constant *C,
ArrayRef<Constant *> IdxList, Type *DestTy);
public:
static GetElementPtrConstantExpr *Create(Constant *C,
ArrayRef<Constant*> IdxList,
Type *DestTy,
unsigned Flags) {
return Create(
cast<PointerType>(C->getType()->getScalarType())->getElementType(), C,
IdxList, DestTy, Flags);
}
static GetElementPtrConstantExpr *Create(Type *SrcElementTy, Constant *C,
ArrayRef<Constant *> IdxList,
Type *DestTy, unsigned Flags) {
GetElementPtrConstantExpr *Result = new (IdxList.size() + 1)
GetElementPtrConstantExpr(SrcElementTy, C, IdxList, DestTy);
Result->SubclassOptionalData = Flags;
return Result;
}
Type *getSourceElementType() const;
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
// CompareConstantExpr - This class is private to Constants.cpp, and is used
// behind the scenes to implement ICmp and FCmp constant expressions. This is
// needed in order to store the predicate value for these instructions.
class CompareConstantExpr : public ConstantExpr {
void anchor() override;
void *operator new(size_t, unsigned) = delete;
public:
// allocate space for exactly two operands
void *operator new(size_t s) {
return User::operator new(s, 2);
}
unsigned short predicate;
CompareConstantExpr(Type *ty, Instruction::OtherOps opc,
unsigned short pred, Constant* LHS, Constant* RHS)
: ConstantExpr(ty, opc, &Op<0>(), 2), predicate(pred) {
Op<0>() = LHS;
Op<1>() = RHS;
}
/// Transparently provide more efficient getOperand methods.
DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
};
template <>
struct OperandTraits<UnaryConstantExpr>
: public FixedNumOperandTraits<UnaryConstantExpr, 1> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(UnaryConstantExpr, Value)
template <>
struct OperandTraits<BinaryConstantExpr>
: public FixedNumOperandTraits<BinaryConstantExpr, 2> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BinaryConstantExpr, Value)
template <>
struct OperandTraits<SelectConstantExpr>
: public FixedNumOperandTraits<SelectConstantExpr, 3> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectConstantExpr, Value)
template <>
struct OperandTraits<ExtractElementConstantExpr>
: public FixedNumOperandTraits<ExtractElementConstantExpr, 2> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementConstantExpr, Value)
template <>
struct OperandTraits<InsertElementConstantExpr>
: public FixedNumOperandTraits<InsertElementConstantExpr, 3> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementConstantExpr, Value)
template <>
struct OperandTraits<ShuffleVectorConstantExpr>
: public FixedNumOperandTraits<ShuffleVectorConstantExpr, 3> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorConstantExpr, Value)
template <>
struct OperandTraits<ExtractValueConstantExpr>
: public FixedNumOperandTraits<ExtractValueConstantExpr, 1> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractValueConstantExpr, Value)
template <>
struct OperandTraits<InsertValueConstantExpr>
: public FixedNumOperandTraits<InsertValueConstantExpr, 2> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueConstantExpr, Value)
template <>
struct OperandTraits<GetElementPtrConstantExpr>
: public VariadicOperandTraits<GetElementPtrConstantExpr, 1> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrConstantExpr, Value)
template <>
struct OperandTraits<CompareConstantExpr>
: public FixedNumOperandTraits<CompareConstantExpr, 2> {};
DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CompareConstantExpr, Value)
template <class ConstantClass> struct ConstantAggrKeyType;
struct InlineAsmKeyType;
struct ConstantExprKeyType;
template <class ConstantClass> struct ConstantInfo;
template <> struct ConstantInfo<ConstantExpr> {
typedef ConstantExprKeyType ValType;
typedef Type TypeClass;
};
template <> struct ConstantInfo<InlineAsm> {
typedef InlineAsmKeyType ValType;
typedef PointerType TypeClass;
};
template <> struct ConstantInfo<ConstantArray> {
typedef ConstantAggrKeyType<ConstantArray> ValType;
typedef ArrayType TypeClass;
};
template <> struct ConstantInfo<ConstantStruct> {
typedef ConstantAggrKeyType<ConstantStruct> ValType;
typedef StructType TypeClass;
};
template <> struct ConstantInfo<ConstantVector> {
typedef ConstantAggrKeyType<ConstantVector> ValType;
typedef VectorType TypeClass;
};
template <class ConstantClass> struct ConstantAggrKeyType {
ArrayRef<Constant *> Operands;
ConstantAggrKeyType(ArrayRef<Constant *> Operands) : Operands(Operands) {}
ConstantAggrKeyType(ArrayRef<Constant *> Operands, const ConstantClass *)
: Operands(Operands) {}
ConstantAggrKeyType(const ConstantClass *C,
SmallVectorImpl<Constant *> &Storage) {
assert(Storage.empty() && "Expected empty storage");
for (unsigned I = 0, E = C->getNumOperands(); I != E; ++I)
Storage.push_back(C->getOperand(I));
Operands = Storage;
}
bool operator==(const ConstantAggrKeyType &X) const {
return Operands == X.Operands;
}
bool operator==(const ConstantClass *C) const {
if (Operands.size() != C->getNumOperands())
return false;
for (unsigned I = 0, E = Operands.size(); I != E; ++I)
if (Operands[I] != C->getOperand(I))
return false;
return true;
}
unsigned getHash() const {
return hash_combine_range(Operands.begin(), Operands.end());
}
typedef typename ConstantInfo<ConstantClass>::TypeClass TypeClass;
ConstantClass *create(TypeClass *Ty) const {
return new (Operands.size()) ConstantClass(Ty, Operands);
}
};
struct InlineAsmKeyType {
StringRef AsmString;
StringRef Constraints;
bool HasSideEffects;
bool IsAlignStack;
InlineAsm::AsmDialect AsmDialect;
InlineAsmKeyType(StringRef AsmString, StringRef Constraints,
bool HasSideEffects, bool IsAlignStack,
InlineAsm::AsmDialect AsmDialect)
: AsmString(AsmString), Constraints(Constraints),
HasSideEffects(HasSideEffects), IsAlignStack(IsAlignStack),
AsmDialect(AsmDialect) {}
InlineAsmKeyType(const InlineAsm *Asm, SmallVectorImpl<Constant *> &)
: AsmString(Asm->getAsmString()), Constraints(Asm->getConstraintString()),
HasSideEffects(Asm->hasSideEffects()),
IsAlignStack(Asm->isAlignStack()), AsmDialect(Asm->getDialect()) {}
bool operator==(const InlineAsmKeyType &X) const {
return HasSideEffects == X.HasSideEffects &&
IsAlignStack == X.IsAlignStack && AsmDialect == X.AsmDialect &&
AsmString == X.AsmString && Constraints == X.Constraints;
}
bool operator==(const InlineAsm *Asm) const {
return HasSideEffects == Asm->hasSideEffects() &&
IsAlignStack == Asm->isAlignStack() &&
AsmDialect == Asm->getDialect() &&
AsmString == Asm->getAsmString() &&
Constraints == Asm->getConstraintString();
}
unsigned getHash() const {
return hash_combine(AsmString, Constraints, HasSideEffects, IsAlignStack,
AsmDialect);
}
typedef ConstantInfo<InlineAsm>::TypeClass TypeClass;
InlineAsm *create(TypeClass *Ty) const {
return new InlineAsm(Ty, AsmString, Constraints, HasSideEffects,
IsAlignStack, AsmDialect);
}
};
struct ConstantExprKeyType {
uint8_t Opcode;
uint8_t SubclassOptionalData;
uint16_t SubclassData;
ArrayRef<Constant *> Ops;
ArrayRef<unsigned> Indexes;
Type *ExplicitTy;
ConstantExprKeyType(unsigned Opcode, ArrayRef<Constant *> Ops,
unsigned short SubclassData = 0,
unsigned short SubclassOptionalData = 0,
ArrayRef<unsigned> Indexes = None,
Type *ExplicitTy = nullptr)
: Opcode(Opcode), SubclassOptionalData(SubclassOptionalData),
SubclassData(SubclassData), Ops(Ops), Indexes(Indexes),
ExplicitTy(ExplicitTy) {}
ConstantExprKeyType(ArrayRef<Constant *> Operands, const ConstantExpr *CE)
: Opcode(CE->getOpcode()),
SubclassOptionalData(CE->getRawSubclassOptionalData()),
SubclassData(CE->isCompare() ? CE->getPredicate() : 0), Ops(Operands),
Indexes(CE->hasIndices() ? CE->getIndices() : ArrayRef<unsigned>()) {}
ConstantExprKeyType(const ConstantExpr *CE,
SmallVectorImpl<Constant *> &Storage)
: Opcode(CE->getOpcode()),
SubclassOptionalData(CE->getRawSubclassOptionalData()),
SubclassData(CE->isCompare() ? CE->getPredicate() : 0),
Indexes(CE->hasIndices() ? CE->getIndices() : ArrayRef<unsigned>()) {
assert(Storage.empty() && "Expected empty storage");
for (unsigned I = 0, E = CE->getNumOperands(); I != E; ++I)
Storage.push_back(CE->getOperand(I));
Ops = Storage;
}
bool operator==(const ConstantExprKeyType &X) const {
return Opcode == X.Opcode && SubclassData == X.SubclassData &&
SubclassOptionalData == X.SubclassOptionalData && Ops == X.Ops &&
Indexes == X.Indexes;
}
bool operator==(const ConstantExpr *CE) const {
if (Opcode != CE->getOpcode())
return false;
if (SubclassOptionalData != CE->getRawSubclassOptionalData())
return false;
if (Ops.size() != CE->getNumOperands())
return false;
if (SubclassData != (CE->isCompare() ? CE->getPredicate() : 0))
return false;
for (unsigned I = 0, E = Ops.size(); I != E; ++I)
if (Ops[I] != CE->getOperand(I))
return false;
if (Indexes != (CE->hasIndices() ? CE->getIndices() : ArrayRef<unsigned>()))
return false;
return true;
}
unsigned getHash() const {
return hash_combine(Opcode, SubclassOptionalData, SubclassData,
hash_combine_range(Ops.begin(), Ops.end()),
hash_combine_range(Indexes.begin(), Indexes.end()));
}
typedef ConstantInfo<ConstantExpr>::TypeClass TypeClass;
ConstantExpr *create(TypeClass *Ty) const {
switch (Opcode) {
default:
if (Instruction::isCast(Opcode))
return new UnaryConstantExpr(Opcode, Ops[0], Ty);
if ((Opcode >= Instruction::BinaryOpsBegin &&
Opcode < Instruction::BinaryOpsEnd))
return new BinaryConstantExpr(Opcode, Ops[0], Ops[1],
SubclassOptionalData);
llvm_unreachable("Invalid ConstantExpr!");
case Instruction::Select:
return new SelectConstantExpr(Ops[0], Ops[1], Ops[2]);
case Instruction::ExtractElement:
return new ExtractElementConstantExpr(Ops[0], Ops[1]);
case Instruction::InsertElement:
return new InsertElementConstantExpr(Ops[0], Ops[1], Ops[2]);
case Instruction::ShuffleVector:
return new ShuffleVectorConstantExpr(Ops[0], Ops[1], Ops[2]);
case Instruction::InsertValue:
return new InsertValueConstantExpr(Ops[0], Ops[1], Indexes, Ty);
case Instruction::ExtractValue:
return new ExtractValueConstantExpr(Ops[0], Indexes, Ty);
case Instruction::GetElementPtr:
return GetElementPtrConstantExpr::Create(
ExplicitTy ? ExplicitTy
: cast<PointerType>(Ops[0]->getType()->getScalarType())
->getElementType(),
Ops[0], Ops.slice(1), Ty, SubclassOptionalData);
case Instruction::ICmp:
return new CompareConstantExpr(Ty, Instruction::ICmp, SubclassData,
Ops[0], Ops[1]);
case Instruction::FCmp:
return new CompareConstantExpr(Ty, Instruction::FCmp, SubclassData,
Ops[0], Ops[1]);
}
}
};
template <class ConstantClass> class ConstantUniqueMap {
public:
typedef typename ConstantInfo<ConstantClass>::ValType ValType;
typedef typename ConstantInfo<ConstantClass>::TypeClass TypeClass;
typedef std::pair<TypeClass *, ValType> LookupKey;
private:
struct MapInfo {
typedef DenseMapInfo<ConstantClass *> ConstantClassInfo;
static inline ConstantClass *getEmptyKey() {
return ConstantClassInfo::getEmptyKey();
}
static inline ConstantClass *getTombstoneKey() {
return ConstantClassInfo::getTombstoneKey();
}
static unsigned getHashValue(const ConstantClass *CP) {
SmallVector<Constant *, 8> Storage;
return getHashValue(LookupKey(CP->getType(), ValType(CP, Storage)));
}
static bool isEqual(const ConstantClass *LHS, const ConstantClass *RHS) {
return LHS == RHS;
}
static unsigned getHashValue(const LookupKey &Val) {
return hash_combine(Val.first, Val.second.getHash());
}
static bool isEqual(const LookupKey &LHS, const ConstantClass *RHS) {
if (RHS == getEmptyKey() || RHS == getTombstoneKey())
return false;
if (LHS.first != RHS->getType())
return false;
return LHS.second == RHS;
}
};
public:
typedef DenseMap<ConstantClass *, char, MapInfo> MapTy;
private:
MapTy Map;
public:
typename MapTy::iterator map_begin() { return Map.begin(); }
typename MapTy::iterator map_end() { return Map.end(); }
void freeConstants() {
for (auto &I : Map)
// Asserts that use_empty().
delete I.first;
}
private:
ConstantClass *create(TypeClass *Ty, ValType V) {
ConstantClass *Result = V.create(Ty);
assert(Result->getType() == Ty && "Type specified is not correct!");
insert(Result);
return Result;
}
public:
/// Return the specified constant from the map, creating it if necessary.
ConstantClass *getOrCreate(TypeClass *Ty, ValType V) {
LookupKey Lookup(Ty, V);
ConstantClass *Result = nullptr;
auto I = find(Lookup);
if (I == Map.end())
Result = create(Ty, V);
else
Result = I->first;
assert(Result && "Unexpected nullptr");
return Result;
}
/// Find the constant by lookup key.
typename MapTy::iterator find(LookupKey Lookup) {
return Map.find_as(Lookup);
}
/// Insert the constant into its proper slot.
void insert(ConstantClass *CP) { Map[CP] = '\0'; }
/// Remove this constant from the map
void remove(ConstantClass *CP) {
typename MapTy::iterator I = Map.find(CP);
assert(I != Map.end() && "Constant not found in constant table!");
assert(I->first == CP && "Didn't find correct element?");
Map.erase(I);
}
ConstantClass *replaceOperandsInPlace(ArrayRef<Constant *> Operands,
ConstantClass *CP, Value *From,
Constant *To, unsigned NumUpdated = 0,
unsigned OperandNo = ~0u) {
LookupKey Lookup(CP->getType(), ValType(Operands, CP));
auto I = find(Lookup);
if (I != Map.end())
return I->first;
// Update to the new value. Optimize for the case when we have a single
// operand that we're changing, but handle bulk updates efficiently.
remove(CP);
if (NumUpdated == 1) {
assert(OperandNo < CP->getNumOperands() && "Invalid index");
assert(CP->getOperand(OperandNo) != To && "I didn't contain From!");
CP->setOperand(OperandNo, To);
} else {
for (unsigned I = 0, E = CP->getNumOperands(); I != E; ++I)
if (CP->getOperand(I) == From)
CP->setOperand(I, To);
}
insert(CP);
return nullptr;
}
void dump() const { DEBUG(dbgs() << "Constant.cpp: ConstantUniqueMap\n"); }
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/AttributeImpl.h | //===-- AttributeImpl.h - Attribute Internals -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file defines various helper methods and classes used by
/// LLVMContextImpl for creating and managing attributes.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_IR_ATTRIBUTEIMPL_H
#define LLVM_LIB_IR_ATTRIBUTEIMPL_H
#include "llvm/ADT/FoldingSet.h"
#include "llvm/IR/Attributes.h"
#include <string>
namespace llvm {
class Constant;
class LLVMContext;
//===----------------------------------------------------------------------===//
/// \class
/// \brief This class represents a single, uniqued attribute. That attribute
/// could be a single enum, a tuple, or a string.
class AttributeImpl : public FoldingSetNode {
unsigned char KindID; ///< Holds the AttrEntryKind of the attribute
// AttributesImpl is uniqued, these should not be publicly available.
void operator=(const AttributeImpl &) = delete;
AttributeImpl(const AttributeImpl &) = delete;
protected:
enum AttrEntryKind {
EnumAttrEntry,
IntAttrEntry,
StringAttrEntry
};
AttributeImpl(AttrEntryKind KindID) : KindID(KindID) {}
public:
virtual ~AttributeImpl();
bool isEnumAttribute() const { return KindID == EnumAttrEntry; }
bool isIntAttribute() const { return KindID == IntAttrEntry; }
bool isStringAttribute() const { return KindID == StringAttrEntry; }
bool hasAttribute(Attribute::AttrKind A) const;
bool hasAttribute(StringRef Kind) const;
Attribute::AttrKind getKindAsEnum() const;
uint64_t getValueAsInt() const;
StringRef getKindAsString() const;
StringRef getValueAsString() const;
/// \brief Used when sorting the attributes.
bool operator<(const AttributeImpl &AI) const;
void Profile(FoldingSetNodeID &ID) const {
if (isEnumAttribute())
Profile(ID, getKindAsEnum(), 0);
else if (isIntAttribute())
Profile(ID, getKindAsEnum(), getValueAsInt());
else
Profile(ID, getKindAsString(), getValueAsString());
}
static void Profile(FoldingSetNodeID &ID, Attribute::AttrKind Kind,
uint64_t Val) {
ID.AddInteger(Kind);
if (Val) ID.AddInteger(Val);
}
static void Profile(FoldingSetNodeID &ID, StringRef Kind, StringRef Values) {
ID.AddString(Kind);
if (!Values.empty()) ID.AddString(Values);
}
// FIXME: Remove this!
static uint64_t getAttrMask(Attribute::AttrKind Val);
};
//===----------------------------------------------------------------------===//
/// \class
/// \brief A set of classes that contain the value of the
/// attribute object. There are three main categories: enum attribute entries,
/// represented by Attribute::AttrKind; alignment attribute entries; and string
/// attribute enties, which are for target-dependent attributes.
class EnumAttributeImpl : public AttributeImpl {
virtual void anchor();
Attribute::AttrKind Kind;
protected:
EnumAttributeImpl(AttrEntryKind ID, Attribute::AttrKind Kind)
: AttributeImpl(ID), Kind(Kind) {}
public:
EnumAttributeImpl(Attribute::AttrKind Kind)
: AttributeImpl(EnumAttrEntry), Kind(Kind) {}
Attribute::AttrKind getEnumKind() const { return Kind; }
};
class IntAttributeImpl : public EnumAttributeImpl {
void anchor() override;
uint64_t Val;
public:
IntAttributeImpl(Attribute::AttrKind Kind, uint64_t Val)
: EnumAttributeImpl(IntAttrEntry, Kind), Val(Val) {
assert((Kind == Attribute::Alignment || Kind == Attribute::StackAlignment ||
Kind == Attribute::Dereferenceable ||
Kind == Attribute::DereferenceableOrNull) &&
"Wrong kind for int attribute!");
}
uint64_t getValue() const { return Val; }
};
class StringAttributeImpl : public AttributeImpl {
virtual void anchor();
std::string Kind;
std::string Val;
public:
StringAttributeImpl(StringRef Kind, StringRef Val = StringRef())
: AttributeImpl(StringAttrEntry), Kind(Kind), Val(Val) {}
StringRef getStringKind() const { return Kind; }
StringRef getStringValue() const { return Val; }
};
//===----------------------------------------------------------------------===//
/// \class
/// \brief This class represents a group of attributes that apply to one
/// element: function, return type, or parameter.
class AttributeSetNode : public FoldingSetNode {
unsigned NumAttrs; ///< Number of attributes in this node.
AttributeSetNode(ArrayRef<Attribute> Attrs) : NumAttrs(Attrs.size()) {
// There's memory after the node where we can store the entries in.
std::copy(Attrs.begin(), Attrs.end(),
reinterpret_cast<Attribute *>(this + 1));
}
// AttributesSetNode is uniqued, these should not be publicly available.
void operator=(const AttributeSetNode &) = delete;
AttributeSetNode(const AttributeSetNode &) = delete;
public:
static AttributeSetNode *get(LLVMContext &C, ArrayRef<Attribute> Attrs);
bool hasAttribute(Attribute::AttrKind Kind) const;
bool hasAttribute(StringRef Kind) const;
bool hasAttributes() const { return NumAttrs != 0; }
Attribute getAttribute(Attribute::AttrKind Kind) const;
Attribute getAttribute(StringRef Kind) const;
unsigned getAlignment() const;
unsigned getStackAlignment() const;
uint64_t getDereferenceableBytes() const;
uint64_t getDereferenceableOrNullBytes() const;
std::string getAsString(bool InAttrGrp) const;
typedef const Attribute *iterator;
iterator begin() const { return reinterpret_cast<iterator>(this + 1); }
iterator end() const { return begin() + NumAttrs; }
void Profile(FoldingSetNodeID &ID) const {
Profile(ID, makeArrayRef(begin(), end()));
}
static void Profile(FoldingSetNodeID &ID, ArrayRef<Attribute> AttrList) {
for (unsigned I = 0, E = AttrList.size(); I != E; ++I)
AttrList[I].Profile(ID);
}
};
static_assert(
AlignOf<AttributeSetNode>::Alignment >= AlignOf<Attribute>::Alignment,
"Alignment is insufficient for objects appended to AttributeSetNode");
// //
///////////////////////////////////////////////////////////////////////////////
/// \class
/// \brief This class represents a set of attributes that apply to the function,
/// return type, and parameters.
class AttributeSetImpl : public FoldingSetNode {
friend class AttributeSet;
public:
typedef std::pair<unsigned, AttributeSetNode*> IndexAttrPair;
private:
LLVMContext &Context;
unsigned NumAttrs; ///< Number of entries in this set.
/// \brief Return a pointer to the IndexAttrPair for the specified slot.
const IndexAttrPair *getNode(unsigned Slot) const {
return reinterpret_cast<const IndexAttrPair *>(this + 1) + Slot;
}
// AttributesSet is uniqued, these should not be publicly available.
void operator=(const AttributeSetImpl &) = delete;
AttributeSetImpl(const AttributeSetImpl &) = delete;
public:
AttributeSetImpl(LLVMContext &C,
ArrayRef<std::pair<unsigned, AttributeSetNode *> > Attrs)
: Context(C), NumAttrs(Attrs.size()) {
#ifndef NDEBUG
if (Attrs.size() >= 2) {
for (const std::pair<unsigned, AttributeSetNode *> *i = Attrs.begin() + 1,
*e = Attrs.end();
i != e; ++i) {
assert((i-1)->first <= i->first && "Attribute set not ordered!");
}
}
#endif
// There's memory after the node where we can store the entries in.
std::copy(Attrs.begin(), Attrs.end(),
reinterpret_cast<IndexAttrPair *>(this + 1));
}
/// \brief Get the context that created this AttributeSetImpl.
LLVMContext &getContext() { return Context; }
/// \brief Return the number of attributes this AttributeSet contains.
unsigned getNumAttributes() const { return NumAttrs; }
/// \brief Get the index of the given "slot" in the AttrNodes list. This index
/// is the index of the return, parameter, or function object that the
/// attributes are applied to, not the index into the AttrNodes list where the
/// attributes reside.
unsigned getSlotIndex(unsigned Slot) const {
return getNode(Slot)->first;
}
/// \brief Retrieve the attributes for the given "slot" in the AttrNode list.
/// \p Slot is an index into the AttrNodes list, not the index of the return /
/// parameter/ function which the attributes apply to.
AttributeSet getSlotAttributes(unsigned Slot) const {
return AttributeSet::get(Context, *getNode(Slot));
}
/// \brief Retrieve the attribute set node for the given "slot" in the
/// AttrNode list.
AttributeSetNode *getSlotNode(unsigned Slot) const {
return getNode(Slot)->second;
}
typedef AttributeSetNode::iterator iterator;
iterator begin(unsigned Slot) const { return getSlotNode(Slot)->begin(); }
iterator end(unsigned Slot) const { return getSlotNode(Slot)->end(); }
void Profile(FoldingSetNodeID &ID) const {
Profile(ID, makeArrayRef(getNode(0), getNumAttributes()));
}
static void Profile(FoldingSetNodeID &ID,
ArrayRef<std::pair<unsigned, AttributeSetNode*> > Nodes) {
for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
ID.AddInteger(Nodes[i].first);
ID.AddPointer(Nodes[i].second);
}
}
// FIXME: This atrocity is temporary.
uint64_t Raw(unsigned Index) const;
void dump() const;
};
static_assert(
AlignOf<AttributeSetImpl>::Alignment >=
AlignOf<AttributeSetImpl::IndexAttrPair>::Alignment,
"Alignment is insufficient for objects appended to AttributeSetImpl");
} // end llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/Constants.cpp | //===-- Constants.cpp - Implement Constant nodes --------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the Constant* classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Constants.h"
#include "ConstantFold.h"
#include "LLVMContextImpl.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GetElementPtrTypeIterator.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cstdarg>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Constant Class
//===----------------------------------------------------------------------===//
void Constant::anchor() { }
bool Constant::isNegativeZeroValue() const {
// Floating point values have an explicit -0.0 value.
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return CFP->isZero() && CFP->isNegative();
// Equivalent for a vector of -0.0's.
if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
return true;
// We've already handled true FP case; any other FP vectors can't represent -0.0.
if (getType()->isFPOrFPVectorTy())
return false;
// Otherwise, just use +0.0.
return isNullValue();
}
// Return true iff this constant is positive zero (floating point), negative
// zero (floating point), or a null value.
bool Constant::isZeroValue() const {
// Floating point values have an explicit -0.0 value.
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return CFP->isZero();
// Otherwise, just use +0.0.
return isNullValue();
}
bool Constant::isNullValue() const {
// 0 is null.
if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
return CI->isZero();
// +0.0 is null.
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return CFP->isZero() && !CFP->isNegative();
// constant zero is zero for aggregates and cpnull is null for pointers.
return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this);
}
bool Constant::isAllOnesValue() const {
// Check for -1 integers
if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
return CI->isMinusOne();
// Check for FP which are bitcasted from -1 integers
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
// Check for constant vectors which are splats of -1 values.
if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
if (Constant *Splat = CV->getSplatValue())
return Splat->isAllOnesValue();
// Check for constant vectors which are splats of -1 values.
if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
if (Constant *Splat = CV->getSplatValue())
return Splat->isAllOnesValue();
return false;
}
bool Constant::isOneValue() const {
// Check for 1 integers
if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
return CI->isOne();
// Check for FP which are bitcasted from 1 integers
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return CFP->getValueAPF().bitcastToAPInt() == 1;
// Check for constant vectors which are splats of 1 values.
if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
if (Constant *Splat = CV->getSplatValue())
return Splat->isOneValue();
// Check for constant vectors which are splats of 1 values.
if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
if (Constant *Splat = CV->getSplatValue())
return Splat->isOneValue();
return false;
}
bool Constant::isMinSignedValue() const {
// Check for INT_MIN integers
if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
return CI->isMinValue(/*isSigned=*/true);
// Check for FP which are bitcasted from INT_MIN integers
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
// Check for constant vectors which are splats of INT_MIN values.
if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
if (Constant *Splat = CV->getSplatValue())
return Splat->isMinSignedValue();
// Check for constant vectors which are splats of INT_MIN values.
if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
if (Constant *Splat = CV->getSplatValue())
return Splat->isMinSignedValue();
return false;
}
bool Constant::isNotMinSignedValue() const {
// Check for INT_MIN integers
if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
return !CI->isMinValue(/*isSigned=*/true);
// Check for FP which are bitcasted from INT_MIN integers
if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
// Check for constant vectors which are splats of INT_MIN values.
if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
if (Constant *Splat = CV->getSplatValue())
return Splat->isNotMinSignedValue();
// Check for constant vectors which are splats of INT_MIN values.
if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
if (Constant *Splat = CV->getSplatValue())
return Splat->isNotMinSignedValue();
// It *may* contain INT_MIN, we can't tell.
return false;
}
// Constructor to create a '0' constant of arbitrary type...
Constant *Constant::getNullValue(Type *Ty) {
switch (Ty->getTypeID()) {
case Type::IntegerTyID:
return ConstantInt::get(Ty, 0);
case Type::HalfTyID:
return ConstantFP::get(Ty->getContext(),
APFloat::getZero(APFloat::IEEEhalf));
case Type::FloatTyID:
return ConstantFP::get(Ty->getContext(),
APFloat::getZero(APFloat::IEEEsingle));
case Type::DoubleTyID:
return ConstantFP::get(Ty->getContext(),
APFloat::getZero(APFloat::IEEEdouble));
case Type::X86_FP80TyID:
return ConstantFP::get(Ty->getContext(),
APFloat::getZero(APFloat::x87DoubleExtended));
case Type::FP128TyID:
return ConstantFP::get(Ty->getContext(),
APFloat::getZero(APFloat::IEEEquad));
case Type::PPC_FP128TyID:
return ConstantFP::get(Ty->getContext(),
APFloat(APFloat::PPCDoubleDouble,
APInt::getNullValue(128)));
case Type::PointerTyID:
return ConstantPointerNull::get(cast<PointerType>(Ty));
case Type::StructTyID:
case Type::ArrayTyID:
case Type::VectorTyID:
return ConstantAggregateZero::get(Ty);
default:
// Function, Label, or Opaque type?
llvm_unreachable("Cannot create a null constant of that type!");
}
}
Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
Type *ScalarTy = Ty->getScalarType();
// Create the base integer constant.
Constant *C = ConstantInt::get(Ty->getContext(), V);
// Convert an integer to a pointer, if necessary.
if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
C = ConstantExpr::getIntToPtr(C, PTy);
// Broadcast a scalar to a vector, if necessary.
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
C = ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
Constant *Constant::getAllOnesValue(Type *Ty) {
if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
return ConstantInt::get(Ty->getContext(),
APInt::getAllOnesValue(ITy->getBitWidth()));
if (Ty->isFloatingPointTy()) {
APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
!Ty->isPPC_FP128Ty());
return ConstantFP::get(Ty->getContext(), FL);
}
VectorType *VTy = cast<VectorType>(Ty);
return ConstantVector::getSplat(VTy->getNumElements(),
getAllOnesValue(VTy->getElementType()));
}
/// getAggregateElement - For aggregates (struct/array/vector) return the
/// constant that corresponds to the specified element if possible, or null if
/// not. This can return null if the element index is a ConstantExpr, or if
/// 'this' is a constant expr.
Constant *Constant::getAggregateElement(unsigned Elt) const {
if (const ConstantStruct *CS = dyn_cast<ConstantStruct>(this))
return Elt < CS->getNumOperands() ? CS->getOperand(Elt) : nullptr;
if (const ConstantArray *CA = dyn_cast<ConstantArray>(this))
return Elt < CA->getNumOperands() ? CA->getOperand(Elt) : nullptr;
if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
return Elt < CV->getNumOperands() ? CV->getOperand(Elt) : nullptr;
if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
if (const UndefValue *UV = dyn_cast<UndefValue>(this))
return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
: nullptr;
return nullptr;
}
Constant *Constant::getAggregateElement(Constant *Elt) const {
assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt))
return getAggregateElement(CI->getZExtValue());
return nullptr;
}
void Constant::destroyConstant() {
/// First call destroyConstantImpl on the subclass. This gives the subclass
/// a chance to remove the constant from any maps/pools it's contained in.
switch (getValueID()) {
default:
llvm_unreachable("Not a constant!");
#define HANDLE_CONSTANT(Name) \
case Value::Name##Val: \
cast<Name>(this)->destroyConstantImpl(); \
break;
#include "llvm/IR/Value.def"
}
// When a Constant is destroyed, there may be lingering
// references to the constant by other constants in the constant pool. These
// constants are implicitly dependent on the module that is being deleted,
// but they don't know that. Because we only find out when the CPV is
// deleted, we must now notify all of our users (that should only be
// Constants) that they are, in fact, invalid now and should be deleted.
//
while (!use_empty()) {
Value *V = user_back();
#ifndef NDEBUG // Only in -g mode...
if (!isa<Constant>(V)) {
dbgs() << "While deleting: " << *this
<< "\n\nUse still stuck around after Def is destroyed: " << *V
<< "\n\n";
}
#endif
assert(isa<Constant>(V) && "References remain to Constant being destroyed");
cast<Constant>(V)->destroyConstant();
// The constant should remove itself from our use list...
assert((use_empty() || user_back() != V) && "Constant not removed!");
}
// Value has no outstanding references it is safe to delete it now...
delete this;
}
static bool canTrapImpl(const Constant *C,
SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
// The only thing that could possibly trap are constant exprs.
const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
if (!CE)
return false;
// ConstantExpr traps if any operands can trap.
for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
return true;
}
}
// Otherwise, only specific operations can trap.
switch (CE->getOpcode()) {
default:
return false;
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::FDiv:
case Instruction::URem:
case Instruction::SRem:
case Instruction::FRem:
// Div and rem can trap if the RHS is not known to be non-zero.
if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
return true;
return false;
}
}
/// canTrap - Return true if evaluation of this constant could trap. This is
/// true for things like constant expressions that could divide by zero.
bool Constant::canTrap() const {
SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
return canTrapImpl(this, NonTrappingOps);
}
/// Check if C contains a GlobalValue for which Predicate is true.
static bool
ConstHasGlobalValuePredicate(const Constant *C,
bool (*Predicate)(const GlobalValue *)) {
SmallPtrSet<const Constant *, 8> Visited;
SmallVector<const Constant *, 8> WorkList;
WorkList.push_back(C);
Visited.insert(C);
while (!WorkList.empty()) {
const Constant *WorkItem = WorkList.pop_back_val();
if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
if (Predicate(GV))
return true;
for (const Value *Op : WorkItem->operands()) {
const Constant *ConstOp = dyn_cast<Constant>(Op);
if (!ConstOp)
continue;
if (Visited.insert(ConstOp).second)
WorkList.push_back(ConstOp);
}
}
return false;
}
/// Return true if the value can vary between threads.
bool Constant::isThreadDependent() const {
auto DLLImportPredicate = [](const GlobalValue *GV) {
return GV->isThreadLocal();
};
return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
}
bool Constant::isDLLImportDependent() const {
auto DLLImportPredicate = [](const GlobalValue *GV) {
return GV->hasDLLImportStorageClass();
};
return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
}
/// Return true if the constant has users other than constant exprs and other
/// dangling things.
bool Constant::isConstantUsed() const {
for (const User *U : users()) {
const Constant *UC = dyn_cast<Constant>(U);
if (!UC || isa<GlobalValue>(UC))
return true;
if (UC->isConstantUsed())
return true;
}
return false;
}
/// getRelocationInfo - This method classifies the entry according to
/// whether or not it may generate a relocation entry. This must be
/// conservative, so if it might codegen to a relocatable entry, it should say
/// so. The return values are:
///
/// NoRelocation: This constant pool entry is guaranteed to never have a
/// relocation applied to it (because it holds a simple constant like
/// '4').
/// LocalRelocation: This entry has relocations, but the entries are
/// guaranteed to be resolvable by the static linker, so the dynamic
/// linker will never see them.
/// GlobalRelocations: This entry may have arbitrary relocations.
///
/// FIXME: This really should not be in IR.
Constant::PossibleRelocationsTy Constant::getRelocationInfo() const {
if (const GlobalValue *GV = dyn_cast<GlobalValue>(this)) {
if (GV->hasLocalLinkage() || GV->hasHiddenVisibility())
return LocalRelocation; // Local to this file/library.
return GlobalRelocations; // Global reference.
}
if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
return BA->getFunction()->getRelocationInfo();
// While raw uses of blockaddress need to be relocated, differences between
// two of them don't when they are for labels in the same function. This is a
// common idiom when creating a table for the indirect goto extension, so we
// handle it efficiently here.
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this))
if (CE->getOpcode() == Instruction::Sub) {
ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
if (LHS && RHS &&
LHS->getOpcode() == Instruction::PtrToInt &&
RHS->getOpcode() == Instruction::PtrToInt &&
isa<BlockAddress>(LHS->getOperand(0)) &&
isa<BlockAddress>(RHS->getOperand(0)) &&
cast<BlockAddress>(LHS->getOperand(0))->getFunction() ==
cast<BlockAddress>(RHS->getOperand(0))->getFunction())
return NoRelocation;
}
PossibleRelocationsTy Result = NoRelocation;
for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
Result = std::max(Result,
cast<Constant>(getOperand(i))->getRelocationInfo());
return Result;
}
/// removeDeadUsersOfConstant - If the specified constantexpr is dead, remove
/// it. This involves recursively eliminating any dead users of the
/// constantexpr.
static bool removeDeadUsersOfConstant(const Constant *C) {
if (isa<GlobalValue>(C)) return false; // Cannot remove this
while (!C->use_empty()) {
const Constant *User = dyn_cast<Constant>(C->user_back());
if (!User) return false; // Non-constant usage;
if (!removeDeadUsersOfConstant(User))
return false; // Constant wasn't dead
}
const_cast<Constant*>(C)->destroyConstant();
return true;
}
/// removeDeadConstantUsers - If there are any dead constant users dangling
/// off of this constant, remove them. This method is useful for clients
/// that want to check to see if a global is unused, but don't want to deal
/// with potentially dead constants hanging off of the globals.
void Constant::removeDeadConstantUsers() const {
Value::const_user_iterator I = user_begin(), E = user_end();
Value::const_user_iterator LastNonDeadUser = E;
while (I != E) {
const Constant *User = dyn_cast<Constant>(*I);
if (!User) {
LastNonDeadUser = I;
++I;
continue;
}
if (!removeDeadUsersOfConstant(User)) {
// If the constant wasn't dead, remember that this was the last live use
// and move on to the next constant.
LastNonDeadUser = I;
++I;
continue;
}
// If the constant was dead, then the iterator is invalidated.
if (LastNonDeadUser == E) {
I = user_begin();
if (I == E) break;
} else {
I = LastNonDeadUser;
++I;
}
}
}
//===----------------------------------------------------------------------===//
// ConstantInt
//===----------------------------------------------------------------------===//
void ConstantInt::anchor() { }
ConstantInt::ConstantInt(IntegerType *Ty, const APInt& V)
: Constant(Ty, ConstantIntVal, nullptr, 0), Val(V) {
assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
}
ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
LLVMContextImpl *pImpl = Context.pImpl;
if (!pImpl->TheTrueVal)
pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
return pImpl->TheTrueVal;
}
ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
LLVMContextImpl *pImpl = Context.pImpl;
if (!pImpl->TheFalseVal)
pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
return pImpl->TheFalseVal;
}
Constant *ConstantInt::getTrue(Type *Ty) {
VectorType *VTy = dyn_cast<VectorType>(Ty);
if (!VTy) {
assert(Ty->isIntegerTy(1) && "True must be i1 or vector of i1.");
return ConstantInt::getTrue(Ty->getContext());
}
assert(VTy->getElementType()->isIntegerTy(1) &&
"True must be vector of i1 or i1.");
return ConstantVector::getSplat(VTy->getNumElements(),
ConstantInt::getTrue(Ty->getContext()));
}
Constant *ConstantInt::getFalse(Type *Ty) {
VectorType *VTy = dyn_cast<VectorType>(Ty);
if (!VTy) {
assert(Ty->isIntegerTy(1) && "False must be i1 or vector of i1.");
return ConstantInt::getFalse(Ty->getContext());
}
assert(VTy->getElementType()->isIntegerTy(1) &&
"False must be vector of i1 or i1.");
return ConstantVector::getSplat(VTy->getNumElements(),
ConstantInt::getFalse(Ty->getContext()));
}
// Get a ConstantInt from an APInt.
ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
// get an existing value or the insertion position
LLVMContextImpl *pImpl = Context.pImpl;
ConstantInt *&Slot = pImpl->IntConstants[V];
if (!Slot) {
// Get the corresponding integer type for the bit width of the value.
IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
Slot = new ConstantInt(ITy, V);
}
assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
return Slot;
}
Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
// For vectors, broadcast the value.
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V,
bool isSigned) {
return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
}
ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
return get(Ty, V, true);
}
Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
return get(Ty, V, true);
}
Constant *ConstantInt::get(Type *Ty, const APInt& V) {
ConstantInt *C = get(Ty->getContext(), V);
assert(C->getType() == Ty->getScalarType() &&
"ConstantInt type doesn't match the type implied by its value!");
// For vectors, broadcast the value.
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str,
uint8_t radix) {
return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
}
/// Remove the constant from the constant table.
void ConstantInt::destroyConstantImpl() {
llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
}
//===----------------------------------------------------------------------===//
// ConstantFP
//===----------------------------------------------------------------------===//
static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
if (Ty->isHalfTy())
return &APFloat::IEEEhalf;
if (Ty->isFloatTy())
return &APFloat::IEEEsingle;
if (Ty->isDoubleTy())
return &APFloat::IEEEdouble;
if (Ty->isX86_FP80Ty())
return &APFloat::x87DoubleExtended;
else if (Ty->isFP128Ty())
return &APFloat::IEEEquad;
assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
return &APFloat::PPCDoubleDouble;
}
void ConstantFP::anchor() { }
/// get() - This returns a constant fp for the specified value in the
/// specified type. This should only be used for simple constant values like
/// 2.0/1.0 etc, that are known-valid both as double and as the target format.
Constant *ConstantFP::get(Type *Ty, double V) {
LLVMContext &Context = Ty->getContext();
APFloat FV(V);
bool ignored;
FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
APFloat::rmNearestTiesToEven, &ignored);
Constant *C = get(Context, FV);
// For vectors, broadcast the value.
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
Constant *ConstantFP::get(Type *Ty, StringRef Str) {
LLVMContext &Context = Ty->getContext();
APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
Constant *C = get(Context, FV);
// For vectors, broadcast the value.
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
Constant *ConstantFP::getNaN(Type *Ty, bool Negative, unsigned Type) {
const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
APFloat NaN = APFloat::getNaN(Semantics, Negative, Type);
Constant *C = get(Ty->getContext(), NaN);
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
Constant *ConstantFP::getNegativeZero(Type *Ty) {
const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
Constant *C = get(Ty->getContext(), NegZero);
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
if (Ty->isFPOrFPVectorTy())
return getNegativeZero(Ty);
return Constant::getNullValue(Ty);
}
// ConstantFP accessors.
ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
LLVMContextImpl* pImpl = Context.pImpl;
ConstantFP *&Slot = pImpl->FPConstants[V];
if (!Slot) {
Type *Ty;
if (&V.getSemantics() == &APFloat::IEEEhalf)
Ty = Type::getHalfTy(Context);
else if (&V.getSemantics() == &APFloat::IEEEsingle)
Ty = Type::getFloatTy(Context);
else if (&V.getSemantics() == &APFloat::IEEEdouble)
Ty = Type::getDoubleTy(Context);
else if (&V.getSemantics() == &APFloat::x87DoubleExtended)
Ty = Type::getX86_FP80Ty(Context);
else if (&V.getSemantics() == &APFloat::IEEEquad)
Ty = Type::getFP128Ty(Context);
else {
assert(&V.getSemantics() == &APFloat::PPCDoubleDouble &&
"Unknown FP format");
Ty = Type::getPPC_FP128Ty(Context);
}
Slot = new ConstantFP(Ty, V);
}
return Slot;
}
Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
if (VectorType *VTy = dyn_cast<VectorType>(Ty))
return ConstantVector::getSplat(VTy->getNumElements(), C);
return C;
}
ConstantFP::ConstantFP(Type *Ty, const APFloat& V)
: Constant(Ty, ConstantFPVal, nullptr, 0), Val(V) {
assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
"FP type Mismatch");
}
bool ConstantFP::isExactlyValue(const APFloat &V) const {
return Val.bitwiseIsEqual(V);
}
/// Remove the constant from the constant table.
void ConstantFP::destroyConstantImpl() {
llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
}
//===----------------------------------------------------------------------===//
// ConstantAggregateZero Implementation
//===----------------------------------------------------------------------===//
/// getSequentialElement - If this CAZ has array or vector type, return a zero
/// with the right element type.
Constant *ConstantAggregateZero::getSequentialElement() const {
return Constant::getNullValue(getType()->getSequentialElementType());
}
/// getStructElement - If this CAZ has struct type, return a zero with the
/// right element type for the specified element.
Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
return Constant::getNullValue(getType()->getStructElementType(Elt));
}
/// getElementValue - Return a zero of the right value for the specified GEP
/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
if (isa<SequentialType>(getType()))
return getSequentialElement();
return getStructElement(cast<ConstantInt>(C)->getZExtValue());
}
/// getElementValue - Return a zero of the right value for the specified GEP
/// index.
Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
if (isa<SequentialType>(getType()))
return getSequentialElement();
return getStructElement(Idx);
}
unsigned ConstantAggregateZero::getNumElements() const {
const Type *Ty = getType();
if (const auto *AT = dyn_cast<ArrayType>(Ty))
return AT->getNumElements();
if (const auto *VT = dyn_cast<VectorType>(Ty))
return VT->getNumElements();
return Ty->getStructNumElements();
}
//===----------------------------------------------------------------------===//
// UndefValue Implementation
//===----------------------------------------------------------------------===//
/// getSequentialElement - If this undef has array or vector type, return an
/// undef with the right element type.
UndefValue *UndefValue::getSequentialElement() const {
return UndefValue::get(getType()->getSequentialElementType());
}
/// getStructElement - If this undef has struct type, return a zero with the
/// right element type for the specified element.
UndefValue *UndefValue::getStructElement(unsigned Elt) const {
return UndefValue::get(getType()->getStructElementType(Elt));
}
/// getElementValue - Return an undef of the right value for the specified GEP
/// index if we can, otherwise return null (e.g. if C is a ConstantExpr).
UndefValue *UndefValue::getElementValue(Constant *C) const {
if (isa<SequentialType>(getType()))
return getSequentialElement();
return getStructElement(cast<ConstantInt>(C)->getZExtValue());
}
/// getElementValue - Return an undef of the right value for the specified GEP
/// index.
UndefValue *UndefValue::getElementValue(unsigned Idx) const {
if (isa<SequentialType>(getType()))
return getSequentialElement();
return getStructElement(Idx);
}
unsigned UndefValue::getNumElements() const {
const Type *Ty = getType();
if (const auto *AT = dyn_cast<ArrayType>(Ty))
return AT->getNumElements();
if (const auto *VT = dyn_cast<VectorType>(Ty))
return VT->getNumElements();
return Ty->getStructNumElements();
}
//===----------------------------------------------------------------------===//
// ConstantXXX Classes
//===----------------------------------------------------------------------===//
template <typename ItTy, typename EltTy>
static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
for (; Start != End; ++Start)
if (*Start != Elt)
return false;
return true;
}
ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
: Constant(T, ConstantArrayVal,
OperandTraits<ConstantArray>::op_end(this) - V.size(),
V.size()) {
assert(V.size() == T->getNumElements() &&
"Invalid initializer vector for constant array");
for (unsigned i = 0, e = V.size(); i != e; ++i)
assert(V[i]->getType() == T->getElementType() &&
"Initializer for array element doesn't match array element type!");
std::copy(V.begin(), V.end(), op_begin());
}
Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
if (Constant *C = getImpl(Ty, V))
return C;
return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
}
Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
// Empty arrays are canonicalized to ConstantAggregateZero.
if (V.empty())
return ConstantAggregateZero::get(Ty);
for (unsigned i = 0, e = V.size(); i != e; ++i) {
assert(V[i]->getType() == Ty->getElementType() &&
"Wrong type in array element initializer");
}
// If this is an all-zero array, return a ConstantAggregateZero object. If
// all undef, return an UndefValue, if "all simple", then return a
// ConstantDataArray.
Constant *C = V[0];
if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
return UndefValue::get(Ty);
if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
return ConstantAggregateZero::get(Ty);
// Check to see if all of the elements are ConstantFP or ConstantInt and if
// the element type is compatible with ConstantDataVector. If so, use it.
if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
// We speculatively build the elements here even if it turns out that there
// is a constantexpr or something else weird in the array, since it is so
// uncommon for that to happen.
if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
if (CI->getType()->isIntegerTy(8)) {
SmallVector<uint8_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(16)) {
SmallVector<uint16_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(32)) {
SmallVector<uint32_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(64)) {
SmallVector<uint64_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::get(C->getContext(), Elts);
}
}
if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
if (CFP->getType()->isFloatTy()) {
SmallVector<uint32_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
Elts.push_back(
CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::getFP(C->getContext(), Elts);
} else if (CFP->getType()->isDoubleTy()) {
SmallVector<uint64_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
Elts.push_back(
CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataArray::getFP(C->getContext(), Elts);
}
}
}
// Otherwise, we really do want to create a ConstantArray.
return nullptr;
}
/// getTypeForElements - Return an anonymous struct type to use for a constant
/// with the specified set of elements. The list must not be empty.
StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
ArrayRef<Constant*> V,
bool Packed) {
unsigned VecSize = V.size();
SmallVector<Type*, 16> EltTypes(VecSize);
for (unsigned i = 0; i != VecSize; ++i)
EltTypes[i] = V[i]->getType();
return StructType::get(Context, EltTypes, Packed);
}
StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
bool Packed) {
assert(!V.empty() &&
"ConstantStruct::getTypeForElements cannot be called on empty list");
return getTypeForElements(V[0]->getContext(), V, Packed);
}
ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
: Constant(T, ConstantStructVal,
OperandTraits<ConstantStruct>::op_end(this) - V.size(),
V.size()) {
assert(V.size() == T->getNumElements() &&
"Invalid initializer vector for constant structure");
for (unsigned i = 0, e = V.size(); i != e; ++i)
assert((T->isOpaque() || V[i]->getType() == T->getElementType(i)) &&
"Initializer for struct element doesn't match struct element type!");
std::copy(V.begin(), V.end(), op_begin());
}
// ConstantStruct accessors.
Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
"Incorrect # elements specified to ConstantStruct::get");
// Create a ConstantAggregateZero value if all elements are zeros.
bool isZero = true;
bool isUndef = false;
if (!V.empty()) {
isUndef = isa<UndefValue>(V[0]);
isZero = V[0]->isNullValue();
if (isUndef || isZero) {
for (unsigned i = 0, e = V.size(); i != e; ++i) {
if (!V[i]->isNullValue())
isZero = false;
if (!isa<UndefValue>(V[i]))
isUndef = false;
}
}
}
if (isZero)
return ConstantAggregateZero::get(ST);
if (isUndef)
return UndefValue::get(ST);
return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
}
Constant *ConstantStruct::get(StructType *T, ...) {
va_list ap;
SmallVector<Constant*, 8> Values;
va_start(ap, T);
while (Constant *Val = va_arg(ap, llvm::Constant*))
Values.push_back(Val);
va_end(ap);
return get(T, Values);
}
ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
: Constant(T, ConstantVectorVal,
OperandTraits<ConstantVector>::op_end(this) - V.size(),
V.size()) {
for (size_t i = 0, e = V.size(); i != e; i++)
assert(V[i]->getType() == T->getElementType() &&
"Initializer for vector element doesn't match vector element type!");
std::copy(V.begin(), V.end(), op_begin());
}
// ConstantVector accessors.
Constant *ConstantVector::get(ArrayRef<Constant*> V) {
if (Constant *C = getImpl(V))
return C;
VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
}
Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
assert(!V.empty() && "Vectors can't be empty");
VectorType *T = VectorType::get(V.front()->getType(), V.size());
// If this is an all-undef or all-zero vector, return a
// ConstantAggregateZero or UndefValue.
Constant *C = V[0];
bool isZero = C->isNullValue();
bool isUndef = isa<UndefValue>(C);
if (isZero || isUndef) {
for (unsigned i = 1, e = V.size(); i != e; ++i)
if (V[i] != C) {
isZero = isUndef = false;
break;
}
}
if (isZero)
return ConstantAggregateZero::get(T);
if (isUndef)
return UndefValue::get(T);
// Check to see if all of the elements are ConstantFP or ConstantInt and if
// the element type is compatible with ConstantDataVector. If so, use it.
if (ConstantDataSequential::isElementTypeCompatible(C->getType())) {
// We speculatively build the elements here even if it turns out that there
// is a constantexpr or something else weird in the array, since it is so
// uncommon for that to happen.
if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
if (CI->getType()->isIntegerTy(8)) {
SmallVector<uint8_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataVector::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(16)) {
SmallVector<uint16_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataVector::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(32)) {
SmallVector<uint32_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataVector::get(C->getContext(), Elts);
} else if (CI->getType()->isIntegerTy(64)) {
SmallVector<uint64_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantInt *CI = dyn_cast<ConstantInt>(V[i]))
Elts.push_back(CI->getZExtValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataVector::get(C->getContext(), Elts);
}
}
if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
if (CFP->getType()->isFloatTy()) {
SmallVector<uint32_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
Elts.push_back(
CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataVector::getFP(C->getContext(), Elts);
} else if (CFP->getType()->isDoubleTy()) {
SmallVector<uint64_t, 16> Elts;
for (unsigned i = 0, e = V.size(); i != e; ++i)
if (ConstantFP *CFP = dyn_cast<ConstantFP>(V[i]))
Elts.push_back(
CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
else
break;
if (Elts.size() == V.size())
return ConstantDataVector::getFP(C->getContext(), Elts);
}
}
}
// Otherwise, the element type isn't compatible with ConstantDataVector, or
// the operand list constants a ConstantExpr or something else strange.
return nullptr;
}
Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
// If this splat is compatible with ConstantDataVector, use it instead of
// ConstantVector.
if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
ConstantDataSequential::isElementTypeCompatible(V->getType()))
return ConstantDataVector::getSplat(NumElts, V);
SmallVector<Constant*, 32> Elts(NumElts, V);
return get(Elts);
}
// Utility function for determining if a ConstantExpr is a CastOp or not. This
// can't be inline because we don't want to #include Instruction.h into
// Constant.h
bool ConstantExpr::isCast() const {
return Instruction::isCast(getOpcode());
}
bool ConstantExpr::isCompare() const {
return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
}
bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
if (getOpcode() != Instruction::GetElementPtr) return false;
gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
User::const_op_iterator OI = std::next(this->op_begin());
// Skip the first index, as it has no static limit.
++GEPI;
++OI;
// The remaining indices must be compile-time known integers within the
// bounds of the corresponding notional static array types.
for (; GEPI != E; ++GEPI, ++OI) {
ConstantInt *CI = dyn_cast<ConstantInt>(*OI);
if (!CI) return false;
if (ArrayType *ATy = dyn_cast<ArrayType>(*GEPI))
if (CI->getValue().getActiveBits() > 64 ||
CI->getZExtValue() >= ATy->getNumElements())
return false;
}
// All the indices checked out.
return true;
}
bool ConstantExpr::hasIndices() const {
return getOpcode() == Instruction::ExtractValue ||
getOpcode() == Instruction::InsertValue;
}
ArrayRef<unsigned> ConstantExpr::getIndices() const {
if (const ExtractValueConstantExpr *EVCE =
dyn_cast<ExtractValueConstantExpr>(this))
return EVCE->Indices;
return cast<InsertValueConstantExpr>(this)->Indices;
}
unsigned ConstantExpr::getPredicate() const {
assert(isCompare());
return ((const CompareConstantExpr*)this)->predicate;
}
/// getWithOperandReplaced - Return a constant expression identical to this
/// one, but with the specified operand set to the specified value.
Constant *
ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
assert(Op->getType() == getOperand(OpNo)->getType() &&
"Replacing operand with value of different type!");
if (getOperand(OpNo) == Op)
return const_cast<ConstantExpr*>(this);
SmallVector<Constant*, 8> NewOps;
for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
NewOps.push_back(i == OpNo ? Op : getOperand(i));
return getWithOperands(NewOps);
}
/// getWithOperands - This returns the current constant expression with the
/// operands replaced with the specified values. The specified array must
/// have the same number of operands as our current one.
Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
bool OnlyIfReduced) const {
assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
// If no operands changed return self.
if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
return const_cast<ConstantExpr*>(this);
Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
switch (getOpcode()) {
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::FPTrunc:
case Instruction::FPExt:
case Instruction::UIToFP:
case Instruction::SIToFP:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::PtrToInt:
case Instruction::IntToPtr:
case Instruction::BitCast:
case Instruction::AddrSpaceCast:
return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
case Instruction::Select:
return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
case Instruction::InsertElement:
return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
OnlyIfReducedTy);
case Instruction::ExtractElement:
return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
case Instruction::InsertValue:
return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
OnlyIfReducedTy);
case Instruction::ExtractValue:
return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
case Instruction::ShuffleVector:
return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
OnlyIfReducedTy);
case Instruction::GetElementPtr:
return ConstantExpr::getGetElementPtr(nullptr, Ops[0], Ops.slice(1),
cast<GEPOperator>(this)->isInBounds(),
OnlyIfReducedTy);
case Instruction::ICmp:
case Instruction::FCmp:
return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
OnlyIfReducedTy);
default:
assert(getNumOperands() == 2 && "Must be binary operator?");
return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
OnlyIfReducedTy);
}
}
//===----------------------------------------------------------------------===//
// isValueValidForType implementations
bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
if (Ty->isIntegerTy(1))
return Val == 0 || Val == 1;
if (NumBits >= 64)
return true; // always true, has to fit in largest type
uint64_t Max = (1ll << NumBits) - 1;
return Val <= Max;
}
bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
unsigned NumBits = Ty->getIntegerBitWidth();
if (Ty->isIntegerTy(1))
return Val == 0 || Val == 1 || Val == -1;
if (NumBits >= 64)
return true; // always true, has to fit in largest type
int64_t Min = -(1ll << (NumBits-1));
int64_t Max = (1ll << (NumBits-1)) - 1;
return (Val >= Min && Val <= Max);
}
bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
// convert modifies in place, so make a copy.
APFloat Val2 = APFloat(Val);
bool losesInfo;
switch (Ty->getTypeID()) {
default:
return false; // These can't be represented as floating point!
// FIXME rounding mode needs to be more flexible
case Type::HalfTyID: {
if (&Val2.getSemantics() == &APFloat::IEEEhalf)
return true;
Val2.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &losesInfo);
return !losesInfo;
}
case Type::FloatTyID: {
if (&Val2.getSemantics() == &APFloat::IEEEsingle)
return true;
Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &losesInfo);
return !losesInfo;
}
case Type::DoubleTyID: {
if (&Val2.getSemantics() == &APFloat::IEEEhalf ||
&Val2.getSemantics() == &APFloat::IEEEsingle ||
&Val2.getSemantics() == &APFloat::IEEEdouble)
return true;
Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &losesInfo);
return !losesInfo;
}
case Type::X86_FP80TyID:
return &Val2.getSemantics() == &APFloat::IEEEhalf ||
&Val2.getSemantics() == &APFloat::IEEEsingle ||
&Val2.getSemantics() == &APFloat::IEEEdouble ||
&Val2.getSemantics() == &APFloat::x87DoubleExtended;
case Type::FP128TyID:
return &Val2.getSemantics() == &APFloat::IEEEhalf ||
&Val2.getSemantics() == &APFloat::IEEEsingle ||
&Val2.getSemantics() == &APFloat::IEEEdouble ||
&Val2.getSemantics() == &APFloat::IEEEquad;
case Type::PPC_FP128TyID:
return &Val2.getSemantics() == &APFloat::IEEEhalf ||
&Val2.getSemantics() == &APFloat::IEEEsingle ||
&Val2.getSemantics() == &APFloat::IEEEdouble ||
&Val2.getSemantics() == &APFloat::PPCDoubleDouble;
}
}
//===----------------------------------------------------------------------===//
// Factory Function Implementation
ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
"Cannot create an aggregate zero of non-aggregate type!");
ConstantAggregateZero *&Entry = Ty->getContext().pImpl->CAZConstants[Ty];
if (!Entry)
Entry = new ConstantAggregateZero(Ty);
return Entry;
}
/// destroyConstant - Remove the constant from the constant table.
///
void ConstantAggregateZero::destroyConstantImpl() {
getContext().pImpl->CAZConstants.erase(getType());
}
/// destroyConstant - Remove the constant from the constant table...
///
void ConstantArray::destroyConstantImpl() {
getType()->getContext().pImpl->ArrayConstants.remove(this);
}
//---- ConstantStruct::get() implementation...
//
// destroyConstant - Remove the constant from the constant table...
//
void ConstantStruct::destroyConstantImpl() {
getType()->getContext().pImpl->StructConstants.remove(this);
}
// destroyConstant - Remove the constant from the constant table...
//
void ConstantVector::destroyConstantImpl() {
getType()->getContext().pImpl->VectorConstants.remove(this);
}
/// getSplatValue - If this is a splat vector constant, meaning that all of
/// the elements have the same value, return that value. Otherwise return 0.
Constant *Constant::getSplatValue() const {
assert(this->getType()->isVectorTy() && "Only valid for vectors!");
if (isa<ConstantAggregateZero>(this))
return getNullValue(this->getType()->getVectorElementType());
if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
return CV->getSplatValue();
if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
return CV->getSplatValue();
return nullptr;
}
/// getSplatValue - If this is a splat constant, where all of the
/// elements have the same value, return that value. Otherwise return null.
Constant *ConstantVector::getSplatValue() const {
// Check out first element.
Constant *Elt = getOperand(0);
// Then make sure all remaining elements point to the same value.
for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
if (getOperand(I) != Elt)
return nullptr;
return Elt;
}
/// If C is a constant integer then return its value, otherwise C must be a
/// vector of constant integers, all equal, and the common value is returned.
const APInt &Constant::getUniqueInteger() const {
if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
return CI->getValue();
assert(this->getSplatValue() && "Doesn't contain a unique integer!");
const Constant *C = this->getAggregateElement(0U);
assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
return cast<ConstantInt>(C)->getValue();
}
//---- ConstantPointerNull::get() implementation.
//
ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
ConstantPointerNull *&Entry = Ty->getContext().pImpl->CPNConstants[Ty];
if (!Entry)
Entry = new ConstantPointerNull(Ty);
return Entry;
}
// destroyConstant - Remove the constant from the constant table...
//
void ConstantPointerNull::destroyConstantImpl() {
getContext().pImpl->CPNConstants.erase(getType());
}
//---- UndefValue::get() implementation.
//
UndefValue *UndefValue::get(Type *Ty) {
UndefValue *&Entry = Ty->getContext().pImpl->UVConstants[Ty];
if (!Entry)
Entry = new UndefValue(Ty);
return Entry;
}
// destroyConstant - Remove the constant from the constant table.
//
void UndefValue::destroyConstantImpl() {
// Free the constant and any dangling references to it.
getContext().pImpl->UVConstants.erase(getType());
}
//---- BlockAddress::get() implementation.
//
BlockAddress *BlockAddress::get(BasicBlock *BB) {
assert(BB->getParent() && "Block must have a parent");
return get(BB->getParent(), BB);
}
BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
BlockAddress *&BA =
F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
if (!BA)
BA = new BlockAddress(F, BB);
assert(BA->getFunction() == F && "Basic block moved between functions");
return BA;
}
BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
: Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
&Op<0>(), 2) {
setOperand(0, F);
setOperand(1, BB);
BB->AdjustBlockAddressRefCount(1);
}
BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
if (!BB->hasAddressTaken())
return nullptr;
const Function *F = BB->getParent();
assert(F && "Block must have a parent");
BlockAddress *BA =
F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
assert(BA && "Refcount and block address map disagree!");
return BA;
}
// destroyConstant - Remove the constant from the constant table.
//
void BlockAddress::destroyConstantImpl() {
getFunction()->getType()->getContext().pImpl
->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
getBasicBlock()->AdjustBlockAddressRefCount(-1);
}
Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
// This could be replacing either the Basic Block or the Function. In either
// case, we have to remove the map entry.
Function *NewF = getFunction();
BasicBlock *NewBB = getBasicBlock();
if (U == &Op<0>())
NewF = cast<Function>(To->stripPointerCasts());
else
NewBB = cast<BasicBlock>(To);
// See if the 'new' entry already exists, if not, just update this in place
// and return early.
BlockAddress *&NewBA =
getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
if (NewBA)
return NewBA;
getBasicBlock()->AdjustBlockAddressRefCount(-1);
// Remove the old entry, this can't cause the map to rehash (just a
// tombstone will get added).
getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
getBasicBlock()));
NewBA = this;
setOperand(0, NewF);
setOperand(1, NewBB);
getBasicBlock()->AdjustBlockAddressRefCount(1);
// If we just want to keep the existing value, then return null.
// Callers know that this means we shouldn't delete this value.
return nullptr;
}
//---- ConstantExpr::get() implementations.
//
/// This is a utility function to handle folding of casts and lookup of the
/// cast in the ExprConstants map. It is used by the various get* methods below.
static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
bool OnlyIfReduced = false) {
assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
// Fold a few common cases
if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
return FC;
if (OnlyIfReduced)
return nullptr;
LLVMContextImpl *pImpl = Ty->getContext().pImpl;
// Look up the constant in the table first to ensure uniqueness.
ConstantExprKeyType Key(opc, C);
return pImpl->ExprConstants.getOrCreate(Ty, Key);
}
Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
bool OnlyIfReduced) {
Instruction::CastOps opc = Instruction::CastOps(oc);
assert(Instruction::isCast(opc) && "opcode out of range");
assert(C && Ty && "Null arguments to getCast");
assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
switch (opc) {
default:
llvm_unreachable("Invalid cast opcode");
case Instruction::Trunc:
return getTrunc(C, Ty, OnlyIfReduced);
case Instruction::ZExt:
return getZExt(C, Ty, OnlyIfReduced);
case Instruction::SExt:
return getSExt(C, Ty, OnlyIfReduced);
case Instruction::FPTrunc:
return getFPTrunc(C, Ty, OnlyIfReduced);
case Instruction::FPExt:
return getFPExtend(C, Ty, OnlyIfReduced);
case Instruction::UIToFP:
return getUIToFP(C, Ty, OnlyIfReduced);
case Instruction::SIToFP:
return getSIToFP(C, Ty, OnlyIfReduced);
case Instruction::FPToUI:
return getFPToUI(C, Ty, OnlyIfReduced);
case Instruction::FPToSI:
return getFPToSI(C, Ty, OnlyIfReduced);
case Instruction::PtrToInt:
return getPtrToInt(C, Ty, OnlyIfReduced);
case Instruction::IntToPtr:
return getIntToPtr(C, Ty, OnlyIfReduced);
case Instruction::BitCast:
return getBitCast(C, Ty, OnlyIfReduced);
case Instruction::AddrSpaceCast:
return getAddrSpaceCast(C, Ty, OnlyIfReduced);
}
}
Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return getBitCast(C, Ty);
return getZExt(C, Ty);
}
Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return getBitCast(C, Ty);
return getSExt(C, Ty);
}
Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return getBitCast(C, Ty);
return getTrunc(C, Ty);
}
Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
"Invalid cast");
if (Ty->isIntOrIntVectorTy())
return getPtrToInt(S, Ty);
unsigned SrcAS = S->getType()->getPointerAddressSpace();
if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
return getAddrSpaceCast(S, Ty);
return getBitCast(S, Ty);
}
Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
Type *Ty) {
assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
return getAddrSpaceCast(S, Ty);
return getBitCast(S, Ty);
}
Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty,
bool isSigned) {
assert(C->getType()->isIntOrIntVectorTy() &&
Ty->isIntOrIntVectorTy() && "Invalid cast");
unsigned SrcBits = C->getType()->getScalarSizeInBits();
unsigned DstBits = Ty->getScalarSizeInBits();
Instruction::CastOps opcode =
(SrcBits == DstBits ? Instruction::BitCast :
(SrcBits > DstBits ? Instruction::Trunc :
(isSigned ? Instruction::SExt : Instruction::ZExt)));
return getCast(opcode, C, Ty);
}
Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
"Invalid cast");
unsigned SrcBits = C->getType()->getScalarSizeInBits();
unsigned DstBits = Ty->getScalarSizeInBits();
if (SrcBits == DstBits)
return C; // Avoid a useless cast
Instruction::CastOps opcode =
(SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
return getCast(opcode, C, Ty);
}
Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
#ifndef NDEBUG
bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
bool toVec = Ty->getTypeID() == Type::VectorTyID;
#endif
assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
"SrcTy must be larger than DestTy for Trunc!");
return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
}
Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
#ifndef NDEBUG
bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
bool toVec = Ty->getTypeID() == Type::VectorTyID;
#endif
assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
"SrcTy must be smaller than DestTy for SExt!");
return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
}
Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
#ifndef NDEBUG
bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
bool toVec = Ty->getTypeID() == Type::VectorTyID;
#endif
assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
"SrcTy must be smaller than DestTy for ZExt!");
return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
}
Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
#ifndef NDEBUG
bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
bool toVec = Ty->getTypeID() == Type::VectorTyID;
#endif
assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
"This is an illegal floating point truncation!");
return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
}
Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
#ifndef NDEBUG
bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
bool toVec = Ty->getTypeID() == Type::VectorTyID;
#endif
assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
"This is an illegal floating point extension!");
return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
}
Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
#ifndef NDEBUG
bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
bool toVec = Ty->getTypeID() == Type::VectorTyID;
#endif
assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
"This is an illegal uint to floating point cast!");
return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
}
Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
#ifndef NDEBUG
bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
bool toVec = Ty->getTypeID() == Type::VectorTyID;
#endif
assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
"This is an illegal sint to floating point cast!");
return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
}
Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
#ifndef NDEBUG
bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
bool toVec = Ty->getTypeID() == Type::VectorTyID;
#endif
assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
"This is an illegal floating point to uint cast!");
return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
}
Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
#ifndef NDEBUG
bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
bool toVec = Ty->getTypeID() == Type::VectorTyID;
#endif
assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
"This is an illegal floating point to sint cast!");
return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
}
Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
bool OnlyIfReduced) {
assert(C->getType()->getScalarType()->isPointerTy() &&
"PtrToInt source must be pointer or pointer vector");
assert(DstTy->getScalarType()->isIntegerTy() &&
"PtrToInt destination must be integer or integer vector");
assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
if (isa<VectorType>(C->getType()))
assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
"Invalid cast between a different number of vector elements");
return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
}
Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
bool OnlyIfReduced) {
assert(C->getType()->getScalarType()->isIntegerTy() &&
"IntToPtr source must be integer or integer vector");
assert(DstTy->getScalarType()->isPointerTy() &&
"IntToPtr destination must be a pointer or pointer vector");
assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
if (isa<VectorType>(C->getType()))
assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
"Invalid cast between a different number of vector elements");
return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
}
Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
bool OnlyIfReduced) {
assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
"Invalid constantexpr bitcast!");
// It is common to ask for a bitcast of a value to its own type, handle this
// speedily.
if (C->getType() == DstTy) return C;
return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
}
Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
bool OnlyIfReduced) {
assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
"Invalid constantexpr addrspacecast!");
// Canonicalize addrspacecasts between different pointer types by first
// bitcasting the pointer type and then converting the address space.
PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
Type *DstElemTy = DstScalarTy->getElementType();
if (SrcScalarTy->getElementType() != DstElemTy) {
Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
// Handle vectors of pointers.
MidTy = VectorType::get(MidTy, VT->getNumElements());
}
C = getBitCast(C, MidTy);
}
return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
}
Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
unsigned Flags, Type *OnlyIfReducedTy) {
// Check the operands for consistency first.
assert(Opcode >= Instruction::BinaryOpsBegin &&
Opcode < Instruction::BinaryOpsEnd &&
"Invalid opcode in binary constant expression");
assert(C1->getType() == C2->getType() &&
"Operand types in binary constant expression should match");
#ifndef NDEBUG
switch (Opcode) {
case Instruction::Add:
case Instruction::Sub:
case Instruction::Mul:
assert(C1->getType() == C2->getType() && "Op types should be identical!");
assert(C1->getType()->isIntOrIntVectorTy() &&
"Tried to create an integer operation on a non-integer type!");
break;
case Instruction::FAdd:
case Instruction::FSub:
case Instruction::FMul:
assert(C1->getType() == C2->getType() && "Op types should be identical!");
assert(C1->getType()->isFPOrFPVectorTy() &&
"Tried to create a floating-point operation on a "
"non-floating-point type!");
break;
case Instruction::UDiv:
case Instruction::SDiv:
assert(C1->getType() == C2->getType() && "Op types should be identical!");
assert(C1->getType()->isIntOrIntVectorTy() &&
"Tried to create an arithmetic operation on a non-arithmetic type!");
break;
case Instruction::FDiv:
assert(C1->getType() == C2->getType() && "Op types should be identical!");
assert(C1->getType()->isFPOrFPVectorTy() &&
"Tried to create an arithmetic operation on a non-arithmetic type!");
break;
case Instruction::URem:
case Instruction::SRem:
assert(C1->getType() == C2->getType() && "Op types should be identical!");
assert(C1->getType()->isIntOrIntVectorTy() &&
"Tried to create an arithmetic operation on a non-arithmetic type!");
break;
case Instruction::FRem:
assert(C1->getType() == C2->getType() && "Op types should be identical!");
assert(C1->getType()->isFPOrFPVectorTy() &&
"Tried to create an arithmetic operation on a non-arithmetic type!");
break;
case Instruction::And:
case Instruction::Or:
case Instruction::Xor:
assert(C1->getType() == C2->getType() && "Op types should be identical!");
assert(C1->getType()->isIntOrIntVectorTy() &&
"Tried to create a logical operation on a non-integral type!");
break;
case Instruction::Shl:
case Instruction::LShr:
case Instruction::AShr:
assert(C1->getType() == C2->getType() && "Op types should be identical!");
assert(C1->getType()->isIntOrIntVectorTy() &&
"Tried to create a shift operation on a non-integer type!");
break;
default:
break;
}
#endif
if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
return FC; // Fold a few common cases.
if (OnlyIfReducedTy == C1->getType())
return nullptr;
Constant *ArgVec[] = { C1, C2 };
ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
LLVMContextImpl *pImpl = C1->getContext().pImpl;
return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
}
Constant *ConstantExpr::getSizeOf(Type* Ty) {
// sizeof is implemented as: (i64) gep (Ty*)null, 1
// Note that a non-inbounds gep is used, as null isn't within any object.
Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Constant *GEP = getGetElementPtr(
Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
return getPtrToInt(GEP,
Type::getInt64Ty(Ty->getContext()));
}
Constant *ConstantExpr::getAlignOf(Type* Ty) {
// alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
// Note that a non-inbounds gep is used, as null isn't within any object.
Type *AligningTy =
StructType::get(Type::getInt1Ty(Ty->getContext()), Ty, nullptr);
Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
Constant *Indices[2] = { Zero, One };
Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
return getPtrToInt(GEP,
Type::getInt64Ty(Ty->getContext()));
}
Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
FieldNo));
}
Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
// offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
// Note that a non-inbounds gep is used, as null isn't within any object.
Constant *GEPIdx[] = {
ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
FieldNo
};
Constant *GEP = getGetElementPtr(
Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
return getPtrToInt(GEP,
Type::getInt64Ty(Ty->getContext()));
}
Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
Constant *C2, bool OnlyIfReduced) {
assert(C1->getType() == C2->getType() && "Op types should be identical!");
switch (Predicate) {
default: llvm_unreachable("Invalid CmpInst predicate");
case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
case CmpInst::FCMP_TRUE:
return getFCmp(Predicate, C1, C2, OnlyIfReduced);
case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
case CmpInst::ICMP_SLE:
return getICmp(Predicate, C1, C2, OnlyIfReduced);
}
}
Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
Type *OnlyIfReducedTy) {
assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
return SC; // Fold common cases
if (OnlyIfReducedTy == V1->getType())
return nullptr;
Constant *ArgVec[] = { C, V1, V2 };
ConstantExprKeyType Key(Instruction::Select, ArgVec);
LLVMContextImpl *pImpl = C->getContext().pImpl;
return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
}
Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
ArrayRef<Value *> Idxs, bool InBounds,
Type *OnlyIfReducedTy) {
if (!Ty)
Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
else
assert(
Ty ==
cast<PointerType>(C->getType()->getScalarType())->getContainedType(0u));
if (Constant *FC = ConstantFoldGetElementPtr(Ty, C, InBounds, Idxs))
return FC; // Fold a few common cases.
// Get the result type of the getelementptr!
Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
assert(DestTy && "GEP indices invalid!");
unsigned AS = C->getType()->getPointerAddressSpace();
Type *ReqTy = DestTy->getPointerTo(AS);
if (VectorType *VecTy = dyn_cast<VectorType>(C->getType()))
ReqTy = VectorType::get(ReqTy, VecTy->getNumElements());
if (OnlyIfReducedTy == ReqTy)
return nullptr;
// Look up the constant in the table first to ensure uniqueness
std::vector<Constant*> ArgVec;
ArgVec.reserve(1 + Idxs.size());
ArgVec.push_back(C);
for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
assert(Idxs[i]->getType()->isVectorTy() == ReqTy->isVectorTy() &&
"getelementptr index type missmatch");
assert((!Idxs[i]->getType()->isVectorTy() ||
ReqTy->getVectorNumElements() ==
Idxs[i]->getType()->getVectorNumElements()) &&
"getelementptr index type missmatch");
ArgVec.push_back(cast<Constant>(Idxs[i]));
}
const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
InBounds ? GEPOperator::IsInBounds : 0, None,
Ty);
LLVMContextImpl *pImpl = C->getContext().pImpl;
return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
}
Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
Constant *RHS, bool OnlyIfReduced) {
assert(LHS->getType() == RHS->getType());
assert(pred >= ICmpInst::FIRST_ICMP_PREDICATE &&
pred <= ICmpInst::LAST_ICMP_PREDICATE && "Invalid ICmp Predicate");
if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
return FC; // Fold a few common cases...
if (OnlyIfReduced)
return nullptr;
// Look up the constant in the table first to ensure uniqueness
Constant *ArgVec[] = { LHS, RHS };
// Get the key type with both the opcode and predicate
const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
Type *ResultTy = Type::getInt1Ty(LHS->getContext());
if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
ResultTy = VectorType::get(ResultTy, VT->getNumElements());
LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
}
Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
Constant *RHS, bool OnlyIfReduced) {
assert(LHS->getType() == RHS->getType());
assert(pred <= FCmpInst::LAST_FCMP_PREDICATE && "Invalid FCmp Predicate");
if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
return FC; // Fold a few common cases...
if (OnlyIfReduced)
return nullptr;
// Look up the constant in the table first to ensure uniqueness
Constant *ArgVec[] = { LHS, RHS };
// Get the key type with both the opcode and predicate
const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
Type *ResultTy = Type::getInt1Ty(LHS->getContext());
if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
ResultTy = VectorType::get(ResultTy, VT->getNumElements());
LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
}
Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
Type *OnlyIfReducedTy) {
assert(Val->getType()->isVectorTy() &&
"Tried to create extractelement operation on non-vector type!");
assert(Idx->getType()->isIntegerTy() &&
"Extractelement index must be an integer type!");
if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
return FC; // Fold a few common cases.
Type *ReqTy = Val->getType()->getVectorElementType();
if (OnlyIfReducedTy == ReqTy)
return nullptr;
// Look up the constant in the table first to ensure uniqueness
Constant *ArgVec[] = { Val, Idx };
const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
LLVMContextImpl *pImpl = Val->getContext().pImpl;
return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
}
Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
Constant *Idx, Type *OnlyIfReducedTy) {
assert(Val->getType()->isVectorTy() &&
"Tried to create insertelement operation on non-vector type!");
assert(Elt->getType() == Val->getType()->getVectorElementType() &&
"Insertelement types must match!");
assert(Idx->getType()->isIntegerTy() &&
"Insertelement index must be i32 type!");
if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
return FC; // Fold a few common cases.
if (OnlyIfReducedTy == Val->getType())
return nullptr;
// Look up the constant in the table first to ensure uniqueness
Constant *ArgVec[] = { Val, Elt, Idx };
const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
LLVMContextImpl *pImpl = Val->getContext().pImpl;
return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
}
Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
Constant *Mask, Type *OnlyIfReducedTy) {
assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
"Invalid shuffle vector constant expr operands!");
if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
return FC; // Fold a few common cases.
unsigned NElts = Mask->getType()->getVectorNumElements();
Type *EltTy = V1->getType()->getVectorElementType();
Type *ShufTy = VectorType::get(EltTy, NElts);
if (OnlyIfReducedTy == ShufTy)
return nullptr;
// Look up the constant in the table first to ensure uniqueness
Constant *ArgVec[] = { V1, V2, Mask };
const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
}
Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
ArrayRef<unsigned> Idxs,
Type *OnlyIfReducedTy) {
assert(Agg->getType()->isFirstClassType() &&
"Non-first-class type for constant insertvalue expression");
assert(ExtractValueInst::getIndexedType(Agg->getType(),
Idxs) == Val->getType() &&
"insertvalue indices invalid!");
Type *ReqTy = Val->getType();
if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
return FC;
if (OnlyIfReducedTy == ReqTy)
return nullptr;
Constant *ArgVec[] = { Agg, Val };
const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
LLVMContextImpl *pImpl = Agg->getContext().pImpl;
return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
}
Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
Type *OnlyIfReducedTy) {
assert(Agg->getType()->isFirstClassType() &&
"Tried to create extractelement operation on non-first-class type!");
Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
(void)ReqTy;
assert(ReqTy && "extractvalue indices invalid!");
assert(Agg->getType()->isFirstClassType() &&
"Non-first-class type for constant extractvalue expression");
if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
return FC;
if (OnlyIfReducedTy == ReqTy)
return nullptr;
Constant *ArgVec[] = { Agg };
const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
LLVMContextImpl *pImpl = Agg->getContext().pImpl;
return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
}
Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
assert(C->getType()->isIntOrIntVectorTy() &&
"Cannot NEG a nonintegral value!");
return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
C, HasNUW, HasNSW);
}
Constant *ConstantExpr::getFNeg(Constant *C) {
assert(C->getType()->isFPOrFPVectorTy() &&
"Cannot FNEG a non-floating-point value!");
return getFSub(ConstantFP::getZeroValueForNegation(C->getType()), C);
}
Constant *ConstantExpr::getNot(Constant *C) {
assert(C->getType()->isIntOrIntVectorTy() &&
"Cannot NOT a nonintegral value!");
return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
}
Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
bool HasNUW, bool HasNSW) {
unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
(HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
return get(Instruction::Add, C1, C2, Flags);
}
Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
return get(Instruction::FAdd, C1, C2);
}
Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
bool HasNUW, bool HasNSW) {
unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
(HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
return get(Instruction::Sub, C1, C2, Flags);
}
Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
return get(Instruction::FSub, C1, C2);
}
Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
bool HasNUW, bool HasNSW) {
unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
(HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
return get(Instruction::Mul, C1, C2, Flags);
}
Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
return get(Instruction::FMul, C1, C2);
}
Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
return get(Instruction::UDiv, C1, C2,
isExact ? PossiblyExactOperator::IsExact : 0);
}
Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
return get(Instruction::SDiv, C1, C2,
isExact ? PossiblyExactOperator::IsExact : 0);
}
Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
return get(Instruction::FDiv, C1, C2);
}
Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
return get(Instruction::URem, C1, C2);
}
Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
return get(Instruction::SRem, C1, C2);
}
Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
return get(Instruction::FRem, C1, C2);
}
Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
return get(Instruction::And, C1, C2);
}
Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
return get(Instruction::Or, C1, C2);
}
Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
return get(Instruction::Xor, C1, C2);
}
Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
bool HasNUW, bool HasNSW) {
unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
(HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
return get(Instruction::Shl, C1, C2, Flags);
}
Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
return get(Instruction::LShr, C1, C2,
isExact ? PossiblyExactOperator::IsExact : 0);
}
Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
return get(Instruction::AShr, C1, C2,
isExact ? PossiblyExactOperator::IsExact : 0);
}
/// getBinOpIdentity - Return the identity for the given binary operation,
/// i.e. a constant C such that X op C = X and C op X = X for every X. It
/// returns null if the operator doesn't have an identity.
Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty) {
switch (Opcode) {
default:
// Doesn't have an identity.
return nullptr;
case Instruction::Add:
case Instruction::Or:
case Instruction::Xor:
return Constant::getNullValue(Ty);
case Instruction::Mul:
return ConstantInt::get(Ty, 1);
case Instruction::And:
return Constant::getAllOnesValue(Ty);
}
}
/// getBinOpAbsorber - Return the absorbing element for the given binary
/// operation, i.e. a constant C such that X op C = C and C op X = C for
/// every X. For example, this returns zero for integer multiplication.
/// It returns null if the operator doesn't have an absorbing element.
Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
switch (Opcode) {
default:
// Doesn't have an absorber.
return nullptr;
case Instruction::Or:
return Constant::getAllOnesValue(Ty);
case Instruction::And:
case Instruction::Mul:
return Constant::getNullValue(Ty);
}
}
// destroyConstant - Remove the constant from the constant table...
//
void ConstantExpr::destroyConstantImpl() {
getType()->getContext().pImpl->ExprConstants.remove(this);
}
const char *ConstantExpr::getOpcodeName() const {
return Instruction::getOpcodeName(getOpcode());
}
GetElementPtrConstantExpr::GetElementPtrConstantExpr(
Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
: ConstantExpr(DestTy, Instruction::GetElementPtr,
OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
(IdxList.size() + 1),
IdxList.size() + 1),
SrcElementTy(SrcElementTy) {
Op<0>() = C;
Use *OperandList = getOperandList();
for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
OperandList[i+1] = IdxList[i];
}
Type *GetElementPtrConstantExpr::getSourceElementType() const {
return SrcElementTy;
}
//===----------------------------------------------------------------------===//
// ConstantData* implementations
void ConstantDataArray::anchor() {}
void ConstantDataVector::anchor() {}
/// getElementType - Return the element type of the array/vector.
Type *ConstantDataSequential::getElementType() const {
return getType()->getElementType();
}
StringRef ConstantDataSequential::getRawDataValues() const {
return StringRef(DataElements, getNumElements()*getElementByteSize());
}
/// isElementTypeCompatible - Return true if a ConstantDataSequential can be
/// formed with a vector or array of the specified element type.
/// ConstantDataArray only works with normal float and int types that are
/// stored densely in memory, not with things like i42 or x86_f80.
bool ConstantDataSequential::isElementTypeCompatible(const Type *Ty) {
if (Ty->isFloatTy() || Ty->isDoubleTy()) return true;
if (const IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
switch (IT->getBitWidth()) {
case 8:
case 16:
case 32:
case 64:
return true;
default: break;
}
}
return false;
}
/// getNumElements - Return the number of elements in the array or vector.
unsigned ConstantDataSequential::getNumElements() const {
if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
return AT->getNumElements();
return getType()->getVectorNumElements();
}
/// getElementByteSize - Return the size in bytes of the elements in the data.
uint64_t ConstantDataSequential::getElementByteSize() const {
return getElementType()->getPrimitiveSizeInBits()/8;
}
/// getElementPointer - Return the start of the specified element.
const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
assert(Elt < getNumElements() && "Invalid Elt");
return DataElements+Elt*getElementByteSize();
}
/// isAllZeros - return true if the array is empty or all zeros.
static bool isAllZeros(StringRef Arr) {
for (StringRef::iterator I = Arr.begin(), E = Arr.end(); I != E; ++I)
if (*I != 0)
return false;
return true;
}
/// getImpl - This is the underlying implementation of all of the
/// ConstantDataSequential::get methods. They all thunk down to here, providing
/// the correct element type. We take the bytes in as a StringRef because
/// we *want* an underlying "char*" to avoid TBAA type punning violations.
Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
assert(isElementTypeCompatible(Ty->getSequentialElementType()));
// If the elements are all zero or there are no elements, return a CAZ, which
// is more dense and canonical.
if (isAllZeros(Elements))
return ConstantAggregateZero::get(Ty);
// Do a lookup to see if we have already formed one of these.
auto &Slot =
*Ty->getContext()
.pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
.first;
// The bucket can point to a linked list of different CDS's that have the same
// body but different types. For example, 0,0,0,1 could be a 4 element array
// of i8, or a 1-element array of i32. They'll both end up in the same
/// StringMap bucket, linked up by their Next pointers. Walk the list.
ConstantDataSequential **Entry = &Slot.second;
for (ConstantDataSequential *Node = *Entry; Node;
Entry = &Node->Next, Node = *Entry)
if (Node->getType() == Ty)
return Node;
// Okay, we didn't get a hit. Create a node of the right class, link it in,
// and return it.
if (isa<ArrayType>(Ty))
return *Entry = new ConstantDataArray(Ty, Slot.first().data());
assert(isa<VectorType>(Ty));
return *Entry = new ConstantDataVector(Ty, Slot.first().data());
}
void ConstantDataSequential::destroyConstantImpl() {
// Remove the constant from the StringMap.
StringMap<ConstantDataSequential*> &CDSConstants =
getType()->getContext().pImpl->CDSConstants;
StringMap<ConstantDataSequential*>::iterator Slot =
CDSConstants.find(getRawDataValues());
assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
ConstantDataSequential **Entry = &Slot->getValue();
// Remove the entry from the hash table.
if (!(*Entry)->Next) {
// If there is only one value in the bucket (common case) it must be this
// entry, and removing the entry should remove the bucket completely.
assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
getContext().pImpl->CDSConstants.erase(Slot);
} else {
// Otherwise, there are multiple entries linked off the bucket, unlink the
// node we care about but keep the bucket around.
for (ConstantDataSequential *Node = *Entry; ;
Entry = &Node->Next, Node = *Entry) {
assert(Node && "Didn't find entry in its uniquing hash table!");
// If we found our entry, unlink it from the list and we're done.
if (Node == this) {
*Entry = Node->Next;
break;
}
}
}
// If we were part of a list, make sure that we don't delete the list that is
// still owned by the uniquing map.
Next = nullptr;
}
/// get() constructors - Return a constant with array type with an element
/// count and element type matching the ArrayRef passed in. Note that this
/// can return a ConstantAggregateZero object.
Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint8_t> Elts) {
Type *Ty = ArrayType::get(Type::getInt8Ty(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
}
Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Type *Ty = ArrayType::get(Type::getInt16Ty(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
}
Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Type *Ty = ArrayType::get(Type::getInt32Ty(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
}
Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Type *Ty = ArrayType::get(Type::getInt64Ty(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
}
Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<float> Elts) {
Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
}
Constant *ConstantDataArray::get(LLVMContext &Context, ArrayRef<double> Elts) {
Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
}
/// getFP() constructors - Return a constant with array type with an element
/// count and element type of float with precision matching the number of
/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
/// double for 64bits) Note that this can return a ConstantAggregateZero
/// object.
Constant *ConstantDataArray::getFP(LLVMContext &Context,
ArrayRef<uint16_t> Elts) {
Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
}
Constant *ConstantDataArray::getFP(LLVMContext &Context,
ArrayRef<uint32_t> Elts) {
Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
}
Constant *ConstantDataArray::getFP(LLVMContext &Context,
ArrayRef<uint64_t> Elts) {
Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
}
/// getString - This method constructs a CDS and initializes it with a text
/// string. The default behavior (AddNull==true) causes a null terminator to
/// be placed at the end of the array (increasing the length of the string by
/// one more than the StringRef would normally indicate. Pass AddNull=false
/// to disable this behavior.
Constant *ConstantDataArray::getString(LLVMContext &Context,
StringRef Str, bool AddNull) {
if (!AddNull) {
const uint8_t *Data = reinterpret_cast<const uint8_t *>(Str.data());
return get(Context, makeArrayRef(const_cast<uint8_t *>(Data),
Str.size()));
}
SmallVector<uint8_t, 64> ElementVals;
ElementVals.append(Str.begin(), Str.end());
ElementVals.push_back(0);
return get(Context, ElementVals);
}
/// get() constructors - Return a constant with vector type with an element
/// count and element type matching the ArrayRef passed in. Note that this
/// can return a ConstantAggregateZero object.
Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*1), Ty);
}
Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*2), Ty);
}
Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
}
Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*8), Ty);
}
Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size()*4), Ty);
}
Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
}
/// getFP() constructors - Return a constant with vector type with an element
/// count and element type of float with the precision matching the number of
/// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
/// double for 64bits) Note that this can return a ConstantAggregateZero
/// object.
Constant *ConstantDataVector::getFP(LLVMContext &Context,
ArrayRef<uint16_t> Elts) {
Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 2), Ty);
}
Constant *ConstantDataVector::getFP(LLVMContext &Context,
ArrayRef<uint32_t> Elts) {
Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 4), Ty);
}
Constant *ConstantDataVector::getFP(LLVMContext &Context,
ArrayRef<uint64_t> Elts) {
Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
const char *Data = reinterpret_cast<const char *>(Elts.data());
return getImpl(StringRef(const_cast<char *>(Data), Elts.size() * 8), Ty);
}
Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
assert(isElementTypeCompatible(V->getType()) &&
"Element type not compatible with ConstantData");
if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
if (CI->getType()->isIntegerTy(8)) {
SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
return get(V->getContext(), Elts);
}
if (CI->getType()->isIntegerTy(16)) {
SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
return get(V->getContext(), Elts);
}
if (CI->getType()->isIntegerTy(32)) {
SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
return get(V->getContext(), Elts);
}
assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
return get(V->getContext(), Elts);
}
if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
if (CFP->getType()->isFloatTy()) {
SmallVector<uint32_t, 16> Elts(
NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
return getFP(V->getContext(), Elts);
}
if (CFP->getType()->isDoubleTy()) {
SmallVector<uint64_t, 16> Elts(
NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
return getFP(V->getContext(), Elts);
}
}
return ConstantVector::getSplat(NumElts, V);
}
/// getElementAsInteger - If this is a sequential container of integers (of
/// any size), return the specified element in the low bits of a uint64_t.
uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
assert(isa<IntegerType>(getElementType()) &&
"Accessor can only be used when element is an integer");
const char *EltPtr = getElementPointer(Elt);
// The data is stored in host byte order, make sure to cast back to the right
// type to load with the right endianness.
switch (getElementType()->getIntegerBitWidth()) {
default: llvm_unreachable("Invalid bitwidth for CDS");
case 8:
return *const_cast<uint8_t *>(reinterpret_cast<const uint8_t *>(EltPtr));
case 16:
return *const_cast<uint16_t *>(reinterpret_cast<const uint16_t *>(EltPtr));
case 32:
return *const_cast<uint32_t *>(reinterpret_cast<const uint32_t *>(EltPtr));
case 64:
return *const_cast<uint64_t *>(reinterpret_cast<const uint64_t *>(EltPtr));
}
}
/// getElementAsAPFloat - If this is a sequential container of floating point
/// type, return the specified element as an APFloat.
APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
const char *EltPtr = getElementPointer(Elt);
switch (getElementType()->getTypeID()) {
default:
llvm_unreachable("Accessor can only be used when element is float/double!");
case Type::FloatTyID: {
auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
return APFloat(APFloat::IEEEsingle, APInt(32, EltVal));
}
case Type::DoubleTyID: {
auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
return APFloat(APFloat::IEEEdouble, APInt(64, EltVal));
}
}
}
/// getElementAsFloat - If this is an sequential container of floats, return
/// the specified element as a float.
float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
assert(getElementType()->isFloatTy() &&
"Accessor can only be used when element is a 'float'");
const float *EltPtr = reinterpret_cast<const float *>(getElementPointer(Elt));
return *const_cast<float *>(EltPtr);
}
/// getElementAsDouble - If this is an sequential container of doubles, return
/// the specified element as a float.
double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
assert(getElementType()->isDoubleTy() &&
"Accessor can only be used when element is a 'float'");
const double *EltPtr =
reinterpret_cast<const double *>(getElementPointer(Elt));
return *const_cast<double *>(EltPtr);
}
/// getElementAsConstant - Return a Constant for a specified index's element.
/// Note that this has to compute a new constant to return, so it isn't as
/// efficient as getElementAsInteger/Float/Double.
Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
if (getElementType()->isFloatTy() || getElementType()->isDoubleTy())
return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
}
/// isString - This method returns true if this is an array of i8.
bool ConstantDataSequential::isString() const {
return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(8);
}
/// isCString - This method returns true if the array "isString", ends with a
/// nul byte, and does not contains any other nul bytes.
bool ConstantDataSequential::isCString() const {
if (!isString())
return false;
StringRef Str = getAsString();
// The last value must be nul.
if (Str.back() != 0) return false;
// Other elements must be non-nul.
return Str.drop_back().find(0) == StringRef::npos;
}
/// getSplatValue - If this is a splat constant, meaning that all of the
/// elements have the same value, return that value. Otherwise return nullptr.
Constant *ConstantDataVector::getSplatValue() const {
const char *Base = getRawDataValues().data();
// Compare elements 1+ to the 0'th element.
unsigned EltSize = getElementByteSize();
for (unsigned i = 1, e = getNumElements(); i != e; ++i)
if (memcmp(Base, Base+i*EltSize, EltSize))
return nullptr;
// If they're all the same, return the 0th one as a representative.
return getElementAsConstant(0);
}
//===----------------------------------------------------------------------===//
// handleOperandChange implementations
/// Update this constant array to change uses of
/// 'From' to be uses of 'To'. This must update the uniquing data structures
/// etc.
///
/// Note that we intentionally replace all uses of From with To here. Consider
/// a large array that uses 'From' 1000 times. By handling this case all here,
/// ConstantArray::handleOperandChange is only invoked once, and that
/// single invocation handles all 1000 uses. Handling them one at a time would
/// work, but would be really slow because it would have to unique each updated
/// array instance.
///
void Constant::handleOperandChange(Value *From, Value *To, Use *U) {
Value *Replacement = nullptr;
switch (getValueID()) {
default:
llvm_unreachable("Not a constant!");
#define HANDLE_CONSTANT(Name) \
case Value::Name##Val: \
Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To, U); \
break;
#include "llvm/IR/Value.def"
}
// If handleOperandChangeImpl returned nullptr, then it handled
// replacing itself and we don't want to delete or replace anything else here.
if (!Replacement)
return;
// I do need to replace this with an existing value.
assert(Replacement != this && "I didn't contain From!");
// Everyone using this now uses the replacement.
replaceAllUsesWith(Replacement);
// Delete the old constant!
destroyConstant();
}
Value *ConstantInt::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
llvm_unreachable("Unsupported class for handleOperandChange()!");
}
Value *ConstantFP::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
llvm_unreachable("Unsupported class for handleOperandChange()!");
}
Value *UndefValue::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
llvm_unreachable("Unsupported class for handleOperandChange()!");
}
Value *ConstantPointerNull::handleOperandChangeImpl(Value *From, Value *To,
Use *U) {
llvm_unreachable("Unsupported class for handleOperandChange()!");
}
Value *ConstantAggregateZero::handleOperandChangeImpl(Value *From, Value *To,
Use *U) {
llvm_unreachable("Unsupported class for handleOperandChange()!");
}
Value *ConstantDataSequential::handleOperandChangeImpl(Value *From, Value *To,
Use *U) {
llvm_unreachable("Unsupported class for handleOperandChange()!");
}
Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Constant *ToC = cast<Constant>(To);
SmallVector<Constant*, 8> Values;
Values.reserve(getNumOperands()); // Build replacement array.
// Fill values with the modified operands of the constant array. Also,
// compute whether this turns into an all-zeros array.
unsigned NumUpdated = 0;
// Keep track of whether all the values in the array are "ToC".
bool AllSame = true;
Use *OperandList = getOperandList();
for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
Constant *Val = cast<Constant>(O->get());
if (Val == From) {
Val = ToC;
++NumUpdated;
}
Values.push_back(Val);
AllSame &= Val == ToC;
}
if (AllSame && ToC->isNullValue())
return ConstantAggregateZero::get(getType());
if (AllSame && isa<UndefValue>(ToC))
return UndefValue::get(getType());
// Check for any other type of constant-folding.
if (Constant *C = getImpl(getType(), Values))
return C;
// Update to the new value.
return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
Values, this, From, ToC, NumUpdated, U - OperandList);
}
Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Constant *ToC = cast<Constant>(To);
Use *OperandList = getOperandList();
unsigned OperandToUpdate = U-OperandList;
assert(getOperand(OperandToUpdate) == From && "ReplaceAllUsesWith broken!");
SmallVector<Constant*, 8> Values;
Values.reserve(getNumOperands()); // Build replacement struct.
// Fill values with the modified operands of the constant struct. Also,
// compute whether this turns into an all-zeros struct.
bool isAllZeros = false;
bool isAllUndef = false;
if (ToC->isNullValue()) {
isAllZeros = true;
for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
Constant *Val = cast<Constant>(O->get());
Values.push_back(Val);
if (isAllZeros) isAllZeros = Val->isNullValue();
}
} else if (isa<UndefValue>(ToC)) {
isAllUndef = true;
for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
Constant *Val = cast<Constant>(O->get());
Values.push_back(Val);
if (isAllUndef) isAllUndef = isa<UndefValue>(Val);
}
} else {
for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O)
Values.push_back(cast<Constant>(O->get()));
}
Values[OperandToUpdate] = ToC;
if (isAllZeros)
return ConstantAggregateZero::get(getType());
if (isAllUndef)
return UndefValue::get(getType());
// Update to the new value.
return getContext().pImpl->StructConstants.replaceOperandsInPlace(
Values, this, From, ToC);
}
Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To, Use *U) {
assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
Constant *ToC = cast<Constant>(To);
SmallVector<Constant*, 8> Values;
Values.reserve(getNumOperands()); // Build replacement array...
unsigned NumUpdated = 0;
for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Constant *Val = getOperand(i);
if (Val == From) {
++NumUpdated;
Val = ToC;
}
Values.push_back(Val);
}
if (Constant *C = getImpl(Values))
return C;
// Update to the new value.
Use *OperandList = getOperandList();
return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
Values, this, From, ToC, NumUpdated, U - OperandList);
}
Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV, Use *U) {
assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
Constant *To = cast<Constant>(ToV);
SmallVector<Constant*, 8> NewOps;
unsigned NumUpdated = 0;
for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Constant *Op = getOperand(i);
if (Op == From) {
++NumUpdated;
Op = To;
}
NewOps.push_back(Op);
}
assert(NumUpdated && "I didn't contain From!");
if (Constant *C = getWithOperands(NewOps, getType(), true))
return C;
// Update to the new value.
Use *OperandList = getOperandList();
return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
NewOps, this, From, To, NumUpdated, U - OperandList);
}
Instruction *ConstantExpr::getAsInstruction() {
SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
ArrayRef<Value*> Ops(ValueOperands);
switch (getOpcode()) {
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::FPTrunc:
case Instruction::FPExt:
case Instruction::UIToFP:
case Instruction::SIToFP:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::PtrToInt:
case Instruction::IntToPtr:
case Instruction::BitCast:
case Instruction::AddrSpaceCast:
return CastInst::Create((Instruction::CastOps)getOpcode(),
Ops[0], getType());
case Instruction::Select:
return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
case Instruction::InsertElement:
return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
case Instruction::ExtractElement:
return ExtractElementInst::Create(Ops[0], Ops[1]);
case Instruction::InsertValue:
return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
case Instruction::ExtractValue:
return ExtractValueInst::Create(Ops[0], getIndices());
case Instruction::ShuffleVector:
return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
case Instruction::GetElementPtr: {
const auto *GO = cast<GEPOperator>(this);
if (GO->isInBounds())
return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
Ops[0], Ops.slice(1));
return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
Ops.slice(1));
}
case Instruction::ICmp:
case Instruction::FCmp:
return CmpInst::Create((Instruction::OtherOps)getOpcode(),
getPredicate(), Ops[0], Ops[1]);
default:
assert(getNumOperands() == 2 && "Must be binary operator?");
BinaryOperator *BO =
BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
Ops[0], Ops[1]);
if (isa<OverflowingBinaryOperator>(BO)) {
BO->setHasNoUnsignedWrap(SubclassOptionalData &
OverflowingBinaryOperator::NoUnsignedWrap);
BO->setHasNoSignedWrap(SubclassOptionalData &
OverflowingBinaryOperator::NoSignedWrap);
}
if (isa<PossiblyExactOperator>(BO))
BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
return BO;
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/PassManager.cpp | //===- PassManager.cpp - Infrastructure for managing & running IR passes --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/PassManager.h"
using namespace llvm;
char FunctionAnalysisManagerModuleProxy::PassID;
FunctionAnalysisManagerModuleProxy::Result
FunctionAnalysisManagerModuleProxy::run(Module &M) {
assert(FAM->empty() && "Function analyses ran prior to the module proxy!");
return Result(*FAM);
}
FunctionAnalysisManagerModuleProxy::Result::~Result() {
// Clear out the analysis manager if we're being destroyed -- it means we
// didn't even see an invalidate call when we got invalidated.
FAM->clear();
}
bool FunctionAnalysisManagerModuleProxy::Result::invalidate(
Module &M, const PreservedAnalyses &PA) {
// If this proxy isn't marked as preserved, then we can't even invalidate
// individual function analyses, there may be an invalid set of Function
// objects in the cache making it impossible to incrementally preserve them.
// Just clear the entire manager.
if (!PA.preserved(ID()))
FAM->clear();
// Return false to indicate that this result is still a valid proxy.
return false;
}
char ModuleAnalysisManagerFunctionProxy::PassID;
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/Pass.cpp | //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the LLVM Pass infrastructure. It is primarily
// responsible with ensuring that passes are executed and batched together
// optimally.
//
//===----------------------------------------------------------------------===//
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRPrintingPasses.h"
#include "llvm/IR/LegacyPassNameParser.h"
#include "llvm/PassRegistry.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm> // HLSL Change
using namespace llvm;
#define DEBUG_TYPE "ir"
//===----------------------------------------------------------------------===//
// Pass Implementation
//
// Force out-of-line virtual method.
Pass::~Pass() {
delete Resolver;
}
// HLSL Change Starts
void Pass::dumpConfig(llvm::raw_ostream &OS) {
OS << '-' << this->getPassArgument();
}
const char *Pass::getPassArgument() const {
AnalysisID AID = getPassID();
const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
if (PI)
return PI->getPassArgument();
return "Unnamed pass: implement Pass::getPassArgument()";
}
// HLSL Change Ends
// Force out-of-line virtual method.
ModulePass::~ModulePass() { }
Pass *ModulePass::createPrinterPass(raw_ostream &O,
const std::string &Banner) const {
return createPrintModulePass(O, Banner);
}
PassManagerType ModulePass::getPotentialPassManagerType() const {
return PMT_ModulePassManager;
}
bool Pass::mustPreserveAnalysisID(char &AID) const {
return Resolver->getAnalysisIfAvailable(&AID, true) != nullptr;
}
// dumpPassStructure - Implement the -debug-pass=Structure option
void Pass::dumpPassStructure(unsigned Offset) {
dbgs().indent(Offset*2) << getPassName() << "\n";
}
/// getPassName - Return a nice clean name for a pass. This usually
/// implemented in terms of the name that is registered by one of the
/// Registration templates, but can be overloaded directly.
///
StringRef Pass::getPassName() const {
AnalysisID AID = getPassID();
const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(AID);
if (PI)
return PI->getPassName();
return "Unnamed pass: implement Pass::getPassName()";
}
void Pass::preparePassManager(PMStack &) {
// By default, don't do anything.
}
PassManagerType Pass::getPotentialPassManagerType() const {
// Default implementation.
return PMT_Unknown;
}
void Pass::getAnalysisUsage(AnalysisUsage &) const {
// By default, no analysis results are used, all are invalidated.
}
void Pass::releaseMemory() {
// By default, don't do anything.
}
void Pass::verifyAnalysis() const {
// By default, don't do anything.
}
void *Pass::getAdjustedAnalysisPointer(AnalysisID AID) {
return this;
}
ImmutablePass *Pass::getAsImmutablePass() {
return nullptr;
}
PMDataManager *Pass::getAsPMDataManager() {
return nullptr;
}
void Pass::setResolver(AnalysisResolver *AR) {
assert(!Resolver && "Resolver is already set");
Resolver = AR;
}
// print - Print out the internal state of the pass. This is called by Analyze
// to print out the contents of an analysis. Otherwise it is not necessary to
// implement this method.
//
void Pass::print(raw_ostream &O,const Module*) const {
O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
}
// dump - call print(cerr);
void Pass::dump() const {
print(dbgs(), nullptr);
}
//===----------------------------------------------------------------------===//
// ImmutablePass Implementation
//
// Force out-of-line virtual method.
ImmutablePass::~ImmutablePass() { }
void ImmutablePass::initializePass() {
// By default, don't do anything.
}
//===----------------------------------------------------------------------===//
// FunctionPass Implementation
//
Pass *FunctionPass::createPrinterPass(raw_ostream &O,
const std::string &Banner) const {
return createPrintFunctionPass(O, Banner);
}
PassManagerType FunctionPass::getPotentialPassManagerType() const {
return PMT_FunctionPassManager;
}
bool FunctionPass::skipOptnoneFunction(const Function &F) const {
if (F.hasFnAttribute(Attribute::OptimizeNone)) {
DEBUG(dbgs() << "Skipping pass '" << getPassName()
<< "' on function " << F.getName() << "\n");
return true;
}
return false;
}
//===----------------------------------------------------------------------===//
// BasicBlockPass Implementation
//
Pass *BasicBlockPass::createPrinterPass(raw_ostream &O,
const std::string &Banner) const {
return createPrintBasicBlockPass(O, Banner);
}
bool BasicBlockPass::doInitialization(Function &) {
// By default, don't do anything.
return false;
}
bool BasicBlockPass::doFinalization(Function &) {
// By default, don't do anything.
return false;
}
bool BasicBlockPass::skipOptnoneFunction(const BasicBlock &BB) const {
const Function *F = BB.getParent();
if (F && F->hasFnAttribute(Attribute::OptimizeNone)) {
// Report this only once per function.
if (&BB == &F->getEntryBlock())
DEBUG(dbgs() << "Skipping pass '" << getPassName()
<< "' on function " << F->getName() << "\n");
return true;
}
return false;
}
PassManagerType BasicBlockPass::getPotentialPassManagerType() const {
return PMT_BasicBlockPassManager;
}
const PassInfo *Pass::lookupPassInfo(const void *TI) {
return PassRegistry::getPassRegistry()->getPassInfo(TI);
}
const PassInfo *Pass::lookupPassInfo(StringRef Arg) {
return PassRegistry::getPassRegistry()->getPassInfo(Arg);
}
Pass *Pass::createPass(AnalysisID ID) {
const PassInfo *PI = PassRegistry::getPassRegistry()->getPassInfo(ID);
if (!PI)
return nullptr;
return PI->createPass();
}
//===----------------------------------------------------------------------===//
// Analysis Group Implementation Code
//===----------------------------------------------------------------------===//
// RegisterAGBase implementation
//
RegisterAGBase::RegisterAGBase(const char *Name, const void *InterfaceID,
const void *PassID, bool isDefault)
: PassInfo(Name, InterfaceID) {
PassRegistry::getPassRegistry()->registerAnalysisGroup(InterfaceID, PassID,
*this, isDefault);
}
//===----------------------------------------------------------------------===//
// PassRegistrationListener implementation
//
// enumeratePasses - Iterate over the registered passes, calling the
// passEnumerate callback on each PassInfo object.
//
void PassRegistrationListener::enumeratePasses() {
PassRegistry::getPassRegistry()->enumerateWith(this);
}
PassNameParser::PassNameParser(cl::Option &O)
: cl::parser<const PassInfo *>(O) {
PassRegistry::getPassRegistry()->addRegistrationListener(this);
}
PassNameParser::~PassNameParser() {
// This only gets called during static destruction, in which case the
// PassRegistry will have already been destroyed by llvm_shutdown(). So
// attempting to remove the registration listener is an error.
}
//===----------------------------------------------------------------------===//
// AnalysisUsage Class Implementation
//
namespace {
struct GetCFGOnlyPasses : public PassRegistrationListener {
typedef AnalysisUsage::VectorType VectorType;
VectorType &CFGOnlyList;
GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {}
void passEnumerate(const PassInfo *P) override {
if (P->isCFGOnlyPass())
CFGOnlyList.push_back(P->getTypeInfo());
}
};
}
// setPreservesCFG - This function should be called to by the pass, iff they do
// not:
//
// 1. Add or remove basic blocks from the function
// 2. Modify terminator instructions in any way.
//
// This function annotates the AnalysisUsage info object to say that analyses
// that only depend on the CFG are preserved by this pass.
//
void AnalysisUsage::setPreservesCFG() {
// Since this transformation doesn't modify the CFG, it preserves all analyses
// that only depend on the CFG (like dominators, loop info, etc...)
GetCFGOnlyPasses(Preserved).enumeratePasses();
}
AnalysisUsage &AnalysisUsage::addPreserved(StringRef Arg) {
const PassInfo *PI = Pass::lookupPassInfo(Arg);
// If the pass exists, preserve it. Otherwise silently do nothing.
if (PI) Preserved.push_back(PI->getTypeInfo());
return *this;
}
AnalysisUsage &AnalysisUsage::addRequiredID(const void *ID) {
Required.push_back(ID);
return *this;
}
AnalysisUsage &AnalysisUsage::addRequiredID(char &ID) {
Required.push_back(&ID);
return *this;
}
AnalysisUsage &AnalysisUsage::addRequiredTransitiveID(char &ID) {
Required.push_back(&ID);
RequiredTransitive.push_back(&ID);
return *this;
}
// HLSL Changes Start
bool llvm::GetPassOption(PassOptions &O, StringRef name, StringRef *pValue) {
PassOption OpVal(name, StringRef());
const PassOption *Op = std::lower_bound(O.begin(), O.end(), OpVal, PassOptionsCompare());
if (Op != O.end() && Op->first == name) {
*pValue = Op->second;
return true;
}
return false;
}
bool llvm::GetPassOptionBool(PassOptions &O, llvm::StringRef name, bool *pValue, bool defaultValue) {
StringRef val;
if (GetPassOption(O, name, &val)) {
*pValue = (val.startswith_lower("t") || val.equals("1"));
return true;
}
*pValue = defaultValue;
return false;
}
bool llvm::GetPassOptionUnsigned(PassOptions &O, llvm::StringRef name, unsigned *pValue, unsigned defaultValue) {
StringRef val;
if (GetPassOption(O, name, &val)) {
val.getAsInteger<unsigned>(0, *pValue);
return true;
}
*pValue = defaultValue;
return false;
}
bool llvm::GetPassOptionInt(PassOptions &O, llvm::StringRef name, int *pValue, int defaultValue) {
StringRef val;
if (GetPassOption(O, name, &val)) {
val.getAsInteger<int>(0, *pValue);
return true;
}
*pValue = defaultValue;
return false;
}
bool llvm::GetPassOptionUInt32(PassOptions &O, llvm::StringRef name, uint32_t *pValue, uint32_t defaultValue) {
StringRef val;
if (GetPassOption(O, name, &val)) {
val.getAsInteger<uint32_t>(0, *pValue);
return true;
}
*pValue = defaultValue;
return false;
}
bool llvm::GetPassOptionUInt64(PassOptions &O, llvm::StringRef name, uint64_t *pValue, uint64_t defaultValue) {
StringRef val;
if (GetPassOption(O, name, &val)) {
val.getAsInteger<uint64_t>(0, *pValue);
return true;
}
*pValue = defaultValue;
return false;
}
bool llvm::GetPassOptionFloat(PassOptions &O, llvm::StringRef name, float *pValue, float defaultValue) {
StringRef val;
if (GetPassOption(O, name, &val)) {
std::string str;
str.assign(val.begin(), val.end());
*pValue = atof(str.c_str());
return true;
}
*pValue = defaultValue;
return false;
}
// HLSL Changes End
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/Attributes.cpp | //===-- Attributes.cpp - Implement AttributesList -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// \file
// \brief This file implements the Attribute, AttributeImpl, AttrBuilder,
// AttributeSetImpl, and AttributeSet classes.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/Attributes.h"
#include "AttributeImpl.h"
#include "LLVMContextImpl.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Atomic.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/Mutex.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Attribute Construction Methods
//===----------------------------------------------------------------------===//
Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
uint64_t Val) {
LLVMContextImpl *pImpl = Context.pImpl;
FoldingSetNodeID ID;
ID.AddInteger(Kind);
if (Val) ID.AddInteger(Val);
void *InsertPoint;
AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
if (!PA) {
// If we didn't find any existing attributes of the same shape then create a
// new one and insert it.
if (!Val)
PA = new EnumAttributeImpl(Kind);
else
PA = new IntAttributeImpl(Kind, Val);
pImpl->AttrsSet.InsertNode(PA, InsertPoint);
}
// Return the Attribute that we found or created.
return Attribute(PA);
}
Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) {
LLVMContextImpl *pImpl = Context.pImpl;
FoldingSetNodeID ID;
ID.AddString(Kind);
if (!Val.empty()) ID.AddString(Val);
void *InsertPoint;
AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
if (!PA) {
// If we didn't find any existing attributes of the same shape then create a
// new one and insert it.
PA = new StringAttributeImpl(Kind, Val);
pImpl->AttrsSet.InsertNode(PA, InsertPoint);
}
// Return the Attribute that we found or created.
return Attribute(PA);
}
Attribute Attribute::getWithAlignment(LLVMContext &Context, uint64_t Align) {
assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
assert(Align <= 0x40000000 && "Alignment too large.");
return get(Context, Alignment, Align);
}
Attribute Attribute::getWithStackAlignment(LLVMContext &Context,
uint64_t Align) {
assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
assert(Align <= 0x100 && "Alignment too large.");
return get(Context, StackAlignment, Align);
}
Attribute Attribute::getWithDereferenceableBytes(LLVMContext &Context,
uint64_t Bytes) {
assert(Bytes && "Bytes must be non-zero.");
return get(Context, Dereferenceable, Bytes);
}
Attribute Attribute::getWithDereferenceableOrNullBytes(LLVMContext &Context,
uint64_t Bytes) {
assert(Bytes && "Bytes must be non-zero.");
return get(Context, DereferenceableOrNull, Bytes);
}
//===----------------------------------------------------------------------===//
// Attribute Accessor Methods
//===----------------------------------------------------------------------===//
bool Attribute::isEnumAttribute() const {
return pImpl && pImpl->isEnumAttribute();
}
bool Attribute::isIntAttribute() const {
return pImpl && pImpl->isIntAttribute();
}
bool Attribute::isStringAttribute() const {
return pImpl && pImpl->isStringAttribute();
}
Attribute::AttrKind Attribute::getKindAsEnum() const {
if (!pImpl) return None;
assert((isEnumAttribute() || isIntAttribute()) &&
"Invalid attribute type to get the kind as an enum!");
return pImpl ? pImpl->getKindAsEnum() : None;
}
uint64_t Attribute::getValueAsInt() const {
if (!pImpl) return 0;
assert(isIntAttribute() &&
"Expected the attribute to be an integer attribute!");
return pImpl ? pImpl->getValueAsInt() : 0;
}
StringRef Attribute::getKindAsString() const {
if (!pImpl) return StringRef();
assert(isStringAttribute() &&
"Invalid attribute type to get the kind as a string!");
return pImpl ? pImpl->getKindAsString() : StringRef();
}
StringRef Attribute::getValueAsString() const {
if (!pImpl) return StringRef();
assert(isStringAttribute() &&
"Invalid attribute type to get the value as a string!");
return pImpl ? pImpl->getValueAsString() : StringRef();
}
bool Attribute::hasAttribute(AttrKind Kind) const {
return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None);
}
bool Attribute::hasAttribute(StringRef Kind) const {
if (!isStringAttribute()) return false;
return pImpl && pImpl->hasAttribute(Kind);
}
/// This returns the alignment field of an attribute as a byte alignment value.
unsigned Attribute::getAlignment() const {
assert(hasAttribute(Attribute::Alignment) &&
"Trying to get alignment from non-alignment attribute!");
return pImpl->getValueAsInt();
}
/// This returns the stack alignment field of an attribute as a byte alignment
/// value.
unsigned Attribute::getStackAlignment() const {
assert(hasAttribute(Attribute::StackAlignment) &&
"Trying to get alignment from non-alignment attribute!");
return pImpl->getValueAsInt();
}
/// This returns the number of dereferenceable bytes.
uint64_t Attribute::getDereferenceableBytes() const {
assert(hasAttribute(Attribute::Dereferenceable) &&
"Trying to get dereferenceable bytes from "
"non-dereferenceable attribute!");
return pImpl->getValueAsInt();
}
uint64_t Attribute::getDereferenceableOrNullBytes() const {
assert(hasAttribute(Attribute::DereferenceableOrNull) &&
"Trying to get dereferenceable bytes from "
"non-dereferenceable attribute!");
return pImpl->getValueAsInt();
}
std::string Attribute::getAsString(bool InAttrGrp) const {
if (!pImpl) return "";
if (hasAttribute(Attribute::SanitizeAddress))
return "sanitize_address";
if (hasAttribute(Attribute::AlwaysInline))
return "alwaysinline";
if (hasAttribute(Attribute::ArgMemOnly))
return "argmemonly";
if (hasAttribute(Attribute::Builtin))
return "builtin";
if (hasAttribute(Attribute::ByVal))
return "byval";
if (hasAttribute(Attribute::Convergent))
return "convergent";
if (hasAttribute(Attribute::InAlloca))
return "inalloca";
if (hasAttribute(Attribute::InlineHint))
return "inlinehint";
if (hasAttribute(Attribute::InReg))
return "inreg";
if (hasAttribute(Attribute::JumpTable))
return "jumptable";
if (hasAttribute(Attribute::MinSize))
return "minsize";
if (hasAttribute(Attribute::Naked))
return "naked";
if (hasAttribute(Attribute::Nest))
return "nest";
if (hasAttribute(Attribute::NoAlias))
return "noalias";
if (hasAttribute(Attribute::NoBuiltin))
return "nobuiltin";
if (hasAttribute(Attribute::NoCapture))
return "nocapture";
if (hasAttribute(Attribute::NoDuplicate))
return "noduplicate";
if (hasAttribute(Attribute::NoImplicitFloat))
return "noimplicitfloat";
if (hasAttribute(Attribute::NoInline))
return "noinline";
if (hasAttribute(Attribute::NonLazyBind))
return "nonlazybind";
if (hasAttribute(Attribute::NonNull))
return "nonnull";
if (hasAttribute(Attribute::NoRedZone))
return "noredzone";
if (hasAttribute(Attribute::NoReturn))
return "noreturn";
if (hasAttribute(Attribute::NoUnwind))
return "nounwind";
if (hasAttribute(Attribute::OptimizeNone))
return "optnone";
if (hasAttribute(Attribute::OptimizeForSize))
return "optsize";
if (hasAttribute(Attribute::ReadNone))
return "readnone";
if (hasAttribute(Attribute::ReadOnly))
return "readonly";
if (hasAttribute(Attribute::Returned))
return "returned";
if (hasAttribute(Attribute::ReturnsTwice))
return "returns_twice";
if (hasAttribute(Attribute::SExt))
return "signext";
if (hasAttribute(Attribute::StackProtect))
return "ssp";
if (hasAttribute(Attribute::StackProtectReq))
return "sspreq";
if (hasAttribute(Attribute::StackProtectStrong))
return "sspstrong";
if (hasAttribute(Attribute::SafeStack))
return "safestack";
if (hasAttribute(Attribute::StructRet))
return "sret";
if (hasAttribute(Attribute::SanitizeThread))
return "sanitize_thread";
if (hasAttribute(Attribute::SanitizeMemory))
return "sanitize_memory";
if (hasAttribute(Attribute::UWTable))
return "uwtable";
if (hasAttribute(Attribute::ZExt))
return "zeroext";
if (hasAttribute(Attribute::Cold))
return "cold";
// FIXME: These should be output like this:
//
// align=4
// alignstack=8
//
if (hasAttribute(Attribute::Alignment)) {
std::string Result;
Result += "align";
Result += (InAttrGrp) ? "=" : " ";
Result += utostr(getValueAsInt());
return Result;
}
auto AttrWithBytesToString = [&](const char *Name) {
std::string Result;
Result += Name;
if (InAttrGrp) {
Result += "=";
Result += utostr(getValueAsInt());
} else {
Result += "(";
Result += utostr(getValueAsInt());
Result += ")";
}
return Result;
};
if (hasAttribute(Attribute::StackAlignment))
return AttrWithBytesToString("alignstack");
if (hasAttribute(Attribute::Dereferenceable))
return AttrWithBytesToString("dereferenceable");
if (hasAttribute(Attribute::DereferenceableOrNull))
return AttrWithBytesToString("dereferenceable_or_null");
// Convert target-dependent attributes to strings of the form:
//
// "kind"
// "kind" = "value"
//
if (isStringAttribute()) {
std::string Result;
Result += (Twine('"') + getKindAsString() + Twine('"')).str();
StringRef Val = pImpl->getValueAsString();
if (Val.empty()) return Result;
Result += ("=\"" + Val + Twine('"')).str();
return Result;
}
llvm_unreachable("Unknown attribute");
}
bool Attribute::operator<(Attribute A) const {
if (!pImpl && !A.pImpl) return false;
if (!pImpl) return true;
if (!A.pImpl) return false;
return *pImpl < *A.pImpl;
}
//===----------------------------------------------------------------------===//
// AttributeImpl Definition
//===----------------------------------------------------------------------===//
// Pin the vtables to this file.
AttributeImpl::~AttributeImpl() {}
void EnumAttributeImpl::anchor() {}
void IntAttributeImpl::anchor() {}
void StringAttributeImpl::anchor() {}
bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
if (isStringAttribute()) return false;
return getKindAsEnum() == A;
}
bool AttributeImpl::hasAttribute(StringRef Kind) const {
if (!isStringAttribute()) return false;
return getKindAsString() == Kind;
}
Attribute::AttrKind AttributeImpl::getKindAsEnum() const {
assert(isEnumAttribute() || isIntAttribute());
return static_cast<const EnumAttributeImpl *>(this)->getEnumKind();
}
uint64_t AttributeImpl::getValueAsInt() const {
assert(isIntAttribute());
return static_cast<const IntAttributeImpl *>(this)->getValue();
}
StringRef AttributeImpl::getKindAsString() const {
assert(isStringAttribute());
return static_cast<const StringAttributeImpl *>(this)->getStringKind();
}
StringRef AttributeImpl::getValueAsString() const {
assert(isStringAttribute());
return static_cast<const StringAttributeImpl *>(this)->getStringValue();
}
bool AttributeImpl::operator<(const AttributeImpl &AI) const {
// This sorts the attributes with Attribute::AttrKinds coming first (sorted
// relative to their enum value) and then strings.
if (isEnumAttribute()) {
if (AI.isEnumAttribute()) return getKindAsEnum() < AI.getKindAsEnum();
if (AI.isIntAttribute()) return true;
if (AI.isStringAttribute()) return true;
}
if (isIntAttribute()) {
if (AI.isEnumAttribute()) return false;
if (AI.isIntAttribute()) return getValueAsInt() < AI.getValueAsInt();
if (AI.isStringAttribute()) return true;
}
if (AI.isEnumAttribute()) return false;
if (AI.isIntAttribute()) return false;
if (getKindAsString() == AI.getKindAsString())
return getValueAsString() < AI.getValueAsString();
return getKindAsString() < AI.getKindAsString();
}
uint64_t AttributeImpl::getAttrMask(Attribute::AttrKind Val) {
// FIXME: Remove this.
switch (Val) {
case Attribute::EndAttrKinds:
llvm_unreachable("Synthetic enumerators which should never get here");
case Attribute::None: return 0;
case Attribute::ZExt: return 1 << 0;
case Attribute::SExt: return 1 << 1;
case Attribute::NoReturn: return 1 << 2;
case Attribute::InReg: return 1 << 3;
case Attribute::StructRet: return 1 << 4;
case Attribute::NoUnwind: return 1 << 5;
case Attribute::NoAlias: return 1 << 6;
case Attribute::ByVal: return 1 << 7;
case Attribute::Nest: return 1 << 8;
case Attribute::ReadNone: return 1 << 9;
case Attribute::ReadOnly: return 1 << 10;
case Attribute::NoInline: return 1 << 11;
case Attribute::AlwaysInline: return 1 << 12;
case Attribute::OptimizeForSize: return 1 << 13;
case Attribute::StackProtect: return 1 << 14;
case Attribute::StackProtectReq: return 1 << 15;
case Attribute::Alignment: return 31 << 16;
case Attribute::NoCapture: return 1 << 21;
case Attribute::NoRedZone: return 1 << 22;
case Attribute::NoImplicitFloat: return 1 << 23;
case Attribute::Naked: return 1 << 24;
case Attribute::InlineHint: return 1 << 25;
case Attribute::StackAlignment: return 7 << 26;
case Attribute::ReturnsTwice: return 1 << 29;
case Attribute::UWTable: return 1 << 30;
case Attribute::NonLazyBind: return 1U << 31;
case Attribute::SanitizeAddress: return 1ULL << 32;
case Attribute::MinSize: return 1ULL << 33;
case Attribute::NoDuplicate: return 1ULL << 34;
case Attribute::StackProtectStrong: return 1ULL << 35;
case Attribute::SanitizeThread: return 1ULL << 36;
case Attribute::SanitizeMemory: return 1ULL << 37;
case Attribute::NoBuiltin: return 1ULL << 38;
case Attribute::Returned: return 1ULL << 39;
case Attribute::Cold: return 1ULL << 40;
case Attribute::Builtin: return 1ULL << 41;
case Attribute::OptimizeNone: return 1ULL << 42;
case Attribute::InAlloca: return 1ULL << 43;
case Attribute::NonNull: return 1ULL << 44;
case Attribute::JumpTable: return 1ULL << 45;
case Attribute::Convergent: return 1ULL << 46;
case Attribute::SafeStack: return 1ULL << 47;
case Attribute::Dereferenceable:
llvm_unreachable("dereferenceable attribute not supported in raw format");
break;
case Attribute::DereferenceableOrNull:
llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
"format");
break;
case Attribute::ArgMemOnly:
llvm_unreachable("argmemonly attribute not supported in raw format");
break;
}
llvm_unreachable("Unsupported attribute type");
}
//===----------------------------------------------------------------------===//
// AttributeSetNode Definition
//===----------------------------------------------------------------------===//
AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
ArrayRef<Attribute> Attrs) {
if (Attrs.empty())
return nullptr;
// Otherwise, build a key to look up the existing attributes.
LLVMContextImpl *pImpl = C.pImpl;
FoldingSetNodeID ID;
SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
array_pod_sort(SortedAttrs.begin(), SortedAttrs.end());
for (SmallVectorImpl<Attribute>::iterator I = SortedAttrs.begin(),
E = SortedAttrs.end(); I != E; ++I)
I->Profile(ID);
void *InsertPoint;
AttributeSetNode *PA =
pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
// If we didn't find any existing attributes of the same shape then create a
// new one and insert it.
if (!PA) {
// Coallocate entries after the AttributeSetNode itself.
void *Mem = ::operator new(sizeof(AttributeSetNode) +
sizeof(Attribute) * SortedAttrs.size());
PA = new (Mem) AttributeSetNode(SortedAttrs);
pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
}
// Return the AttributesListNode that we found or created.
return PA;
}
bool AttributeSetNode::hasAttribute(Attribute::AttrKind Kind) const {
for (iterator I = begin(), E = end(); I != E; ++I)
if (I->hasAttribute(Kind))
return true;
return false;
}
bool AttributeSetNode::hasAttribute(StringRef Kind) const {
for (iterator I = begin(), E = end(); I != E; ++I)
if (I->hasAttribute(Kind))
return true;
return false;
}
Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const {
for (iterator I = begin(), E = end(); I != E; ++I)
if (I->hasAttribute(Kind))
return *I;
return Attribute();
}
Attribute AttributeSetNode::getAttribute(StringRef Kind) const {
for (iterator I = begin(), E = end(); I != E; ++I)
if (I->hasAttribute(Kind))
return *I;
return Attribute();
}
unsigned AttributeSetNode::getAlignment() const {
for (iterator I = begin(), E = end(); I != E; ++I)
if (I->hasAttribute(Attribute::Alignment))
return I->getAlignment();
return 0;
}
unsigned AttributeSetNode::getStackAlignment() const {
for (iterator I = begin(), E = end(); I != E; ++I)
if (I->hasAttribute(Attribute::StackAlignment))
return I->getStackAlignment();
return 0;
}
uint64_t AttributeSetNode::getDereferenceableBytes() const {
for (iterator I = begin(), E = end(); I != E; ++I)
if (I->hasAttribute(Attribute::Dereferenceable))
return I->getDereferenceableBytes();
return 0;
}
uint64_t AttributeSetNode::getDereferenceableOrNullBytes() const {
for (iterator I = begin(), E = end(); I != E; ++I)
if (I->hasAttribute(Attribute::DereferenceableOrNull))
return I->getDereferenceableOrNullBytes();
return 0;
}
std::string AttributeSetNode::getAsString(bool InAttrGrp) const {
std::string Str;
for (iterator I = begin(), E = end(); I != E; ++I) {
if (I != begin())
Str += ' ';
Str += I->getAsString(InAttrGrp);
}
return Str;
}
//===----------------------------------------------------------------------===//
// AttributeSetImpl Definition
//===----------------------------------------------------------------------===//
uint64_t AttributeSetImpl::Raw(unsigned Index) const {
for (unsigned I = 0, E = getNumAttributes(); I != E; ++I) {
if (getSlotIndex(I) != Index) continue;
const AttributeSetNode *ASN = getSlotNode(I);
uint64_t Mask = 0;
for (AttributeSetNode::iterator II = ASN->begin(),
IE = ASN->end(); II != IE; ++II) {
Attribute Attr = *II;
// This cannot handle string attributes.
if (Attr.isStringAttribute()) continue;
Attribute::AttrKind Kind = Attr.getKindAsEnum();
if (Kind == Attribute::Alignment)
Mask |= ((uint64_t)(Log2_32(ASN->getAlignment())) + 1) << 16; // HLSL Change: widen to 64-bits before shift not after
else if (Kind == Attribute::StackAlignment)
Mask |= ((uint64_t)(Log2_32(ASN->getStackAlignment())) + 1) << 26; // HLSL Change: widen to 64-bits before shift not after
else if (Kind == Attribute::Dereferenceable)
llvm_unreachable("dereferenceable not supported in bit mask");
else
Mask |= AttributeImpl::getAttrMask(Kind);
}
return Mask;
}
return 0;
}
void AttributeSetImpl::dump() const {
AttributeSet(const_cast<AttributeSetImpl *>(this)).dump();
}
//===----------------------------------------------------------------------===//
// AttributeSet Construction and Mutation Methods
//===----------------------------------------------------------------------===//
AttributeSet
AttributeSet::getImpl(LLVMContext &C,
ArrayRef<std::pair<unsigned, AttributeSetNode*> > Attrs) {
LLVMContextImpl *pImpl = C.pImpl;
FoldingSetNodeID ID;
AttributeSetImpl::Profile(ID, Attrs);
void *InsertPoint;
AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
// If we didn't find any existing attributes of the same shape then
// create a new one and insert it.
if (!PA) {
// Coallocate entries after the AttributeSetImpl itself.
void *Mem = ::operator new(sizeof(AttributeSetImpl) +
sizeof(std::pair<unsigned, AttributeSetNode *>) *
Attrs.size());
PA = new (Mem) AttributeSetImpl(C, Attrs);
pImpl->AttrsLists.InsertNode(PA, InsertPoint);
}
// Return the AttributesList that we found or created.
return AttributeSet(PA);
}
AttributeSet AttributeSet::get(LLVMContext &C,
ArrayRef<std::pair<unsigned, Attribute> > Attrs){
// If there are no attributes then return a null AttributesList pointer.
if (Attrs.empty())
return AttributeSet();
#ifndef NDEBUG
for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
assert((!i || Attrs[i-1].first <= Attrs[i].first) &&
"Misordered Attributes list!");
assert(!Attrs[i].second.hasAttribute(Attribute::None) &&
"Pointless attribute!");
}
#endif
// Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
// list.
SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrPairVec;
for (ArrayRef<std::pair<unsigned, Attribute> >::iterator I = Attrs.begin(),
E = Attrs.end(); I != E; ) {
unsigned Index = I->first;
SmallVector<Attribute, 4> AttrVec;
while (I != E && I->first == Index) {
AttrVec.push_back(I->second);
++I;
}
AttrPairVec.push_back(std::make_pair(Index,
AttributeSetNode::get(C, AttrVec)));
}
return getImpl(C, AttrPairVec);
}
AttributeSet AttributeSet::get(LLVMContext &C,
ArrayRef<std::pair<unsigned,
AttributeSetNode*> > Attrs) {
// If there are no attributes then return a null AttributesList pointer.
if (Attrs.empty())
return AttributeSet();
return getImpl(C, Attrs);
}
AttributeSet AttributeSet::get(LLVMContext &C, unsigned Index,
const AttrBuilder &B) {
if (!B.hasAttributes())
return AttributeSet();
// Add target-independent attributes.
SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
for (Attribute::AttrKind Kind = Attribute::None;
Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) {
if (!B.contains(Kind))
continue;
if (Kind == Attribute::Alignment)
Attrs.push_back(std::make_pair(Index, Attribute::
getWithAlignment(C, B.getAlignment())));
else if (Kind == Attribute::StackAlignment)
Attrs.push_back(std::make_pair(Index, Attribute::
getWithStackAlignment(C, B.getStackAlignment())));
else if (Kind == Attribute::Dereferenceable)
Attrs.push_back(std::make_pair(Index,
Attribute::getWithDereferenceableBytes(C,
B.getDereferenceableBytes())));
else if (Kind == Attribute::DereferenceableOrNull)
Attrs.push_back(
std::make_pair(Index, Attribute::getWithDereferenceableOrNullBytes(
C, B.getDereferenceableOrNullBytes())));
else
Attrs.push_back(std::make_pair(Index, Attribute::get(C, Kind)));
}
// Add target-dependent (string) attributes.
for (const auto &TDA : B.td_attrs())
Attrs.push_back(
std::make_pair(Index, Attribute::get(C, TDA.first, TDA.second)));
return get(C, Attrs);
}
AttributeSet AttributeSet::get(LLVMContext &C, unsigned Index,
ArrayRef<Attribute::AttrKind> Kind) {
SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
for (ArrayRef<Attribute::AttrKind>::iterator I = Kind.begin(),
E = Kind.end(); I != E; ++I)
Attrs.push_back(std::make_pair(Index, Attribute::get(C, *I)));
return get(C, Attrs);
}
AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<AttributeSet> Attrs) {
if (Attrs.empty()) return AttributeSet();
if (Attrs.size() == 1) return Attrs[0];
SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrNodeVec;
AttributeSetImpl *A0 = Attrs[0].pImpl;
if (A0)
AttrNodeVec.append(A0->getNode(0), A0->getNode(A0->getNumAttributes()));
// Copy all attributes from Attrs into AttrNodeVec while keeping AttrNodeVec
// ordered by index. Because we know that each list in Attrs is ordered by
// index we only need to merge each successive list in rather than doing a
// full sort.
for (unsigned I = 1, E = Attrs.size(); I != E; ++I) {
AttributeSetImpl *AS = Attrs[I].pImpl;
if (!AS) continue;
SmallVector<std::pair<unsigned, AttributeSetNode *>, 8>::iterator
ANVI = AttrNodeVec.begin(), ANVE;
for (const AttributeSetImpl::IndexAttrPair
*AI = AS->getNode(0),
*AE = AS->getNode(AS->getNumAttributes());
AI != AE; ++AI) {
ANVE = AttrNodeVec.end();
while (ANVI != ANVE && ANVI->first <= AI->first)
++ANVI;
ANVI = AttrNodeVec.insert(ANVI, *AI) + 1;
}
}
return getImpl(C, AttrNodeVec);
}
AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
Attribute::AttrKind Attr) const {
if (hasAttribute(Index, Attr)) return *this;
return addAttributes(C, Index, AttributeSet::get(C, Index, Attr));
}
AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
StringRef Kind) const {
llvm::AttrBuilder B;
B.addAttribute(Kind);
return addAttributes(C, Index, AttributeSet::get(C, Index, B));
}
AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
StringRef Kind, StringRef Value) const {
llvm::AttrBuilder B;
B.addAttribute(Kind, Value);
return addAttributes(C, Index, AttributeSet::get(C, Index, B));
}
AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Index,
AttributeSet Attrs) const {
if (!pImpl) return Attrs;
if (!Attrs.pImpl) return *this;
#ifndef NDEBUG
// FIXME it is not obvious how this should work for alignment. For now, say
// we can't change a known alignment.
unsigned OldAlign = getParamAlignment(Index);
unsigned NewAlign = Attrs.getParamAlignment(Index);
assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
"Attempt to change alignment!");
#endif
// Add the attribute slots before the one we're trying to add.
SmallVector<AttributeSet, 4> AttrSet;
uint64_t NumAttrs = pImpl->getNumAttributes();
AttributeSet AS;
uint64_t LastIndex = 0;
for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
if (getSlotIndex(I) >= Index) {
if (getSlotIndex(I) == Index) AS = getSlotAttributes(LastIndex++);
break;
}
LastIndex = I + 1;
AttrSet.push_back(getSlotAttributes(I));
}
// Now add the attribute into the correct slot. There may already be an
// AttributeSet there.
AttrBuilder B(AS, Index);
for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
if (Attrs.getSlotIndex(I) == Index) {
for (AttributeSetImpl::iterator II = Attrs.pImpl->begin(I),
IE = Attrs.pImpl->end(I); II != IE; ++II)
B.addAttribute(*II);
break;
}
AttrSet.push_back(AttributeSet::get(C, Index, B));
// Add the remaining attribute slots.
for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
AttrSet.push_back(getSlotAttributes(I));
return get(C, AttrSet);
}
AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Index,
Attribute::AttrKind Attr) const {
if (!hasAttribute(Index, Attr)) return *this;
return removeAttributes(C, Index, AttributeSet::get(C, Index, Attr));
}
AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Index,
AttributeSet Attrs) const {
if (!pImpl) return AttributeSet();
if (!Attrs.pImpl) return *this;
// FIXME it is not obvious how this should work for alignment.
// For now, say we can't pass in alignment, which no current use does.
assert(!Attrs.hasAttribute(Index, Attribute::Alignment) &&
"Attempt to change alignment!");
// Add the attribute slots before the one we're trying to add.
SmallVector<AttributeSet, 4> AttrSet;
uint64_t NumAttrs = pImpl->getNumAttributes();
AttributeSet AS;
uint64_t LastIndex = 0;
for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
if (getSlotIndex(I) >= Index) {
if (getSlotIndex(I) == Index) AS = getSlotAttributes(LastIndex++);
break;
}
LastIndex = I + 1;
AttrSet.push_back(getSlotAttributes(I));
}
// Now remove the attribute from the correct slot. There may already be an
// AttributeSet there.
AttrBuilder B(AS, Index);
for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
if (Attrs.getSlotIndex(I) == Index) {
B.removeAttributes(Attrs.pImpl->getSlotAttributes(I), Index);
break;
}
AttrSet.push_back(AttributeSet::get(C, Index, B));
// Add the remaining attribute slots.
for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
AttrSet.push_back(getSlotAttributes(I));
return get(C, AttrSet);
}
AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Index,
const AttrBuilder &Attrs) const {
if (!pImpl) return AttributeSet();
// FIXME it is not obvious how this should work for alignment.
// For now, say we can't pass in alignment, which no current use does.
assert(!Attrs.hasAlignmentAttr() && "Attempt to change alignment!");
// Add the attribute slots before the one we're trying to add.
SmallVector<AttributeSet, 4> AttrSet;
uint64_t NumAttrs = pImpl->getNumAttributes();
AttributeSet AS;
uint64_t LastIndex = 0;
for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
if (getSlotIndex(I) >= Index) {
if (getSlotIndex(I) == Index) AS = getSlotAttributes(LastIndex++);
break;
}
LastIndex = I + 1;
AttrSet.push_back(getSlotAttributes(I));
}
// Now remove the attribute from the correct slot. There may already be an
// AttributeSet there.
AttrBuilder B(AS, Index);
B.remove(Attrs);
AttrSet.push_back(AttributeSet::get(C, Index, B));
// Add the remaining attribute slots.
for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
AttrSet.push_back(getSlotAttributes(I));
return get(C, AttrSet);
}
AttributeSet AttributeSet::addDereferenceableAttr(LLVMContext &C, unsigned Index,
uint64_t Bytes) const {
llvm::AttrBuilder B;
B.addDereferenceableAttr(Bytes);
return addAttributes(C, Index, AttributeSet::get(C, Index, B));
}
AttributeSet AttributeSet::addDereferenceableOrNullAttr(LLVMContext &C,
unsigned Index,
uint64_t Bytes) const {
llvm::AttrBuilder B;
B.addDereferenceableOrNullAttr(Bytes);
return addAttributes(C, Index, AttributeSet::get(C, Index, B));
}
//===----------------------------------------------------------------------===//
// AttributeSet Accessor Methods
//===----------------------------------------------------------------------===//
LLVMContext &AttributeSet::getContext() const {
return pImpl->getContext();
}
AttributeSet AttributeSet::getParamAttributes(unsigned Index) const {
return pImpl && hasAttributes(Index) ?
AttributeSet::get(pImpl->getContext(),
ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
std::make_pair(Index, getAttributes(Index)))) :
AttributeSet();
}
AttributeSet AttributeSet::getRetAttributes() const {
return pImpl && hasAttributes(ReturnIndex) ?
AttributeSet::get(pImpl->getContext(),
ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
std::make_pair(ReturnIndex,
getAttributes(ReturnIndex)))) :
AttributeSet();
}
AttributeSet AttributeSet::getFnAttributes() const {
return pImpl && hasAttributes(FunctionIndex) ?
AttributeSet::get(pImpl->getContext(),
ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
std::make_pair(FunctionIndex,
getAttributes(FunctionIndex)))) :
AttributeSet();
}
bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
AttributeSetNode *ASN = getAttributes(Index);
return ASN ? ASN->hasAttribute(Kind) : false;
}
bool AttributeSet::hasAttribute(unsigned Index, StringRef Kind) const {
AttributeSetNode *ASN = getAttributes(Index);
return ASN ? ASN->hasAttribute(Kind) : false;
}
bool AttributeSet::hasAttributes(unsigned Index) const {
AttributeSetNode *ASN = getAttributes(Index);
return ASN ? ASN->hasAttributes() : false;
}
/// \brief Return true if the specified attribute is set for at least one
/// parameter or for the return value.
bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
if (!pImpl) return false;
for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
for (AttributeSetImpl::iterator II = pImpl->begin(I),
IE = pImpl->end(I); II != IE; ++II)
if (II->hasAttribute(Attr))
return true;
return false;
}
Attribute AttributeSet::getAttribute(unsigned Index,
Attribute::AttrKind Kind) const {
AttributeSetNode *ASN = getAttributes(Index);
return ASN ? ASN->getAttribute(Kind) : Attribute();
}
Attribute AttributeSet::getAttribute(unsigned Index,
StringRef Kind) const {
AttributeSetNode *ASN = getAttributes(Index);
return ASN ? ASN->getAttribute(Kind) : Attribute();
}
unsigned AttributeSet::getParamAlignment(unsigned Index) const {
AttributeSetNode *ASN = getAttributes(Index);
return ASN ? ASN->getAlignment() : 0;
}
unsigned AttributeSet::getStackAlignment(unsigned Index) const {
AttributeSetNode *ASN = getAttributes(Index);
return ASN ? ASN->getStackAlignment() : 0;
}
uint64_t AttributeSet::getDereferenceableBytes(unsigned Index) const {
AttributeSetNode *ASN = getAttributes(Index);
return ASN ? ASN->getDereferenceableBytes() : 0;
}
uint64_t AttributeSet::getDereferenceableOrNullBytes(unsigned Index) const {
AttributeSetNode *ASN = getAttributes(Index);
return ASN ? ASN->getDereferenceableOrNullBytes() : 0;
}
std::string AttributeSet::getAsString(unsigned Index,
bool InAttrGrp) const {
AttributeSetNode *ASN = getAttributes(Index);
return ASN ? ASN->getAsString(InAttrGrp) : std::string("");
}
/// \brief The attributes for the specified index are returned.
AttributeSetNode *AttributeSet::getAttributes(unsigned Index) const {
if (!pImpl) return nullptr;
// Loop through to find the attribute node we want.
for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
if (pImpl->getSlotIndex(I) == Index)
return pImpl->getSlotNode(I);
return nullptr;
}
AttributeSet::iterator AttributeSet::begin(unsigned Slot) const {
if (!pImpl)
return ArrayRef<Attribute>().begin();
return pImpl->begin(Slot);
}
AttributeSet::iterator AttributeSet::end(unsigned Slot) const {
if (!pImpl)
return ArrayRef<Attribute>().end();
return pImpl->end(Slot);
}
//===----------------------------------------------------------------------===//
// AttributeSet Introspection Methods
//===----------------------------------------------------------------------===//
/// \brief Return the number of slots used in this attribute list. This is the
/// number of arguments that have an attribute set on them (including the
/// function itself).
unsigned AttributeSet::getNumSlots() const {
return pImpl ? pImpl->getNumAttributes() : 0;
}
unsigned AttributeSet::getSlotIndex(unsigned Slot) const {
assert(pImpl && Slot < pImpl->getNumAttributes() &&
"Slot # out of range!");
return pImpl->getSlotIndex(Slot);
}
AttributeSet AttributeSet::getSlotAttributes(unsigned Slot) const {
assert(pImpl && Slot < pImpl->getNumAttributes() &&
"Slot # out of range!");
return pImpl->getSlotAttributes(Slot);
}
uint64_t AttributeSet::Raw(unsigned Index) const {
// FIXME: Remove this.
return pImpl ? pImpl->Raw(Index) : 0;
}
void AttributeSet::dump() const {
dbgs() << "PAL[\n";
for (unsigned i = 0, e = getNumSlots(); i < e; ++i) {
uint64_t Index = getSlotIndex(i);
dbgs() << " { ";
if (Index == ~0U)
dbgs() << "~0U";
else
dbgs() << Index;
dbgs() << " => " << getAsString(Index) << " }\n";
}
dbgs() << "]\n";
}
//===----------------------------------------------------------------------===//
// AttrBuilder Method Implementations
//===----------------------------------------------------------------------===//
AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Index)
: Attrs(0), Alignment(0), StackAlignment(0), DerefBytes(0),
DerefOrNullBytes(0) {
AttributeSetImpl *pImpl = AS.pImpl;
if (!pImpl) return;
for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I) {
if (pImpl->getSlotIndex(I) != Index) continue;
for (AttributeSetImpl::iterator II = pImpl->begin(I),
IE = pImpl->end(I); II != IE; ++II)
addAttribute(*II);
break;
}
}
void AttrBuilder::clear() {
Attrs.reset();
Alignment = StackAlignment = DerefBytes = DerefOrNullBytes = 0;
}
AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment &&
Val != Attribute::Dereferenceable &&
"Adding integer attribute without adding a value!");
Attrs[Val] = true;
return *this;
}
AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
if (Attr.isStringAttribute()) {
addAttribute(Attr.getKindAsString(), Attr.getValueAsString());
return *this;
}
Attribute::AttrKind Kind = Attr.getKindAsEnum();
Attrs[Kind] = true;
if (Kind == Attribute::Alignment)
Alignment = Attr.getAlignment();
else if (Kind == Attribute::StackAlignment)
StackAlignment = Attr.getStackAlignment();
else if (Kind == Attribute::Dereferenceable)
DerefBytes = Attr.getDereferenceableBytes();
else if (Kind == Attribute::DereferenceableOrNull)
DerefOrNullBytes = Attr.getDereferenceableOrNullBytes();
return *this;
}
AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
TargetDepAttrs[A] = V;
return *this;
}
AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
Attrs[Val] = false;
if (Val == Attribute::Alignment)
Alignment = 0;
else if (Val == Attribute::StackAlignment)
StackAlignment = 0;
else if (Val == Attribute::Dereferenceable)
DerefBytes = 0;
else if (Val == Attribute::DereferenceableOrNull)
DerefOrNullBytes = 0;
return *this;
}
AttrBuilder &AttrBuilder::removeAttributes(AttributeSet A, uint64_t Index) {
unsigned Slot = ~0U;
for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
if (A.getSlotIndex(I) == Index) {
Slot = I;
break;
}
assert(Slot != ~0U && "Couldn't find index in AttributeSet!");
for (AttributeSet::iterator I = A.begin(Slot), E = A.end(Slot); I != E; ++I) {
Attribute Attr = *I;
if (Attr.isEnumAttribute() || Attr.isIntAttribute()) {
Attribute::AttrKind Kind = I->getKindAsEnum();
Attrs[Kind] = false;
if (Kind == Attribute::Alignment)
Alignment = 0;
else if (Kind == Attribute::StackAlignment)
StackAlignment = 0;
else if (Kind == Attribute::Dereferenceable)
DerefBytes = 0;
else if (Kind == Attribute::DereferenceableOrNull)
DerefOrNullBytes = 0;
} else {
assert(Attr.isStringAttribute() && "Invalid attribute type!");
std::map<std::string, std::string>::iterator
Iter = TargetDepAttrs.find(Attr.getKindAsString());
if (Iter != TargetDepAttrs.end())
TargetDepAttrs.erase(Iter);
}
}
return *this;
}
AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(A);
if (I != TargetDepAttrs.end())
TargetDepAttrs.erase(I);
return *this;
}
AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
if (Align == 0) return *this;
assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
assert(Align <= 0x40000000 && "Alignment too large.");
Attrs[Attribute::Alignment] = true;
Alignment = Align;
return *this;
}
AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
// Default alignment, allow the target to define how to align it.
if (Align == 0) return *this;
assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
assert(Align <= 0x100 && "Alignment too large.");
Attrs[Attribute::StackAlignment] = true;
StackAlignment = Align;
return *this;
}
AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) {
if (Bytes == 0) return *this;
Attrs[Attribute::Dereferenceable] = true;
DerefBytes = Bytes;
return *this;
}
AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) {
if (Bytes == 0)
return *this;
Attrs[Attribute::DereferenceableOrNull] = true;
DerefOrNullBytes = Bytes;
return *this;
}
AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) {
// FIXME: What if both have alignments, but they don't match?!
if (!Alignment)
Alignment = B.Alignment;
if (!StackAlignment)
StackAlignment = B.StackAlignment;
if (!DerefBytes)
DerefBytes = B.DerefBytes;
if (!DerefOrNullBytes)
DerefOrNullBytes = B.DerefOrNullBytes;
Attrs |= B.Attrs;
for (const auto &I : B.td_attrs())
TargetDepAttrs[I.first] = I.second;
return *this;
}
AttrBuilder &AttrBuilder::remove(const AttrBuilder &B) {
// FIXME: What if both have alignments, but they don't match?!
if (B.Alignment)
Alignment = 0;
if (B.StackAlignment)
StackAlignment = 0;
if (B.DerefBytes)
DerefBytes = 0;
if (B.DerefOrNullBytes)
DerefOrNullBytes = 0;
Attrs &= ~B.Attrs;
for (const auto &I : B.td_attrs())
TargetDepAttrs.erase(I.first);
return *this;
}
bool AttrBuilder::overlaps(const AttrBuilder &B) const {
// First check if any of the target independent attributes overlap.
if ((Attrs & B.Attrs).any())
return true;
// Then check if any target dependent ones do.
for (const auto &I : td_attrs())
if (B.contains(I.first))
return true;
return false;
}
bool AttrBuilder::contains(StringRef A) const {
return TargetDepAttrs.find(A) != TargetDepAttrs.end();
}
bool AttrBuilder::hasAttributes() const {
return !Attrs.none() || !TargetDepAttrs.empty();
}
bool AttrBuilder::hasAttributes(AttributeSet A, uint64_t Index) const {
unsigned Slot = ~0U;
for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
if (A.getSlotIndex(I) == Index) {
Slot = I;
break;
}
assert(Slot != ~0U && "Couldn't find the index!");
for (AttributeSet::iterator I = A.begin(Slot), E = A.end(Slot);
I != E; ++I) {
Attribute Attr = *I;
if (Attr.isEnumAttribute() || Attr.isIntAttribute()) {
if (Attrs[I->getKindAsEnum()])
return true;
} else {
assert(Attr.isStringAttribute() && "Invalid attribute kind!");
return TargetDepAttrs.find(Attr.getKindAsString())!=TargetDepAttrs.end();
}
}
return false;
}
bool AttrBuilder::hasAlignmentAttr() const {
return Alignment != 0;
}
bool AttrBuilder::operator==(const AttrBuilder &B) {
if (Attrs != B.Attrs)
return false;
for (td_const_iterator I = TargetDepAttrs.begin(),
E = TargetDepAttrs.end(); I != E; ++I)
if (B.TargetDepAttrs.find(I->first) == B.TargetDepAttrs.end())
return false;
return Alignment == B.Alignment && StackAlignment == B.StackAlignment &&
DerefBytes == B.DerefBytes;
}
AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
// FIXME: Remove this in 4.0.
if (!Val) return *this;
for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
I = Attribute::AttrKind(I + 1)) {
if (I == Attribute::Dereferenceable ||
I == Attribute::DereferenceableOrNull ||
I == Attribute::ArgMemOnly)
continue;
if (uint64_t A = (Val & AttributeImpl::getAttrMask(I))) {
Attrs[I] = true;
if (I == Attribute::Alignment)
Alignment = 1ULL << ((A >> 16) - 1);
else if (I == Attribute::StackAlignment)
StackAlignment = 1ULL << ((A >> 26)-1);
}
}
return *this;
}
//===----------------------------------------------------------------------===//
// AttributeFuncs Function Defintions
//===----------------------------------------------------------------------===//
/// \brief Which attributes cannot be applied to a type.
AttrBuilder AttributeFuncs::typeIncompatible(const Type *Ty) {
AttrBuilder Incompatible;
if (!Ty->isIntegerTy())
// Attribute that only apply to integers.
Incompatible.addAttribute(Attribute::SExt)
.addAttribute(Attribute::ZExt);
if (!Ty->isPointerTy())
// Attribute that only apply to pointers.
Incompatible.addAttribute(Attribute::ByVal)
.addAttribute(Attribute::Nest)
.addAttribute(Attribute::NoAlias)
.addAttribute(Attribute::NoCapture)
.addAttribute(Attribute::NonNull)
.addDereferenceableAttr(1) // the int here is ignored
.addDereferenceableOrNullAttr(1) // the int here is ignored
.addAttribute(Attribute::ReadNone)
.addAttribute(Attribute::ReadOnly)
.addAttribute(Attribute::StructRet)
.addAttribute(Attribute::InAlloca);
return Incompatible;
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/IR/ValueSymbolTable.cpp | //===-- ValueSymbolTable.cpp - Implement the ValueSymbolTable class -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the ValueSymbolTable class for the IR library.
//
//===----------------------------------------------------------------------===//
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "valuesymtab"
// Class destructor
ValueSymbolTable::~ValueSymbolTable() {
#ifndef NDEBUG // Only do this in -g mode...
for (iterator VI = vmap.begin(), VE = vmap.end(); VI != VE; ++VI)
dbgs() << "Value still in symbol table! Type = '"
<< *VI->getValue()->getType() << "' Name = '"
<< VI->getKeyData() << "'\n";
assert(vmap.empty() && "Values remain in symbol table!");
#endif
}
// Insert a value into the symbol table with the specified name...
//
void ValueSymbolTable::reinsertValue(Value* V) {
assert(V->hasName() && "Can't insert nameless Value into symbol table");
// Try inserting the name, assuming it won't conflict.
if (vmap.insert(V->getValueName())) {
//DEBUG(dbgs() << " Inserted value: " << V->getValueName() << ": " << *V << "\n");
return;
}
// Otherwise, there is a naming conflict. Rename this value.
SmallString<256> UniqueName(V->getName().begin(), V->getName().end());
// The name is too already used, just free it so we can allocate a new name.
V->getValueName()->Destroy();
unsigned BaseSize = UniqueName.size();
while (1) {
// Trim any suffix off and append the next number.
UniqueName.resize(BaseSize);
raw_svector_ostream(UniqueName) << "." << ++LastUnique;
// Try insert the vmap entry with this suffix.
auto IterBool = vmap.insert(std::make_pair(UniqueName, V));
if (IterBool.second) {
// Newly inserted name. Success!
V->setValueName(&*IterBool.first);
//DEBUG(dbgs() << " Inserted value: " << UniqueName << ": " << *V << "\n");
return;
}
}
}
void ValueSymbolTable::removeValueName(ValueName *V) {
//DEBUG(dbgs() << " Removing Value: " << V->getKeyData() << "\n");
// Remove the value from the symbol table.
vmap.remove(V);
}
/// createValueName - This method attempts to create a value name and insert
/// it into the symbol table with the specified name. If it conflicts, it
/// auto-renames the name and returns that instead.
ValueName *ValueSymbolTable::createValueName(StringRef Name, Value *V) {
// In the common case, the name is not already in the symbol table.
auto IterBool = vmap.insert(std::make_pair(Name, V));
if (IterBool.second) {
//DEBUG(dbgs() << " Inserted value: " << Entry.getKeyData() << ": "
// << *V << "\n");
return &*IterBool.first;
}
// Otherwise, there is a naming conflict. Rename this value.
SmallString<256> UniqueName(Name.begin(), Name.end());
while (1) {
// Trim any suffix off and append the next number.
UniqueName.resize(Name.size());
raw_svector_ostream(UniqueName) << ++LastUnique;
// Try insert the vmap entry with this suffix.
auto IterBool = vmap.insert(std::make_pair(UniqueName, V));
if (IterBool.second) {
// DEBUG(dbgs() << " Inserted value: " << UniqueName << ": " << *V <<
// "\n");
return &*IterBool.first;
}
}
}
// dump - print out the symbol table
//
void ValueSymbolTable::dump() const {
//DEBUG(dbgs() << "ValueSymbolTable:\n");
for (const_iterator I = begin(), E = end(); I != E; ++I) {
//DEBUG(dbgs() << " '" << I->getKeyData() << "' = ");
I->getValue()->dump();
//DEBUG(dbgs() << "\n");
}
}
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DebugInfo/CMakeLists.txt |
add_subdirectory(DWARF)
add_subdirectory(PDB)
|
0 | repos/DirectXShaderCompiler/lib | repos/DirectXShaderCompiler/lib/DebugInfo/LLVMBuild.txt | ;===- ./lib/DebugInfo/LLVMBuild.txt ----------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[common]
subdirectories = DWARF PDB
[component_0]
type = Group
name = DebugInfo
parent = $ROOT
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFDebugRangeList.cpp | //===-- DWARFDebugRangesList.cpp ------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
void DWARFDebugRangeList::clear() {
Offset = -1U;
AddressSize = 0;
Entries.clear();
}
bool DWARFDebugRangeList::extract(DataExtractor data, uint32_t *offset_ptr) {
clear();
if (!data.isValidOffset(*offset_ptr))
return false;
AddressSize = data.getAddressSize();
if (AddressSize != 4 && AddressSize != 8)
return false;
Offset = *offset_ptr;
while (true) {
RangeListEntry entry;
uint32_t prev_offset = *offset_ptr;
entry.StartAddress = data.getAddress(offset_ptr);
entry.EndAddress = data.getAddress(offset_ptr);
// Check that both values were extracted correctly.
if (*offset_ptr != prev_offset + 2 * AddressSize) {
clear();
return false;
}
if (entry.isEndOfListEntry())
break;
Entries.push_back(entry);
}
return true;
}
void DWARFDebugRangeList::dump(raw_ostream &OS) const {
for (const RangeListEntry &RLE : Entries) {
const char *format_str = (AddressSize == 4
? "%08x %08" PRIx64 " %08" PRIx64 "\n"
: "%08x %016" PRIx64 " %016" PRIx64 "\n");
OS << format(format_str, Offset, RLE.StartAddress, RLE.EndAddress);
}
OS << format("%08x <End of list>\n", Offset);
}
DWARFAddressRangesVector
DWARFDebugRangeList::getAbsoluteRanges(uint64_t BaseAddress) const {
DWARFAddressRangesVector Res;
for (const RangeListEntry &RLE : Entries) {
if (RLE.isBaseAddressSelectionEntry(AddressSize)) {
BaseAddress = RLE.EndAddress;
} else {
Res.push_back(std::make_pair(BaseAddress + RLE.StartAddress,
BaseAddress + RLE.EndAddress));
}
}
return Res;
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFDebugLine.cpp | //===-- DWARFDebugLine.cpp ------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;
using namespace dwarf;
typedef DILineInfoSpecifier::FileLineInfoKind FileLineInfoKind;
DWARFDebugLine::Prologue::Prologue() {
clear();
}
void DWARFDebugLine::Prologue::clear() {
TotalLength = Version = PrologueLength = 0;
MinInstLength = MaxOpsPerInst = DefaultIsStmt = LineBase = LineRange = 0;
OpcodeBase = 0;
IsDWARF64 = false;
StandardOpcodeLengths.clear();
IncludeDirectories.clear();
FileNames.clear();
}
void DWARFDebugLine::Prologue::dump(raw_ostream &OS) const {
OS << "Line table prologue:\n"
<< format(" total_length: 0x%8.8" PRIx64 "\n", TotalLength)
<< format(" version: %u\n", Version)
<< format(" prologue_length: 0x%8.8" PRIx64 "\n", PrologueLength)
<< format(" min_inst_length: %u\n", MinInstLength)
<< format(Version >= 4 ? "max_ops_per_inst: %u\n" : "", MaxOpsPerInst)
<< format(" default_is_stmt: %u\n", DefaultIsStmt)
<< format(" line_base: %i\n", LineBase)
<< format(" line_range: %u\n", LineRange)
<< format(" opcode_base: %u\n", OpcodeBase);
for (uint32_t i = 0; i < StandardOpcodeLengths.size(); ++i)
OS << format("standard_opcode_lengths[%s] = %u\n", LNStandardString(i+1),
StandardOpcodeLengths[i]);
if (!IncludeDirectories.empty())
for (uint32_t i = 0; i < IncludeDirectories.size(); ++i)
OS << format("include_directories[%3u] = '", i+1)
<< IncludeDirectories[i] << "'\n";
if (!FileNames.empty()) {
OS << " Dir Mod Time File Len File Name\n"
<< " ---- ---------- ---------- -----------"
"----------------\n";
for (uint32_t i = 0; i < FileNames.size(); ++i) {
const FileNameEntry& fileEntry = FileNames[i];
OS << format("file_names[%3u] %4" PRIu64 " ", i+1, fileEntry.DirIdx)
<< format("0x%8.8" PRIx64 " 0x%8.8" PRIx64 " ",
fileEntry.ModTime, fileEntry.Length)
<< fileEntry.Name << '\n';
}
}
}
bool DWARFDebugLine::Prologue::parse(DataExtractor debug_line_data,
uint32_t *offset_ptr) {
const uint64_t prologue_offset = *offset_ptr;
clear();
TotalLength = debug_line_data.getU32(offset_ptr);
if (TotalLength == UINT32_MAX) {
IsDWARF64 = true;
TotalLength = debug_line_data.getU64(offset_ptr);
} else if (TotalLength > 0xffffff00) {
return false;
}
Version = debug_line_data.getU16(offset_ptr);
if (Version < 2)
return false;
PrologueLength = debug_line_data.getUnsigned(offset_ptr,
sizeofPrologueLength());
const uint64_t end_prologue_offset = PrologueLength + *offset_ptr;
MinInstLength = debug_line_data.getU8(offset_ptr);
if (Version >= 4)
MaxOpsPerInst = debug_line_data.getU8(offset_ptr);
DefaultIsStmt = debug_line_data.getU8(offset_ptr);
LineBase = debug_line_data.getU8(offset_ptr);
LineRange = debug_line_data.getU8(offset_ptr);
OpcodeBase = debug_line_data.getU8(offset_ptr);
StandardOpcodeLengths.reserve(OpcodeBase - 1);
for (uint32_t i = 1; i < OpcodeBase; ++i) {
uint8_t op_len = debug_line_data.getU8(offset_ptr);
StandardOpcodeLengths.push_back(op_len);
}
while (*offset_ptr < end_prologue_offset) {
const char *s = debug_line_data.getCStr(offset_ptr);
if (s && s[0])
IncludeDirectories.push_back(s);
else
break;
}
while (*offset_ptr < end_prologue_offset) {
const char *name = debug_line_data.getCStr(offset_ptr);
if (name && name[0]) {
FileNameEntry fileEntry;
fileEntry.Name = name;
fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
FileNames.push_back(fileEntry);
} else {
break;
}
}
if (*offset_ptr != end_prologue_offset) {
fprintf(stderr, "warning: parsing line table prologue at 0x%8.8" PRIx64
" should have ended at 0x%8.8" PRIx64
" but it ended at 0x%8.8" PRIx64 "\n",
prologue_offset, end_prologue_offset, (uint64_t)*offset_ptr);
return false;
}
return true;
}
DWARFDebugLine::Row::Row(bool default_is_stmt) {
reset(default_is_stmt);
}
void DWARFDebugLine::Row::postAppend() {
BasicBlock = false;
PrologueEnd = false;
EpilogueBegin = false;
}
void DWARFDebugLine::Row::reset(bool default_is_stmt) {
Address = 0;
Line = 1;
Column = 0;
File = 1;
Isa = 0;
Discriminator = 0;
IsStmt = default_is_stmt;
BasicBlock = false;
EndSequence = false;
PrologueEnd = false;
EpilogueBegin = false;
}
void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column)
<< format(" %6u %3u %13u ", File, Isa, Discriminator)
<< (IsStmt ? " is_stmt" : "")
<< (BasicBlock ? " basic_block" : "")
<< (PrologueEnd ? " prologue_end" : "")
<< (EpilogueBegin ? " epilogue_begin" : "")
<< (EndSequence ? " end_sequence" : "")
<< '\n';
}
DWARFDebugLine::Sequence::Sequence() {
reset();
}
void DWARFDebugLine::Sequence::reset() {
LowPC = 0;
HighPC = 0;
FirstRowIndex = 0;
LastRowIndex = 0;
Empty = true;
}
DWARFDebugLine::LineTable::LineTable() {
clear();
}
void DWARFDebugLine::LineTable::dump(raw_ostream &OS) const {
Prologue.dump(OS);
OS << '\n';
if (!Rows.empty()) {
OS << "Address Line Column File ISA Discriminator Flags\n"
<< "------------------ ------ ------ ------ --- ------------- "
"-------------\n";
for (const Row &R : Rows) {
R.dump(OS);
}
}
}
void DWARFDebugLine::LineTable::clear() {
Prologue.clear();
Rows.clear();
Sequences.clear();
}
DWARFDebugLine::ParsingState::ParsingState(struct LineTable *LT)
: LineTable(LT), RowNumber(0) {
resetRowAndSequence();
}
void DWARFDebugLine::ParsingState::resetRowAndSequence() {
Row.reset(LineTable->Prologue.DefaultIsStmt);
Sequence.reset();
}
void DWARFDebugLine::ParsingState::appendRowToMatrix(uint32_t offset) {
if (Sequence.Empty) {
// Record the beginning of instruction sequence.
Sequence.Empty = false;
Sequence.LowPC = Row.Address;
Sequence.FirstRowIndex = RowNumber;
}
++RowNumber;
LineTable->appendRow(Row);
if (Row.EndSequence) {
// Record the end of instruction sequence.
Sequence.HighPC = Row.Address;
Sequence.LastRowIndex = RowNumber;
if (Sequence.isValid())
LineTable->appendSequence(Sequence);
Sequence.reset();
}
Row.postAppend();
}
const DWARFDebugLine::LineTable *
DWARFDebugLine::getLineTable(uint32_t offset) const {
LineTableConstIter pos = LineTableMap.find(offset);
if (pos != LineTableMap.end())
return &pos->second;
return nullptr;
}
const DWARFDebugLine::LineTable *
DWARFDebugLine::getOrParseLineTable(DataExtractor debug_line_data,
uint32_t offset) {
std::pair<LineTableIter, bool> pos =
LineTableMap.insert(LineTableMapTy::value_type(offset, LineTable()));
LineTable *LT = &pos.first->second;
if (pos.second) {
if (!LT->parse(debug_line_data, RelocMap, &offset))
return nullptr;
}
return LT;
}
bool DWARFDebugLine::LineTable::parse(DataExtractor debug_line_data,
const RelocAddrMap *RMap,
uint32_t *offset_ptr) {
const uint32_t debug_line_offset = *offset_ptr;
clear();
if (!Prologue.parse(debug_line_data, offset_ptr)) {
// Restore our offset and return false to indicate failure!
*offset_ptr = debug_line_offset;
return false;
}
const uint32_t end_offset = debug_line_offset + Prologue.TotalLength +
Prologue.sizeofTotalLength();
ParsingState State(this);
while (*offset_ptr < end_offset) {
uint8_t opcode = debug_line_data.getU8(offset_ptr);
if (opcode == 0) {
// Extended Opcodes always start with a zero opcode followed by
// a uleb128 length so you can skip ones you don't know about
uint32_t ext_offset = *offset_ptr;
uint64_t len = debug_line_data.getULEB128(offset_ptr);
uint32_t arg_size = len - (*offset_ptr - ext_offset);
uint8_t sub_opcode = debug_line_data.getU8(offset_ptr);
switch (sub_opcode) {
case DW_LNE_end_sequence:
// Set the end_sequence register of the state machine to true and
// append a row to the matrix using the current values of the
// state-machine registers. Then reset the registers to the initial
// values specified above. Every statement program sequence must end
// with a DW_LNE_end_sequence instruction which creates a row whose
// address is that of the byte after the last target machine instruction
// of the sequence.
State.Row.EndSequence = true;
State.appendRowToMatrix(*offset_ptr);
State.resetRowAndSequence();
break;
case DW_LNE_set_address:
// Takes a single relocatable address as an operand. The size of the
// operand is the size appropriate to hold an address on the target
// machine. Set the address register to the value given by the
// relocatable address. All of the other statement program opcodes
// that affect the address register add a delta to it. This instruction
// stores a relocatable value into it instead.
{
// If this address is in our relocation map, apply the relocation.
RelocAddrMap::const_iterator AI = RMap->find(*offset_ptr);
if (AI != RMap->end()) {
const std::pair<uint8_t, int64_t> &R = AI->second;
State.Row.Address =
debug_line_data.getAddress(offset_ptr) + R.second;
} else
State.Row.Address = debug_line_data.getAddress(offset_ptr);
}
break;
case DW_LNE_define_file:
// Takes 4 arguments. The first is a null terminated string containing
// a source file name. The second is an unsigned LEB128 number
// representing the directory index of the directory in which the file
// was found. The third is an unsigned LEB128 number representing the
// time of last modification of the file. The fourth is an unsigned
// LEB128 number representing the length in bytes of the file. The time
// and length fields may contain LEB128(0) if the information is not
// available.
//
// The directory index represents an entry in the include_directories
// section of the statement program prologue. The index is LEB128(0)
// if the file was found in the current directory of the compilation,
// LEB128(1) if it was found in the first directory in the
// include_directories section, and so on. The directory index is
// ignored for file names that represent full path names.
//
// The files are numbered, starting at 1, in the order in which they
// appear; the names in the prologue come before names defined by
// the DW_LNE_define_file instruction. These numbers are used in the
// the file register of the state machine.
{
FileNameEntry fileEntry;
fileEntry.Name = debug_line_data.getCStr(offset_ptr);
fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
Prologue.FileNames.push_back(fileEntry);
}
break;
case DW_LNE_set_discriminator:
State.Row.Discriminator = debug_line_data.getULEB128(offset_ptr);
break;
default:
// Length doesn't include the zero opcode byte or the length itself, but
// it does include the sub_opcode, so we have to adjust for that below
(*offset_ptr) += arg_size;
break;
}
} else if (opcode < Prologue.OpcodeBase) {
switch (opcode) {
// Standard Opcodes
case DW_LNS_copy:
// Takes no arguments. Append a row to the matrix using the
// current values of the state-machine registers. Then set
// the basic_block register to false.
State.appendRowToMatrix(*offset_ptr);
break;
case DW_LNS_advance_pc:
// Takes a single unsigned LEB128 operand, multiplies it by the
// min_inst_length field of the prologue, and adds the
// result to the address register of the state machine.
State.Row.Address +=
debug_line_data.getULEB128(offset_ptr) * Prologue.MinInstLength;
break;
case DW_LNS_advance_line:
// Takes a single signed LEB128 operand and adds that value to
// the line register of the state machine.
State.Row.Line += debug_line_data.getSLEB128(offset_ptr);
break;
case DW_LNS_set_file:
// Takes a single unsigned LEB128 operand and stores it in the file
// register of the state machine.
State.Row.File = debug_line_data.getULEB128(offset_ptr);
break;
case DW_LNS_set_column:
// Takes a single unsigned LEB128 operand and stores it in the
// column register of the state machine.
State.Row.Column = debug_line_data.getULEB128(offset_ptr);
break;
case DW_LNS_negate_stmt:
// Takes no arguments. Set the is_stmt register of the state
// machine to the logical negation of its current value.
State.Row.IsStmt = !State.Row.IsStmt;
break;
case DW_LNS_set_basic_block:
// Takes no arguments. Set the basic_block register of the
// state machine to true
State.Row.BasicBlock = true;
break;
case DW_LNS_const_add_pc:
// Takes no arguments. Add to the address register of the state
// machine the address increment value corresponding to special
// opcode 255. The motivation for DW_LNS_const_add_pc is this:
// when the statement program needs to advance the address by a
// small amount, it can use a single special opcode, which occupies
// a single byte. When it needs to advance the address by up to
// twice the range of the last special opcode, it can use
// DW_LNS_const_add_pc followed by a special opcode, for a total
// of two bytes. Only if it needs to advance the address by more
// than twice that range will it need to use both DW_LNS_advance_pc
// and a special opcode, requiring three or more bytes.
{
uint8_t adjust_opcode = 255 - Prologue.OpcodeBase;
uint64_t addr_offset =
(adjust_opcode / Prologue.LineRange) * Prologue.MinInstLength;
State.Row.Address += addr_offset;
}
break;
case DW_LNS_fixed_advance_pc:
// Takes a single uhalf operand. Add to the address register of
// the state machine the value of the (unencoded) operand. This
// is the only extended opcode that takes an argument that is not
// a variable length number. The motivation for DW_LNS_fixed_advance_pc
// is this: existing assemblers cannot emit DW_LNS_advance_pc or
// special opcodes because they cannot encode LEB128 numbers or
// judge when the computation of a special opcode overflows and
// requires the use of DW_LNS_advance_pc. Such assemblers, however,
// can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
State.Row.Address += debug_line_data.getU16(offset_ptr);
break;
case DW_LNS_set_prologue_end:
// Takes no arguments. Set the prologue_end register of the
// state machine to true
State.Row.PrologueEnd = true;
break;
case DW_LNS_set_epilogue_begin:
// Takes no arguments. Set the basic_block register of the
// state machine to true
State.Row.EpilogueBegin = true;
break;
case DW_LNS_set_isa:
// Takes a single unsigned LEB128 operand and stores it in the
// column register of the state machine.
State.Row.Isa = debug_line_data.getULEB128(offset_ptr);
break;
default:
// Handle any unknown standard opcodes here. We know the lengths
// of such opcodes because they are specified in the prologue
// as a multiple of LEB128 operands for each opcode.
{
assert(opcode - 1U < Prologue.StandardOpcodeLengths.size());
uint8_t opcode_length = Prologue.StandardOpcodeLengths[opcode - 1];
for (uint8_t i = 0; i < opcode_length; ++i)
debug_line_data.getULEB128(offset_ptr);
}
break;
}
} else {
// Special Opcodes
// A special opcode value is chosen based on the amount that needs
// to be added to the line and address registers. The maximum line
// increment for a special opcode is the value of the line_base
// field in the header, plus the value of the line_range field,
// minus 1 (line base + line range - 1). If the desired line
// increment is greater than the maximum line increment, a standard
// opcode must be used instead of a special opcode. The "address
// advance" is calculated by dividing the desired address increment
// by the minimum_instruction_length field from the header. The
// special opcode is then calculated using the following formula:
//
// opcode = (desired line increment - line_base) +
// (line_range * address advance) + opcode_base
//
// If the resulting opcode is greater than 255, a standard opcode
// must be used instead.
//
// To decode a special opcode, subtract the opcode_base from the
// opcode itself to give the adjusted opcode. The amount to
// increment the address register is the result of the adjusted
// opcode divided by the line_range multiplied by the
// minimum_instruction_length field from the header. That is:
//
// address increment = (adjusted opcode / line_range) *
// minimum_instruction_length
//
// The amount to increment the line register is the line_base plus
// the result of the adjusted opcode modulo the line_range. That is:
//
// line increment = line_base + (adjusted opcode % line_range)
uint8_t adjust_opcode = opcode - Prologue.OpcodeBase;
uint64_t addr_offset =
(adjust_opcode / Prologue.LineRange) * Prologue.MinInstLength;
int32_t line_offset =
Prologue.LineBase + (adjust_opcode % Prologue.LineRange);
State.Row.Line += line_offset;
State.Row.Address += addr_offset;
State.appendRowToMatrix(*offset_ptr);
}
}
if (!State.Sequence.Empty) {
fprintf(stderr, "warning: last sequence in debug line table is not"
"terminated!\n");
}
// Sort all sequences so that address lookup will work faster.
if (!Sequences.empty()) {
std::sort(Sequences.begin(), Sequences.end(), Sequence::orderByLowPC);
// Note: actually, instruction address ranges of sequences should not
// overlap (in shared objects and executables). If they do, the address
// lookup would still work, though, but result would be ambiguous.
// We don't report warning in this case. For example,
// sometimes .so compiled from multiple object files contains a few
// rudimentary sequences for address ranges [0x0, 0xsomething).
}
return end_offset;
}
uint32_t
DWARFDebugLine::LineTable::findRowInSeq(const DWARFDebugLine::Sequence &seq,
uint64_t address) const {
if (!seq.containsPC(address))
return UnknownRowIndex;
// Search for instruction address in the rows describing the sequence.
// Rows are stored in a vector, so we may use arithmetical operations with
// iterators.
DWARFDebugLine::Row row;
row.Address = address;
RowIter first_row = Rows.begin() + seq.FirstRowIndex;
RowIter last_row = Rows.begin() + seq.LastRowIndex;
LineTable::RowIter row_pos = std::lower_bound(
first_row, last_row, row, DWARFDebugLine::Row::orderByAddress);
if (row_pos == last_row) {
return seq.LastRowIndex - 1;
}
uint32_t index = seq.FirstRowIndex + (row_pos - first_row);
if (row_pos->Address > address) {
if (row_pos == first_row)
return UnknownRowIndex;
else
index--;
}
return index;
}
uint32_t DWARFDebugLine::LineTable::lookupAddress(uint64_t address) const {
if (Sequences.empty())
return UnknownRowIndex;
// First, find an instruction sequence containing the given address.
DWARFDebugLine::Sequence sequence;
sequence.LowPC = address;
SequenceIter first_seq = Sequences.begin();
SequenceIter last_seq = Sequences.end();
SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
DWARFDebugLine::Sequence::orderByLowPC);
DWARFDebugLine::Sequence found_seq;
if (seq_pos == last_seq) {
found_seq = Sequences.back();
} else if (seq_pos->LowPC == address) {
found_seq = *seq_pos;
} else {
if (seq_pos == first_seq)
return UnknownRowIndex;
found_seq = *(seq_pos - 1);
}
return findRowInSeq(found_seq, address);
}
bool DWARFDebugLine::LineTable::lookupAddressRange(
uint64_t address, uint64_t size, std::vector<uint32_t> &result) const {
if (Sequences.empty())
return false;
uint64_t end_addr = address + size;
// First, find an instruction sequence containing the given address.
DWARFDebugLine::Sequence sequence;
sequence.LowPC = address;
SequenceIter first_seq = Sequences.begin();
SequenceIter last_seq = Sequences.end();
SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
DWARFDebugLine::Sequence::orderByLowPC);
if (seq_pos == last_seq || seq_pos->LowPC != address) {
if (seq_pos == first_seq)
return false;
seq_pos--;
}
if (!seq_pos->containsPC(address))
return false;
SequenceIter start_pos = seq_pos;
// Add the rows from the first sequence to the vector, starting with the
// index we just calculated
while (seq_pos != last_seq && seq_pos->LowPC < end_addr) {
const DWARFDebugLine::Sequence &cur_seq = *seq_pos;
// For the first sequence, we need to find which row in the sequence is the
// first in our range.
uint32_t first_row_index = cur_seq.FirstRowIndex;
if (seq_pos == start_pos)
first_row_index = findRowInSeq(cur_seq, address);
// Figure out the last row in the range.
uint32_t last_row_index = findRowInSeq(cur_seq, end_addr - 1);
if (last_row_index == UnknownRowIndex)
last_row_index = cur_seq.LastRowIndex - 1;
assert(first_row_index != UnknownRowIndex);
assert(last_row_index != UnknownRowIndex);
for (uint32_t i = first_row_index; i <= last_row_index; ++i) {
result.push_back(i);
}
++seq_pos;
}
return true;
}
bool
DWARFDebugLine::LineTable::getFileNameByIndex(uint64_t FileIndex,
const char *CompDir,
FileLineInfoKind Kind,
std::string &Result) const {
if (FileIndex == 0 || FileIndex > Prologue.FileNames.size() ||
Kind == FileLineInfoKind::None)
return false;
const FileNameEntry &Entry = Prologue.FileNames[FileIndex - 1];
const char *FileName = Entry.Name;
if (Kind != FileLineInfoKind::AbsoluteFilePath ||
sys::path::is_absolute(FileName)) {
Result = FileName;
return true;
}
SmallString<16> FilePath;
uint64_t IncludeDirIndex = Entry.DirIdx;
const char *IncludeDir = "";
// Be defensive about the contents of Entry.
if (IncludeDirIndex > 0 &&
IncludeDirIndex <= Prologue.IncludeDirectories.size())
IncludeDir = Prologue.IncludeDirectories[IncludeDirIndex - 1];
// We may still need to append compilation directory of compile unit.
// We know that FileName is not absolute, the only way to have an
// absolute path at this point would be if IncludeDir is absolute.
if (CompDir && Kind == FileLineInfoKind::AbsoluteFilePath &&
sys::path::is_relative(IncludeDir))
sys::path::append(FilePath, CompDir);
// sys::path::append skips empty strings.
sys::path::append(FilePath, IncludeDir, FileName);
Result = FilePath.str();
return true;
}
bool
DWARFDebugLine::LineTable::getFileLineInfoForAddress(uint64_t Address,
const char *CompDir,
FileLineInfoKind Kind,
DILineInfo &Result) const {
// Get the index of row we're looking for in the line table.
uint32_t RowIndex = lookupAddress(Address);
if (RowIndex == -1U)
return false;
// Take file number and line/column from the row.
const auto &Row = Rows[RowIndex];
if (!getFileNameByIndex(Row.File, CompDir, Kind, Result.FileName))
return false;
Result.Line = Row.Line;
Result.Column = Row.Column;
return true;
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFAbbreviationDeclaration.cpp | //===-- DWARFAbbreviationDeclaration.cpp ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace dwarf;
void DWARFAbbreviationDeclaration::clear() {
Code = 0;
Tag = 0;
HasChildren = false;
AttributeSpecs.clear();
}
DWARFAbbreviationDeclaration::DWARFAbbreviationDeclaration() {
clear();
}
bool
DWARFAbbreviationDeclaration::extract(DataExtractor Data, uint32_t* OffsetPtr) {
clear();
Code = Data.getULEB128(OffsetPtr);
if (Code == 0) {
return false;
}
Tag = Data.getULEB128(OffsetPtr);
uint8_t ChildrenByte = Data.getU8(OffsetPtr);
HasChildren = (ChildrenByte == DW_CHILDREN_yes);
while (true) {
uint32_t CurOffset = *OffsetPtr;
uint16_t Attr = Data.getULEB128(OffsetPtr);
if (CurOffset == *OffsetPtr) {
clear();
return false;
}
CurOffset = *OffsetPtr;
uint16_t Form = Data.getULEB128(OffsetPtr);
if (CurOffset == *OffsetPtr) {
clear();
return false;
}
if (Attr == 0 && Form == 0)
break;
AttributeSpecs.push_back(AttributeSpec(Attr, Form));
}
if (Tag == 0) {
clear();
return false;
}
return true;
}
void DWARFAbbreviationDeclaration::dump(raw_ostream &OS) const {
const char *tagString = TagString(getTag());
OS << '[' << getCode() << "] ";
if (tagString)
OS << tagString;
else
OS << format("DW_TAG_Unknown_%x", getTag());
OS << "\tDW_CHILDREN_" << (hasChildren() ? "yes" : "no") << '\n';
for (const AttributeSpec &Spec : AttributeSpecs) {
OS << '\t';
const char *attrString = AttributeString(Spec.Attr);
if (attrString)
OS << attrString;
else
OS << format("DW_AT_Unknown_%x", Spec.Attr);
OS << '\t';
const char *formString = FormEncodingString(Spec.Form);
if (formString)
OS << formString;
else
OS << format("DW_FORM_Unknown_%x", Spec.Form);
OS << '\n';
}
OS << '\n';
}
uint32_t
DWARFAbbreviationDeclaration::findAttributeIndex(uint16_t attr) const {
for (uint32_t i = 0, e = AttributeSpecs.size(); i != e; ++i) {
if (AttributeSpecs[i].Attr == attr)
return i;
}
return -1U;
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFDebugAranges.cpp | //===-- DWARFDebugAranges.cpp -----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugAranges.h"
#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <set>
using namespace llvm;
void DWARFDebugAranges::extract(DataExtractor DebugArangesData) {
if (!DebugArangesData.isValidOffset(0))
return;
uint32_t Offset = 0;
DWARFDebugArangeSet Set;
while (Set.extract(DebugArangesData, &Offset)) {
uint32_t CUOffset = Set.getCompileUnitDIEOffset();
for (const auto &Desc : Set.descriptors()) {
uint64_t LowPC = Desc.Address;
uint64_t HighPC = Desc.getEndAddress();
appendRange(CUOffset, LowPC, HighPC);
}
ParsedCUOffsets.insert(CUOffset);
}
}
void DWARFDebugAranges::generate(DWARFContext *CTX) {
clear();
if (!CTX)
return;
// Extract aranges from .debug_aranges section.
DataExtractor ArangesData(CTX->getARangeSection(), CTX->isLittleEndian(), 0);
extract(ArangesData);
// Generate aranges from DIEs: even if .debug_aranges section is present,
// it may describe only a small subset of compilation units, so we need to
// manually build aranges for the rest of them.
for (const auto &CU : CTX->compile_units()) {
uint32_t CUOffset = CU->getOffset();
if (ParsedCUOffsets.insert(CUOffset).second) {
DWARFAddressRangesVector CURanges;
CU->collectAddressRanges(CURanges);
for (const auto &R : CURanges) {
appendRange(CUOffset, R.first, R.second);
}
}
}
construct();
}
void DWARFDebugAranges::clear() {
Endpoints.clear();
Aranges.clear();
ParsedCUOffsets.clear();
}
void DWARFDebugAranges::appendRange(uint32_t CUOffset, uint64_t LowPC,
uint64_t HighPC) {
if (LowPC >= HighPC)
return;
Endpoints.emplace_back(LowPC, CUOffset, true);
Endpoints.emplace_back(HighPC, CUOffset, false);
}
void DWARFDebugAranges::construct() {
std::multiset<uint32_t> ValidCUs; // Maintain the set of CUs describing
// a current address range.
std::sort(Endpoints.begin(), Endpoints.end());
uint64_t PrevAddress = -1ULL;
for (const auto &E : Endpoints) {
if (PrevAddress < E.Address && ValidCUs.size() > 0) {
// If the address range between two endpoints is described by some
// CU, first try to extend the last range in Aranges. If we can't
// do it, start a new range.
if (!Aranges.empty() && Aranges.back().HighPC() == PrevAddress &&
ValidCUs.find(Aranges.back().CUOffset) != ValidCUs.end()) {
Aranges.back().setHighPC(E.Address);
} else {
Aranges.emplace_back(PrevAddress, E.Address, *ValidCUs.begin());
}
}
// Update the set of valid CUs.
if (E.IsRangeStart) {
ValidCUs.insert(E.CUOffset);
} else {
auto CUPos = ValidCUs.find(E.CUOffset);
assert(CUPos != ValidCUs.end());
ValidCUs.erase(CUPos);
}
PrevAddress = E.Address;
}
assert(ValidCUs.empty());
// Endpoints are not needed now.
std::vector<RangeEndpoint> EmptyEndpoints;
EmptyEndpoints.swap(Endpoints);
}
uint32_t DWARFDebugAranges::findAddress(uint64_t Address) const {
if (!Aranges.empty()) {
Range range(Address);
RangeCollIterator begin = Aranges.begin();
RangeCollIterator end = Aranges.end();
RangeCollIterator pos =
std::lower_bound(begin, end, range);
if (pos != end && pos->containsAddress(Address)) {
return pos->CUOffset;
} else if (pos != begin) {
--pos;
if (pos->containsAddress(Address))
return pos->CUOffset;
}
}
return -1U;
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFDebugLoc.cpp | //===-- DWARFDebugLoc.cpp -------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
void DWARFDebugLoc::dump(raw_ostream &OS) const {
for (const LocationList &L : Locations) {
OS << format("0x%8.8x: ", L.Offset);
const unsigned Indent = 12;
for (const Entry &E : L.Entries) {
if (&E != L.Entries.begin())
OS.indent(Indent);
OS << "Beginning address offset: " << format("0x%016" PRIx64, E.Begin)
<< '\n';
OS.indent(Indent) << " Ending address offset: "
<< format("0x%016" PRIx64, E.End) << '\n';
OS.indent(Indent) << " Location description: ";
for (unsigned char Loc : E.Loc) {
OS << format("%2.2x ", Loc);
}
OS << "\n\n";
}
}
}
void DWARFDebugLoc::parse(DataExtractor data, unsigned AddressSize) {
uint32_t Offset = 0;
while (data.isValidOffset(Offset+AddressSize-1)) {
Locations.resize(Locations.size() + 1);
LocationList &Loc = Locations.back();
Loc.Offset = Offset;
// 2.6.2 Location Lists
// A location list entry consists of:
while (true) {
Entry E;
RelocAddrMap::const_iterator AI = RelocMap.find(Offset);
// 1. A beginning address offset. ...
E.Begin = data.getUnsigned(&Offset, AddressSize);
if (AI != RelocMap.end())
E.Begin += AI->second.second;
AI = RelocMap.find(Offset);
// 2. An ending address offset. ...
E.End = data.getUnsigned(&Offset, AddressSize);
if (AI != RelocMap.end())
E.End += AI->second.second;
// The end of any given location list is marked by an end of list entry,
// which consists of a 0 for the beginning address offset and a 0 for the
// ending address offset.
if (E.Begin == 0 && E.End == 0)
break;
unsigned Bytes = data.getU16(&Offset);
// A single location description describing the location of the object...
StringRef str = data.getData().substr(Offset, Bytes);
Offset += Bytes;
E.Loc.append(str.begin(), str.end());
Loc.Entries.push_back(std::move(E));
}
}
if (data.isValidOffset(Offset))
llvm::errs() << "error: failed to consume entire .debug_loc section\n";
}
void DWARFDebugLocDWO::parse(DataExtractor data) {
uint32_t Offset = 0;
while (data.isValidOffset(Offset)) {
Locations.resize(Locations.size() + 1);
LocationList &Loc = Locations.back();
Loc.Offset = Offset;
dwarf::LocationListEntry Kind;
while ((Kind = static_cast<dwarf::LocationListEntry>(
data.getU8(&Offset))) != dwarf::DW_LLE_end_of_list_entry) {
if (Kind != dwarf::DW_LLE_start_length_entry) {
llvm::errs() << "error: dumping support for LLE of kind " << (int)Kind
<< " not implemented\n";
return;
}
Entry E;
E.Start = data.getULEB128(&Offset);
E.Length = data.getU32(&Offset);
unsigned Bytes = data.getU16(&Offset);
// A single location description describing the location of the object...
StringRef str = data.getData().substr(Offset, Bytes);
Offset += Bytes;
E.Loc.resize(str.size());
std::copy(str.begin(), str.end(), E.Loc.begin());
Loc.Entries.push_back(std::move(E));
}
}
}
void DWARFDebugLocDWO::dump(raw_ostream &OS) const {
for (const LocationList &L : Locations) {
OS << format("0x%8.8x: ", L.Offset);
const unsigned Indent = 12;
for (const Entry &E : L.Entries) {
if (&E != L.Entries.begin())
OS.indent(Indent);
OS << "Beginning address index: " << E.Start << '\n';
OS.indent(Indent) << " Length: " << E.Length << '\n';
OS.indent(Indent) << " Location description: ";
for (unsigned char Loc : E.Loc)
OS << format("%2.2x ", Loc);
OS << "\n\n";
}
}
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFAcceleratorTable.cpp | //===--- DWARFAcceleratorTable.cpp ----------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
namespace llvm {
bool DWARFAcceleratorTable::extract() {
uint32_t Offset = 0;
// Check that we can at least read the header.
if (!AccelSection.isValidOffset(offsetof(Header, HeaderDataLength)+4))
return false;
Hdr.Magic = AccelSection.getU32(&Offset);
Hdr.Version = AccelSection.getU16(&Offset);
Hdr.HashFunction = AccelSection.getU16(&Offset);
Hdr.NumBuckets = AccelSection.getU32(&Offset);
Hdr.NumHashes = AccelSection.getU32(&Offset);
Hdr.HeaderDataLength = AccelSection.getU32(&Offset);
// Check that we can read all the hashes and offsets from the
// section (see SourceLevelDebugging.rst for the structure of the index).
if (!AccelSection.isValidOffset(sizeof(Hdr) + Hdr.HeaderDataLength +
Hdr.NumBuckets*4 + Hdr.NumHashes*8))
return false;
HdrData.DIEOffsetBase = AccelSection.getU32(&Offset);
uint32_t NumAtoms = AccelSection.getU32(&Offset);
for (unsigned i = 0; i < NumAtoms; ++i) {
uint16_t AtomType = AccelSection.getU16(&Offset);
uint16_t AtomForm = AccelSection.getU16(&Offset);
HdrData.Atoms.push_back(std::make_pair(AtomType, AtomForm));
}
return true;
}
void DWARFAcceleratorTable::dump(raw_ostream &OS) const {
// Dump the header.
OS << "Magic = " << format("0x%08x", Hdr.Magic) << '\n'
<< "Version = " << format("0x%04x", Hdr.Version) << '\n'
<< "Hash function = " << format("0x%08x", Hdr.HashFunction) << '\n'
<< "Bucket count = " << Hdr.NumBuckets << '\n'
<< "Hashes count = " << Hdr.NumHashes << '\n'
<< "HeaderData length = " << Hdr.HeaderDataLength << '\n'
<< "DIE offset base = " << HdrData.DIEOffsetBase << '\n'
<< "Number of atoms = " << HdrData.Atoms.size() << '\n';
unsigned i = 0;
SmallVector<DWARFFormValue, 3> AtomForms;
for (const auto &Atom: HdrData.Atoms) {
OS << format("Atom[%d] Type: ", i++);
if (const char *TypeString = dwarf::AtomTypeString(Atom.first))
OS << TypeString;
else
OS << format("DW_ATOM_Unknown_0x%x", Atom.first);
OS << " Form: ";
if (const char *FormString = dwarf::FormEncodingString(Atom.second))
OS << FormString;
else
OS << format("DW_FORM_Unknown_0x%x", Atom.second);
OS << '\n';
AtomForms.push_back(DWARFFormValue(Atom.second));
}
// Now go through the actual tables and dump them.
uint32_t Offset = sizeof(Hdr) + Hdr.HeaderDataLength;
unsigned HashesBase = Offset + Hdr.NumBuckets * 4;
unsigned OffsetsBase = HashesBase + Hdr.NumHashes * 4;
for (unsigned Bucket = 0; Bucket < Hdr.NumBuckets; ++Bucket) {
unsigned Index = AccelSection.getU32(&Offset);
OS << format("Bucket[%d]\n", Bucket);
if (Index == UINT32_MAX) {
OS << " EMPTY\n";
continue;
}
for (unsigned HashIdx = Index; HashIdx < Hdr.NumHashes; ++HashIdx) {
unsigned HashOffset = HashesBase + HashIdx*4;
unsigned OffsetsOffset = OffsetsBase + HashIdx*4;
uint32_t Hash = AccelSection.getU32(&HashOffset);
if (Hash % Hdr.NumBuckets != Bucket)
break;
unsigned DataOffset = AccelSection.getU32(&OffsetsOffset);
OS << format(" Hash = 0x%08x Offset = 0x%08x\n", Hash, DataOffset);
if (!AccelSection.isValidOffset(DataOffset)) {
OS << " Invalid section offset\n";
continue;
}
while (AccelSection.isValidOffsetForDataOfSize(DataOffset, 4)) {
unsigned StringOffset = AccelSection.getU32(&DataOffset);
RelocAddrMap::const_iterator Reloc = Relocs.find(DataOffset-4);
if (Reloc != Relocs.end())
StringOffset += Reloc->second.second;
if (!StringOffset)
break;
OS << format(" Name: %08x \"%s\"\n", StringOffset,
StringSection.getCStr(&StringOffset));
unsigned NumData = AccelSection.getU32(&DataOffset);
for (unsigned Data = 0; Data < NumData; ++Data) {
OS << format(" Data[%d] => ", Data);
unsigned i = 0;
for (auto &Atom : AtomForms) {
OS << format("{Atom[%d]: ", i++);
if (Atom.extractValue(AccelSection, &DataOffset, nullptr))
Atom.dump(OS, nullptr);
else
OS << "Error extracting the value";
OS << "} ";
}
OS << '\n';
}
}
}
}
}
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFDebugInfoEntry.cpp | //===-- DWARFDebugInfoEntry.cpp -------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "SyntaxHighlighting.h"
#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace dwarf;
using namespace syntax;
// Small helper to extract a DIE pointed by a reference
// attribute. It looks up the Unit containing the DIE and calls
// DIE.extractFast with the right unit. Returns new unit on success,
// nullptr otherwise.
static const DWARFUnit *findUnitAndExtractFast(DWARFDebugInfoEntryMinimal &DIE,
const DWARFUnit *Unit,
uint32_t *Offset) {
Unit = Unit->getUnitSection().getUnitForOffset(*Offset);
return (Unit && DIE.extractFast(Unit, Offset)) ? Unit : nullptr;
}
void DWARFDebugInfoEntryMinimal::dump(raw_ostream &OS, DWARFUnit *u,
unsigned recurseDepth,
unsigned indent) const {
DataExtractor debug_info_data = u->getDebugInfoExtractor();
uint32_t offset = Offset;
if (debug_info_data.isValidOffset(offset)) {
uint32_t abbrCode = debug_info_data.getULEB128(&offset);
WithColor(OS, syntax::Address).get() << format("\n0x%8.8x: ", Offset);
if (abbrCode) {
if (AbbrevDecl) {
const char *tagString = TagString(getTag());
if (tagString)
WithColor(OS, syntax::Tag).get().indent(indent) << tagString;
else
WithColor(OS, syntax::Tag).get().indent(indent) <<
format("DW_TAG_Unknown_%x", getTag());
OS << format(" [%u] %c\n", abbrCode,
AbbrevDecl->hasChildren() ? '*' : ' ');
// Dump all data in the DIE for the attributes.
for (const auto &AttrSpec : AbbrevDecl->attributes()) {
dumpAttribute(OS, u, &offset, AttrSpec.Attr, AttrSpec.Form, indent);
}
const DWARFDebugInfoEntryMinimal *child = getFirstChild();
if (recurseDepth > 0 && child) {
while (child) {
child->dump(OS, u, recurseDepth-1, indent+2);
child = child->getSibling();
}
}
} else {
OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
<< abbrCode << '\n';
}
} else {
OS.indent(indent) << "NULL\n";
}
}
}
static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) {
OS << " (";
do {
uint64_t Shift = countTrailingZeros(Val);
assert(Shift < 64 && "undefined behavior");
uint64_t Bit = 1ULL << Shift;
if (const char *PropName = ApplePropertyString(Bit))
OS << PropName;
else
OS << format("DW_APPLE_PROPERTY_0x%" PRIx64, Bit);
if (!(Val ^= Bit))
break;
OS << ", ";
} while (true);
OS << ")";
}
static void dumpRanges(raw_ostream &OS, const DWARFAddressRangesVector& Ranges,
unsigned AddressSize, unsigned Indent) {
if (Ranges.empty())
return;
for (const auto &Range: Ranges) {
OS << '\n';
OS.indent(Indent);
OS << format("[0x%0*" PRIx64 " - 0x%0*" PRIx64 ")",
AddressSize*2, Range.first,
AddressSize*2, Range.second);
}
}
void DWARFDebugInfoEntryMinimal::dumpAttribute(raw_ostream &OS,
DWARFUnit *u,
uint32_t *offset_ptr,
uint16_t attr, uint16_t form,
unsigned indent) const {
const char BaseIndent[] = " ";
OS << BaseIndent;
OS.indent(indent+2);
const char *attrString = AttributeString(attr);
if (attrString)
WithColor(OS, syntax::Attribute) << attrString;
else
WithColor(OS, syntax::Attribute).get() << format("DW_AT_Unknown_%x", attr);
const char *formString = FormEncodingString(form);
if (formString)
OS << " [" << formString << ']';
else
OS << format(" [DW_FORM_Unknown_%x]", form);
DWARFFormValue formValue(form);
if (!formValue.extractValue(u->getDebugInfoExtractor(), offset_ptr, u))
return;
OS << "\t(";
const char *Name = nullptr;
std::string File;
auto Color = syntax::Enumerator;
if (attr == DW_AT_decl_file || attr == DW_AT_call_file) {
Color = syntax::String;
if (const auto *LT = u->getContext().getLineTableForUnit(u))
if (LT->getFileNameByIndex(
formValue.getAsUnsignedConstant().getValue(),
u->getCompilationDir(),
DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, File)) {
File = '"' + File + '"';
Name = File.c_str();
}
} else if (Optional<uint64_t> Val = formValue.getAsUnsignedConstant())
Name = AttributeValueString(attr, *Val);
if (Name)
WithColor(OS, Color) << Name;
else if (attr == DW_AT_decl_line || attr == DW_AT_call_line)
OS << *formValue.getAsUnsignedConstant();
else
formValue.dump(OS, u);
// We have dumped the attribute raw value. For some attributes
// having both the raw value and the pretty-printed value is
// interesting. These attributes are handled below.
if (attr == DW_AT_specification || attr == DW_AT_abstract_origin) {
Optional<uint64_t> Ref = formValue.getAsReference(u);
if (Ref.hasValue()) {
uint32_t RefOffset = Ref.getValue();
DWARFDebugInfoEntryMinimal DIE;
if (const DWARFUnit *RefU = findUnitAndExtractFast(DIE, u, &RefOffset))
if (const char *Name = DIE.getName(RefU, DINameKind::LinkageName))
OS << " \"" << Name << '\"';
}
} else if (attr == DW_AT_APPLE_property_attribute) {
if (Optional<uint64_t> OptVal = formValue.getAsUnsignedConstant())
dumpApplePropertyAttribute(OS, *OptVal);
} else if (attr == DW_AT_ranges) {
dumpRanges(OS, getAddressRanges(u), u->getAddressByteSize(),
sizeof(BaseIndent)+indent+4);
}
OS << ")\n";
}
bool DWARFDebugInfoEntryMinimal::extractFast(const DWARFUnit *U,
uint32_t *OffsetPtr) {
Offset = *OffsetPtr;
DataExtractor DebugInfoData = U->getDebugInfoExtractor();
uint32_t UEndOffset = U->getNextUnitOffset();
if (Offset >= UEndOffset || !DebugInfoData.isValidOffset(Offset))
return false;
uint64_t AbbrCode = DebugInfoData.getULEB128(OffsetPtr);
if (0 == AbbrCode) {
// NULL debug tag entry.
AbbrevDecl = nullptr;
return true;
}
AbbrevDecl = U->getAbbreviations()->getAbbreviationDeclaration(AbbrCode);
if (nullptr == AbbrevDecl) {
// Restore the original offset.
*OffsetPtr = Offset;
return false;
}
ArrayRef<uint8_t> FixedFormSizes = DWARFFormValue::getFixedFormSizes(
U->getAddressByteSize(), U->getVersion());
assert(FixedFormSizes.size() > 0);
// Skip all data in the .debug_info for the attributes
for (const auto &AttrSpec : AbbrevDecl->attributes()) {
uint16_t Form = AttrSpec.Form;
uint8_t FixedFormSize =
(Form < FixedFormSizes.size()) ? FixedFormSizes[Form] : 0;
if (FixedFormSize)
*OffsetPtr += FixedFormSize;
else if (!DWARFFormValue::skipValue(Form, DebugInfoData, OffsetPtr, U)) {
// Restore the original offset.
*OffsetPtr = Offset;
return false;
}
}
return true;
}
bool DWARFDebugInfoEntryMinimal::isSubprogramDIE() const {
return getTag() == DW_TAG_subprogram;
}
bool DWARFDebugInfoEntryMinimal::isSubroutineDIE() const {
uint32_t Tag = getTag();
return Tag == DW_TAG_subprogram ||
Tag == DW_TAG_inlined_subroutine;
}
bool DWARFDebugInfoEntryMinimal::getAttributeValue(
const DWARFUnit *U, const uint16_t Attr, DWARFFormValue &FormValue) const {
if (!AbbrevDecl)
return false;
uint32_t AttrIdx = AbbrevDecl->findAttributeIndex(Attr);
if (AttrIdx == -1U)
return false;
DataExtractor DebugInfoData = U->getDebugInfoExtractor();
uint32_t DebugInfoOffset = getOffset();
// Skip the abbreviation code so we are at the data for the attributes
DebugInfoData.getULEB128(&DebugInfoOffset);
// Skip preceding attribute values.
for (uint32_t i = 0; i < AttrIdx; ++i) {
DWARFFormValue::skipValue(AbbrevDecl->getFormByIndex(i),
DebugInfoData, &DebugInfoOffset, U);
}
FormValue = DWARFFormValue(AbbrevDecl->getFormByIndex(AttrIdx));
return FormValue.extractValue(DebugInfoData, &DebugInfoOffset, U);
}
const char *DWARFDebugInfoEntryMinimal::getAttributeValueAsString(
const DWARFUnit *U, const uint16_t Attr, const char *FailValue) const {
DWARFFormValue FormValue;
if (!getAttributeValue(U, Attr, FormValue))
return FailValue;
Optional<const char *> Result = FormValue.getAsCString(U);
return Result.hasValue() ? Result.getValue() : FailValue;
}
uint64_t DWARFDebugInfoEntryMinimal::getAttributeValueAsAddress(
const DWARFUnit *U, const uint16_t Attr, uint64_t FailValue) const {
DWARFFormValue FormValue;
if (!getAttributeValue(U, Attr, FormValue))
return FailValue;
Optional<uint64_t> Result = FormValue.getAsAddress(U);
return Result.hasValue() ? Result.getValue() : FailValue;
}
uint64_t DWARFDebugInfoEntryMinimal::getAttributeValueAsUnsignedConstant(
const DWARFUnit *U, const uint16_t Attr, uint64_t FailValue) const {
DWARFFormValue FormValue;
if (!getAttributeValue(U, Attr, FormValue))
return FailValue;
Optional<uint64_t> Result = FormValue.getAsUnsignedConstant();
return Result.hasValue() ? Result.getValue() : FailValue;
}
uint64_t DWARFDebugInfoEntryMinimal::getAttributeValueAsReference(
const DWARFUnit *U, const uint16_t Attr, uint64_t FailValue) const {
DWARFFormValue FormValue;
if (!getAttributeValue(U, Attr, FormValue))
return FailValue;
Optional<uint64_t> Result = FormValue.getAsReference(U);
return Result.hasValue() ? Result.getValue() : FailValue;
}
uint64_t DWARFDebugInfoEntryMinimal::getAttributeValueAsSectionOffset(
const DWARFUnit *U, const uint16_t Attr, uint64_t FailValue) const {
DWARFFormValue FormValue;
if (!getAttributeValue(U, Attr, FormValue))
return FailValue;
Optional<uint64_t> Result = FormValue.getAsSectionOffset();
return Result.hasValue() ? Result.getValue() : FailValue;
}
uint64_t
DWARFDebugInfoEntryMinimal::getRangesBaseAttribute(const DWARFUnit *U,
uint64_t FailValue) const {
uint64_t Result =
getAttributeValueAsSectionOffset(U, DW_AT_ranges_base, -1ULL);
if (Result != -1ULL)
return Result;
return getAttributeValueAsSectionOffset(U, DW_AT_GNU_ranges_base, FailValue);
}
bool DWARFDebugInfoEntryMinimal::getLowAndHighPC(const DWARFUnit *U,
uint64_t &LowPC,
uint64_t &HighPC) const {
LowPC = getAttributeValueAsAddress(U, DW_AT_low_pc, -1ULL);
if (LowPC == -1ULL)
return false;
HighPC = getAttributeValueAsAddress(U, DW_AT_high_pc, -1ULL);
if (HighPC == -1ULL) {
// Since DWARF4, DW_AT_high_pc may also be of class constant, in which case
// it represents function size.
HighPC = getAttributeValueAsUnsignedConstant(U, DW_AT_high_pc, -1ULL);
if (HighPC != -1ULL)
HighPC += LowPC;
}
return (HighPC != -1ULL);
}
DWARFAddressRangesVector
DWARFDebugInfoEntryMinimal::getAddressRanges(const DWARFUnit *U) const {
if (isNULL())
return DWARFAddressRangesVector();
// Single range specified by low/high PC.
uint64_t LowPC, HighPC;
if (getLowAndHighPC(U, LowPC, HighPC)) {
return DWARFAddressRangesVector(1, std::make_pair(LowPC, HighPC));
}
// Multiple ranges from .debug_ranges section.
uint32_t RangesOffset =
getAttributeValueAsSectionOffset(U, DW_AT_ranges, -1U);
if (RangesOffset != -1U) {
DWARFDebugRangeList RangeList;
if (U->extractRangeList(RangesOffset, RangeList))
return RangeList.getAbsoluteRanges(U->getBaseAddress());
}
return DWARFAddressRangesVector();
}
void DWARFDebugInfoEntryMinimal::collectChildrenAddressRanges(
const DWARFUnit *U, DWARFAddressRangesVector& Ranges) const {
if (isNULL())
return;
if (isSubprogramDIE()) {
const auto &DIERanges = getAddressRanges(U);
Ranges.insert(Ranges.end(), DIERanges.begin(), DIERanges.end());
}
const DWARFDebugInfoEntryMinimal *Child = getFirstChild();
while (Child) {
Child->collectChildrenAddressRanges(U, Ranges);
Child = Child->getSibling();
}
}
bool DWARFDebugInfoEntryMinimal::addressRangeContainsAddress(
const DWARFUnit *U, const uint64_t Address) const {
for (const auto& R : getAddressRanges(U)) {
if (R.first <= Address && Address < R.second)
return true;
}
return false;
}
const char *
DWARFDebugInfoEntryMinimal::getSubroutineName(const DWARFUnit *U,
DINameKind Kind) const {
if (!isSubroutineDIE())
return nullptr;
return getName(U, Kind);
}
const char *
DWARFDebugInfoEntryMinimal::getName(const DWARFUnit *U,
DINameKind Kind) const {
if (Kind == DINameKind::None)
return nullptr;
// Try to get mangled name only if it was asked for.
if (Kind == DINameKind::LinkageName) {
if (const char *name =
getAttributeValueAsString(U, DW_AT_MIPS_linkage_name, nullptr))
return name;
if (const char *name =
getAttributeValueAsString(U, DW_AT_linkage_name, nullptr))
return name;
}
if (const char *name = getAttributeValueAsString(U, DW_AT_name, nullptr))
return name;
// Try to get name from specification DIE.
uint32_t spec_ref =
getAttributeValueAsReference(U, DW_AT_specification, -1U);
if (spec_ref != -1U) {
DWARFDebugInfoEntryMinimal spec_die;
if (const DWARFUnit *RefU = findUnitAndExtractFast(spec_die, U, &spec_ref)) {
if (const char *name = spec_die.getName(RefU, Kind))
return name;
}
}
// Try to get name from abstract origin DIE.
uint32_t abs_origin_ref =
getAttributeValueAsReference(U, DW_AT_abstract_origin, -1U);
if (abs_origin_ref != -1U) {
DWARFDebugInfoEntryMinimal abs_origin_die;
if (const DWARFUnit *RefU = findUnitAndExtractFast(abs_origin_die, U,
&abs_origin_ref)) {
if (const char *name = abs_origin_die.getName(RefU, Kind))
return name;
}
}
return nullptr;
}
void DWARFDebugInfoEntryMinimal::getCallerFrame(const DWARFUnit *U,
uint32_t &CallFile,
uint32_t &CallLine,
uint32_t &CallColumn) const {
CallFile = getAttributeValueAsUnsignedConstant(U, DW_AT_call_file, 0);
CallLine = getAttributeValueAsUnsignedConstant(U, DW_AT_call_line, 0);
CallColumn = getAttributeValueAsUnsignedConstant(U, DW_AT_call_column, 0);
}
DWARFDebugInfoEntryInlinedChain
DWARFDebugInfoEntryMinimal::getInlinedChainForAddress(
const DWARFUnit *U, const uint64_t Address) const {
DWARFDebugInfoEntryInlinedChain InlinedChain;
InlinedChain.U = U;
if (isNULL())
return InlinedChain;
for (const DWARFDebugInfoEntryMinimal *DIE = this; DIE; ) {
// Append current DIE to inlined chain only if it has correct tag
// (e.g. it is not a lexical block).
if (DIE->isSubroutineDIE()) {
InlinedChain.DIEs.push_back(*DIE);
}
// Try to get child which also contains provided address.
const DWARFDebugInfoEntryMinimal *Child = DIE->getFirstChild();
while (Child) {
if (Child->addressRangeContainsAddress(U, Address)) {
// Assume there is only one such child.
break;
}
Child = Child->getSibling();
}
DIE = Child;
}
// Reverse the obtained chain to make the root of inlined chain last.
std::reverse(InlinedChain.DIEs.begin(), InlinedChain.DIEs.end());
return InlinedChain;
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFContext.cpp | //===-- DWARFContext.cpp --------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
#include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
#include "llvm/Support/Compression.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace llvm;
using namespace dwarf;
using namespace object;
#define DEBUG_TYPE "dwarf"
typedef DWARFDebugLine::LineTable DWARFLineTable;
typedef DILineInfoSpecifier::FileLineInfoKind FileLineInfoKind;
typedef DILineInfoSpecifier::FunctionNameKind FunctionNameKind;
static void dumpPubSection(raw_ostream &OS, StringRef Name, StringRef Data,
bool LittleEndian, bool GnuStyle) {
OS << "\n." << Name << " contents:\n";
DataExtractor pubNames(Data, LittleEndian, 0);
uint32_t offset = 0;
while (pubNames.isValidOffset(offset)) {
OS << "length = " << format("0x%08x", pubNames.getU32(&offset));
OS << " version = " << format("0x%04x", pubNames.getU16(&offset));
OS << " unit_offset = " << format("0x%08x", pubNames.getU32(&offset));
OS << " unit_size = " << format("0x%08x", pubNames.getU32(&offset)) << '\n';
if (GnuStyle)
OS << "Offset Linkage Kind Name\n";
else
OS << "Offset Name\n";
while (offset < Data.size()) {
uint32_t dieRef = pubNames.getU32(&offset);
if (dieRef == 0)
break;
OS << format("0x%8.8x ", dieRef);
if (GnuStyle) {
PubIndexEntryDescriptor desc(pubNames.getU8(&offset));
OS << format("%-8s", dwarf::GDBIndexEntryLinkageString(desc.Linkage))
<< ' ' << format("%-8s", dwarf::GDBIndexEntryKindString(desc.Kind))
<< ' ';
}
OS << '\"' << pubNames.getCStr(&offset) << "\"\n";
}
}
}
static void dumpAccelSection(raw_ostream &OS, StringRef Name,
const DWARFSection& Section, StringRef StringSection,
bool LittleEndian) {
DataExtractor AccelSection(Section.Data, LittleEndian, 0);
DataExtractor StrData(StringSection, LittleEndian, 0);
OS << "\n." << Name << " contents:\n";
DWARFAcceleratorTable Accel(AccelSection, StrData, Section.Relocs);
if (!Accel.extract())
return;
Accel.dump(OS);
}
void DWARFContext::dump(raw_ostream &OS, DIDumpType DumpType) {
if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
OS << ".debug_abbrev contents:\n";
getDebugAbbrev()->dump(OS);
}
if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo)
if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
OS << "\n.debug_abbrev.dwo contents:\n";
D->dump(OS);
}
if (DumpType == DIDT_All || DumpType == DIDT_Info) {
OS << "\n.debug_info contents:\n";
for (const auto &CU : compile_units())
CU->dump(OS);
}
if ((DumpType == DIDT_All || DumpType == DIDT_InfoDwo) &&
getNumDWOCompileUnits()) {
OS << "\n.debug_info.dwo contents:\n";
for (const auto &DWOCU : dwo_compile_units())
DWOCU->dump(OS);
}
if ((DumpType == DIDT_All || DumpType == DIDT_Types) && getNumTypeUnits()) {
OS << "\n.debug_types contents:\n";
for (const auto &TUS : type_unit_sections())
for (const auto &TU : TUS)
TU->dump(OS);
}
if ((DumpType == DIDT_All || DumpType == DIDT_TypesDwo) &&
getNumDWOTypeUnits()) {
OS << "\n.debug_types.dwo contents:\n";
for (const auto &DWOTUS : dwo_type_unit_sections())
for (const auto &DWOTU : DWOTUS)
DWOTU->dump(OS);
}
if (DumpType == DIDT_All || DumpType == DIDT_Loc) {
OS << "\n.debug_loc contents:\n";
getDebugLoc()->dump(OS);
}
if (DumpType == DIDT_All || DumpType == DIDT_LocDwo) {
OS << "\n.debug_loc.dwo contents:\n";
getDebugLocDWO()->dump(OS);
}
if (DumpType == DIDT_All || DumpType == DIDT_Frames) {
OS << "\n.debug_frame contents:\n";
getDebugFrame()->dump(OS);
}
uint32_t offset = 0;
if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
OS << "\n.debug_aranges contents:\n";
DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
DWARFDebugArangeSet set;
while (set.extract(arangesData, &offset))
set.dump(OS);
}
uint8_t savedAddressByteSize = 0;
if (DumpType == DIDT_All || DumpType == DIDT_Line) {
OS << "\n.debug_line contents:\n";
for (const auto &CU : compile_units()) {
savedAddressByteSize = CU->getAddressByteSize();
const auto *CUDIE = CU->getUnitDIE();
if (CUDIE == nullptr)
continue;
unsigned stmtOffset = CUDIE->getAttributeValueAsSectionOffset(
CU.get(), DW_AT_stmt_list, -1U);
if (stmtOffset != -1U) {
DataExtractor lineData(getLineSection().Data, isLittleEndian(),
savedAddressByteSize);
DWARFDebugLine::LineTable LineTable;
LineTable.parse(lineData, &getLineSection().Relocs, &stmtOffset);
LineTable.dump(OS);
}
}
}
if (DumpType == DIDT_All || DumpType == DIDT_LineDwo) {
OS << "\n.debug_line.dwo contents:\n";
unsigned stmtOffset = 0;
DataExtractor lineData(getLineDWOSection().Data, isLittleEndian(),
savedAddressByteSize);
DWARFDebugLine::LineTable LineTable;
while (LineTable.Prologue.parse(lineData, &stmtOffset)) {
LineTable.dump(OS);
LineTable.clear();
}
}
if (DumpType == DIDT_All || DumpType == DIDT_Str) {
OS << "\n.debug_str contents:\n";
DataExtractor strData(getStringSection(), isLittleEndian(), 0);
offset = 0;
uint32_t strOffset = 0;
while (const char *s = strData.getCStr(&offset)) {
OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
strOffset = offset;
}
}
if ((DumpType == DIDT_All || DumpType == DIDT_StrDwo) &&
!getStringDWOSection().empty()) {
OS << "\n.debug_str.dwo contents:\n";
DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
offset = 0;
uint32_t strDWOOffset = 0;
while (const char *s = strDWOData.getCStr(&offset)) {
OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
strDWOOffset = offset;
}
}
if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
OS << "\n.debug_ranges contents:\n";
// In fact, different compile units may have different address byte
// sizes, but for simplicity we just use the address byte size of the last
// compile unit (there is no easy and fast way to associate address range
// list and the compile unit it describes).
DataExtractor rangesData(getRangeSection(), isLittleEndian(),
savedAddressByteSize);
offset = 0;
DWARFDebugRangeList rangeList;
while (rangeList.extract(rangesData, &offset))
rangeList.dump(OS);
}
if (DumpType == DIDT_All || DumpType == DIDT_Pubnames)
dumpPubSection(OS, "debug_pubnames", getPubNamesSection(),
isLittleEndian(), false);
if (DumpType == DIDT_All || DumpType == DIDT_Pubtypes)
dumpPubSection(OS, "debug_pubtypes", getPubTypesSection(),
isLittleEndian(), false);
if (DumpType == DIDT_All || DumpType == DIDT_GnuPubnames)
dumpPubSection(OS, "debug_gnu_pubnames", getGnuPubNamesSection(),
isLittleEndian(), true /* GnuStyle */);
if (DumpType == DIDT_All || DumpType == DIDT_GnuPubtypes)
dumpPubSection(OS, "debug_gnu_pubtypes", getGnuPubTypesSection(),
isLittleEndian(), true /* GnuStyle */);
if ((DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) &&
!getStringOffsetDWOSection().empty()) {
OS << "\n.debug_str_offsets.dwo contents:\n";
DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(),
0);
offset = 0;
uint64_t size = getStringOffsetDWOSection().size();
while (offset < size) {
OS << format("0x%8.8x: ", offset);
OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
}
}
if (DumpType == DIDT_All || DumpType == DIDT_AppleNames)
dumpAccelSection(OS, "apple_names", getAppleNamesSection(),
getStringSection(), isLittleEndian());
if (DumpType == DIDT_All || DumpType == DIDT_AppleTypes)
dumpAccelSection(OS, "apple_types", getAppleTypesSection(),
getStringSection(), isLittleEndian());
if (DumpType == DIDT_All || DumpType == DIDT_AppleNamespaces)
dumpAccelSection(OS, "apple_namespaces", getAppleNamespacesSection(),
getStringSection(), isLittleEndian());
if (DumpType == DIDT_All || DumpType == DIDT_AppleObjC)
dumpAccelSection(OS, "apple_objc", getAppleObjCSection(),
getStringSection(), isLittleEndian());
}
const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
if (Abbrev)
return Abbrev.get();
DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
Abbrev.reset(new DWARFDebugAbbrev());
Abbrev->extract(abbrData);
return Abbrev.get();
}
const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
if (AbbrevDWO)
return AbbrevDWO.get();
DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
AbbrevDWO.reset(new DWARFDebugAbbrev());
AbbrevDWO->extract(abbrData);
return AbbrevDWO.get();
}
const DWARFDebugLoc *DWARFContext::getDebugLoc() {
if (Loc)
return Loc.get();
DataExtractor LocData(getLocSection().Data, isLittleEndian(), 0);
Loc.reset(new DWARFDebugLoc(getLocSection().Relocs));
// assume all compile units have the same address byte size
if (getNumCompileUnits())
Loc->parse(LocData, getCompileUnitAtIndex(0)->getAddressByteSize());
return Loc.get();
}
const DWARFDebugLocDWO *DWARFContext::getDebugLocDWO() {
if (LocDWO)
return LocDWO.get();
DataExtractor LocData(getLocDWOSection().Data, isLittleEndian(), 0);
LocDWO.reset(new DWARFDebugLocDWO());
LocDWO->parse(LocData);
return LocDWO.get();
}
const DWARFDebugAranges *DWARFContext::getDebugAranges() {
if (Aranges)
return Aranges.get();
Aranges.reset(new DWARFDebugAranges());
Aranges->generate(this);
return Aranges.get();
}
const DWARFDebugFrame *DWARFContext::getDebugFrame() {
if (DebugFrame)
return DebugFrame.get();
// There's a "bug" in the DWARFv3 standard with respect to the target address
// size within debug frame sections. While DWARF is supposed to be independent
// of its container, FDEs have fields with size being "target address size",
// which isn't specified in DWARF in general. It's only specified for CUs, but
// .eh_frame can appear without a .debug_info section. Follow the example of
// other tools (libdwarf) and extract this from the container (ObjectFile
// provides this information). This problem is fixed in DWARFv4
// See this dwarf-discuss discussion for more details:
// http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
getAddressSize());
DebugFrame.reset(new DWARFDebugFrame());
DebugFrame->parse(debugFrameData);
return DebugFrame.get();
}
const DWARFLineTable *
DWARFContext::getLineTableForUnit(DWARFUnit *U) {
if (!Line)
Line.reset(new DWARFDebugLine(&getLineSection().Relocs));
const auto *UnitDIE = U->getUnitDIE();
if (UnitDIE == nullptr)
return nullptr;
unsigned stmtOffset =
UnitDIE->getAttributeValueAsSectionOffset(U, DW_AT_stmt_list, -1U);
if (stmtOffset == -1U)
return nullptr; // No line table for this compile unit.
// See if the line table is cached.
if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
return lt;
// We have to parse it first.
DataExtractor lineData(getLineSection().Data, isLittleEndian(),
U->getAddressByteSize());
return Line->getOrParseLineTable(lineData, stmtOffset);
}
void DWARFContext::parseCompileUnits() {
CUs.parse(*this, getInfoSection());
}
void DWARFContext::parseTypeUnits() {
if (!TUs.empty())
return;
for (const auto &I : getTypesSections()) {
TUs.emplace_back();
TUs.back().parse(*this, I.second);
}
}
void DWARFContext::parseDWOCompileUnits() {
DWOCUs.parseDWO(*this, getInfoDWOSection());
}
void DWARFContext::parseDWOTypeUnits() {
if (!DWOTUs.empty())
return;
for (const auto &I : getTypesDWOSections()) {
DWOTUs.emplace_back();
DWOTUs.back().parseDWO(*this, I.second);
}
}
DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
parseCompileUnits();
return CUs.getUnitForOffset(Offset);
}
DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
// First, get the offset of the compile unit.
uint32_t CUOffset = getDebugAranges()->findAddress(Address);
// Retrieve the compile unit.
return getCompileUnitForOffset(CUOffset);
}
static bool getFunctionNameForAddress(DWARFCompileUnit *CU, uint64_t Address,
FunctionNameKind Kind,
std::string &FunctionName) {
if (Kind == FunctionNameKind::None)
return false;
// The address may correspond to instruction in some inlined function,
// so we have to build the chain of inlined functions and take the
// name of the topmost function in it.
const DWARFDebugInfoEntryInlinedChain &InlinedChain =
CU->getInlinedChainForAddress(Address);
if (InlinedChain.DIEs.size() == 0)
return false;
const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain.DIEs[0];
if (const char *Name =
TopFunctionDIE.getSubroutineName(InlinedChain.U, Kind)) {
FunctionName = Name;
return true;
}
return false;
}
DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
DILineInfoSpecifier Spec) {
DILineInfo Result;
DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
if (!CU)
return Result;
getFunctionNameForAddress(CU, Address, Spec.FNKind, Result.FunctionName);
if (Spec.FLIKind != FileLineInfoKind::None) {
if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
Spec.FLIKind, Result);
}
return Result;
}
DILineInfoTable
DWARFContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
DILineInfoSpecifier Spec) {
DILineInfoTable Lines;
DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
if (!CU)
return Lines;
std::string FunctionName = "<invalid>";
getFunctionNameForAddress(CU, Address, Spec.FNKind, FunctionName);
// If the Specifier says we don't need FileLineInfo, just
// return the top-most function at the starting address.
if (Spec.FLIKind == FileLineInfoKind::None) {
DILineInfo Result;
Result.FunctionName = FunctionName;
Lines.push_back(std::make_pair(Address, Result));
return Lines;
}
const DWARFLineTable *LineTable = getLineTableForUnit(CU);
// Get the index of row we're looking for in the line table.
std::vector<uint32_t> RowVector;
if (!LineTable->lookupAddressRange(Address, Size, RowVector))
return Lines;
for (uint32_t RowIndex : RowVector) {
// Take file number and line/column from the row.
const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
DILineInfo Result;
LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
Spec.FLIKind, Result.FileName);
Result.FunctionName = FunctionName;
Result.Line = Row.Line;
Result.Column = Row.Column;
Lines.push_back(std::make_pair(Row.Address, Result));
}
return Lines;
}
DIInliningInfo
DWARFContext::getInliningInfoForAddress(uint64_t Address,
DILineInfoSpecifier Spec) {
DIInliningInfo InliningInfo;
DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
if (!CU)
return InliningInfo;
const DWARFLineTable *LineTable = nullptr;
const DWARFDebugInfoEntryInlinedChain &InlinedChain =
CU->getInlinedChainForAddress(Address);
if (InlinedChain.DIEs.size() == 0) {
// If there is no DIE for address (e.g. it is in unavailable .dwo file),
// try to at least get file/line info from symbol table.
if (Spec.FLIKind != FileLineInfoKind::None) {
DILineInfo Frame;
LineTable = getLineTableForUnit(CU);
if (LineTable &&
LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
Spec.FLIKind, Frame))
InliningInfo.addFrame(Frame);
}
return InliningInfo;
}
uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
for (uint32_t i = 0, n = InlinedChain.DIEs.size(); i != n; i++) {
const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain.DIEs[i];
DILineInfo Frame;
// Get function name if necessary.
if (const char *Name =
FunctionDIE.getSubroutineName(InlinedChain.U, Spec.FNKind))
Frame.FunctionName = Name;
if (Spec.FLIKind != FileLineInfoKind::None) {
if (i == 0) {
// For the topmost frame, initialize the line table of this
// compile unit and fetch file/line info from it.
LineTable = getLineTableForUnit(CU);
// For the topmost routine, get file/line info from line table.
if (LineTable)
LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
Spec.FLIKind, Frame);
} else {
// Otherwise, use call file, call line and call column from
// previous DIE in inlined chain.
if (LineTable)
LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
Spec.FLIKind, Frame.FileName);
Frame.Line = CallLine;
Frame.Column = CallColumn;
}
// Get call file/line/column of a current DIE.
if (i + 1 < n) {
FunctionDIE.getCallerFrame(InlinedChain.U, CallFile, CallLine,
CallColumn);
}
}
InliningInfo.addFrame(Frame);
}
return InliningInfo;
}
static bool consumeCompressedDebugSectionHeader(StringRef &data,
uint64_t &OriginalSize) {
// Consume "ZLIB" prefix.
if (!data.startswith("ZLIB"))
return false;
data = data.substr(4);
// Consume uncompressed section size (big-endian 8 bytes).
DataExtractor extractor(data, false, 8);
uint32_t Offset = 0;
OriginalSize = extractor.getU64(&Offset);
if (Offset == 0)
return false;
data = data.substr(Offset);
return true;
}
DWARFContextInMemory::DWARFContextInMemory(const object::ObjectFile &Obj,
const LoadedObjectInfo *L)
: IsLittleEndian(Obj.isLittleEndian()),
AddressSize(Obj.getBytesInAddress()) {
for (const SectionRef &Section : Obj.sections()) {
StringRef name;
Section.getName(name);
// Skip BSS and Virtual sections, they aren't interesting.
bool IsBSS = Section.isBSS();
if (IsBSS)
continue;
bool IsVirtual = Section.isVirtual();
if (IsVirtual)
continue;
StringRef data;
// Try to obtain an already relocated version of this section.
// Else use the unrelocated section from the object file. We'll have to
// apply relocations ourselves later.
if (!L || !L->getLoadedSectionContents(name,data))
Section.getContents(data);
name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
// Check if debug info section is compressed with zlib.
if (name.startswith("zdebug_")) {
uint64_t OriginalSize;
if (!zlib::isAvailable() ||
!consumeCompressedDebugSectionHeader(data, OriginalSize))
continue;
UncompressedSections.resize(UncompressedSections.size() + 1);
if (zlib::uncompress(data, UncompressedSections.back(), OriginalSize) !=
zlib::StatusOK) {
UncompressedSections.pop_back();
continue;
}
// Make data point to uncompressed section contents and save its contents.
name = name.substr(1);
data = UncompressedSections.back();
}
StringRef *SectionData =
StringSwitch<StringRef *>(name)
.Case("debug_info", &InfoSection.Data)
.Case("debug_abbrev", &AbbrevSection)
.Case("debug_loc", &LocSection.Data)
.Case("debug_line", &LineSection.Data)
.Case("debug_aranges", &ARangeSection)
.Case("debug_frame", &DebugFrameSection)
.Case("debug_str", &StringSection)
.Case("debug_ranges", &RangeSection)
.Case("debug_pubnames", &PubNamesSection)
.Case("debug_pubtypes", &PubTypesSection)
.Case("debug_gnu_pubnames", &GnuPubNamesSection)
.Case("debug_gnu_pubtypes", &GnuPubTypesSection)
.Case("debug_info.dwo", &InfoDWOSection.Data)
.Case("debug_abbrev.dwo", &AbbrevDWOSection)
.Case("debug_loc.dwo", &LocDWOSection.Data)
.Case("debug_line.dwo", &LineDWOSection.Data)
.Case("debug_str.dwo", &StringDWOSection)
.Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
.Case("debug_addr", &AddrSection)
.Case("apple_names", &AppleNamesSection.Data)
.Case("apple_types", &AppleTypesSection.Data)
.Case("apple_namespaces", &AppleNamespacesSection.Data)
.Case("apple_namespac", &AppleNamespacesSection.Data)
.Case("apple_objc", &AppleObjCSection.Data)
// Any more debug info sections go here.
.Default(nullptr);
if (SectionData) {
*SectionData = data;
if (name == "debug_ranges") {
// FIXME: Use the other dwo range section when we emit it.
RangeDWOSection = data;
}
} else if (name == "debug_types") {
// Find debug_types data by section rather than name as there are
// multiple, comdat grouped, debug_types sections.
TypesSections[Section].Data = data;
} else if (name == "debug_types.dwo") {
TypesDWOSections[Section].Data = data;
}
section_iterator RelocatedSection = Section.getRelocatedSection();
if (RelocatedSection == Obj.section_end())
continue;
StringRef RelSecName;
StringRef RelSecData;
RelocatedSection->getName(RelSecName);
// If the section we're relocating was relocated already by the JIT,
// then we used the relocated version above, so we do not need to process
// relocations for it now.
if (L && L->getLoadedSectionContents(RelSecName,RelSecData))
continue;
RelSecName = RelSecName.substr(
RelSecName.find_first_not_of("._")); // Skip . and _ prefixes.
// TODO: Add support for relocations in other sections as needed.
// Record relocations for the debug_info and debug_line sections.
RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(RelSecName)
.Case("debug_info", &InfoSection.Relocs)
.Case("debug_loc", &LocSection.Relocs)
.Case("debug_info.dwo", &InfoDWOSection.Relocs)
.Case("debug_line", &LineSection.Relocs)
.Case("apple_names", &AppleNamesSection.Relocs)
.Case("apple_types", &AppleTypesSection.Relocs)
.Case("apple_namespaces", &AppleNamespacesSection.Relocs)
.Case("apple_namespac", &AppleNamespacesSection.Relocs)
.Case("apple_objc", &AppleObjCSection.Relocs)
.Default(nullptr);
if (!Map) {
// Find debug_types relocs by section rather than name as there are
// multiple, comdat grouped, debug_types sections.
if (RelSecName == "debug_types")
Map = &TypesSections[*RelocatedSection].Relocs;
else if (RelSecName == "debug_types.dwo")
Map = &TypesDWOSections[*RelocatedSection].Relocs;
else
continue;
}
if (Section.relocation_begin() != Section.relocation_end()) {
uint64_t SectionSize = RelocatedSection->getSize();
for (const RelocationRef &Reloc : Section.relocations()) {
uint64_t Address = Reloc.getOffset();
uint64_t Type = Reloc.getType();
uint64_t SymAddr = 0;
uint64_t SectionLoadAddress = 0;
object::symbol_iterator Sym = Reloc.getSymbol();
object::section_iterator RSec = Obj.section_end();
// First calculate the address of the symbol or section as it appears
// in the objct file
if (Sym != Obj.symbol_end()) {
ErrorOr<uint64_t> SymAddrOrErr = Sym->getAddress();
if (std::error_code EC = SymAddrOrErr.getError()) {
errs() << "error: failed to compute symbol address: "
<< EC.message() << '\n';
continue;
}
SymAddr = *SymAddrOrErr;
// Also remember what section this symbol is in for later
Sym->getSection(RSec);
} else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
// MachO also has relocations that point to sections and
// scattered relocations.
// FIXME: We are not handling scattered relocations, do we have to?
RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
SymAddr = RSec->getAddress();
}
// If we are given load addresses for the sections, we need to adjust:
// SymAddr = (Address of Symbol Or Section in File) -
// (Address of Section in File) +
// (Load Address of Section)
if (L != nullptr && RSec != Obj.section_end()) {
// RSec is now either the section being targetted or the section
// containing the symbol being targetted. In either case,
// we need to perform the same computation.
StringRef SecName;
RSec->getName(SecName);
SectionLoadAddress = L->getSectionLoadAddress(SecName);
if (SectionLoadAddress != 0)
SymAddr += SectionLoadAddress - RSec->getAddress();
}
object::RelocVisitor V(Obj);
object::RelocToApply R(V.visit(Type, Reloc, SymAddr));
if (V.error()) {
SmallString<32> Name;
Reloc.getTypeName(Name);
errs() << "error: failed to compute relocation: "
<< Name << "\n";
continue;
}
if (Address + R.Width > SectionSize) {
errs() << "error: " << R.Width << "-byte relocation starting "
<< Address << " bytes into section " << name << " which is "
<< SectionSize << " bytes long.\n";
continue;
}
if (R.Width > 8) {
errs() << "error: can't handle a relocation of more than 8 bytes at "
"a time.\n";
continue;
}
DEBUG(dbgs() << "Writing " << format("%p", R.Value)
<< " at " << format("%p", Address)
<< " with width " << format("%d", R.Width)
<< "\n");
Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
}
}
}
}
void DWARFContextInMemory::anchor() { }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/CMakeLists.txt | add_llvm_library(LLVMDebugInfoDWARF
DWARFAbbreviationDeclaration.cpp
DWARFAcceleratorTable.cpp
DWARFCompileUnit.cpp
DWARFContext.cpp
DWARFDebugAbbrev.cpp
DWARFDebugArangeSet.cpp
DWARFDebugAranges.cpp
DWARFDebugFrame.cpp
DWARFDebugInfoEntry.cpp
DWARFDebugLine.cpp
DWARFDebugLoc.cpp
DWARFDebugRangeList.cpp
DWARFFormValue.cpp
DWARFTypeUnit.cpp
DWARFUnit.cpp
SyntaxHighlighting.cpp
ADDITIONAL_HEADER_DIRS
${LLVM_MAIN_INCLUDE_DIR}/llvm/DebugInfo/DWARF
${LLVM_MAIN_INCLUDE_DIR}/llvm/DebugInfo
)
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFFormValue.cpp | //===-- DWARFFormValue.cpp ------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "SyntaxHighlighting.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <cassert>
#include <climits>
using namespace llvm;
using namespace dwarf;
using namespace syntax;
namespace {
uint8_t getRefAddrSize(uint8_t AddrSize, uint16_t Version) {
// FIXME: Support DWARF64.
return (Version == 2) ? AddrSize : 4;
}
template <uint8_t AddrSize, uint8_t RefAddrSize>
ArrayRef<uint8_t> makeFixedFormSizesArrayRef() {
static const uint8_t sizes[] = {
0, // 0x00 unused
AddrSize, // 0x01 DW_FORM_addr
0, // 0x02 unused
0, // 0x03 DW_FORM_block2
0, // 0x04 DW_FORM_block4
2, // 0x05 DW_FORM_data2
4, // 0x06 DW_FORM_data4
8, // 0x07 DW_FORM_data8
0, // 0x08 DW_FORM_string
0, // 0x09 DW_FORM_block
0, // 0x0a DW_FORM_block1
1, // 0x0b DW_FORM_data1
1, // 0x0c DW_FORM_flag
0, // 0x0d DW_FORM_sdata
4, // 0x0e DW_FORM_strp
0, // 0x0f DW_FORM_udata
RefAddrSize, // 0x10 DW_FORM_ref_addr
1, // 0x11 DW_FORM_ref1
2, // 0x12 DW_FORM_ref2
4, // 0x13 DW_FORM_ref4
8, // 0x14 DW_FORM_ref8
0, // 0x15 DW_FORM_ref_udata
0, // 0x16 DW_FORM_indirect
4, // 0x17 DW_FORM_sec_offset
0, // 0x18 DW_FORM_exprloc
0, // 0x19 DW_FORM_flag_present
};
return makeArrayRef(sizes);
}
}
ArrayRef<uint8_t> DWARFFormValue::getFixedFormSizes(uint8_t AddrSize,
uint16_t Version) {
uint8_t RefAddrSize = getRefAddrSize(AddrSize, Version);
if (AddrSize == 4 && RefAddrSize == 4)
return makeFixedFormSizesArrayRef<4, 4>();
if (AddrSize == 4 && RefAddrSize == 8)
return makeFixedFormSizesArrayRef<4, 8>();
if (AddrSize == 8 && RefAddrSize == 4)
return makeFixedFormSizesArrayRef<8, 4>();
if (AddrSize == 8 && RefAddrSize == 8)
return makeFixedFormSizesArrayRef<8, 8>();
return None;
}
static const DWARFFormValue::FormClass DWARF4FormClasses[] = {
DWARFFormValue::FC_Unknown, // 0x0
DWARFFormValue::FC_Address, // 0x01 DW_FORM_addr
DWARFFormValue::FC_Unknown, // 0x02 unused
DWARFFormValue::FC_Block, // 0x03 DW_FORM_block2
DWARFFormValue::FC_Block, // 0x04 DW_FORM_block4
DWARFFormValue::FC_Constant, // 0x05 DW_FORM_data2
// --- These can be FC_SectionOffset in DWARF3 and below:
DWARFFormValue::FC_Constant, // 0x06 DW_FORM_data4
DWARFFormValue::FC_Constant, // 0x07 DW_FORM_data8
// ---
DWARFFormValue::FC_String, // 0x08 DW_FORM_string
DWARFFormValue::FC_Block, // 0x09 DW_FORM_block
DWARFFormValue::FC_Block, // 0x0a DW_FORM_block1
DWARFFormValue::FC_Constant, // 0x0b DW_FORM_data1
DWARFFormValue::FC_Flag, // 0x0c DW_FORM_flag
DWARFFormValue::FC_Constant, // 0x0d DW_FORM_sdata
DWARFFormValue::FC_String, // 0x0e DW_FORM_strp
DWARFFormValue::FC_Constant, // 0x0f DW_FORM_udata
DWARFFormValue::FC_Reference, // 0x10 DW_FORM_ref_addr
DWARFFormValue::FC_Reference, // 0x11 DW_FORM_ref1
DWARFFormValue::FC_Reference, // 0x12 DW_FORM_ref2
DWARFFormValue::FC_Reference, // 0x13 DW_FORM_ref4
DWARFFormValue::FC_Reference, // 0x14 DW_FORM_ref8
DWARFFormValue::FC_Reference, // 0x15 DW_FORM_ref_udata
DWARFFormValue::FC_Indirect, // 0x16 DW_FORM_indirect
DWARFFormValue::FC_SectionOffset, // 0x17 DW_FORM_sec_offset
DWARFFormValue::FC_Exprloc, // 0x18 DW_FORM_exprloc
DWARFFormValue::FC_Flag, // 0x19 DW_FORM_flag_present
};
bool DWARFFormValue::isFormClass(DWARFFormValue::FormClass FC) const {
// First, check DWARF4 form classes.
if (Form < ArrayRef<FormClass>(DWARF4FormClasses).size() &&
DWARF4FormClasses[Form] == FC)
return true;
// Check more forms from DWARF4 and DWARF5 proposals.
switch (Form) {
case DW_FORM_ref_sig8:
case DW_FORM_GNU_ref_alt:
return (FC == FC_Reference);
case DW_FORM_GNU_addr_index:
return (FC == FC_Address);
case DW_FORM_GNU_str_index:
case DW_FORM_GNU_strp_alt:
return (FC == FC_String);
}
// In DWARF3 DW_FORM_data4 and DW_FORM_data8 served also as a section offset.
// Don't check for DWARF version here, as some producers may still do this
// by mistake.
return (Form == DW_FORM_data4 || Form == DW_FORM_data8) &&
FC == FC_SectionOffset;
}
bool DWARFFormValue::extractValue(DataExtractor data, uint32_t *offset_ptr,
const DWARFUnit *cu) {
bool indirect = false;
bool is_block = false;
Value.data = nullptr;
// Read the value for the form into value and follow and DW_FORM_indirect
// instances we run into
do {
indirect = false;
switch (Form) {
case DW_FORM_addr:
case DW_FORM_ref_addr: {
if (!cu)
return false;
uint16_t AddrSize =
(Form == DW_FORM_addr)
? cu->getAddressByteSize()
: getRefAddrSize(cu->getAddressByteSize(), cu->getVersion());
RelocAddrMap::const_iterator AI = cu->getRelocMap()->find(*offset_ptr);
if (AI != cu->getRelocMap()->end()) {
const std::pair<uint8_t, int64_t> &R = AI->second;
Value.uval = data.getUnsigned(offset_ptr, AddrSize) + R.second;
} else
Value.uval = data.getUnsigned(offset_ptr, AddrSize);
break;
}
case DW_FORM_exprloc:
case DW_FORM_block:
Value.uval = data.getULEB128(offset_ptr);
is_block = true;
break;
case DW_FORM_block1:
Value.uval = data.getU8(offset_ptr);
is_block = true;
break;
case DW_FORM_block2:
Value.uval = data.getU16(offset_ptr);
is_block = true;
break;
case DW_FORM_block4:
Value.uval = data.getU32(offset_ptr);
is_block = true;
break;
case DW_FORM_data1:
case DW_FORM_ref1:
case DW_FORM_flag:
Value.uval = data.getU8(offset_ptr);
break;
case DW_FORM_data2:
case DW_FORM_ref2:
Value.uval = data.getU16(offset_ptr);
break;
case DW_FORM_data4:
case DW_FORM_ref4: {
Value.uval = data.getU32(offset_ptr);
if (!cu)
break;
RelocAddrMap::const_iterator AI = cu->getRelocMap()->find(*offset_ptr-4);
if (AI != cu->getRelocMap()->end())
Value.uval += AI->second.second;
break;
}
case DW_FORM_data8:
case DW_FORM_ref8:
Value.uval = data.getU64(offset_ptr);
break;
case DW_FORM_sdata:
Value.sval = data.getSLEB128(offset_ptr);
break;
case DW_FORM_udata:
case DW_FORM_ref_udata:
Value.uval = data.getULEB128(offset_ptr);
break;
case DW_FORM_string:
Value.cstr = data.getCStr(offset_ptr);
break;
case DW_FORM_indirect:
Form = data.getULEB128(offset_ptr);
indirect = true;
break;
case DW_FORM_sec_offset:
case DW_FORM_strp:
case DW_FORM_GNU_ref_alt:
case DW_FORM_GNU_strp_alt: {
// FIXME: This is 64-bit for DWARF64.
Value.uval = data.getU32(offset_ptr);
if (!cu)
break;
RelocAddrMap::const_iterator AI =
cu->getRelocMap()->find(*offset_ptr - 4);
if (AI != cu->getRelocMap()->end())
Value.uval += AI->second.second;
break;
}
case DW_FORM_flag_present:
Value.uval = 1;
break;
case DW_FORM_ref_sig8:
Value.uval = data.getU64(offset_ptr);
break;
case DW_FORM_GNU_addr_index:
case DW_FORM_GNU_str_index:
Value.uval = data.getULEB128(offset_ptr);
break;
default:
return false;
}
} while (indirect);
if (is_block) {
StringRef str = data.getData().substr(*offset_ptr, Value.uval);
Value.data = nullptr;
if (!str.empty()) {
Value.data = reinterpret_cast<const uint8_t *>(str.data());
*offset_ptr += Value.uval;
}
}
return true;
}
bool
DWARFFormValue::skipValue(DataExtractor debug_info_data, uint32_t* offset_ptr,
const DWARFUnit *cu) const {
return DWARFFormValue::skipValue(Form, debug_info_data, offset_ptr, cu);
}
bool
DWARFFormValue::skipValue(uint16_t form, DataExtractor debug_info_data,
uint32_t *offset_ptr, const DWARFUnit *cu) {
bool indirect = false;
do {
switch (form) {
// Blocks if inlined data that have a length field and the data bytes
// inlined in the .debug_info
case DW_FORM_exprloc:
case DW_FORM_block: {
uint64_t size = debug_info_data.getULEB128(offset_ptr);
*offset_ptr += size;
return true;
}
case DW_FORM_block1: {
uint8_t size = debug_info_data.getU8(offset_ptr);
*offset_ptr += size;
return true;
}
case DW_FORM_block2: {
uint16_t size = debug_info_data.getU16(offset_ptr);
*offset_ptr += size;
return true;
}
case DW_FORM_block4: {
uint32_t size = debug_info_data.getU32(offset_ptr);
*offset_ptr += size;
return true;
}
// Inlined NULL terminated C-strings
case DW_FORM_string:
debug_info_data.getCStr(offset_ptr);
return true;
// Compile unit address sized values
case DW_FORM_addr:
*offset_ptr += cu->getAddressByteSize();
return true;
case DW_FORM_ref_addr:
*offset_ptr += getRefAddrSize(cu->getAddressByteSize(), cu->getVersion());
return true;
// 0 byte values - implied from the form.
case DW_FORM_flag_present:
return true;
// 1 byte values
case DW_FORM_data1:
case DW_FORM_flag:
case DW_FORM_ref1:
*offset_ptr += 1;
return true;
// 2 byte values
case DW_FORM_data2:
case DW_FORM_ref2:
*offset_ptr += 2;
return true;
// 4 byte values
case DW_FORM_data4:
case DW_FORM_ref4:
*offset_ptr += 4;
return true;
// 8 byte values
case DW_FORM_data8:
case DW_FORM_ref8:
case DW_FORM_ref_sig8:
*offset_ptr += 8;
return true;
// signed or unsigned LEB 128 values
// case DW_FORM_APPLE_db_str:
case DW_FORM_sdata:
case DW_FORM_udata:
case DW_FORM_ref_udata:
case DW_FORM_GNU_str_index:
case DW_FORM_GNU_addr_index:
debug_info_data.getULEB128(offset_ptr);
return true;
case DW_FORM_indirect:
indirect = true;
form = debug_info_data.getULEB128(offset_ptr);
break;
// FIXME: 4 for DWARF32, 8 for DWARF64.
case DW_FORM_sec_offset:
case DW_FORM_strp:
case DW_FORM_GNU_ref_alt:
case DW_FORM_GNU_strp_alt:
*offset_ptr += 4;
return true;
default:
return false;
}
} while (indirect);
return true;
}
void
DWARFFormValue::dump(raw_ostream &OS, const DWARFUnit *cu) const {
uint64_t uvalue = Value.uval;
bool cu_relative_offset = false;
switch (Form) {
case DW_FORM_addr: OS << format("0x%016" PRIx64, uvalue); break;
case DW_FORM_GNU_addr_index: {
OS << format(" indexed (%8.8x) address = ", (uint32_t)uvalue);
uint64_t Address;
if (cu->getAddrOffsetSectionItem(uvalue, Address))
OS << format("0x%016" PRIx64, Address);
else
OS << "<no .debug_addr section>";
break;
}
case DW_FORM_flag_present: OS << "true"; break;
case DW_FORM_flag:
case DW_FORM_data1: OS << format("0x%02x", (uint8_t)uvalue); break;
case DW_FORM_data2: OS << format("0x%04x", (uint16_t)uvalue); break;
case DW_FORM_data4: OS << format("0x%08x", (uint32_t)uvalue); break;
case DW_FORM_ref_sig8:
case DW_FORM_data8: OS << format("0x%016" PRIx64, uvalue); break;
case DW_FORM_string:
OS << '"';
OS.write_escaped(Value.cstr);
OS << '"';
break;
case DW_FORM_exprloc:
case DW_FORM_block:
case DW_FORM_block1:
case DW_FORM_block2:
case DW_FORM_block4:
if (uvalue > 0) {
switch (Form) {
case DW_FORM_exprloc:
case DW_FORM_block: OS << format("<0x%" PRIx64 "> ", uvalue); break;
case DW_FORM_block1: OS << format("<0x%2.2x> ", (uint8_t)uvalue); break;
case DW_FORM_block2: OS << format("<0x%4.4x> ", (uint16_t)uvalue); break;
case DW_FORM_block4: OS << format("<0x%8.8x> ", (uint32_t)uvalue); break;
default: break;
}
const uint8_t* data_ptr = Value.data;
if (data_ptr) {
// uvalue contains size of block
const uint8_t* end_data_ptr = data_ptr + uvalue;
while (data_ptr < end_data_ptr) {
OS << format("%2.2x ", *data_ptr);
++data_ptr;
}
}
else
OS << "NULL";
}
break;
case DW_FORM_sdata: OS << Value.sval; break;
case DW_FORM_udata: OS << Value.uval; break;
case DW_FORM_strp: {
OS << format(" .debug_str[0x%8.8x] = ", (uint32_t)uvalue);
dumpString(OS, cu);
break;
}
case DW_FORM_GNU_str_index: {
OS << format(" indexed (%8.8x) string = ", (uint32_t)uvalue);
dumpString(OS, cu);
break;
}
case DW_FORM_GNU_strp_alt: {
OS << format("alt indirect string, offset: 0x%" PRIx64 "", uvalue);
dumpString(OS, cu);
break;
}
case DW_FORM_ref_addr:
OS << format("0x%016" PRIx64, uvalue);
break;
case DW_FORM_ref1:
cu_relative_offset = true;
OS << format("cu + 0x%2.2x", (uint8_t)uvalue);
break;
case DW_FORM_ref2:
cu_relative_offset = true;
OS << format("cu + 0x%4.4x", (uint16_t)uvalue);
break;
case DW_FORM_ref4:
cu_relative_offset = true;
OS << format("cu + 0x%4.4x", (uint32_t)uvalue);
break;
case DW_FORM_ref8:
cu_relative_offset = true;
OS << format("cu + 0x%8.8" PRIx64, uvalue);
break;
case DW_FORM_ref_udata:
cu_relative_offset = true;
OS << format("cu + 0x%" PRIx64, uvalue);
break;
case DW_FORM_GNU_ref_alt:
OS << format("<alt 0x%" PRIx64 ">", uvalue);
break;
// All DW_FORM_indirect attributes should be resolved prior to calling
// this function
case DW_FORM_indirect:
OS << "DW_FORM_indirect";
break;
// Should be formatted to 64-bit for DWARF64.
case DW_FORM_sec_offset:
OS << format("0x%08x", (uint32_t)uvalue);
break;
default:
OS << format("DW_FORM(0x%4.4x)", Form);
break;
}
if (cu_relative_offset) {
OS << " => {";
WithColor(OS, syntax::Address).get()
<< format("0x%8.8" PRIx64, uvalue + (cu ? cu->getOffset() : 0));
OS << "}";
}
}
void DWARFFormValue::dumpString(raw_ostream &OS, const DWARFUnit *U) const {
Optional<const char *> DbgStr = getAsCString(U);
if (DbgStr.hasValue()) {
raw_ostream &COS = WithColor(OS, syntax::String);
COS << '"';
COS.write_escaped(DbgStr.getValue());
COS << '"';
}
}
Optional<const char *> DWARFFormValue::getAsCString(const DWARFUnit *U) const {
if (!isFormClass(FC_String))
return None;
if (Form == DW_FORM_string)
return Value.cstr;
// FIXME: Add support for DW_FORM_GNU_strp_alt
if (Form == DW_FORM_GNU_strp_alt || U == nullptr)
return None;
uint32_t Offset = Value.uval;
if (Form == DW_FORM_GNU_str_index) {
uint32_t StrOffset;
if (!U->getStringOffsetSectionItem(Offset, StrOffset))
return None;
Offset = StrOffset;
}
if (const char *Str = U->getStringExtractor().getCStr(&Offset)) {
return Str;
}
return None;
}
Optional<uint64_t> DWARFFormValue::getAsAddress(const DWARFUnit *U) const {
if (!isFormClass(FC_Address))
return None;
if (Form == DW_FORM_GNU_addr_index) {
uint32_t Index = Value.uval;
uint64_t Result;
if (!U || !U->getAddrOffsetSectionItem(Index, Result))
return None;
return Result;
}
return Value.uval;
}
Optional<uint64_t> DWARFFormValue::getAsReference(const DWARFUnit *U) const {
if (!isFormClass(FC_Reference))
return None;
switch (Form) {
case DW_FORM_ref1:
case DW_FORM_ref2:
case DW_FORM_ref4:
case DW_FORM_ref8:
case DW_FORM_ref_udata:
if (!U)
return None;
return Value.uval + U->getOffset();
case DW_FORM_ref_addr:
return Value.uval;
// FIXME: Add proper support for DW_FORM_ref_sig8 and DW_FORM_GNU_ref_alt.
default:
return None;
}
}
Optional<uint64_t> DWARFFormValue::getAsSectionOffset() const {
if (!isFormClass(FC_SectionOffset))
return None;
return Value.uval;
}
Optional<uint64_t> DWARFFormValue::getAsUnsignedConstant() const {
if ((!isFormClass(FC_Constant) && !isFormClass(FC_Flag))
|| Form == DW_FORM_sdata)
return None;
return Value.uval;
}
Optional<int64_t> DWARFFormValue::getAsSignedConstant() const {
if ((!isFormClass(FC_Constant) && !isFormClass(FC_Flag)) ||
(Form == DW_FORM_udata && uint64_t(LLONG_MAX) < Value.uval))
return None;
switch (Form) {
case DW_FORM_data4:
return int32_t(Value.uval);
case DW_FORM_data2:
return int16_t(Value.uval);
case DW_FORM_data1:
return int8_t(Value.uval);
case DW_FORM_sdata:
case DW_FORM_data8:
default:
return Value.sval;
}
}
Optional<ArrayRef<uint8_t>> DWARFFormValue::getAsBlock() const {
if (!isFormClass(FC_Block) && !isFormClass(FC_Exprloc))
return None;
return ArrayRef<uint8_t>(Value.data, Value.uval);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/LLVMBuild.txt | ;===- ./lib/DebugInfo/DWARF/LLVMBuild.txt ----------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = DebugInfoDWARF
parent = DebugInfo
required_libraries = Object Support
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFDebugFrame.cpp | //===-- DWARFDebugFrame.h - Parsing of .debug_frame -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <string>
#include <vector>
using namespace llvm;
using namespace dwarf;
/// \brief Abstract frame entry defining the common interface concrete
/// entries implement.
class llvm::FrameEntry {
public:
enum FrameKind {FK_CIE, FK_FDE};
FrameEntry(FrameKind K, uint64_t Offset, uint64_t Length)
: Kind(K), Offset(Offset), Length(Length) {}
virtual ~FrameEntry() {
}
FrameKind getKind() const { return Kind; }
virtual uint64_t getOffset() const { return Offset; }
/// \brief Parse and store a sequence of CFI instructions from Data,
/// starting at *Offset and ending at EndOffset. If everything
/// goes well, *Offset should be equal to EndOffset when this method
/// returns. Otherwise, an error occurred.
virtual void parseInstructions(DataExtractor Data, uint32_t *Offset,
uint32_t EndOffset);
/// \brief Dump the entry header to the given output stream.
virtual void dumpHeader(raw_ostream &OS) const = 0;
/// \brief Dump the entry's instructions to the given output stream.
virtual void dumpInstructions(raw_ostream &OS) const;
protected:
const FrameKind Kind;
/// \brief Offset of this entry in the section.
uint64_t Offset;
/// \brief Entry length as specified in DWARF.
uint64_t Length;
/// An entry may contain CFI instructions. An instruction consists of an
/// opcode and an optional sequence of operands.
typedef std::vector<uint64_t> Operands;
struct Instruction {
Instruction(uint8_t Opcode)
: Opcode(Opcode)
{}
uint8_t Opcode;
Operands Ops;
};
std::vector<Instruction> Instructions;
/// Convenience methods to add a new instruction with the given opcode and
/// operands to the Instructions vector.
void addInstruction(uint8_t Opcode) {
Instructions.push_back(Instruction(Opcode));
}
void addInstruction(uint8_t Opcode, uint64_t Operand1) {
Instructions.push_back(Instruction(Opcode));
Instructions.back().Ops.push_back(Operand1);
}
void addInstruction(uint8_t Opcode, uint64_t Operand1, uint64_t Operand2) {
Instructions.push_back(Instruction(Opcode));
Instructions.back().Ops.push_back(Operand1);
Instructions.back().Ops.push_back(Operand2);
}
};
// See DWARF standard v3, section 7.23
const uint8_t DWARF_CFI_PRIMARY_OPCODE_MASK = 0xc0;
const uint8_t DWARF_CFI_PRIMARY_OPERAND_MASK = 0x3f;
void FrameEntry::parseInstructions(DataExtractor Data, uint32_t *Offset,
uint32_t EndOffset) {
while (*Offset < EndOffset) {
uint8_t Opcode = Data.getU8(Offset);
// Some instructions have a primary opcode encoded in the top bits.
uint8_t Primary = Opcode & DWARF_CFI_PRIMARY_OPCODE_MASK;
if (Primary) {
// If it's a primary opcode, the first operand is encoded in the bottom
// bits of the opcode itself.
uint64_t Op1 = Opcode & DWARF_CFI_PRIMARY_OPERAND_MASK;
switch (Primary) {
default: llvm_unreachable("Impossible primary CFI opcode");
case DW_CFA_advance_loc:
case DW_CFA_restore:
addInstruction(Primary, Op1);
break;
case DW_CFA_offset:
addInstruction(Primary, Op1, Data.getULEB128(Offset));
break;
}
} else {
// Extended opcode - its value is Opcode itself.
switch (Opcode) {
default: llvm_unreachable("Invalid extended CFI opcode");
case DW_CFA_nop:
case DW_CFA_remember_state:
case DW_CFA_restore_state:
case DW_CFA_GNU_window_save:
// No operands
addInstruction(Opcode);
break;
case DW_CFA_set_loc:
// Operands: Address
addInstruction(Opcode, Data.getAddress(Offset));
break;
case DW_CFA_advance_loc1:
// Operands: 1-byte delta
addInstruction(Opcode, Data.getU8(Offset));
break;
case DW_CFA_advance_loc2:
// Operands: 2-byte delta
addInstruction(Opcode, Data.getU16(Offset));
break;
case DW_CFA_advance_loc4:
// Operands: 4-byte delta
addInstruction(Opcode, Data.getU32(Offset));
break;
case DW_CFA_restore_extended:
case DW_CFA_undefined:
case DW_CFA_same_value:
case DW_CFA_def_cfa_register:
case DW_CFA_def_cfa_offset:
// Operands: ULEB128
addInstruction(Opcode, Data.getULEB128(Offset));
break;
case DW_CFA_def_cfa_offset_sf:
// Operands: SLEB128
addInstruction(Opcode, Data.getSLEB128(Offset));
break;
case DW_CFA_offset_extended:
case DW_CFA_register:
case DW_CFA_def_cfa:
case DW_CFA_val_offset:
// Operands: ULEB128, ULEB128
addInstruction(Opcode, Data.getULEB128(Offset),
Data.getULEB128(Offset));
break;
case DW_CFA_offset_extended_sf:
case DW_CFA_def_cfa_sf:
case DW_CFA_val_offset_sf:
// Operands: ULEB128, SLEB128
addInstruction(Opcode, Data.getULEB128(Offset),
Data.getSLEB128(Offset));
break;
case DW_CFA_def_cfa_expression:
case DW_CFA_expression:
case DW_CFA_val_expression:
// TODO: implement this
report_fatal_error("Values with expressions not implemented yet!");
}
}
}
}
namespace {
/// \brief DWARF Common Information Entry (CIE)
class CIE : public FrameEntry {
public:
// CIEs (and FDEs) are simply container classes, so the only sensible way to
// create them is by providing the full parsed contents in the constructor.
CIE(uint64_t Offset, uint64_t Length, uint8_t Version,
SmallString<8> Augmentation, uint8_t AddressSize,
uint8_t SegmentDescriptorSize, uint64_t CodeAlignmentFactor,
int64_t DataAlignmentFactor, uint64_t ReturnAddressRegister)
: FrameEntry(FK_CIE, Offset, Length), Version(Version),
Augmentation(std::move(Augmentation)),
AddressSize(AddressSize),
SegmentDescriptorSize(SegmentDescriptorSize),
CodeAlignmentFactor(CodeAlignmentFactor),
DataAlignmentFactor(DataAlignmentFactor),
ReturnAddressRegister(ReturnAddressRegister) {}
~CIE() override {}
uint64_t getCodeAlignmentFactor() const { return CodeAlignmentFactor; }
int64_t getDataAlignmentFactor() const { return DataAlignmentFactor; }
void dumpHeader(raw_ostream &OS) const override {
OS << format("%08x %08x %08x CIE",
(uint32_t)Offset, (uint32_t)Length, DW_CIE_ID)
<< "\n";
OS << format(" Version: %d\n", Version);
OS << " Augmentation: \"" << Augmentation << "\"\n";
if (Version >= 4) {
OS << format(" Address size: %u\n",
(uint32_t)AddressSize);
OS << format(" Segment desc size: %u\n",
(uint32_t)SegmentDescriptorSize);
}
OS << format(" Code alignment factor: %u\n",
(uint32_t)CodeAlignmentFactor);
OS << format(" Data alignment factor: %d\n",
(int32_t)DataAlignmentFactor);
OS << format(" Return address column: %d\n",
(int32_t)ReturnAddressRegister);
OS << "\n";
}
static bool classof(const FrameEntry *FE) {
return FE->getKind() == FK_CIE;
}
private:
/// The following fields are defined in section 6.4.1 of the DWARF standard v4
uint8_t Version;
SmallString<8> Augmentation;
uint8_t AddressSize;
uint8_t SegmentDescriptorSize;
uint64_t CodeAlignmentFactor;
int64_t DataAlignmentFactor;
uint64_t ReturnAddressRegister;
};
/// \brief DWARF Frame Description Entry (FDE)
class FDE : public FrameEntry {
public:
// Each FDE has a CIE it's "linked to". Our FDE contains is constructed with
// an offset to the CIE (provided by parsing the FDE header). The CIE itself
// is obtained lazily once it's actually required.
FDE(uint64_t Offset, uint64_t Length, int64_t LinkedCIEOffset,
uint64_t InitialLocation, uint64_t AddressRange,
CIE *Cie)
: FrameEntry(FK_FDE, Offset, Length), LinkedCIEOffset(LinkedCIEOffset),
InitialLocation(InitialLocation), AddressRange(AddressRange),
LinkedCIE(Cie) {}
~FDE() override {}
CIE *getLinkedCIE() const { return LinkedCIE; }
void dumpHeader(raw_ostream &OS) const override {
OS << format("%08x %08x %08x FDE ",
(uint32_t)Offset, (uint32_t)Length, (int32_t)LinkedCIEOffset);
OS << format("cie=%08x pc=%08x...%08x\n",
(int32_t)LinkedCIEOffset,
(uint32_t)InitialLocation,
(uint32_t)InitialLocation + (uint32_t)AddressRange);
}
static bool classof(const FrameEntry *FE) {
return FE->getKind() == FK_FDE;
}
private:
/// The following fields are defined in section 6.4.1 of the DWARF standard v3
uint64_t LinkedCIEOffset;
uint64_t InitialLocation;
uint64_t AddressRange;
CIE *LinkedCIE;
};
/// \brief Types of operands to CF instructions.
enum OperandType {
OT_Unset,
OT_None,
OT_Address,
OT_Offset,
OT_FactoredCodeOffset,
OT_SignedFactDataOffset,
OT_UnsignedFactDataOffset,
OT_Register,
OT_Expression
};
} // end anonymous namespace
/// \brief Initialize the array describing the types of operands.
static ArrayRef<OperandType[2]> getOperandTypes() {
static OperandType OpTypes[DW_CFA_restore+1][2];
#define DECLARE_OP2(OP, OPTYPE0, OPTYPE1) \
do { \
OpTypes[OP][0] = OPTYPE0; \
OpTypes[OP][1] = OPTYPE1; \
} while (0)
#define DECLARE_OP1(OP, OPTYPE0) DECLARE_OP2(OP, OPTYPE0, OT_None)
#define DECLARE_OP0(OP) DECLARE_OP1(OP, OT_None)
DECLARE_OP1(DW_CFA_set_loc, OT_Address);
DECLARE_OP1(DW_CFA_advance_loc, OT_FactoredCodeOffset);
DECLARE_OP1(DW_CFA_advance_loc1, OT_FactoredCodeOffset);
DECLARE_OP1(DW_CFA_advance_loc2, OT_FactoredCodeOffset);
DECLARE_OP1(DW_CFA_advance_loc4, OT_FactoredCodeOffset);
DECLARE_OP1(DW_CFA_MIPS_advance_loc8, OT_FactoredCodeOffset);
DECLARE_OP2(DW_CFA_def_cfa, OT_Register, OT_Offset);
DECLARE_OP2(DW_CFA_def_cfa_sf, OT_Register, OT_SignedFactDataOffset);
DECLARE_OP1(DW_CFA_def_cfa_register, OT_Register);
DECLARE_OP1(DW_CFA_def_cfa_offset, OT_Offset);
DECLARE_OP1(DW_CFA_def_cfa_offset_sf, OT_SignedFactDataOffset);
DECLARE_OP1(DW_CFA_def_cfa_expression, OT_Expression);
DECLARE_OP1(DW_CFA_undefined, OT_Register);
DECLARE_OP1(DW_CFA_same_value, OT_Register);
DECLARE_OP2(DW_CFA_offset, OT_Register, OT_UnsignedFactDataOffset);
DECLARE_OP2(DW_CFA_offset_extended, OT_Register, OT_UnsignedFactDataOffset);
DECLARE_OP2(DW_CFA_offset_extended_sf, OT_Register, OT_SignedFactDataOffset);
DECLARE_OP2(DW_CFA_val_offset, OT_Register, OT_UnsignedFactDataOffset);
DECLARE_OP2(DW_CFA_val_offset_sf, OT_Register, OT_SignedFactDataOffset);
DECLARE_OP2(DW_CFA_register, OT_Register, OT_Register);
DECLARE_OP2(DW_CFA_expression, OT_Register, OT_Expression);
DECLARE_OP2(DW_CFA_val_expression, OT_Register, OT_Expression);
DECLARE_OP1(DW_CFA_restore, OT_Register);
DECLARE_OP1(DW_CFA_restore_extended, OT_Register);
DECLARE_OP0(DW_CFA_remember_state);
DECLARE_OP0(DW_CFA_restore_state);
DECLARE_OP0(DW_CFA_GNU_window_save);
DECLARE_OP1(DW_CFA_GNU_args_size, OT_Offset);
DECLARE_OP0(DW_CFA_nop);
#undef DECLARE_OP0
#undef DECLARE_OP1
#undef DECLARE_OP2
return ArrayRef<OperandType[2]>(&OpTypes[0], DW_CFA_restore+1);
}
static ArrayRef<OperandType[2]> OpTypes = getOperandTypes();
/// \brief Print \p Opcode's operand number \p OperandIdx which has
/// value \p Operand.
static void printOperand(raw_ostream &OS, uint8_t Opcode, unsigned OperandIdx,
uint64_t Operand, uint64_t CodeAlignmentFactor,
int64_t DataAlignmentFactor) {
assert(OperandIdx < 2);
OperandType Type = OpTypes[Opcode][OperandIdx];
switch (Type) {
case OT_Unset:
OS << " Unsupported " << (OperandIdx ? "second" : "first") << " operand to";
if (const char *OpcodeName = CallFrameString(Opcode))
OS << " " << OpcodeName;
else
OS << format(" Opcode %x", Opcode);
break;
case OT_None:
break;
case OT_Address:
OS << format(" %" PRIx64, Operand);
break;
case OT_Offset:
// The offsets are all encoded in a unsigned form, but in practice
// consumers use them signed. It's most certainly legacy due to
// the lack of signed variants in the first Dwarf standards.
OS << format(" %+" PRId64, int64_t(Operand));
break;
case OT_FactoredCodeOffset: // Always Unsigned
if (CodeAlignmentFactor)
OS << format(" %" PRId64, Operand * CodeAlignmentFactor);
else
OS << format(" %" PRId64 "*code_alignment_factor" , Operand);
break;
case OT_SignedFactDataOffset:
if (DataAlignmentFactor)
OS << format(" %" PRId64, int64_t(Operand) * DataAlignmentFactor);
else
OS << format(" %" PRId64 "*data_alignment_factor" , int64_t(Operand));
break;
case OT_UnsignedFactDataOffset:
if (DataAlignmentFactor)
OS << format(" %" PRId64, Operand * DataAlignmentFactor);
else
OS << format(" %" PRId64 "*data_alignment_factor" , Operand);
break;
case OT_Register:
OS << format(" reg%" PRId64, Operand);
break;
case OT_Expression:
OS << " expression";
break;
}
}
void FrameEntry::dumpInstructions(raw_ostream &OS) const {
uint64_t CodeAlignmentFactor = 0;
int64_t DataAlignmentFactor = 0;
const CIE *Cie = dyn_cast<CIE>(this);
if (!Cie)
Cie = cast<FDE>(this)->getLinkedCIE();
if (Cie) {
CodeAlignmentFactor = Cie->getCodeAlignmentFactor();
DataAlignmentFactor = Cie->getDataAlignmentFactor();
}
for (const auto &Instr : Instructions) {
uint8_t Opcode = Instr.Opcode;
if (Opcode & DWARF_CFI_PRIMARY_OPCODE_MASK)
Opcode &= DWARF_CFI_PRIMARY_OPCODE_MASK;
OS << " " << CallFrameString(Opcode) << ":";
for (unsigned i = 0; i < Instr.Ops.size(); ++i)
printOperand(OS, Opcode, i, Instr.Ops[i], CodeAlignmentFactor,
DataAlignmentFactor);
OS << '\n';
}
}
DWARFDebugFrame::DWARFDebugFrame() {
}
DWARFDebugFrame::~DWARFDebugFrame() {
}
static void LLVM_ATTRIBUTE_UNUSED dumpDataAux(DataExtractor Data,
uint32_t Offset, int Length) {
errs() << "DUMP: ";
for (int i = 0; i < Length; ++i) {
uint8_t c = Data.getU8(&Offset);
errs().write_hex(c); errs() << " ";
}
errs() << "\n";
}
void DWARFDebugFrame::parse(DataExtractor Data) {
uint32_t Offset = 0;
DenseMap<uint32_t, CIE *> CIEs;
while (Data.isValidOffset(Offset)) {
uint32_t StartOffset = Offset;
bool IsDWARF64 = false;
uint64_t Length = Data.getU32(&Offset);
uint64_t Id;
if (Length == UINT32_MAX) {
// DWARF-64 is distinguished by the first 32 bits of the initial length
// field being 0xffffffff. Then, the next 64 bits are the actual entry
// length.
IsDWARF64 = true;
Length = Data.getU64(&Offset);
}
// At this point, Offset points to the next field after Length.
// Length is the structure size excluding itself. Compute an offset one
// past the end of the structure (needed to know how many instructions to
// read).
// TODO: For honest DWARF64 support, DataExtractor will have to treat
// offset_ptr as uint64_t*
uint32_t EndStructureOffset = Offset + static_cast<uint32_t>(Length);
// The Id field's size depends on the DWARF format
Id = Data.getUnsigned(&Offset, IsDWARF64 ? 8 : 4);
bool IsCIE = ((IsDWARF64 && Id == DW64_CIE_ID) || Id == DW_CIE_ID);
if (IsCIE) {
uint8_t Version = Data.getU8(&Offset);
const char *Augmentation = Data.getCStr(&Offset);
uint8_t AddressSize = Version < 4 ? Data.getAddressSize() : Data.getU8(&Offset);
Data.setAddressSize(AddressSize);
uint8_t SegmentDescriptorSize = Version < 4 ? 0 : Data.getU8(&Offset);
uint64_t CodeAlignmentFactor = Data.getULEB128(&Offset);
int64_t DataAlignmentFactor = Data.getSLEB128(&Offset);
uint64_t ReturnAddressRegister = Data.getULEB128(&Offset);
auto Cie = make_unique<CIE>(StartOffset, Length, Version,
StringRef(Augmentation), AddressSize,
SegmentDescriptorSize, CodeAlignmentFactor,
DataAlignmentFactor, ReturnAddressRegister);
CIEs[StartOffset] = Cie.get();
Entries.emplace_back(std::move(Cie));
} else {
// FDE
uint64_t CIEPointer = Id;
uint64_t InitialLocation = Data.getAddress(&Offset);
uint64_t AddressRange = Data.getAddress(&Offset);
Entries.emplace_back(new FDE(StartOffset, Length, CIEPointer,
InitialLocation, AddressRange,
CIEs[CIEPointer]));
}
Entries.back()->parseInstructions(Data, &Offset, EndStructureOffset);
if (Offset != EndStructureOffset) {
std::string Str;
raw_string_ostream OS(Str);
OS << format("Parsing entry instructions at %lx failed", StartOffset);
report_fatal_error(Str);
}
}
}
void DWARFDebugFrame::dump(raw_ostream &OS) const {
OS << "\n";
for (const auto &Entry : Entries) {
Entry->dumpHeader(OS);
Entry->dumpInstructions(OS);
OS << "\n";
}
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/module.modulemap | module DebugInfoDWARF { requires cplusplus umbrella "." module * { export * } }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFDebugAbbrev.cpp | //===-- DWARFDebugAbbrev.cpp ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
DWARFAbbreviationDeclarationSet::DWARFAbbreviationDeclarationSet() {
clear();
}
void DWARFAbbreviationDeclarationSet::clear() {
Offset = 0;
FirstAbbrCode = 0;
Decls.clear();
}
bool DWARFAbbreviationDeclarationSet::extract(DataExtractor Data,
uint32_t *OffsetPtr) {
clear();
const uint32_t BeginOffset = *OffsetPtr;
Offset = BeginOffset;
DWARFAbbreviationDeclaration AbbrDecl;
uint32_t PrevAbbrCode = 0;
while (AbbrDecl.extract(Data, OffsetPtr)) {
if (FirstAbbrCode == 0) {
FirstAbbrCode = AbbrDecl.getCode();
} else {
if (PrevAbbrCode + 1 != AbbrDecl.getCode()) {
// Codes are not consecutive, can't do O(1) lookups.
FirstAbbrCode = UINT32_MAX;
}
}
PrevAbbrCode = AbbrDecl.getCode();
Decls.push_back(std::move(AbbrDecl));
}
return BeginOffset != *OffsetPtr;
}
void DWARFAbbreviationDeclarationSet::dump(raw_ostream &OS) const {
for (const auto &Decl : Decls)
Decl.dump(OS);
}
const DWARFAbbreviationDeclaration *
DWARFAbbreviationDeclarationSet::getAbbreviationDeclaration(
uint32_t AbbrCode) const {
if (FirstAbbrCode == UINT32_MAX) {
for (const auto &Decl : Decls) {
if (Decl.getCode() == AbbrCode)
return &Decl;
}
return nullptr;
}
if (AbbrCode < FirstAbbrCode || AbbrCode >= FirstAbbrCode + Decls.size())
return nullptr;
return &Decls[AbbrCode - FirstAbbrCode];
}
DWARFDebugAbbrev::DWARFDebugAbbrev() {
clear();
}
void DWARFDebugAbbrev::clear() {
AbbrDeclSets.clear();
PrevAbbrOffsetPos = AbbrDeclSets.end();
}
void DWARFDebugAbbrev::extract(DataExtractor Data) {
clear();
uint32_t Offset = 0;
DWARFAbbreviationDeclarationSet AbbrDecls;
while (Data.isValidOffset(Offset)) {
uint32_t CUAbbrOffset = Offset;
if (!AbbrDecls.extract(Data, &Offset))
break;
AbbrDeclSets[CUAbbrOffset] = std::move(AbbrDecls);
}
}
void DWARFDebugAbbrev::dump(raw_ostream &OS) const {
if (AbbrDeclSets.empty()) {
OS << "< EMPTY >\n";
return;
}
for (const auto &I : AbbrDeclSets) {
OS << format("Abbrev table for offset: 0x%8.8" PRIx64 "\n", I.first);
I.second.dump(OS);
}
}
const DWARFAbbreviationDeclarationSet*
DWARFDebugAbbrev::getAbbreviationDeclarationSet(uint64_t CUAbbrOffset) const {
const auto End = AbbrDeclSets.end();
if (PrevAbbrOffsetPos != End && PrevAbbrOffsetPos->first == CUAbbrOffset) {
return &(PrevAbbrOffsetPos->second);
}
const auto Pos = AbbrDeclSets.find(CUAbbrOffset);
if (Pos != End) {
PrevAbbrOffsetPos = Pos;
return &(Pos->second);
}
return nullptr;
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFDebugArangeSet.cpp | //===-- DWARFDebugArangeSet.cpp -------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFDebugArangeSet.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
using namespace llvm;
void DWARFDebugArangeSet::clear() {
Offset = -1U;
std::memset(&HeaderData, 0, sizeof(Header));
ArangeDescriptors.clear();
}
bool
DWARFDebugArangeSet::extract(DataExtractor data, uint32_t *offset_ptr) {
if (data.isValidOffset(*offset_ptr)) {
ArangeDescriptors.clear();
Offset = *offset_ptr;
// 7.20 Address Range Table
//
// Each set of entries in the table of address ranges contained in
// the .debug_aranges section begins with a header consisting of: a
// 4-byte length containing the length of the set of entries for this
// compilation unit, not including the length field itself; a 2-byte
// version identifier containing the value 2 for DWARF Version 2; a
// 4-byte offset into the.debug_infosection; a 1-byte unsigned integer
// containing the size in bytes of an address (or the offset portion of
// an address for segmented addressing) on the target system; and a
// 1-byte unsigned integer containing the size in bytes of a segment
// descriptor on the target system. This header is followed by a series
// of tuples. Each tuple consists of an address and a length, each in
// the size appropriate for an address on the target architecture.
HeaderData.Length = data.getU32(offset_ptr);
HeaderData.Version = data.getU16(offset_ptr);
HeaderData.CuOffset = data.getU32(offset_ptr);
HeaderData.AddrSize = data.getU8(offset_ptr);
HeaderData.SegSize = data.getU8(offset_ptr);
// Perform basic validation of the header fields.
if (!data.isValidOffsetForDataOfSize(Offset, HeaderData.Length) ||
(HeaderData.AddrSize != 4 && HeaderData.AddrSize != 8)) {
clear();
return false;
}
// The first tuple following the header in each set begins at an offset
// that is a multiple of the size of a single tuple (that is, twice the
// size of an address). The header is padded, if necessary, to the
// appropriate boundary.
const uint32_t header_size = *offset_ptr - Offset;
const uint32_t tuple_size = HeaderData.AddrSize * 2;
uint32_t first_tuple_offset = 0;
while (first_tuple_offset < header_size)
first_tuple_offset += tuple_size;
*offset_ptr = Offset + first_tuple_offset;
Descriptor arangeDescriptor;
static_assert(sizeof(arangeDescriptor.Address) ==
sizeof(arangeDescriptor.Length),
"Different datatypes for addresses and sizes!");
assert(sizeof(arangeDescriptor.Address) >= HeaderData.AddrSize);
while (data.isValidOffset(*offset_ptr)) {
arangeDescriptor.Address = data.getUnsigned(offset_ptr, HeaderData.AddrSize);
arangeDescriptor.Length = data.getUnsigned(offset_ptr, HeaderData.AddrSize);
// Each set of tuples is terminated by a 0 for the address and 0
// for the length.
if (arangeDescriptor.Address || arangeDescriptor.Length)
ArangeDescriptors.push_back(arangeDescriptor);
else
break; // We are done if we get a zero address and length
}
return !ArangeDescriptors.empty();
}
return false;
}
void DWARFDebugArangeSet::dump(raw_ostream &OS) const {
OS << format("Address Range Header: length = 0x%8.8x, version = 0x%4.4x, ",
HeaderData.Length, HeaderData.Version)
<< format("cu_offset = 0x%8.8x, addr_size = 0x%2.2x, seg_size = 0x%2.2x\n",
HeaderData.CuOffset, HeaderData.AddrSize, HeaderData.SegSize);
const uint32_t hex_width = HeaderData.AddrSize * 2;
for (const auto &Desc : ArangeDescriptors) {
OS << format("[0x%*.*" PRIx64 " -", hex_width, hex_width, Desc.Address)
<< format(" 0x%*.*" PRIx64 ")\n",
hex_width, hex_width, Desc.getEndAddress());
}
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFCompileUnit.cpp | //===-- DWARFCompileUnit.cpp ----------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
void DWARFCompileUnit::dump(raw_ostream &OS) {
OS << format("0x%08x", getOffset()) << ": Compile Unit:"
<< " length = " << format("0x%08x", getLength())
<< " version = " << format("0x%04x", getVersion())
<< " abbr_offset = " << format("0x%04x", getAbbreviations()->getOffset())
<< " addr_size = " << format("0x%02x", getAddressByteSize())
<< " (next unit at " << format("0x%08x", getNextUnitOffset())
<< ")\n";
if (const DWARFDebugInfoEntryMinimal *CU = getUnitDIE(false))
CU->dump(OS, this, -1U);
else
OS << "<compile unit can't be parsed!>\n\n";
}
// VTable anchor.
DWARFCompileUnit::~DWARFCompileUnit() {
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/SyntaxHighlighting.cpp | //===-- SyntaxHighlighting.cpp ----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "SyntaxHighlighting.h"
#include "llvm/Support/CommandLine.h"
using namespace llvm;
using namespace dwarf;
using namespace syntax;
static cl::opt<cl::boolOrDefault>
UseColor("color",
cl::desc("use colored syntax highlighting (default=autodetect)"),
cl::init(cl::BOU_UNSET));
WithColor::WithColor(llvm::raw_ostream &OS, enum HighlightColor Type) : OS(OS) {
// Detect color from terminal type unless the user passed the --color option.
if (UseColor == cl::BOU_UNSET ? OS.has_colors() : UseColor == cl::BOU_TRUE) {
switch (Type) {
case Address: OS.changeColor(llvm::raw_ostream::YELLOW); break;
case String: OS.changeColor(llvm::raw_ostream::GREEN); break;
case Tag: OS.changeColor(llvm::raw_ostream::BLUE); break;
case Attribute: OS.changeColor(llvm::raw_ostream::CYAN); break;
case Enumerator: OS.changeColor(llvm::raw_ostream::MAGENTA); break;
}
}
}
WithColor::~WithColor() {
if (UseColor == cl::BOU_UNSET ? OS.has_colors() : UseColor == cl::BOU_TRUE)
OS.resetColor();
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFTypeUnit.cpp | //===-- DWARFTypeUnit.cpp -------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
bool DWARFTypeUnit::extractImpl(DataExtractor debug_info,
uint32_t *offset_ptr) {
if (!DWARFUnit::extractImpl(debug_info, offset_ptr))
return false;
TypeHash = debug_info.getU64(offset_ptr);
TypeOffset = debug_info.getU32(offset_ptr);
return TypeOffset < getLength();
}
void DWARFTypeUnit::dump(raw_ostream &OS) {
OS << format("0x%08x", getOffset()) << ": Type Unit:"
<< " length = " << format("0x%08x", getLength())
<< " version = " << format("0x%04x", getVersion())
<< " abbr_offset = " << format("0x%04x", getAbbreviations()->getOffset())
<< " addr_size = " << format("0x%02x", getAddressByteSize())
<< " type_signature = " << format("0x%16" PRIx64, TypeHash)
<< " type_offset = " << format("0x%04x", TypeOffset)
<< " (next unit at " << format("0x%08x", getNextUnitOffset())
<< ")\n";
if (const DWARFDebugInfoEntryMinimal *TU = getUnitDIE(false))
TU->dump(OS, this, -1U);
else
OS << "<type unit can't be parsed!>\n\n";
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/SyntaxHighlighting.h | //===-- SyntaxHighlighting.h ------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_DEBUGINFO_SYNTAXHIGHLIGHTING_H
#define LLVM_LIB_DEBUGINFO_SYNTAXHIGHLIGHTING_H
#include "llvm/Support/raw_ostream.h"
namespace llvm {
namespace dwarf {
namespace syntax {
// Symbolic names for various syntax elements.
enum HighlightColor { Address, String, Tag, Attribute, Enumerator };
/// An RAII object that temporarily switches an output stream to a
/// specific color.
class WithColor {
llvm::raw_ostream &OS;
public:
/// To be used like this: WithColor(OS, syntax::String) << "text";
WithColor(llvm::raw_ostream &OS, enum HighlightColor Type);
~WithColor();
llvm::raw_ostream& get() { return OS; }
operator llvm::raw_ostream& () { return OS; }
};
}
}
}
#endif
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/DWARF/DWARFUnit.cpp | //===-- DWARFUnit.cpp -----------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
#include "llvm/Support/Dwarf.h"
#include "llvm/Support/Path.h"
#include <cstdio>
using namespace llvm;
using namespace dwarf;
void DWARFUnitSectionBase::parse(DWARFContext &C, const DWARFSection &Section) {
parseImpl(C, Section, C.getDebugAbbrev(), C.getRangeSection(),
C.getStringSection(), StringRef(), C.getAddrSection(),
C.isLittleEndian());
}
void DWARFUnitSectionBase::parseDWO(DWARFContext &C,
const DWARFSection &DWOSection) {
parseImpl(C, DWOSection, C.getDebugAbbrevDWO(), C.getRangeDWOSection(),
C.getStringDWOSection(), C.getStringOffsetDWOSection(),
C.getAddrSection(), C.isLittleEndian());
}
DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
const DWARFDebugAbbrev *DA, StringRef RS, StringRef SS,
StringRef SOS, StringRef AOS, bool LE,
const DWARFUnitSectionBase &UnitSection)
: Context(DC), InfoSection(Section), Abbrev(DA), RangeSection(RS),
StringSection(SS), StringOffsetSection(SOS), AddrOffsetSection(AOS),
isLittleEndian(LE), UnitSection(UnitSection) {
clear();
}
DWARFUnit::~DWARFUnit() {
}
bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
uint64_t &Result) const {
uint32_t Offset = AddrOffsetSectionBase + Index * AddrSize;
if (AddrOffsetSection.size() < Offset + AddrSize)
return false;
DataExtractor DA(AddrOffsetSection, isLittleEndian, AddrSize);
Result = DA.getAddress(&Offset);
return true;
}
bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index,
uint32_t &Result) const {
// FIXME: string offset section entries are 8-byte for DWARF64.
const uint32_t ItemSize = 4;
uint32_t Offset = Index * ItemSize;
if (StringOffsetSection.size() < Offset + ItemSize)
return false;
DataExtractor DA(StringOffsetSection, isLittleEndian, 0);
Result = DA.getU32(&Offset);
return true;
}
bool DWARFUnit::extractImpl(DataExtractor debug_info, uint32_t *offset_ptr) {
Length = debug_info.getU32(offset_ptr);
Version = debug_info.getU16(offset_ptr);
uint64_t AbbrOffset = debug_info.getU32(offset_ptr);
AddrSize = debug_info.getU8(offset_ptr);
bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
bool VersionOK = DWARFContext::isSupportedVersion(Version);
bool AddrSizeOK = AddrSize == 4 || AddrSize == 8;
if (!LengthOK || !VersionOK || !AddrSizeOK)
return false;
Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
return Abbrevs != nullptr;
}
bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
clear();
Offset = *offset_ptr;
if (debug_info.isValidOffset(*offset_ptr)) {
if (extractImpl(debug_info, offset_ptr))
return true;
// reset the offset to where we tried to parse from if anything went wrong
*offset_ptr = Offset;
}
return false;
}
bool DWARFUnit::extractRangeList(uint32_t RangeListOffset,
DWARFDebugRangeList &RangeList) const {
// Require that compile unit is extracted.
assert(DieArray.size() > 0);
DataExtractor RangesData(RangeSection, isLittleEndian, AddrSize);
uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
return RangeList.extract(RangesData, &ActualRangeListOffset);
}
void DWARFUnit::clear() {
Offset = 0;
Length = 0;
Version = 0;
Abbrevs = nullptr;
AddrSize = 0;
BaseAddr = 0;
RangeSectionBase = 0;
AddrOffsetSectionBase = 0;
clearDIEs(false);
DWO.reset();
}
const char *DWARFUnit::getCompilationDir() {
extractDIEsIfNeeded(true);
if (DieArray.empty())
return nullptr;
return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
}
uint64_t DWARFUnit::getDWOId() {
extractDIEsIfNeeded(true);
const uint64_t FailValue = -1ULL;
if (DieArray.empty())
return FailValue;
return DieArray[0]
.getAttributeValueAsUnsignedConstant(this, DW_AT_GNU_dwo_id, FailValue);
}
void DWARFUnit::setDIERelations() {
if (DieArray.size() <= 1)
return;
std::vector<DWARFDebugInfoEntryMinimal *> ParentChain;
DWARFDebugInfoEntryMinimal *SiblingChain = nullptr;
for (auto &DIE : DieArray) {
if (SiblingChain) {
SiblingChain->setSibling(&DIE);
}
if (const DWARFAbbreviationDeclaration *AbbrDecl =
DIE.getAbbreviationDeclarationPtr()) {
// Normal DIE.
if (AbbrDecl->hasChildren()) {
ParentChain.push_back(&DIE);
SiblingChain = nullptr;
} else {
SiblingChain = &DIE;
}
} else {
// NULL entry terminates the sibling chain.
SiblingChain = ParentChain.back();
ParentChain.pop_back();
}
}
assert(SiblingChain == nullptr || SiblingChain == &DieArray[0]);
assert(ParentChain.empty());
}
void DWARFUnit::extractDIEsToVector(
bool AppendCUDie, bool AppendNonCUDies,
std::vector<DWARFDebugInfoEntryMinimal> &Dies) const {
if (!AppendCUDie && !AppendNonCUDies)
return;
// Set the offset to that of the first DIE and calculate the start of the
// next compilation unit header.
uint32_t DIEOffset = Offset + getHeaderSize();
uint32_t NextCUOffset = getNextUnitOffset();
DWARFDebugInfoEntryMinimal DIE;
uint32_t Depth = 0;
bool IsCUDie = true;
while (DIEOffset < NextCUOffset && DIE.extractFast(this, &DIEOffset)) {
if (IsCUDie) {
if (AppendCUDie)
Dies.push_back(DIE);
if (!AppendNonCUDies)
break;
// The average bytes per DIE entry has been seen to be
// around 14-20 so let's pre-reserve the needed memory for
// our DIE entries accordingly.
Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
IsCUDie = false;
} else {
Dies.push_back(DIE);
}
if (const DWARFAbbreviationDeclaration *AbbrDecl =
DIE.getAbbreviationDeclarationPtr()) {
// Normal DIE
if (AbbrDecl->hasChildren())
++Depth;
} else {
// NULL DIE.
if (Depth > 0)
--Depth;
if (Depth == 0)
break; // We are done with this compile unit!
}
}
// Give a little bit of info if we encounter corrupt DWARF (our offset
// should always terminate at or before the start of the next compilation
// unit header).
if (DIEOffset > NextCUOffset)
fprintf(stderr, "warning: DWARF compile unit extends beyond its "
"bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
}
size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
if ((CUDieOnly && DieArray.size() > 0) ||
DieArray.size() > 1)
return 0; // Already parsed.
bool HasCUDie = DieArray.size() > 0;
extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
if (DieArray.empty())
return 0;
// If CU DIE was just parsed, copy several attribute values from it.
if (!HasCUDie) {
uint64_t BaseAddr =
DieArray[0].getAttributeValueAsAddress(this, DW_AT_low_pc, -1ULL);
if (BaseAddr == -1ULL)
BaseAddr = DieArray[0].getAttributeValueAsAddress(this, DW_AT_entry_pc, 0);
setBaseAddress(BaseAddr);
AddrOffsetSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
this, DW_AT_GNU_addr_base, 0);
RangeSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
this, DW_AT_ranges_base, 0);
// Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
// skeleton CU DIE, so that DWARF users not aware of it are not broken.
}
setDIERelations();
return DieArray.size();
}
DWARFUnit::DWOHolder::DWOHolder(StringRef DWOPath)
: DWOFile(), DWOContext(), DWOU(nullptr) {
auto Obj = object::ObjectFile::createObjectFile(DWOPath);
if (!Obj)
return;
DWOFile = std::move(Obj.get());
DWOContext.reset(
cast<DWARFContext>(new DWARFContextInMemory(*DWOFile.getBinary())));
if (DWOContext->getNumDWOCompileUnits() > 0)
DWOU = DWOContext->getDWOCompileUnitAtIndex(0);
}
bool DWARFUnit::parseDWO() {
if (DWO.get())
return false;
extractDIEsIfNeeded(true);
if (DieArray.empty())
return false;
const char *DWOFileName =
DieArray[0].getAttributeValueAsString(this, DW_AT_GNU_dwo_name, nullptr);
if (!DWOFileName)
return false;
const char *CompilationDir =
DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
SmallString<16> AbsolutePath;
if (sys::path::is_relative(DWOFileName) && CompilationDir != nullptr) {
sys::path::append(AbsolutePath, CompilationDir);
}
sys::path::append(AbsolutePath, DWOFileName);
DWO = llvm::make_unique<DWOHolder>(AbsolutePath);
DWARFUnit *DWOCU = DWO->getUnit();
// Verify that compile unit in .dwo file is valid.
if (!DWOCU || DWOCU->getDWOId() != getDWOId()) {
DWO.reset();
return false;
}
// Share .debug_addr and .debug_ranges section with compile unit in .dwo
DWOCU->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
uint32_t DWORangesBase = DieArray[0].getRangesBaseAttribute(this, 0);
DWOCU->setRangesSection(RangeSection, DWORangesBase);
return true;
}
void DWARFUnit::clearDIEs(bool KeepCUDie) {
if (DieArray.size() > (unsigned)KeepCUDie) {
// std::vectors never get any smaller when resized to a smaller size,
// or when clear() or erase() are called, the size will report that it
// is smaller, but the memory allocated remains intact (call capacity()
// to see this). So we need to create a temporary vector and swap the
// contents which will cause just the internal pointers to be swapped
// so that when temporary vector goes out of scope, it will destroy the
// contents.
std::vector<DWARFDebugInfoEntryMinimal> TmpArray;
DieArray.swap(TmpArray);
// Save at least the compile unit DIE
if (KeepCUDie)
DieArray.push_back(TmpArray.front());
}
}
void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
const auto *U = getUnitDIE();
if (U == nullptr)
return;
// First, check if unit DIE describes address ranges for the whole unit.
const auto &CUDIERanges = U->getAddressRanges(this);
if (!CUDIERanges.empty()) {
CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
return;
}
// This function is usually called if there in no .debug_aranges section
// in order to produce a compile unit level set of address ranges that
// is accurate. If the DIEs weren't parsed, then we don't want all dies for
// all compile units to stay loaded when they weren't needed. So we can end
// up parsing the DWARF and then throwing them all away to keep memory usage
// down.
const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
DieArray[0].collectChildrenAddressRanges(this, CURanges);
// Collect address ranges from DIEs in .dwo if necessary.
bool DWOCreated = parseDWO();
if (DWO.get())
DWO->getUnit()->collectAddressRanges(CURanges);
if (DWOCreated)
DWO.reset();
// Keep memory down by clearing DIEs if this generate function
// caused them to be parsed.
if (ClearDIEs)
clearDIEs(true);
}
const DWARFDebugInfoEntryMinimal *
DWARFUnit::getSubprogramForAddress(uint64_t Address) {
extractDIEsIfNeeded(false);
for (const DWARFDebugInfoEntryMinimal &DIE : DieArray) {
if (DIE.isSubprogramDIE() &&
DIE.addressRangeContainsAddress(this, Address)) {
return &DIE;
}
}
return nullptr;
}
DWARFDebugInfoEntryInlinedChain
DWARFUnit::getInlinedChainForAddress(uint64_t Address) {
// First, find a subprogram that contains the given address (the root
// of inlined chain).
const DWARFUnit *ChainCU = nullptr;
const DWARFDebugInfoEntryMinimal *SubprogramDIE =
getSubprogramForAddress(Address);
if (SubprogramDIE) {
ChainCU = this;
} else {
// Try to look for subprogram DIEs in the DWO file.
parseDWO();
if (DWO.get()) {
SubprogramDIE = DWO->getUnit()->getSubprogramForAddress(Address);
if (SubprogramDIE)
ChainCU = DWO->getUnit();
}
}
// Get inlined chain rooted at this subprogram DIE.
if (!SubprogramDIE)
return DWARFDebugInfoEntryInlinedChain();
return SubprogramDIE->getInlinedChainForAddress(ChainCU, Address);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBContext.cpp | //===-- PDBContext.cpp ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===/
#include "llvm/DebugInfo/PDB/PDBContext.h"
#include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
#include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
#include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
#include "llvm/DebugInfo/PDB/PDBSymbolData.h"
#include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"
#include "llvm/Object/COFF.h"
using namespace llvm;
using namespace llvm::object;
PDBContext::PDBContext(const COFFObjectFile &Object,
std::unique_ptr<IPDBSession> PDBSession,
bool RelativeAddress)
: DIContext(CK_PDB), Session(std::move(PDBSession)) {
if (!RelativeAddress) {
uint64_t ImageBase = 0;
if (Object.is64()) {
const pe32plus_header *Header = nullptr;
Object.getPE32PlusHeader(Header);
if (Header)
ImageBase = Header->ImageBase;
} else {
const pe32_header *Header = nullptr;
Object.getPE32Header(Header);
if (Header)
ImageBase = static_cast<uint64_t>(Header->ImageBase);
}
Session->setLoadAddress(ImageBase);
}
}
void PDBContext::dump(raw_ostream &OS, DIDumpType DumpType) {}
DILineInfo PDBContext::getLineInfoForAddress(uint64_t Address,
DILineInfoSpecifier Specifier) {
DILineInfo Result;
Result.FunctionName = getFunctionName(Address, Specifier.FNKind);
uint32_t Length = 1;
std::unique_ptr<PDBSymbol> Symbol =
Session->findSymbolByAddress(Address, PDB_SymType::None);
if (auto Func = dyn_cast_or_null<PDBSymbolFunc>(Symbol.get())) {
Length = Func->getLength();
} else if (auto Data = dyn_cast_or_null<PDBSymbolData>(Symbol.get())) {
Length = Data->getLength();
}
// If we couldn't find a symbol, then just assume 1 byte, so that we get
// only the line number of the first instruction.
auto LineNumbers = Session->findLineNumbersByAddress(Address, Length);
if (!LineNumbers || LineNumbers->getChildCount() == 0)
return Result;
auto LineInfo = LineNumbers->getNext();
assert(LineInfo);
auto SourceFile = Session->getSourceFileById(LineInfo->getSourceFileId());
if (SourceFile &&
Specifier.FLIKind != DILineInfoSpecifier::FileLineInfoKind::None)
Result.FileName = SourceFile->getFileName();
Result.Column = LineInfo->getColumnNumber();
Result.Line = LineInfo->getLineNumber();
return Result;
}
DILineInfoTable
PDBContext::getLineInfoForAddressRange(uint64_t Address, uint64_t Size,
DILineInfoSpecifier Specifier) {
if (Size == 0)
return DILineInfoTable();
DILineInfoTable Table;
auto LineNumbers = Session->findLineNumbersByAddress(Address, Size);
if (!LineNumbers || LineNumbers->getChildCount() == 0)
return Table;
while (auto LineInfo = LineNumbers->getNext()) {
DILineInfo LineEntry =
getLineInfoForAddress(LineInfo->getVirtualAddress(), Specifier);
Table.push_back(std::make_pair(LineInfo->getVirtualAddress(), LineEntry));
}
return Table;
}
DIInliningInfo
PDBContext::getInliningInfoForAddress(uint64_t Address,
DILineInfoSpecifier Specifier) {
DIInliningInfo InlineInfo;
DILineInfo Frame = getLineInfoForAddress(Address, Specifier);
InlineInfo.addFrame(Frame);
return InlineInfo;
}
std::string PDBContext::getFunctionName(uint64_t Address,
DINameKind NameKind) const {
if (NameKind == DINameKind::None)
return std::string();
if (NameKind == DINameKind::LinkageName) {
// It is not possible to get the mangled linkage name through a
// PDBSymbolFunc. For that we have to specifically request a
// PDBSymbolPublicSymbol.
auto PublicSym =
Session->findSymbolByAddress(Address, PDB_SymType::PublicSymbol);
if (auto PS = dyn_cast_or_null<PDBSymbolPublicSymbol>(PublicSym.get()))
return PS->getName();
}
auto FuncSymbol =
Session->findSymbolByAddress(Address, PDB_SymType::Function);
// This could happen either if there was no public symbol (e.g. not
// external) or the user requested the short name. In the former case,
// although they technically requested the linkage name, if the linkage
// name is not available we fallback to at least returning a non-empty
// string.
if (auto Func = dyn_cast_or_null<PDBSymbolFunc>(FuncSymbol.get()))
return Func->getName();
return std::string();
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbol.cpp | //===- PDBSymbol.cpp - base class for user-facing symbol types --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
#include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymbolAnnotation.h"
#include "llvm/DebugInfo/PDB/PDBSymbolBlock.h"
#include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
#include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h"
#include "llvm/DebugInfo/PDB/PDBSymbolCompilandEnv.h"
#include "llvm/DebugInfo/PDB/PDBSymbolCustom.h"
#include "llvm/DebugInfo/PDB/PDBSymbolData.h"
#include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
#include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
#include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h"
#include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h"
#include "llvm/DebugInfo/PDB/PDBSymbolLabel.h"
#include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymbolThunk.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeArray.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeCustom.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeDimension.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeFriend.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeManaged.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypePointer.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeVTable.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeVTableShape.h"
#include "llvm/DebugInfo/PDB/PDBSymbolUnknown.h"
#include "llvm/DebugInfo/PDB/PDBSymbolUsingNamespace.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <memory>
#include <utility>
#include <memory>
#include <utility>
using namespace llvm;
PDBSymbol::PDBSymbol(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: Session(PDBSession), RawSymbol(std::move(Symbol)) {}
PDBSymbol::~PDBSymbol() {}
#define FACTORY_SYMTAG_CASE(Tag, Type) \
case PDB_SymType::Tag: \
return std::unique_ptr<PDBSymbol>(new Type(PDBSession, std::move(Symbol)));
std::unique_ptr<PDBSymbol>
PDBSymbol::create(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol) {
switch (Symbol->getSymTag()) {
FACTORY_SYMTAG_CASE(Exe, PDBSymbolExe)
FACTORY_SYMTAG_CASE(Compiland, PDBSymbolCompiland)
FACTORY_SYMTAG_CASE(CompilandDetails, PDBSymbolCompilandDetails)
FACTORY_SYMTAG_CASE(CompilandEnv, PDBSymbolCompilandEnv)
FACTORY_SYMTAG_CASE(Function, PDBSymbolFunc)
FACTORY_SYMTAG_CASE(Block, PDBSymbolBlock)
FACTORY_SYMTAG_CASE(Data, PDBSymbolData)
FACTORY_SYMTAG_CASE(Annotation, PDBSymbolAnnotation)
FACTORY_SYMTAG_CASE(Label, PDBSymbolLabel)
FACTORY_SYMTAG_CASE(PublicSymbol, PDBSymbolPublicSymbol)
FACTORY_SYMTAG_CASE(UDT, PDBSymbolTypeUDT)
FACTORY_SYMTAG_CASE(Enum, PDBSymbolTypeEnum)
FACTORY_SYMTAG_CASE(FunctionSig, PDBSymbolTypeFunctionSig)
FACTORY_SYMTAG_CASE(PointerType, PDBSymbolTypePointer)
FACTORY_SYMTAG_CASE(ArrayType, PDBSymbolTypeArray)
FACTORY_SYMTAG_CASE(BuiltinType, PDBSymbolTypeBuiltin)
FACTORY_SYMTAG_CASE(Typedef, PDBSymbolTypeTypedef)
FACTORY_SYMTAG_CASE(BaseClass, PDBSymbolTypeBaseClass)
FACTORY_SYMTAG_CASE(Friend, PDBSymbolTypeFriend)
FACTORY_SYMTAG_CASE(FunctionArg, PDBSymbolTypeFunctionArg)
FACTORY_SYMTAG_CASE(FuncDebugStart, PDBSymbolFuncDebugStart)
FACTORY_SYMTAG_CASE(FuncDebugEnd, PDBSymbolFuncDebugEnd)
FACTORY_SYMTAG_CASE(UsingNamespace, PDBSymbolUsingNamespace)
FACTORY_SYMTAG_CASE(VTableShape, PDBSymbolTypeVTableShape)
FACTORY_SYMTAG_CASE(VTable, PDBSymbolTypeVTable)
FACTORY_SYMTAG_CASE(Custom, PDBSymbolCustom)
FACTORY_SYMTAG_CASE(Thunk, PDBSymbolThunk)
FACTORY_SYMTAG_CASE(CustomType, PDBSymbolTypeCustom)
FACTORY_SYMTAG_CASE(ManagedType, PDBSymbolTypeManaged)
FACTORY_SYMTAG_CASE(Dimension, PDBSymbolTypeDimension)
default:
return std::unique_ptr<PDBSymbol>(
new PDBSymbolUnknown(PDBSession, std::move(Symbol)));
}
}
#define TRY_DUMP_TYPE(Type) \
if (const Type *DerivedThis = dyn_cast<Type>(this)) \
Dumper.dump(OS, Indent, *DerivedThis);
#define ELSE_TRY_DUMP_TYPE(Type, Dumper) else TRY_DUMP_TYPE(Type, Dumper)
void PDBSymbol::defaultDump(raw_ostream &OS, int Indent) const {
RawSymbol->dump(OS, Indent);
}
PDB_SymType PDBSymbol::getSymTag() const { return RawSymbol->getSymTag(); }
std::unique_ptr<IPDBEnumSymbols> PDBSymbol::findAllChildren() const {
return findAllChildren(PDB_SymType::None);
}
std::unique_ptr<IPDBEnumSymbols>
PDBSymbol::findAllChildren(PDB_SymType Type) const {
return RawSymbol->findChildren(Type);
}
std::unique_ptr<IPDBEnumSymbols>
PDBSymbol::findChildren(PDB_SymType Type, StringRef Name,
PDB_NameSearchFlags Flags) const {
return RawSymbol->findChildren(Type, Name, Flags);
}
std::unique_ptr<IPDBEnumSymbols>
PDBSymbol::findChildrenByRVA(PDB_SymType Type, StringRef Name,
PDB_NameSearchFlags Flags, uint32_t RVA) const {
return RawSymbol->findChildrenByRVA(Type, Name, Flags, RVA);
}
std::unique_ptr<IPDBEnumSymbols>
PDBSymbol::findInlineFramesByRVA(uint32_t RVA) const {
return RawSymbol->findInlineFramesByRVA(RVA);
}
std::unique_ptr<IPDBEnumSymbols>
PDBSymbol::getChildStats(TagStats &Stats) const {
std::unique_ptr<IPDBEnumSymbols> Result(findAllChildren());
Stats.clear();
while (auto Child = Result->getNext()) {
++Stats[Child->getSymTag()];
}
Result->reset();
return Result;
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypePointer.cpp | //===- PDBSymbolTypePointer.cpp -----------------------------------*- C++ -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypePointer.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypePointer::PDBSymbolTypePointer(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
std::unique_ptr<PDBSymbol> PDBSymbolTypePointer::getPointeeType() const {
return Session.getSymbolById(getTypeId());
}
void PDBSymbolTypePointer::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolBlock.cpp | //===- PDBSymbolBlock.cpp - -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolBlock.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolBlock::PDBSymbolBlock(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolBlock::dump(PDBSymDumper &Dumper) const { Dumper.dump(*this); }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeManaged.cpp | //===- PDBSymboTypelManaged.cpp - ------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeManaged.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeManaged::PDBSymbolTypeManaged(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeManaged::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolFuncDebugEnd.cpp | //===- PDBSymbolFuncDebugEnd.cpp - ------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugEnd.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolFuncDebugEnd::PDBSymbolFuncDebugEnd(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolFuncDebugEnd::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeCustom.cpp | //===- PDBSymbolTypeCustom.cpp - --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeCustom.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeCustom::PDBSymbolTypeCustom(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeCustom::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeFunctionSig.cpp | //===- PDBSymbolTypeFunctionSig.cpp - --------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h"
#include "llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h"
#include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
namespace {
class FunctionArgEnumerator : public IPDBEnumSymbols {
public:
typedef ConcreteSymbolEnumerator<PDBSymbolTypeFunctionArg> ArgEnumeratorType;
FunctionArgEnumerator(const IPDBSession &PDBSession,
const PDBSymbolTypeFunctionSig &Sig)
: Session(PDBSession),
Enumerator(Sig.findAllChildren<PDBSymbolTypeFunctionArg>()) {}
FunctionArgEnumerator(const IPDBSession &PDBSession,
std::unique_ptr<ArgEnumeratorType> ArgEnumerator)
: Session(PDBSession), Enumerator(std::move(ArgEnumerator)) {}
uint32_t getChildCount() const override {
return Enumerator->getChildCount();
}
std::unique_ptr<PDBSymbol> getChildAtIndex(uint32_t Index) const override {
auto FunctionArgSymbol = Enumerator->getChildAtIndex(Index);
if (!FunctionArgSymbol)
return nullptr;
return Session.getSymbolById(FunctionArgSymbol->getTypeId());
}
std::unique_ptr<PDBSymbol> getNext() override {
auto FunctionArgSymbol = Enumerator->getNext();
if (!FunctionArgSymbol)
return nullptr;
return Session.getSymbolById(FunctionArgSymbol->getTypeId());
}
void reset() override { Enumerator->reset(); }
MyType *clone() const override {
std::unique_ptr<ArgEnumeratorType> Clone(Enumerator->clone());
return new FunctionArgEnumerator(Session, std::move(Clone));
}
private:
const IPDBSession &Session;
std::unique_ptr<ArgEnumeratorType> Enumerator;
};
}
PDBSymbolTypeFunctionSig::PDBSymbolTypeFunctionSig(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
std::unique_ptr<PDBSymbol> PDBSymbolTypeFunctionSig::getReturnType() const {
return Session.getSymbolById(getTypeId());
}
std::unique_ptr<IPDBEnumSymbols>
PDBSymbolTypeFunctionSig::getArguments() const {
return llvm::make_unique<FunctionArgEnumerator>(Session, *this);
}
std::unique_ptr<PDBSymbol> PDBSymbolTypeFunctionSig::getClassParent() const {
uint32_t ClassId = getClassParentId();
if (ClassId == 0)
return nullptr;
return Session.getSymbolById(ClassId);
}
void PDBSymbolTypeFunctionSig::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeDimension.cpp | //===- PDBSymbolTypeDimension.cpp - --------------------------------*- C++
//-*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeDimension.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeDimension::PDBSymbolTypeDimension(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeDimension::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolCompilandEnv.cpp | //===- PDBSymbolCompilandEnv.cpp - compiland env variables ------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolCompilandEnv.h"
#include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolCompilandEnv::PDBSymbolCompilandEnv(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
std::string PDBSymbolCompilandEnv::getValue() const {
// call RawSymbol->getValue() and convert the result to an std::string.
return std::string();
}
void PDBSymbolCompilandEnv::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeVTable.cpp | //===- PDBSymbolTypeVTable.cpp - --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeVTable.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeVTable::PDBSymbolTypeVTable(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeVTable::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/IPDBSourceFile.cpp | //===- IPDBSourceFile.cpp - base interface for a PDB source file *- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/IPDBSourceFile.h"
#include "llvm/DebugInfo/PDB/PDBExtras.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
IPDBSourceFile::~IPDBSourceFile() {}
void IPDBSourceFile::dump(raw_ostream &OS, int Indent) const {
OS.indent(Indent);
PDB_Checksum ChecksumType = getChecksumType();
OS << "[";
if (ChecksumType != PDB_Checksum::None) {
OS << ChecksumType << ": ";
std::string Checksum = getChecksum();
for (uint8_t c : Checksum)
OS << format_hex_no_prefix(c, 2, true);
} else
OS << "No checksum";
OS << "] " << getFileName() << "\n";
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymDumper.cpp | //===- PDBSymDumper.cpp - ---------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include "llvm/Support/ErrorHandling.h"
using namespace llvm;
#define PDB_SYMDUMP_UNREACHABLE(Type) \
if (RequireImpl) \
llvm_unreachable("Attempt to dump " #Type " with no dump implementation");
PDBSymDumper::PDBSymDumper(bool ShouldRequireImpl)
: RequireImpl(ShouldRequireImpl) {}
PDBSymDumper::~PDBSymDumper() {}
void PDBSymDumper::dump(const PDBSymbolAnnotation &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolAnnotation)
}
void PDBSymDumper::dump(const PDBSymbolBlock &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolBlock)
}
void PDBSymDumper::dump(const PDBSymbolCompiland &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolCompiland)
}
void PDBSymDumper::dump(const PDBSymbolCompilandDetails &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolCompilandDetails)
}
void PDBSymDumper::dump(const PDBSymbolCompilandEnv &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolCompilandEnv)
}
void PDBSymDumper::dump(const PDBSymbolCustom &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolCustom)
}
void PDBSymDumper::dump(const PDBSymbolData &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolData)
}
void PDBSymDumper::dump(const PDBSymbolExe &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolExe)
}
void PDBSymDumper::dump(const PDBSymbolFunc &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolFunc)
}
void PDBSymDumper::dump(const PDBSymbolFuncDebugEnd &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolFuncDebugEnd)
}
void PDBSymDumper::dump(const PDBSymbolFuncDebugStart &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolFuncDebugStart)
}
void PDBSymDumper::dump(const PDBSymbolLabel &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolLabel)
}
void PDBSymDumper::dump(const PDBSymbolPublicSymbol &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolPublicSymbol)
}
void PDBSymDumper::dump(const PDBSymbolThunk &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolThunk)
}
void PDBSymDumper::dump(const PDBSymbolTypeArray &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeArray)
}
void PDBSymDumper::dump(const PDBSymbolTypeBaseClass &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeBaseClass)
}
void PDBSymDumper::dump(const PDBSymbolTypeBuiltin &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeBuiltin)
}
void PDBSymDumper::dump(const PDBSymbolTypeCustom &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeCustom)
}
void PDBSymDumper::dump(const PDBSymbolTypeDimension &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeDimension)
}
void PDBSymDumper::dump(const PDBSymbolTypeEnum &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeEnum)
}
void PDBSymDumper::dump(const PDBSymbolTypeFriend &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeFriend)
}
void PDBSymDumper::dump(const PDBSymbolTypeFunctionArg &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeFunctionArg)
}
void PDBSymDumper::dump(const PDBSymbolTypeFunctionSig &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeFunctionSig)
}
void PDBSymDumper::dump(const PDBSymbolTypeManaged &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeManaged)
}
void PDBSymDumper::dump(const PDBSymbolTypePointer &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypePointer)
}
void PDBSymDumper::dump(const PDBSymbolTypeTypedef &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeTypedef)
}
void PDBSymDumper::dump(const PDBSymbolTypeUDT &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeUDT)
}
void PDBSymDumper::dump(const PDBSymbolTypeVTable &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeVTable)
}
void PDBSymDumper::dump(const PDBSymbolTypeVTableShape &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolTypeVTableShape)
}
void PDBSymDumper::dump(const PDBSymbolUnknown &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolUnknown)
}
void PDBSymDumper::dump(const PDBSymbolUsingNamespace &Symbol) {
PDB_SYMDUMP_UNREACHABLE(PDBSymbolUsingNamespace)
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeFunctionArg.cpp | //===- PDBSymbolTypeFunctionArg.cpp - --------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionArg.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeFunctionArg::PDBSymbolTypeFunctionArg(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeFunctionArg::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolCustom.cpp | //===- PDBSymbolCustom.cpp - compiler-specific types ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolCustom.h"
#include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolCustom::PDBSymbolCustom(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> CustomSymbol)
: PDBSymbol(PDBSession, std::move(CustomSymbol)) {}
void PDBSymbolCustom::getDataBytes(llvm::SmallVector<uint8_t, 32> &bytes) {
RawSymbol->getDataBytes(bytes);
}
void PDBSymbolCustom::dump(PDBSymDumper &Dumper) const { Dumper.dump(*this); }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/CMakeLists.txt | macro(add_pdb_impl_folder group)
list(APPEND PDB_IMPL_SOURCES ${ARGN})
source_group(${group} FILES ${ARGN})
endmacro()
if(HAVE_DIA_SDK)
include_directories(${MSVC_DIA_SDK_DIR}/include)
set(LIBPDB_LINK_FOLDERS "${MSVC_DIA_SDK_DIR}\\lib")
if (CMAKE_SIZEOF_VOID_P EQUAL 8)
set(LIBPDB_LINK_FOLDERS "${LIBPDB_LINK_FOLDERS}\\amd64")
endif()
file(TO_CMAKE_PATH "${LIBPDB_LINK_FOLDERS}\\diaguids.lib" LIBPDB_ADDITIONAL_LIBRARIES)
add_pdb_impl_folder(DIA
DIA/DIADataStream.cpp
DIA/DIAEnumDebugStreams.cpp
DIA/DIAEnumLineNumbers.cpp
DIA/DIAEnumSourceFiles.cpp
DIA/DIAEnumSymbols.cpp
DIA/DIALineNumber.cpp
DIA/DIARawSymbol.cpp
DIA/DIASession.cpp
DIA/DIASourceFile.cpp
)
set(LIBPDB_ADDITIONAL_HEADER_DIRS "${LLVM_MAIN_INCLUDE_DIR}/llvm/DebugInfo/PDB/DIA")
endif()
list(APPEND LIBPDB_ADDITIONAL_HEADER_DIRS "${LLVM_MAIN_INCLUDE_DIR}/llvm/DebugInfo/PDB")
add_llvm_library(LLVMDebugInfoPDB
IPDBSourceFile.cpp
PDB.cpp
PDBContext.cpp
PDBExtras.cpp
PDBInterfaceAnchors.cpp
PDBSymbol.cpp
PDBSymbolAnnotation.cpp
PDBSymbolBlock.cpp
PDBSymbolCompiland.cpp
PDBSymbolCompilandDetails.cpp
PDBSymbolCompilandEnv.cpp
PDBSymbolCustom.cpp
PDBSymbolData.cpp
PDBSymbolExe.cpp
PDBSymbolFunc.cpp
PDBSymbolFuncDebugEnd.cpp
PDBSymbolFuncDebugStart.cpp
PDBSymbolLabel.cpp
PDBSymbolPublicSymbol.cpp
PDBSymbolThunk.cpp
PDBSymbolTypeArray.cpp
PDBSymbolTypeBaseClass.cpp
PDBSymbolTypeBuiltin.cpp
PDBSymbolTypeCustom.cpp
PDBSymbolTypeDimension.cpp
PDBSymbolTypeEnum.cpp
PDBSymbolTypeFriend.cpp
PDBSymbolTypeFunctionArg.cpp
PDBSymbolTypeFunctionSig.cpp
PDBSymbolTypeManaged.cpp
PDBSymbolTypePointer.cpp
PDBSymbolTypeTypedef.cpp
PDBSymbolTypeUDT.cpp
PDBSymbolTypeVTable.cpp
PDBSymbolTypeVTableShape.cpp
PDBSymbolUnknown.cpp
PDBSymbolUsingNamespace.cpp
PDBSymDumper.cpp
${PDB_IMPL_SOURCES}
ADDITIONAL_HEADER_DIRS
${LIBPDB_ADDITIONAL_HEADER_DIRS}
)
target_link_libraries(LLVMDebugInfoPDB INTERFACE "${LIBPDB_ADDITIONAL_LIBRARIES}")
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolThunk.cpp | //===- PDBSymbolThunk.cpp - -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolThunk.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolThunk::PDBSymbolThunk(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolThunk::dump(PDBSymDumper &Dumper) const { Dumper.dump(*this); }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeUDT.cpp | //===- PDBSymbolTypeUDT.cpp - --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeUDT::PDBSymbolTypeUDT(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeUDT::dump(PDBSymDumper &Dumper) const { Dumper.dump(*this); }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolPublicSymbol.cpp | //===- PDBSymbolPublicSymbol.cpp - ------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolPublicSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolPublicSymbol::PDBSymbolPublicSymbol(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolPublicSymbol::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/LLVMBuild.txt | ;===- ./lib/DebugInfo/PDB/LLVMBuild.txt ------------------------*- Conf -*--===;
;
; The LLVM Compiler Infrastructure
;
; This file is distributed under the University of Illinois Open Source
; License. See LICENSE.TXT for details.
;
;===------------------------------------------------------------------------===;
;
; This is an LLVMBuild description file for the components in this subdirectory.
;
; For more information on the LLVMBuild system, please see:
;
; http://llvm.org/docs/LLVMBuild.html
;
;===------------------------------------------------------------------------===;
[component_0]
type = Library
name = DebugInfoPDB
parent = DebugInfo
required_libraries = Object Support
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolLabel.cpp | //===- PDBSymbolLabel.cpp - -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolLabel.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolLabel::PDBSymbolLabel(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolLabel::dump(PDBSymDumper &Dumper) const { Dumper.dump(*this); }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolAnnotation.cpp | //===- PDBSymbolAnnotation.cpp - --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolAnnotation.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolAnnotation::PDBSymbolAnnotation(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolAnnotation::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeEnum.cpp | //===- PDBSymbolTypeEnum.cpp - --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeEnum.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeEnum::PDBSymbolTypeEnum(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
std::unique_ptr<PDBSymbolTypeUDT> PDBSymbolTypeEnum::getClassParent() const {
return Session.getConcreteSymbolById<PDBSymbolTypeUDT>(getClassParentId());
}
std::unique_ptr<PDBSymbolTypeBuiltin>
PDBSymbolTypeEnum::getUnderlyingType() const {
return Session.getConcreteSymbolById<PDBSymbolTypeBuiltin>(getTypeId());
}
void PDBSymbolTypeEnum::dump(PDBSymDumper &Dumper) const { Dumper.dump(*this); }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolFuncDebugStart.cpp | //===- PDBSymbolFuncDebugStart.cpp - ----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolFuncDebugStart.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolFuncDebugStart::PDBSymbolFuncDebugStart(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolFuncDebugStart::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolCompilandDetails.cpp | //===- PDBSymbolCompilandDetails.cpp - compiland details --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolCompilandDetails.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolCompilandDetails::PDBSymbolCompilandDetails(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolCompilandDetails::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolData.cpp | //===- PDBSymbolData.cpp - PDB data (e.g. variable) accessors ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolData.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolData::PDBSymbolData(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> DataSymbol)
: PDBSymbol(PDBSession, std::move(DataSymbol)) {}
std::unique_ptr<PDBSymbol> PDBSymbolData::getType() const {
return Session.getSymbolById(getTypeId());
}
void PDBSymbolData::dump(PDBSymDumper &Dumper) const { Dumper.dump(*this); }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolCompiland.cpp | //===- PDBSymbolCompiland.cpp - compiland details --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolCompiland::PDBSymbolCompiland(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolCompiland::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBInterfaceAnchors.cpp | //===- PDBInterfaceAnchors.h - defines class anchor funcions ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Class anchors are necessary per the LLVM Coding style guide, to ensure that
// the vtable is only generated in this object file, and not in every object
// file that incldues the corresponding header.
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/IPDBDataStream.h"
#include "llvm/DebugInfo/PDB/IPDBLineNumber.h"
#include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/IPDBRawSymbol.h"
using namespace llvm;
IPDBSession::~IPDBSession() {}
IPDBDataStream::~IPDBDataStream() {}
IPDBRawSymbol::~IPDBRawSymbol() {}
IPDBLineNumber::~IPDBLineNumber() {}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolUsingNamespace.cpp | //===- PDBSymbolUsingNamespace.cpp - ------------------- --------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolUsingNamespace.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolUsingNamespace::PDBSymbolUsingNamespace(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolUsingNamespace::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeBaseClass.cpp | //===- PDBSymbolTypeBaseClass.cpp - -----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeBaseClass.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeBaseClass::PDBSymbolTypeBaseClass(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeBaseClass::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDB.cpp | //===- PDB.cpp - base header file for creating a PDB reader -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDB.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Config/config.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/PDB.h"
#if HAVE_DIA_SDK
#include "llvm/DebugInfo/PDB/DIA/DIASession.h"
#endif
using namespace llvm;
PDB_ErrorCode llvm::loadDataForPDB(PDB_ReaderType Type, StringRef Path,
std::unique_ptr<IPDBSession> &Session) {
// Create the correct concrete instance type based on the value of Type.
#if HAVE_DIA_SDK
return DIASession::createFromPdb(Path, Session);
#endif
return PDB_ErrorCode::NoPdbImpl;
}
PDB_ErrorCode llvm::loadDataForEXE(PDB_ReaderType Type, StringRef Path,
std::unique_ptr<IPDBSession> &Session) {
// Create the correct concrete instance type based on the value of Type.
#if HAVE_DIA_SDK
return DIASession::createFromExe(Path, Session);
#endif
return PDB_ErrorCode::NoPdbImpl;
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeArray.cpp | //===- PDBSymbolTypeArray.cpp - ---------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeArray.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeArray::PDBSymbolTypeArray(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
std::unique_ptr<PDBSymbol> PDBSymbolTypeArray::getElementType() const {
return Session.getSymbolById(getTypeId());
}
void PDBSymbolTypeArray::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeBuiltin.cpp | //===- PDBSymbolTypeBuiltin.cpp - ------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeBuiltin.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeBuiltin::PDBSymbolTypeBuiltin(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeBuiltin::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolUnknown.cpp | //===- PDBSymbolUnknown.cpp - -----------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolUnknown.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolUnknown::PDBSymbolUnknown(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolUnknown::dump(PDBSymDumper &Dumper) const { Dumper.dump(*this); }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolFunc.cpp | //===- PDBSymbolFunc.cpp - --------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolFunc.h"
#include "llvm/DebugInfo/PDB/ConcreteSymbolEnumerator.h"
#include "llvm/DebugInfo/PDB/IPDBEnumChildren.h"
#include "llvm/DebugInfo/PDB/IPDBSession.h"
#include "llvm/DebugInfo/PDB/PDBSymbolData.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeFunctionSig.h"
#include "llvm/DebugInfo/PDB/PDBSymbolTypeUDT.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include "llvm/DebugInfo/PDB/PDBTypes.h"
#include <unordered_set>
#include <utility>
#include <vector>
using namespace llvm;
namespace {
class FunctionArgEnumerator : public IPDBEnumChildren<PDBSymbolData> {
public:
typedef ConcreteSymbolEnumerator<PDBSymbolData> ArgEnumeratorType;
FunctionArgEnumerator(const IPDBSession &PDBSession,
const PDBSymbolFunc &PDBFunc)
: Session(PDBSession), Func(PDBFunc) {
// Arguments can appear multiple times if they have live range
// information, so we only take the first occurrence.
std::unordered_set<std::string> SeenNames;
auto DataChildren = Func.findAllChildren<PDBSymbolData>();
while (auto Child = DataChildren->getNext()) {
if (Child->getDataKind() == PDB_DataKind::Param) {
std::string Name = Child->getName();
if (SeenNames.find(Name) != SeenNames.end())
continue;
Args.push_back(std::move(Child));
SeenNames.insert(Name);
}
}
reset();
}
uint32_t getChildCount() const override { return Args.size(); }
std::unique_ptr<PDBSymbolData>
getChildAtIndex(uint32_t Index) const override {
if (Index >= Args.size())
return nullptr;
return Session.getConcreteSymbolById<PDBSymbolData>(
Args[Index]->getSymIndexId());
}
std::unique_ptr<PDBSymbolData> getNext() override {
if (CurIter == Args.end())
return nullptr;
const auto &Result = **CurIter;
++CurIter;
return Session.getConcreteSymbolById<PDBSymbolData>(Result.getSymIndexId());
}
void reset() override { CurIter = Args.empty() ? Args.end() : Args.begin(); }
FunctionArgEnumerator *clone() const override {
return new FunctionArgEnumerator(Session, Func);
}
private:
typedef std::vector<std::unique_ptr<PDBSymbolData>> ArgListType;
const IPDBSession &Session;
const PDBSymbolFunc &Func;
ArgListType Args;
ArgListType::const_iterator CurIter;
};
}
PDBSymbolFunc::PDBSymbolFunc(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
std::unique_ptr<PDBSymbolTypeFunctionSig> PDBSymbolFunc::getSignature() const {
return Session.getConcreteSymbolById<PDBSymbolTypeFunctionSig>(getTypeId());
}
std::unique_ptr<IPDBEnumChildren<PDBSymbolData>>
PDBSymbolFunc::getArguments() const {
return llvm::make_unique<FunctionArgEnumerator>(Session, *this);
}
std::unique_ptr<PDBSymbolTypeUDT> PDBSymbolFunc::getClassParent() const {
return Session.getConcreteSymbolById<PDBSymbolTypeUDT>(getClassParentId());
}
void PDBSymbolFunc::dump(PDBSymDumper &Dumper) const { Dumper.dump(*this); }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeTypedef.cpp | //===- PDBSymbolTypeTypedef.cpp ---------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeTypedef.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeTypedef::PDBSymbolTypeTypedef(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeTypedef::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeVTableShape.cpp | //===- PDBSymbolTypeVTableShape.cpp - ---------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeVTableShape.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeVTableShape::PDBSymbolTypeVTableShape(
const IPDBSession &PDBSession, std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeVTableShape::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolExe.cpp | //===- PDBSymbolExe.cpp - ---------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolExe::PDBSymbolExe(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolExe::dump(PDBSymDumper &Dumper) const { Dumper.dump(*this); }
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBSymbolTypeFriend.cpp | //===- PDBSymbolTypeFriend.cpp - --------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbolTypeFriend.h"
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/PDBSymDumper.h"
#include <utility>
using namespace llvm;
PDBSymbolTypeFriend::PDBSymbolTypeFriend(const IPDBSession &PDBSession,
std::unique_ptr<IPDBRawSymbol> Symbol)
: PDBSymbol(PDBSession, std::move(Symbol)) {}
void PDBSymbolTypeFriend::dump(PDBSymDumper &Dumper) const {
Dumper.dump(*this);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/PDBExtras.cpp | //===- PDBExtras.cpp - helper functions and classes for PDBs -----*- C++-*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBExtras.h"
#include "llvm/ADT/ArrayRef.h"
using namespace llvm;
#define CASE_OUTPUT_ENUM_CLASS_STR(Class, Value, Str, Stream) \
case Class::Value: \
Stream << Str; \
break;
#define CASE_OUTPUT_ENUM_CLASS_NAME(Class, Value, Stream) \
CASE_OUTPUT_ENUM_CLASS_STR(Class, Value, #Value, Stream)
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_VariantType &Type) {
switch (Type) {
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, Bool, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, Single, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, Double, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, Int8, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, Int16, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, Int32, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, Int64, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, UInt8, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, UInt16, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, UInt32, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_VariantType, UInt64, OS)
default:
OS << "Unknown";
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_CallingConv &Conv) {
OS << "__";
switch (Conv) {
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, NearCdecl, "cdecl", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, FarCdecl, "cdecl", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, NearPascal, "pascal", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, FarPascal, "pascal", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, NearFastcall, "fastcall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, FarFastcall, "fastcall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, Skipped, "skippedcall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, NearStdcall, "stdcall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, FarStdcall, "stdcall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, NearSyscall, "syscall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, FarSyscall, "syscall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, Thiscall, "thiscall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, MipsCall, "mipscall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, Generic, "genericcall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, Alphacall, "alphacall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, Ppccall, "ppccall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, SuperHCall, "superhcall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, Armcall, "armcall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, AM33call, "am33call", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, Tricall, "tricall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, Sh5call, "sh5call", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, M32R, "m32rcall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, Clrcall, "clrcall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, Inline, "inlinecall", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_CallingConv, NearVectorcall, "vectorcall",
OS)
default:
OS << "unknowncall";
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_DataKind &Data) {
switch (Data) {
CASE_OUTPUT_ENUM_CLASS_STR(PDB_DataKind, Unknown, "unknown", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_DataKind, Local, "local", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_DataKind, StaticLocal, "static local", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_DataKind, Param, "param", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_DataKind, ObjectPtr, "this ptr", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_DataKind, FileStatic, "static global", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_DataKind, Global, "global", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_DataKind, Member, "member", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_DataKind, StaticMember, "static member", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_DataKind, Constant, "const", OS)
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_RegisterId &Reg) {
switch (Reg) {
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, AL, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, CL, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, DL, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, BL, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, AH, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, CH, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, DH, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, BH, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, AX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, CX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, DX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, BX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, SP, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, BP, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, SI, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, DI, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, EAX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, ECX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, EDX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, EBX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, ESP, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, EBP, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, ESI, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, EDI, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, ES, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, CS, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, SS, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, DS, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, FS, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, GS, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, IP, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, RAX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, RBX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, RCX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, RDX, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, RSI, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, RDI, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, RBP, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, RSP, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, R8, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, R9, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, R10, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, R11, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, R12, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, R13, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, R14, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_RegisterId, R15, OS)
default:
OS << static_cast<int>(Reg);
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_LocType &Loc) {
switch (Loc) {
CASE_OUTPUT_ENUM_CLASS_STR(PDB_LocType, Static, "static", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_LocType, TLS, "tls", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_LocType, RegRel, "regrel", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_LocType, ThisRel, "thisrel", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_LocType, Enregistered, "register", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_LocType, BitField, "bitfield", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_LocType, Slot, "slot", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_LocType, IlRel, "IL rel", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_LocType, MetaData, "metadata", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_LocType, Constant, "constant", OS)
default:
OS << "Unknown";
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_ThunkOrdinal &Thunk) {
switch (Thunk) {
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_ThunkOrdinal, BranchIsland, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_ThunkOrdinal, Pcode, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_ThunkOrdinal, Standard, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_ThunkOrdinal, ThisAdjustor, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_ThunkOrdinal, TrampIncremental, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_ThunkOrdinal, UnknownLoad, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_ThunkOrdinal, Vcall, OS)
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_Checksum &Checksum) {
switch (Checksum) {
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Checksum, None, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Checksum, MD5, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Checksum, SHA1, OS)
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_Lang &Lang) {
switch (Lang) {
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, C, OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_Lang, Cpp, "C++", OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, Fortran, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, Masm, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, Pascal, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, Basic, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, Cobol, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, Link, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, Cvtres, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, Cvtpgd, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, CSharp, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, VB, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, ILAsm, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, Java, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, JScript, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, MSIL, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_Lang, HLSL, OS)
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_SymType &Tag) {
switch (Tag) {
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Exe, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Compiland, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, CompilandDetails, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, CompilandEnv, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Function, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Block, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Data, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Annotation, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Label, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, PublicSymbol, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, UDT, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Enum, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, FunctionSig, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, PointerType, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, ArrayType, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, BuiltinType, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Typedef, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, BaseClass, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Friend, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, FunctionArg, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, FuncDebugStart, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, FuncDebugEnd, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, UsingNamespace, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, VTableShape, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, VTable, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Custom, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Thunk, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, CustomType, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, ManagedType, OS)
CASE_OUTPUT_ENUM_CLASS_NAME(PDB_SymType, Dimension, OS)
default:
OS << "Unknown";
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_MemberAccess &Access) {
switch (Access) {
CASE_OUTPUT_ENUM_CLASS_STR(PDB_MemberAccess, Public, "public", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_MemberAccess, Protected, "protected", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_MemberAccess, Private, "private", OS)
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_UdtType &Type) {
switch (Type) {
CASE_OUTPUT_ENUM_CLASS_STR(PDB_UdtType, Class, "class", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_UdtType, Struct, "struct", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_UdtType, Interface, "interface", OS)
CASE_OUTPUT_ENUM_CLASS_STR(PDB_UdtType, Union, "union", OS)
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const PDB_UniqueId &Id) {
static const char *Lookup = "0123456789ABCDEF";
static_assert(sizeof(PDB_UniqueId) == 16, "Expected 16-byte GUID");
ArrayRef<uint8_t> GuidBytes(reinterpret_cast<const uint8_t*>(&Id), 16);
OS << "{";
for (int i=0; i < 16;) {
uint8_t Byte = GuidBytes[i];
uint8_t HighNibble = (Byte >> 4) & 0xF;
uint8_t LowNibble = Byte & 0xF;
OS << Lookup[HighNibble] << Lookup[LowNibble];
++i;
if (i>=4 && i<=10 && i%2==0)
OS << "-";
}
OS << "}";
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const Variant &Value) {
switch (Value.Type) {
case PDB_VariantType::Bool:
OS << (Value.Bool ? "true" : "false");
break;
case PDB_VariantType::Double:
OS << Value.Double;
break;
case PDB_VariantType::Int16:
OS << Value.Int16;
break;
case PDB_VariantType::Int32:
OS << Value.Int32;
break;
case PDB_VariantType::Int64:
OS << Value.Int64;
break;
case PDB_VariantType::Int8:
OS << static_cast<int>(Value.Int8);
break;
case PDB_VariantType::Single:
OS << Value.Single;
break;
case PDB_VariantType::UInt16:
OS << Value.Double;
break;
case PDB_VariantType::UInt32:
OS << Value.UInt32;
break;
case PDB_VariantType::UInt64:
OS << Value.UInt64;
break;
case PDB_VariantType::UInt8:
OS << static_cast<unsigned>(Value.UInt8);
break;
default:
OS << Value.Type;
}
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const VersionInfo &Version) {
OS << Version.Major << "." << Version.Minor << "." << Version.Build;
return OS;
}
raw_ostream &llvm::operator<<(raw_ostream &OS, const TagStats &Stats) {
for (auto Tag : Stats) {
OS << Tag.first << ":" << Tag.second << " ";
}
return OS;
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo/PDB | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/DIA/DIADataStream.cpp | //===- DIADataStream.cpp - DIA implementation of IPDBDataStream -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/DIA/DIADataStream.h"
#include "llvm/Support/ConvertUTF.h"
using namespace llvm;
DIADataStream::DIADataStream(CComPtr<IDiaEnumDebugStreamData> DiaStreamData)
: StreamData(DiaStreamData) {}
uint32_t DIADataStream::getRecordCount() const {
LONG Count = 0;
return (S_OK == StreamData->get_Count(&Count)) ? Count : 0;
}
std::string DIADataStream::getName() const {
CComBSTR Name16;
if (S_OK != StreamData->get_name(&Name16))
return std::string();
std::string Name8;
llvm::ArrayRef<char> Name16Bytes(reinterpret_cast<char *>(Name16.m_str),
Name16.ByteLength());
if (!llvm::convertUTF16ToUTF8String(Name16Bytes, Name8))
return std::string();
return Name8;
}
llvm::Optional<DIADataStream::RecordType>
DIADataStream::getItemAtIndex(uint32_t Index) const {
RecordType Record;
DWORD RecordSize = 0;
StreamData->Item(Index, 0, &RecordSize, nullptr);
if (RecordSize == 0)
return llvm::Optional<RecordType>();
Record.resize(RecordSize);
if (S_OK != StreamData->Item(Index, RecordSize, &RecordSize, &Record[0]))
return llvm::Optional<RecordType>();
return Record;
}
bool DIADataStream::getNext(RecordType &Record) {
Record.clear();
DWORD RecordSize = 0;
ULONG CountFetched = 0;
StreamData->Next(1, 0, &RecordSize, nullptr, &CountFetched);
if (RecordSize == 0)
return false;
Record.resize(RecordSize);
if (S_OK ==
StreamData->Next(1, RecordSize, &RecordSize, &Record[0], &CountFetched))
return false;
return true;
}
void DIADataStream::reset() { StreamData->Reset(); }
DIADataStream *DIADataStream::clone() const {
CComPtr<IDiaEnumDebugStreamData> EnumeratorClone;
if (S_OK != StreamData->Clone(&EnumeratorClone))
return nullptr;
return new DIADataStream(EnumeratorClone);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo/PDB | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/DIA/DIAEnumDebugStreams.cpp | //==- DIAEnumDebugStreams.cpp - DIA Debug Stream Enumerator impl -*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/DIA/DIADataStream.h"
#include "llvm/DebugInfo/PDB/DIA/DIAEnumDebugStreams.h"
using namespace llvm;
DIAEnumDebugStreams::DIAEnumDebugStreams(
CComPtr<IDiaEnumDebugStreams> DiaEnumerator)
: Enumerator(DiaEnumerator) {}
uint32_t DIAEnumDebugStreams::getChildCount() const {
LONG Count = 0;
return (S_OK == Enumerator->get_Count(&Count)) ? Count : 0;
}
std::unique_ptr<IPDBDataStream>
DIAEnumDebugStreams::getChildAtIndex(uint32_t Index) const {
CComPtr<IDiaEnumDebugStreamData> Item;
VARIANT VarIndex;
VarIndex.vt = VT_I4;
VarIndex.lVal = Index;
if (S_OK != Enumerator->Item(VarIndex, &Item))
return nullptr;
return std::unique_ptr<IPDBDataStream>(new DIADataStream(Item));
}
std::unique_ptr<IPDBDataStream> DIAEnumDebugStreams::getNext() {
CComPtr<IDiaEnumDebugStreamData> Item;
ULONG NumFetched = 0;
if (S_OK != Enumerator->Next(1, &Item, &NumFetched))
return nullptr;
return std::unique_ptr<IPDBDataStream>(new DIADataStream(Item));
}
void DIAEnumDebugStreams::reset() { Enumerator->Reset(); }
DIAEnumDebugStreams *DIAEnumDebugStreams::clone() const {
CComPtr<IDiaEnumDebugStreams> EnumeratorClone;
if (S_OK != Enumerator->Clone(&EnumeratorClone))
return nullptr;
return new DIAEnumDebugStreams(EnumeratorClone);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo/PDB | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/DIA/DIARawSymbol.cpp | //===- DIARawSymbol.cpp - DIA implementation of IPDBRawSymbol ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/DebugInfo/PDB/DIA/DIAEnumSymbols.h"
#include "llvm/DebugInfo/PDB/DIA/DIARawSymbol.h"
#include "llvm/DebugInfo/PDB/DIA/DIASession.h"
#include "llvm/DebugInfo/PDB/PDBExtras.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
Variant VariantFromVARIANT(const VARIANT &V) {
Variant Result;
switch (V.vt) {
case VT_I1:
Result.Int8 = V.cVal;
Result.Type = PDB_VariantType::Int8;
break;
case VT_I2:
Result.Int16 = V.iVal;
Result.Type = PDB_VariantType::Int16;
break;
case VT_I4:
Result.Int32 = V.intVal;
Result.Type = PDB_VariantType::Int32;
break;
case VT_I8:
Result.Int64 = V.llVal;
Result.Type = PDB_VariantType::Int64;
break;
case VT_UI1:
Result.UInt8 = V.bVal;
Result.Type = PDB_VariantType::UInt8;
break;
case VT_UI2:
Result.UInt16 = V.uiVal;
Result.Type = PDB_VariantType::UInt16;
break;
case VT_UI4:
Result.UInt32 = V.uintVal;
Result.Type = PDB_VariantType::UInt32;
break;
case VT_UI8:
Result.UInt64 = V.ullVal;
Result.Type = PDB_VariantType::UInt64;
break;
case VT_BOOL:
Result.Bool = (V.boolVal == VARIANT_TRUE) ? true : false;
Result.Type = PDB_VariantType::Bool;
break;
case VT_R4:
Result.Single = V.fltVal;
Result.Type = PDB_VariantType::Single;
break;
case VT_R8:
Result.Double = V.dblVal;
Result.Type = PDB_VariantType::Double;
break;
default:
Result.Type = PDB_VariantType::Unknown;
break;
}
return Result;
}
template <typename ArgType>
ArgType PrivateGetDIAValue(IDiaSymbol *Symbol,
HRESULT (__stdcall IDiaSymbol::*Method)(ArgType *)) {
ArgType Value;
if (S_OK == (Symbol->*Method)(&Value))
return static_cast<ArgType>(Value);
return ArgType();
}
template <typename ArgType, typename RetType>
RetType PrivateGetDIAValue(IDiaSymbol *Symbol,
HRESULT (__stdcall IDiaSymbol::*Method)(ArgType *)) {
ArgType Value;
if (S_OK == (Symbol->*Method)(&Value))
return static_cast<RetType>(Value);
return RetType();
}
std::string
PrivateGetDIAValue(IDiaSymbol *Symbol,
HRESULT (__stdcall IDiaSymbol::*Method)(BSTR *)) {
CComBSTR Result16;
if (S_OK != (Symbol->*Method)(&Result16))
return std::string();
const char *SrcBytes = reinterpret_cast<const char *>(Result16.m_str);
llvm::ArrayRef<char> SrcByteArray(SrcBytes, Result16.ByteLength());
std::string Result8;
if (!llvm::convertUTF16ToUTF8String(SrcByteArray, Result8))
return std::string();
return Result8;
}
PDB_UniqueId
PrivateGetDIAValue(IDiaSymbol *Symbol,
HRESULT (__stdcall IDiaSymbol::*Method)(GUID *)) {
GUID Result;
if (S_OK != (Symbol->*Method)(&Result))
return PDB_UniqueId();
static_assert(sizeof(PDB_UniqueId) == sizeof(GUID),
"PDB_UniqueId is the wrong size!");
PDB_UniqueId IdResult;
::memcpy(&IdResult, &Result, sizeof(GUID));
return IdResult;
}
template <typename ArgType>
void DumpDIAValue(llvm::raw_ostream &OS, int Indent, StringRef Name,
IDiaSymbol *Symbol,
HRESULT (__stdcall IDiaSymbol::*Method)(ArgType *)) {
ArgType Value;
if (S_OK == (Symbol->*Method)(&Value)) {
OS << "\n";
OS.indent(Indent);
OS << Name << ": " << Value;
}
}
void DumpDIAValue(llvm::raw_ostream &OS, int Indent, StringRef Name,
IDiaSymbol *Symbol,
HRESULT (__stdcall IDiaSymbol::*Method)(BSTR *)) {
BSTR Value = nullptr;
if (S_OK != (Symbol->*Method)(&Value))
return;
const char *Bytes = reinterpret_cast<const char *>(Value);
ArrayRef<char> ByteArray(Bytes, ::SysStringByteLen(Value));
std::string Result;
if (llvm::convertUTF16ToUTF8String(ByteArray, Result)) {
OS << "\n";
OS.indent(Indent);
OS << Name << ": " << Result;
}
::SysFreeString(Value);
}
void DumpDIAValue(llvm::raw_ostream &OS, int Indent, StringRef Name,
IDiaSymbol *Symbol,
HRESULT (__stdcall IDiaSymbol::*Method)(VARIANT *)) {
VARIANT Value;
Value.vt = VT_EMPTY;
if (S_OK != (Symbol->*Method)(&Value))
return;
OS << "\n";
OS.indent(Indent);
Variant V = VariantFromVARIANT(Value);
OS << V;
}
}
namespace llvm {
raw_ostream &operator<<(raw_ostream &OS, const GUID &Guid) {
const PDB_UniqueId *Id = reinterpret_cast<const PDB_UniqueId *>(&Guid);
OS << *Id;
return OS;
}
}
DIARawSymbol::DIARawSymbol(const DIASession &PDBSession,
CComPtr<IDiaSymbol> DiaSymbol)
: Session(PDBSession), Symbol(DiaSymbol) {}
#define RAW_METHOD_DUMP(Stream, Method) \
DumpDIAValue(Stream, Indent, StringRef(#Method), Symbol, &IDiaSymbol::Method);
void DIARawSymbol::dump(raw_ostream &OS, int Indent) const {
RAW_METHOD_DUMP(OS, get_access)
RAW_METHOD_DUMP(OS, get_addressOffset)
RAW_METHOD_DUMP(OS, get_addressSection)
RAW_METHOD_DUMP(OS, get_age)
RAW_METHOD_DUMP(OS, get_arrayIndexTypeId)
RAW_METHOD_DUMP(OS, get_backEndMajor)
RAW_METHOD_DUMP(OS, get_backEndMinor)
RAW_METHOD_DUMP(OS, get_backEndBuild)
RAW_METHOD_DUMP(OS, get_backEndQFE)
RAW_METHOD_DUMP(OS, get_baseDataOffset)
RAW_METHOD_DUMP(OS, get_baseDataSlot)
RAW_METHOD_DUMP(OS, get_baseSymbolId)
RAW_METHOD_DUMP(OS, get_baseType)
RAW_METHOD_DUMP(OS, get_bitPosition)
RAW_METHOD_DUMP(OS, get_callingConvention)
RAW_METHOD_DUMP(OS, get_classParentId)
RAW_METHOD_DUMP(OS, get_compilerName)
RAW_METHOD_DUMP(OS, get_count)
RAW_METHOD_DUMP(OS, get_countLiveRanges)
RAW_METHOD_DUMP(OS, get_frontEndMajor)
RAW_METHOD_DUMP(OS, get_frontEndMinor)
RAW_METHOD_DUMP(OS, get_frontEndBuild)
RAW_METHOD_DUMP(OS, get_frontEndQFE)
RAW_METHOD_DUMP(OS, get_lexicalParentId)
RAW_METHOD_DUMP(OS, get_libraryName)
RAW_METHOD_DUMP(OS, get_liveRangeStartAddressOffset)
RAW_METHOD_DUMP(OS, get_liveRangeStartAddressSection)
RAW_METHOD_DUMP(OS, get_liveRangeStartRelativeVirtualAddress)
RAW_METHOD_DUMP(OS, get_localBasePointerRegisterId)
RAW_METHOD_DUMP(OS, get_lowerBoundId)
RAW_METHOD_DUMP(OS, get_memorySpaceKind)
RAW_METHOD_DUMP(OS, get_name)
RAW_METHOD_DUMP(OS, get_numberOfAcceleratorPointerTags)
RAW_METHOD_DUMP(OS, get_numberOfColumns)
RAW_METHOD_DUMP(OS, get_numberOfModifiers)
RAW_METHOD_DUMP(OS, get_numberOfRegisterIndices)
RAW_METHOD_DUMP(OS, get_numberOfRows)
RAW_METHOD_DUMP(OS, get_objectFileName)
RAW_METHOD_DUMP(OS, get_oemId)
RAW_METHOD_DUMP(OS, get_oemSymbolId)
RAW_METHOD_DUMP(OS, get_offsetInUdt)
RAW_METHOD_DUMP(OS, get_platform)
RAW_METHOD_DUMP(OS, get_rank)
RAW_METHOD_DUMP(OS, get_registerId)
RAW_METHOD_DUMP(OS, get_registerType)
RAW_METHOD_DUMP(OS, get_relativeVirtualAddress)
RAW_METHOD_DUMP(OS, get_samplerSlot)
RAW_METHOD_DUMP(OS, get_signature)
RAW_METHOD_DUMP(OS, get_sizeInUdt)
RAW_METHOD_DUMP(OS, get_slot)
RAW_METHOD_DUMP(OS, get_sourceFileName)
RAW_METHOD_DUMP(OS, get_stride)
RAW_METHOD_DUMP(OS, get_subTypeId)
RAW_METHOD_DUMP(OS, get_symbolsFileName)
RAW_METHOD_DUMP(OS, get_symIndexId)
RAW_METHOD_DUMP(OS, get_targetOffset)
RAW_METHOD_DUMP(OS, get_targetRelativeVirtualAddress)
RAW_METHOD_DUMP(OS, get_targetVirtualAddress)
RAW_METHOD_DUMP(OS, get_targetSection)
RAW_METHOD_DUMP(OS, get_textureSlot)
RAW_METHOD_DUMP(OS, get_timeStamp)
RAW_METHOD_DUMP(OS, get_token)
RAW_METHOD_DUMP(OS, get_typeId)
RAW_METHOD_DUMP(OS, get_uavSlot)
RAW_METHOD_DUMP(OS, get_undecoratedName)
RAW_METHOD_DUMP(OS, get_unmodifiedTypeId)
RAW_METHOD_DUMP(OS, get_upperBoundId)
RAW_METHOD_DUMP(OS, get_virtualBaseDispIndex)
RAW_METHOD_DUMP(OS, get_virtualBaseOffset)
RAW_METHOD_DUMP(OS, get_virtualTableShapeId)
RAW_METHOD_DUMP(OS, get_dataKind)
RAW_METHOD_DUMP(OS, get_symTag)
RAW_METHOD_DUMP(OS, get_guid)
RAW_METHOD_DUMP(OS, get_offset)
RAW_METHOD_DUMP(OS, get_thisAdjust)
RAW_METHOD_DUMP(OS, get_virtualBasePointerOffset)
RAW_METHOD_DUMP(OS, get_locationType)
RAW_METHOD_DUMP(OS, get_machineType)
RAW_METHOD_DUMP(OS, get_thunkOrdinal)
RAW_METHOD_DUMP(OS, get_length)
RAW_METHOD_DUMP(OS, get_liveRangeLength)
RAW_METHOD_DUMP(OS, get_virtualAddress)
RAW_METHOD_DUMP(OS, get_udtKind)
RAW_METHOD_DUMP(OS, get_constructor)
RAW_METHOD_DUMP(OS, get_customCallingConvention)
RAW_METHOD_DUMP(OS, get_farReturn)
RAW_METHOD_DUMP(OS, get_code)
RAW_METHOD_DUMP(OS, get_compilerGenerated)
RAW_METHOD_DUMP(OS, get_constType)
RAW_METHOD_DUMP(OS, get_editAndContinueEnabled)
RAW_METHOD_DUMP(OS, get_function)
RAW_METHOD_DUMP(OS, get_stride)
RAW_METHOD_DUMP(OS, get_noStackOrdering)
RAW_METHOD_DUMP(OS, get_hasAlloca)
RAW_METHOD_DUMP(OS, get_hasAssignmentOperator)
RAW_METHOD_DUMP(OS, get_isCTypes)
RAW_METHOD_DUMP(OS, get_hasCastOperator)
RAW_METHOD_DUMP(OS, get_hasDebugInfo)
RAW_METHOD_DUMP(OS, get_hasEH)
RAW_METHOD_DUMP(OS, get_hasEHa)
RAW_METHOD_DUMP(OS, get_hasInlAsm)
RAW_METHOD_DUMP(OS, get_framePointerPresent)
RAW_METHOD_DUMP(OS, get_inlSpec)
RAW_METHOD_DUMP(OS, get_interruptReturn)
RAW_METHOD_DUMP(OS, get_hasLongJump)
RAW_METHOD_DUMP(OS, get_hasManagedCode)
RAW_METHOD_DUMP(OS, get_hasNestedTypes)
RAW_METHOD_DUMP(OS, get_noInline)
RAW_METHOD_DUMP(OS, get_noReturn)
RAW_METHOD_DUMP(OS, get_optimizedCodeDebugInfo)
RAW_METHOD_DUMP(OS, get_overloadedOperator)
RAW_METHOD_DUMP(OS, get_hasSEH)
RAW_METHOD_DUMP(OS, get_hasSecurityChecks)
RAW_METHOD_DUMP(OS, get_hasSetJump)
RAW_METHOD_DUMP(OS, get_strictGSCheck)
RAW_METHOD_DUMP(OS, get_isAcceleratorGroupSharedLocal)
RAW_METHOD_DUMP(OS, get_isAcceleratorPointerTagLiveRange)
RAW_METHOD_DUMP(OS, get_isAcceleratorStubFunction)
RAW_METHOD_DUMP(OS, get_isAggregated)
RAW_METHOD_DUMP(OS, get_intro)
RAW_METHOD_DUMP(OS, get_isCVTCIL)
RAW_METHOD_DUMP(OS, get_isConstructorVirtualBase)
RAW_METHOD_DUMP(OS, get_isCxxReturnUdt)
RAW_METHOD_DUMP(OS, get_isDataAligned)
RAW_METHOD_DUMP(OS, get_isHLSLData)
RAW_METHOD_DUMP(OS, get_isHotpatchable)
RAW_METHOD_DUMP(OS, get_indirectVirtualBaseClass)
RAW_METHOD_DUMP(OS, get_isInterfaceUdt)
RAW_METHOD_DUMP(OS, get_intrinsic)
RAW_METHOD_DUMP(OS, get_isLTCG)
RAW_METHOD_DUMP(OS, get_isLocationControlFlowDependent)
RAW_METHOD_DUMP(OS, get_isMSILNetmodule)
RAW_METHOD_DUMP(OS, get_isMatrixRowMajor)
RAW_METHOD_DUMP(OS, get_managed)
RAW_METHOD_DUMP(OS, get_msil)
RAW_METHOD_DUMP(OS, get_isMultipleInheritance)
RAW_METHOD_DUMP(OS, get_isNaked)
RAW_METHOD_DUMP(OS, get_nested)
RAW_METHOD_DUMP(OS, get_isOptimizedAway)
RAW_METHOD_DUMP(OS, get_packed)
RAW_METHOD_DUMP(OS, get_isPointerBasedOnSymbolValue)
RAW_METHOD_DUMP(OS, get_isPointerToDataMember)
RAW_METHOD_DUMP(OS, get_isPointerToMemberFunction)
RAW_METHOD_DUMP(OS, get_pure)
RAW_METHOD_DUMP(OS, get_RValueReference)
RAW_METHOD_DUMP(OS, get_isRefUdt)
RAW_METHOD_DUMP(OS, get_reference)
RAW_METHOD_DUMP(OS, get_restrictedType)
RAW_METHOD_DUMP(OS, get_isReturnValue)
RAW_METHOD_DUMP(OS, get_isSafeBuffers)
RAW_METHOD_DUMP(OS, get_scoped)
RAW_METHOD_DUMP(OS, get_isSdl)
RAW_METHOD_DUMP(OS, get_isSingleInheritance)
RAW_METHOD_DUMP(OS, get_isSplitted)
RAW_METHOD_DUMP(OS, get_isStatic)
RAW_METHOD_DUMP(OS, get_isStripped)
RAW_METHOD_DUMP(OS, get_unalignedType)
RAW_METHOD_DUMP(OS, get_notReached)
RAW_METHOD_DUMP(OS, get_isValueUdt)
RAW_METHOD_DUMP(OS, get_virtual)
RAW_METHOD_DUMP(OS, get_virtualBaseClass)
RAW_METHOD_DUMP(OS, get_isVirtualInheritance)
RAW_METHOD_DUMP(OS, get_volatileType)
RAW_METHOD_DUMP(OS, get_wasInlined)
RAW_METHOD_DUMP(OS, get_unused)
RAW_METHOD_DUMP(OS, get_value)
}
std::unique_ptr<IPDBEnumSymbols>
DIARawSymbol::findChildren(PDB_SymType Type) const {
enum SymTagEnum EnumVal = static_cast<enum SymTagEnum>(Type);
CComPtr<IDiaEnumSymbols> DiaEnumerator;
if (S_OK != Symbol->findChildrenEx(EnumVal, nullptr, nsNone, &DiaEnumerator))
return nullptr;
return llvm::make_unique<DIAEnumSymbols>(Session, DiaEnumerator);
}
std::unique_ptr<IPDBEnumSymbols>
DIARawSymbol::findChildren(PDB_SymType Type, StringRef Name,
PDB_NameSearchFlags Flags) const {
llvm::SmallVector<UTF16, 32> Name16;
llvm::convertUTF8ToUTF16String(Name, Name16);
enum SymTagEnum EnumVal = static_cast<enum SymTagEnum>(Type);
DWORD CompareFlags = static_cast<DWORD>(Flags);
wchar_t *Name16Str = reinterpret_cast<wchar_t *>(Name16.data());
CComPtr<IDiaEnumSymbols> DiaEnumerator;
if (S_OK !=
Symbol->findChildrenEx(EnumVal, Name16Str, CompareFlags, &DiaEnumerator))
return nullptr;
return llvm::make_unique<DIAEnumSymbols>(Session, DiaEnumerator);
}
std::unique_ptr<IPDBEnumSymbols>
DIARawSymbol::findChildrenByRVA(PDB_SymType Type, StringRef Name,
PDB_NameSearchFlags Flags, uint32_t RVA) const {
llvm::SmallVector<UTF16, 32> Name16;
llvm::convertUTF8ToUTF16String(Name, Name16);
enum SymTagEnum EnumVal = static_cast<enum SymTagEnum>(Type);
DWORD CompareFlags = static_cast<DWORD>(Flags);
wchar_t *Name16Str = reinterpret_cast<wchar_t *>(Name16.data());
CComPtr<IDiaEnumSymbols> DiaEnumerator;
if (S_OK !=
Symbol->findChildrenExByRVA(EnumVal, Name16Str, CompareFlags, RVA,
&DiaEnumerator))
return nullptr;
return llvm::make_unique<DIAEnumSymbols>(Session, DiaEnumerator);
}
std::unique_ptr<IPDBEnumSymbols>
DIARawSymbol::findInlineFramesByRVA(uint32_t RVA) const {
CComPtr<IDiaEnumSymbols> DiaEnumerator;
if (S_OK != Symbol->findInlineFramesByRVA(RVA, &DiaEnumerator))
return nullptr;
return llvm::make_unique<DIAEnumSymbols>(Session, DiaEnumerator);
}
void DIARawSymbol::getDataBytes(llvm::SmallVector<uint8_t, 32> &bytes) const {
bytes.clear();
DWORD DataSize = 0;
Symbol->get_dataBytes(0, &DataSize, nullptr);
if (DataSize == 0)
return;
bytes.resize(DataSize);
Symbol->get_dataBytes(DataSize, &DataSize, bytes.data());
}
PDB_MemberAccess DIARawSymbol::getAccess() const {
return PrivateGetDIAValue<DWORD, PDB_MemberAccess>(Symbol,
&IDiaSymbol::get_access);
}
uint32_t DIARawSymbol::getAddressOffset() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_addressOffset);
}
uint32_t DIARawSymbol::getAddressSection() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_addressSection);
}
uint32_t DIARawSymbol::getAge() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_age);
}
uint32_t DIARawSymbol::getArrayIndexTypeId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_arrayIndexTypeId);
}
void DIARawSymbol::getBackEndVersion(VersionInfo &Version) const {
Version.Major = PrivateGetDIAValue(Symbol, &IDiaSymbol::get_backEndMajor);
Version.Minor = PrivateGetDIAValue(Symbol, &IDiaSymbol::get_backEndMinor);
Version.Build = PrivateGetDIAValue(Symbol, &IDiaSymbol::get_backEndBuild);
Version.QFE = PrivateGetDIAValue(Symbol, &IDiaSymbol::get_backEndQFE);
}
uint32_t DIARawSymbol::getBaseDataOffset() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_baseDataOffset);
}
uint32_t DIARawSymbol::getBaseDataSlot() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_baseDataSlot);
}
uint32_t DIARawSymbol::getBaseSymbolId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_baseSymbolId);
}
PDB_BuiltinType DIARawSymbol::getBuiltinType() const {
return PrivateGetDIAValue<DWORD, PDB_BuiltinType>(Symbol,
&IDiaSymbol::get_baseType);
}
uint32_t DIARawSymbol::getBitPosition() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_bitPosition);
}
PDB_CallingConv DIARawSymbol::getCallingConvention() const {
return PrivateGetDIAValue<DWORD, PDB_CallingConv>(
Symbol, &IDiaSymbol::get_callingConvention);
}
uint32_t DIARawSymbol::getClassParentId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_classParentId);
}
std::string DIARawSymbol::getCompilerName() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_compilerName);
}
uint32_t DIARawSymbol::getCount() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_count);
}
uint32_t DIARawSymbol::getCountLiveRanges() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_countLiveRanges);
}
void DIARawSymbol::getFrontEndVersion(VersionInfo &Version) const {
Version.Major = PrivateGetDIAValue(Symbol, &IDiaSymbol::get_frontEndMajor);
Version.Minor = PrivateGetDIAValue(Symbol, &IDiaSymbol::get_frontEndMinor);
Version.Build = PrivateGetDIAValue(Symbol, &IDiaSymbol::get_frontEndBuild);
Version.QFE = PrivateGetDIAValue(Symbol, &IDiaSymbol::get_frontEndQFE);
}
PDB_Lang DIARawSymbol::getLanguage() const {
return PrivateGetDIAValue<DWORD, PDB_Lang>(Symbol, &IDiaSymbol::get_language);
}
uint32_t DIARawSymbol::getLexicalParentId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_lexicalParentId);
}
std::string DIARawSymbol::getLibraryName() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_libraryName);
}
uint32_t DIARawSymbol::getLiveRangeStartAddressOffset() const {
return PrivateGetDIAValue(Symbol,
&IDiaSymbol::get_liveRangeStartAddressOffset);
}
uint32_t DIARawSymbol::getLiveRangeStartAddressSection() const {
return PrivateGetDIAValue(Symbol,
&IDiaSymbol::get_liveRangeStartAddressSection);
}
uint32_t DIARawSymbol::getLiveRangeStartRelativeVirtualAddress() const {
return PrivateGetDIAValue(
Symbol, &IDiaSymbol::get_liveRangeStartRelativeVirtualAddress);
}
PDB_RegisterId DIARawSymbol::getLocalBasePointerRegisterId() const {
return PrivateGetDIAValue<DWORD, PDB_RegisterId>(
Symbol, &IDiaSymbol::get_localBasePointerRegisterId);
}
uint32_t DIARawSymbol::getLowerBoundId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_lowerBoundId);
}
uint32_t DIARawSymbol::getMemorySpaceKind() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_memorySpaceKind);
}
std::string DIARawSymbol::getName() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_name);
}
uint32_t DIARawSymbol::getNumberOfAcceleratorPointerTags() const {
return PrivateGetDIAValue(Symbol,
&IDiaSymbol::get_numberOfAcceleratorPointerTags);
}
uint32_t DIARawSymbol::getNumberOfColumns() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_numberOfColumns);
}
uint32_t DIARawSymbol::getNumberOfModifiers() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_numberOfModifiers);
}
uint32_t DIARawSymbol::getNumberOfRegisterIndices() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_numberOfRegisterIndices);
}
uint32_t DIARawSymbol::getNumberOfRows() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_numberOfRows);
}
std::string DIARawSymbol::getObjectFileName() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_objectFileName);
}
uint32_t DIARawSymbol::getOemId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_oemId);
}
uint32_t DIARawSymbol::getOemSymbolId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_oemSymbolId);
}
uint32_t DIARawSymbol::getOffsetInUdt() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_offsetInUdt);
}
PDB_Cpu DIARawSymbol::getPlatform() const {
return PrivateGetDIAValue<DWORD, PDB_Cpu>(Symbol, &IDiaSymbol::get_platform);
}
uint32_t DIARawSymbol::getRank() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_rank);
}
PDB_RegisterId DIARawSymbol::getRegisterId() const {
return PrivateGetDIAValue<DWORD, PDB_RegisterId>(Symbol,
&IDiaSymbol::get_registerId);
}
uint32_t DIARawSymbol::getRegisterType() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_registerType);
}
uint32_t DIARawSymbol::getRelativeVirtualAddress() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_relativeVirtualAddress);
}
uint32_t DIARawSymbol::getSamplerSlot() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_samplerSlot);
}
uint32_t DIARawSymbol::getSignature() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_signature);
}
uint32_t DIARawSymbol::getSizeInUdt() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_sizeInUdt);
}
uint32_t DIARawSymbol::getSlot() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_slot);
}
std::string DIARawSymbol::getSourceFileName() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_sourceFileName);
}
uint32_t DIARawSymbol::getStride() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_stride);
}
uint32_t DIARawSymbol::getSubTypeId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_subTypeId);
}
std::string DIARawSymbol::getSymbolsFileName() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_symbolsFileName);
}
uint32_t DIARawSymbol::getSymIndexId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_symIndexId);
}
uint32_t DIARawSymbol::getTargetOffset() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_targetOffset);
}
uint32_t DIARawSymbol::getTargetRelativeVirtualAddress() const {
return PrivateGetDIAValue(Symbol,
&IDiaSymbol::get_targetRelativeVirtualAddress);
}
uint64_t DIARawSymbol::getTargetVirtualAddress() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_targetVirtualAddress);
}
uint32_t DIARawSymbol::getTargetSection() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_targetSection);
}
uint32_t DIARawSymbol::getTextureSlot() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_textureSlot);
}
uint32_t DIARawSymbol::getTimeStamp() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_timeStamp);
}
uint32_t DIARawSymbol::getToken() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_token);
}
uint32_t DIARawSymbol::getTypeId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_typeId);
}
uint32_t DIARawSymbol::getUavSlot() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_uavSlot);
}
std::string DIARawSymbol::getUndecoratedName() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_undecoratedName);
}
uint32_t DIARawSymbol::getUnmodifiedTypeId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_unmodifiedTypeId);
}
uint32_t DIARawSymbol::getUpperBoundId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_upperBoundId);
}
Variant DIARawSymbol::getValue() const {
VARIANT Value;
Value.vt = VT_EMPTY;
if (S_OK != Symbol->get_value(&Value))
return Variant();
return VariantFromVARIANT(Value);
}
uint32_t DIARawSymbol::getVirtualBaseDispIndex() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_virtualBaseDispIndex);
}
uint32_t DIARawSymbol::getVirtualBaseOffset() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_virtualBaseOffset);
}
uint32_t DIARawSymbol::getVirtualTableShapeId() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_virtualTableShapeId);
}
PDB_DataKind DIARawSymbol::getDataKind() const {
return PrivateGetDIAValue<DWORD, PDB_DataKind>(Symbol,
&IDiaSymbol::get_dataKind);
}
PDB_SymType DIARawSymbol::getSymTag() const {
return PrivateGetDIAValue<DWORD, PDB_SymType>(Symbol,
&IDiaSymbol::get_symTag);
}
PDB_UniqueId DIARawSymbol::getGuid() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_guid);
}
int32_t DIARawSymbol::getOffset() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_offset);
}
int32_t DIARawSymbol::getThisAdjust() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_thisAdjust);
}
int32_t DIARawSymbol::getVirtualBasePointerOffset() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_virtualBasePointerOffset);
}
PDB_LocType DIARawSymbol::getLocationType() const {
return PrivateGetDIAValue<DWORD, PDB_LocType>(Symbol,
&IDiaSymbol::get_locationType);
}
PDB_Machine DIARawSymbol::getMachineType() const {
return PrivateGetDIAValue<DWORD, PDB_Machine>(Symbol,
&IDiaSymbol::get_machineType);
}
PDB_ThunkOrdinal DIARawSymbol::getThunkOrdinal() const {
return PrivateGetDIAValue<DWORD, PDB_ThunkOrdinal>(
Symbol, &IDiaSymbol::get_thunkOrdinal);
}
uint64_t DIARawSymbol::getLength() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_length);
}
uint64_t DIARawSymbol::getLiveRangeLength() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_liveRangeLength);
}
uint64_t DIARawSymbol::getVirtualAddress() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_virtualAddress);
}
PDB_UdtType DIARawSymbol::getUdtKind() const {
return PrivateGetDIAValue<DWORD, PDB_UdtType>(Symbol,
&IDiaSymbol::get_udtKind);
}
bool DIARawSymbol::hasConstructor() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_constructor);
}
bool DIARawSymbol::hasCustomCallingConvention() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_customCallingConvention);
}
bool DIARawSymbol::hasFarReturn() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_farReturn);
}
bool DIARawSymbol::isCode() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_code);
}
bool DIARawSymbol::isCompilerGenerated() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_compilerGenerated);
}
bool DIARawSymbol::isConstType() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_constType);
}
bool DIARawSymbol::isEditAndContinueEnabled() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_editAndContinueEnabled);
}
bool DIARawSymbol::isFunction() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_function);
}
bool DIARawSymbol::getAddressTaken() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_addressTaken);
}
bool DIARawSymbol::getNoStackOrdering() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_noStackOrdering);
}
bool DIARawSymbol::hasAlloca() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasAlloca);
}
bool DIARawSymbol::hasAssignmentOperator() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasAssignmentOperator);
}
bool DIARawSymbol::hasCTypes() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isCTypes);
}
bool DIARawSymbol::hasCastOperator() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasCastOperator);
}
bool DIARawSymbol::hasDebugInfo() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasDebugInfo);
}
bool DIARawSymbol::hasEH() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasEH);
}
bool DIARawSymbol::hasEHa() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasEHa);
}
bool DIARawSymbol::hasInlAsm() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasInlAsm);
}
bool DIARawSymbol::hasInlineAttribute() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_inlSpec);
}
bool DIARawSymbol::hasInterruptReturn() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_interruptReturn);
}
bool DIARawSymbol::hasFramePointer() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_framePointerPresent);
}
bool DIARawSymbol::hasLongJump() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasLongJump);
}
bool DIARawSymbol::hasManagedCode() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasManagedCode);
}
bool DIARawSymbol::hasNestedTypes() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasNestedTypes);
}
bool DIARawSymbol::hasNoInlineAttribute() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_noInline);
}
bool DIARawSymbol::hasNoReturnAttribute() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_noReturn);
}
bool DIARawSymbol::hasOptimizedCodeDebugInfo() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_optimizedCodeDebugInfo);
}
bool DIARawSymbol::hasOverloadedOperator() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_overloadedOperator);
}
bool DIARawSymbol::hasSEH() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasSEH);
}
bool DIARawSymbol::hasSecurityChecks() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasSecurityChecks);
}
bool DIARawSymbol::hasSetJump() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_hasSetJump);
}
bool DIARawSymbol::hasStrictGSCheck() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_strictGSCheck);
}
bool DIARawSymbol::isAcceleratorGroupSharedLocal() const {
return PrivateGetDIAValue(Symbol,
&IDiaSymbol::get_isAcceleratorGroupSharedLocal);
}
bool DIARawSymbol::isAcceleratorPointerTagLiveRange() const {
return PrivateGetDIAValue(Symbol,
&IDiaSymbol::get_isAcceleratorPointerTagLiveRange);
}
bool DIARawSymbol::isAcceleratorStubFunction() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isAcceleratorStubFunction);
}
bool DIARawSymbol::isAggregated() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isAggregated);
}
bool DIARawSymbol::isIntroVirtualFunction() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_intro);
}
bool DIARawSymbol::isCVTCIL() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isCVTCIL);
}
bool DIARawSymbol::isConstructorVirtualBase() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isConstructorVirtualBase);
}
bool DIARawSymbol::isCxxReturnUdt() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isCxxReturnUdt);
}
bool DIARawSymbol::isDataAligned() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isDataAligned);
}
bool DIARawSymbol::isHLSLData() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isHLSLData);
}
bool DIARawSymbol::isHotpatchable() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isHotpatchable);
}
bool DIARawSymbol::isIndirectVirtualBaseClass() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_indirectVirtualBaseClass);
}
bool DIARawSymbol::isInterfaceUdt() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isInterfaceUdt);
}
bool DIARawSymbol::isIntrinsic() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_intrinsic);
}
bool DIARawSymbol::isLTCG() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isLTCG);
}
bool DIARawSymbol::isLocationControlFlowDependent() const {
return PrivateGetDIAValue(Symbol,
&IDiaSymbol::get_isLocationControlFlowDependent);
}
bool DIARawSymbol::isMSILNetmodule() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isMSILNetmodule);
}
bool DIARawSymbol::isMatrixRowMajor() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isMatrixRowMajor);
}
bool DIARawSymbol::isManagedCode() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_managed);
}
bool DIARawSymbol::isMSILCode() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_msil);
}
bool DIARawSymbol::isMultipleInheritance() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isMultipleInheritance);
}
bool DIARawSymbol::isNaked() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isNaked);
}
bool DIARawSymbol::isNested() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_nested);
}
bool DIARawSymbol::isOptimizedAway() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isOptimizedAway);
}
bool DIARawSymbol::isPacked() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_packed);
}
bool DIARawSymbol::isPointerBasedOnSymbolValue() const {
return PrivateGetDIAValue(Symbol,
&IDiaSymbol::get_isPointerBasedOnSymbolValue);
}
bool DIARawSymbol::isPointerToDataMember() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isPointerToDataMember);
}
bool DIARawSymbol::isPointerToMemberFunction() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isPointerToMemberFunction);
}
bool DIARawSymbol::isPureVirtual() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_pure);
}
bool DIARawSymbol::isRValueReference() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_RValueReference);
}
bool DIARawSymbol::isRefUdt() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isRefUdt);
}
bool DIARawSymbol::isReference() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_reference);
}
bool DIARawSymbol::isRestrictedType() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_restrictedType);
}
bool DIARawSymbol::isReturnValue() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isReturnValue);
}
bool DIARawSymbol::isSafeBuffers() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isSafeBuffers);
}
bool DIARawSymbol::isScoped() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_scoped);
}
bool DIARawSymbol::isSdl() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isSdl);
}
bool DIARawSymbol::isSingleInheritance() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isSingleInheritance);
}
bool DIARawSymbol::isSplitted() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isSplitted);
}
bool DIARawSymbol::isStatic() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isStatic);
}
bool DIARawSymbol::hasPrivateSymbols() const {
// hasPrivateSymbols is the opposite of isStripped, but we expose
// hasPrivateSymbols as a more intuitive interface.
return !PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isStripped);
}
bool DIARawSymbol::isUnalignedType() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_unalignedType);
}
bool DIARawSymbol::isUnreached() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_notReached);
}
bool DIARawSymbol::isValueUdt() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isValueUdt);
}
bool DIARawSymbol::isVirtual() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_virtual);
}
bool DIARawSymbol::isVirtualBaseClass() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_virtualBaseClass);
}
bool DIARawSymbol::isVirtualInheritance() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_isVirtualInheritance);
}
bool DIARawSymbol::isVolatileType() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_volatileType);
}
bool DIARawSymbol::wasInlined() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_wasInlined);
}
std::string DIARawSymbol::getUnused() const {
return PrivateGetDIAValue(Symbol, &IDiaSymbol::get_unused);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo/PDB | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/DIA/DIASession.cpp | //===- DIASession.cpp - DIA implementation of IPDBSession -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/DebugInfo/PDB/DIA/DIAEnumDebugStreams.h"
#include "llvm/DebugInfo/PDB/DIA/DIAEnumLineNumbers.h"
#include "llvm/DebugInfo/PDB/DIA/DIAEnumSourceFiles.h"
#include "llvm/DebugInfo/PDB/DIA/DIARawSymbol.h"
#include "llvm/DebugInfo/PDB/DIA/DIASession.h"
#include "llvm/DebugInfo/PDB/DIA/DIASourceFile.h"
#include "llvm/DebugInfo/PDB/PDBSymbolCompiland.h"
#include "llvm/DebugInfo/PDB/PDBSymbolExe.h"
#include "llvm/Support/ConvertUTF.h"
using namespace llvm;
namespace {}
DIASession::DIASession(CComPtr<IDiaSession> DiaSession) : Session(DiaSession) {}
PDB_ErrorCode DIASession::createFromPdb(StringRef Path,
std::unique_ptr<IPDBSession> &Session) {
CComPtr<IDiaDataSource> DiaDataSource;
CComPtr<IDiaSession> DiaSession;
// We assume that CoInitializeEx has already been called by the executable.
HRESULT Result = ::CoCreateInstance(
CLSID_DiaSource, nullptr, CLSCTX_INPROC_SERVER, IID_IDiaDataSource,
reinterpret_cast<LPVOID *>(&DiaDataSource));
if (FAILED(Result))
return PDB_ErrorCode::NoPdbImpl;
llvm::SmallVector<UTF16, 128> Path16;
if (!llvm::convertUTF8ToUTF16String(Path, Path16))
return PDB_ErrorCode::InvalidPath;
const wchar_t *Path16Str = reinterpret_cast<const wchar_t*>(Path16.data());
if (FAILED(Result = DiaDataSource->loadDataFromPdb(Path16Str))) {
if (Result == E_PDB_NOT_FOUND)
return PDB_ErrorCode::InvalidPath;
else if (Result == E_PDB_FORMAT)
return PDB_ErrorCode::InvalidFileFormat;
else if (Result == E_INVALIDARG)
return PDB_ErrorCode::InvalidParameter;
else if (Result == E_UNEXPECTED)
return PDB_ErrorCode::AlreadyLoaded;
else
return PDB_ErrorCode::UnknownError;
}
if (FAILED(Result = DiaDataSource->openSession(&DiaSession))) {
if (Result == E_OUTOFMEMORY)
return PDB_ErrorCode::NoMemory;
else
return PDB_ErrorCode::UnknownError;
}
Session.reset(new DIASession(DiaSession));
return PDB_ErrorCode::Success;
}
PDB_ErrorCode DIASession::createFromExe(StringRef Path,
std::unique_ptr<IPDBSession> &Session) {
CComPtr<IDiaDataSource> DiaDataSource;
CComPtr<IDiaSession> DiaSession;
// We assume that CoInitializeEx has already been called by the executable.
HRESULT Result = ::CoCreateInstance(
CLSID_DiaSource, nullptr, CLSCTX_INPROC_SERVER, IID_IDiaDataSource,
reinterpret_cast<LPVOID *>(&DiaDataSource));
if (FAILED(Result))
return PDB_ErrorCode::NoPdbImpl;
llvm::SmallVector<UTF16, 128> Path16;
if (!llvm::convertUTF8ToUTF16String(Path, Path16))
return PDB_ErrorCode::InvalidPath;
const wchar_t *Path16Str = reinterpret_cast<const wchar_t *>(Path16.data());
if (FAILED(Result =
DiaDataSource->loadDataForExe(Path16Str, nullptr, nullptr))) {
if (Result == E_PDB_NOT_FOUND)
return PDB_ErrorCode::InvalidPath;
else if (Result == E_PDB_FORMAT)
return PDB_ErrorCode::InvalidFileFormat;
else if (Result == E_PDB_INVALID_SIG || Result == E_PDB_INVALID_AGE)
return PDB_ErrorCode::DebugInfoMismatch;
else if (Result == E_INVALIDARG)
return PDB_ErrorCode::InvalidParameter;
else if (Result == E_UNEXPECTED)
return PDB_ErrorCode::AlreadyLoaded;
else
return PDB_ErrorCode::UnknownError;
}
if (FAILED(Result = DiaDataSource->openSession(&DiaSession))) {
if (Result == E_OUTOFMEMORY)
return PDB_ErrorCode::NoMemory;
else
return PDB_ErrorCode::UnknownError;
}
Session.reset(new DIASession(DiaSession));
return PDB_ErrorCode::Success;
}
uint64_t DIASession::getLoadAddress() const {
uint64_t LoadAddress;
bool success = (S_OK == Session->get_loadAddress(&LoadAddress));
return (success) ? LoadAddress : 0;
}
void DIASession::setLoadAddress(uint64_t Address) {
Session->put_loadAddress(Address);
}
std::unique_ptr<PDBSymbolExe> DIASession::getGlobalScope() const {
CComPtr<IDiaSymbol> GlobalScope;
if (S_OK != Session->get_globalScope(&GlobalScope))
return nullptr;
auto RawSymbol = llvm::make_unique<DIARawSymbol>(*this, GlobalScope);
auto PdbSymbol(PDBSymbol::create(*this, std::move(RawSymbol)));
std::unique_ptr<PDBSymbolExe> ExeSymbol(
static_cast<PDBSymbolExe *>(PdbSymbol.release()));
return ExeSymbol;
}
std::unique_ptr<PDBSymbol> DIASession::getSymbolById(uint32_t SymbolId) const {
CComPtr<IDiaSymbol> LocatedSymbol;
if (S_OK != Session->symbolById(SymbolId, &LocatedSymbol))
return nullptr;
auto RawSymbol = llvm::make_unique<DIARawSymbol>(*this, LocatedSymbol);
return PDBSymbol::create(*this, std::move(RawSymbol));
}
std::unique_ptr<PDBSymbol>
DIASession::findSymbolByAddress(uint64_t Address, PDB_SymType Type) const {
enum SymTagEnum EnumVal = static_cast<enum SymTagEnum>(Type);
CComPtr<IDiaSymbol> Symbol;
if (S_OK != Session->findSymbolByVA(Address, EnumVal, &Symbol)) {
ULONGLONG LoadAddr = 0;
if (S_OK != Session->get_loadAddress(&LoadAddr))
return nullptr;
DWORD RVA = static_cast<DWORD>(Address - LoadAddr);
if (S_OK != Session->findSymbolByRVA(RVA, EnumVal, &Symbol))
return nullptr;
}
auto RawSymbol = llvm::make_unique<DIARawSymbol>(*this, Symbol);
return PDBSymbol::create(*this, std::move(RawSymbol));
}
std::unique_ptr<IPDBEnumLineNumbers>
DIASession::findLineNumbersByAddress(uint64_t Address, uint32_t Length) const {
CComPtr<IDiaEnumLineNumbers> LineNumbers;
if (S_OK != Session->findLinesByVA(Address, Length, &LineNumbers))
return nullptr;
return llvm::make_unique<DIAEnumLineNumbers>(LineNumbers);
}
std::unique_ptr<IPDBEnumSourceFiles> DIASession::getAllSourceFiles() const {
CComPtr<IDiaEnumSourceFiles> Files;
if (S_OK != Session->findFile(nullptr, nullptr, nsNone, &Files))
return nullptr;
return llvm::make_unique<DIAEnumSourceFiles>(*this, Files);
}
std::unique_ptr<IPDBEnumSourceFiles> DIASession::getSourceFilesForCompiland(
const PDBSymbolCompiland &Compiland) const {
CComPtr<IDiaEnumSourceFiles> Files;
const DIARawSymbol &RawSymbol =
static_cast<const DIARawSymbol &>(Compiland.getRawSymbol());
if (S_OK !=
Session->findFile(RawSymbol.getDiaSymbol(), nullptr, nsNone, &Files))
return nullptr;
return llvm::make_unique<DIAEnumSourceFiles>(*this, Files);
}
std::unique_ptr<IPDBSourceFile>
DIASession::getSourceFileById(uint32_t FileId) const {
CComPtr<IDiaSourceFile> LocatedFile;
if (S_OK != Session->findFileById(FileId, &LocatedFile))
return nullptr;
return llvm::make_unique<DIASourceFile>(*this, LocatedFile);
}
std::unique_ptr<IPDBEnumDataStreams> DIASession::getDebugStreams() const {
CComPtr<IDiaEnumDebugStreams> DiaEnumerator;
if (S_OK != Session->getEnumDebugStreams(&DiaEnumerator))
return nullptr;
return llvm::make_unique<DIAEnumDebugStreams>(DiaEnumerator);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo/PDB | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/DIA/DIAEnumSourceFiles.cpp | //==- DIAEnumSourceFiles.cpp - DIA Source File Enumerator impl ---*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/DIA/DIAEnumSourceFiles.h"
#include "llvm/DebugInfo/PDB/DIA/DIASourceFile.h"
using namespace llvm;
DIAEnumSourceFiles::DIAEnumSourceFiles(
const DIASession &PDBSession, CComPtr<IDiaEnumSourceFiles> DiaEnumerator)
: Session(PDBSession), Enumerator(DiaEnumerator) {}
uint32_t DIAEnumSourceFiles::getChildCount() const {
LONG Count = 0;
return (S_OK == Enumerator->get_Count(&Count)) ? Count : 0;
}
std::unique_ptr<IPDBSourceFile>
DIAEnumSourceFiles::getChildAtIndex(uint32_t Index) const {
CComPtr<IDiaSourceFile> Item;
if (S_OK != Enumerator->Item(Index, &Item))
return nullptr;
return std::unique_ptr<IPDBSourceFile>(new DIASourceFile(Session, Item));
}
std::unique_ptr<IPDBSourceFile> DIAEnumSourceFiles::getNext() {
CComPtr<IDiaSourceFile> Item;
ULONG NumFetched = 0;
if (S_OK != Enumerator->Next(1, &Item, &NumFetched))
return nullptr;
return std::unique_ptr<IPDBSourceFile>(new DIASourceFile(Session, Item));
}
void DIAEnumSourceFiles::reset() { Enumerator->Reset(); }
DIAEnumSourceFiles *DIAEnumSourceFiles::clone() const {
CComPtr<IDiaEnumSourceFiles> EnumeratorClone;
if (S_OK != Enumerator->Clone(&EnumeratorClone))
return nullptr;
return new DIAEnumSourceFiles(Session, EnumeratorClone);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo/PDB | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/DIA/DIAEnumLineNumbers.cpp | //==- DIAEnumLineNumbers.cpp - DIA Line Number Enumerator impl ---*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/PDBSymbol.h"
#include "llvm/DebugInfo/PDB/DIA/DIAEnumLineNumbers.h"
#include "llvm/DebugInfo/PDB/DIA/DIALineNumber.h"
using namespace llvm;
DIAEnumLineNumbers::DIAEnumLineNumbers(
CComPtr<IDiaEnumLineNumbers> DiaEnumerator)
: Enumerator(DiaEnumerator) {}
uint32_t DIAEnumLineNumbers::getChildCount() const {
LONG Count = 0;
return (S_OK == Enumerator->get_Count(&Count)) ? Count : 0;
}
std::unique_ptr<IPDBLineNumber>
DIAEnumLineNumbers::getChildAtIndex(uint32_t Index) const {
CComPtr<IDiaLineNumber> Item;
if (S_OK != Enumerator->Item(Index, &Item))
return nullptr;
return std::unique_ptr<IPDBLineNumber>(new DIALineNumber(Item));
}
std::unique_ptr<IPDBLineNumber> DIAEnumLineNumbers::getNext() {
CComPtr<IDiaLineNumber> Item;
ULONG NumFetched = 0;
if (S_OK != Enumerator->Next(1, &Item, &NumFetched))
return nullptr;
return std::unique_ptr<IPDBLineNumber>(new DIALineNumber(Item));
}
void DIAEnumLineNumbers::reset() { Enumerator->Reset(); }
DIAEnumLineNumbers *DIAEnumLineNumbers::clone() const {
CComPtr<IDiaEnumLineNumbers> EnumeratorClone;
if (S_OK != Enumerator->Clone(&EnumeratorClone))
return nullptr;
return new DIAEnumLineNumbers(EnumeratorClone);
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo/PDB | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/DIA/DIASourceFile.cpp | //===- DIASourceFile.cpp - DIA implementation of IPDBSourceFile -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/DIA/DIAEnumSymbols.h"
#include "llvm/DebugInfo/PDB/DIA/DIASession.h"
#include "llvm/DebugInfo/PDB/DIA/DIASourceFile.h"
#include "llvm/Support/ConvertUTF.h"
using namespace llvm;
DIASourceFile::DIASourceFile(const DIASession &PDBSession,
CComPtr<IDiaSourceFile> DiaSourceFile)
: Session(PDBSession), SourceFile(DiaSourceFile) {}
std::string DIASourceFile::getFileName() const {
CComBSTR FileName16;
HRESULT Result = SourceFile->get_fileName(&FileName16);
if (S_OK != Result)
return std::string();
std::string FileName8;
llvm::ArrayRef<char> FileNameBytes(reinterpret_cast<char *>(FileName16.m_str),
FileName16.ByteLength());
llvm::convertUTF16ToUTF8String(FileNameBytes, FileName8);
return FileName8;
}
uint32_t DIASourceFile::getUniqueId() const {
DWORD Id;
return (S_OK == SourceFile->get_uniqueId(&Id)) ? Id : 0;
}
std::string DIASourceFile::getChecksum() const {
DWORD ByteSize = 0;
HRESULT Result = SourceFile->get_checksum(0, &ByteSize, nullptr);
if (ByteSize == 0)
return std::string();
std::vector<BYTE> ChecksumBytes(ByteSize);
Result = SourceFile->get_checksum(ByteSize, &ByteSize, &ChecksumBytes[0]);
if (S_OK != Result)
return std::string();
return std::string(ChecksumBytes.begin(), ChecksumBytes.end());
}
PDB_Checksum DIASourceFile::getChecksumType() const {
DWORD Type;
HRESULT Result = SourceFile->get_checksumType(&Type);
if (S_OK != Result)
return PDB_Checksum::None;
return static_cast<PDB_Checksum>(Type);
}
std::unique_ptr<IPDBEnumSymbols> DIASourceFile::getCompilands() const {
CComPtr<IDiaEnumSymbols> DiaEnumerator;
HRESULT Result = SourceFile->get_compilands(&DiaEnumerator);
if (S_OK != Result)
return nullptr;
return std::unique_ptr<IPDBEnumSymbols>(
new DIAEnumSymbols(Session, DiaEnumerator));
}
|
0 | repos/DirectXShaderCompiler/lib/DebugInfo/PDB | repos/DirectXShaderCompiler/lib/DebugInfo/PDB/DIA/DIALineNumber.cpp | //===- DIALineNumber.cpp - DIA implementation of IPDBLineNumber -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/PDB/DIA/DIALineNumber.h"
using namespace llvm;
DIALineNumber::DIALineNumber(CComPtr<IDiaLineNumber> DiaLineNumber)
: LineNumber(DiaLineNumber) {}
uint32_t DIALineNumber::getLineNumber() const {
DWORD Line = 0;
return (S_OK == LineNumber->get_lineNumber(&Line)) ? Line : 0;
}
uint32_t DIALineNumber::getLineNumberEnd() const {
DWORD LineEnd = 0;
return (S_OK == LineNumber->get_lineNumberEnd(&LineEnd)) ? LineEnd : 0;
}
uint32_t DIALineNumber::getColumnNumber() const {
DWORD Column = 0;
return (S_OK == LineNumber->get_columnNumber(&Column)) ? Column : 0;
}
uint32_t DIALineNumber::getColumnNumberEnd() const {
DWORD ColumnEnd = 0;
return (S_OK == LineNumber->get_columnNumberEnd(&ColumnEnd)) ? ColumnEnd : 0;
}
uint32_t DIALineNumber::getAddressSection() const {
DWORD Section = 0;
return (S_OK == LineNumber->get_addressSection(&Section)) ? Section : 0;
}
uint32_t DIALineNumber::getAddressOffset() const {
DWORD Offset = 0;
return (S_OK == LineNumber->get_addressOffset(&Offset)) ? Offset : 0;
}
uint32_t DIALineNumber::getRelativeVirtualAddress() const {
DWORD RVA = 0;
return (S_OK == LineNumber->get_relativeVirtualAddress(&RVA)) ? RVA : 0;
}
uint64_t DIALineNumber::getVirtualAddress() const {
ULONGLONG Addr = 0;
return (S_OK == LineNumber->get_virtualAddress(&Addr)) ? Addr : 0;
}
uint32_t DIALineNumber::getLength() const {
DWORD Length = 0;
return (S_OK == LineNumber->get_length(&Length)) ? Length : 0;
}
uint32_t DIALineNumber::getSourceFileId() const {
DWORD Id = 0;
return (S_OK == LineNumber->get_sourceFileId(&Id)) ? Id : 0;
}
uint32_t DIALineNumber::getCompilandId() const {
DWORD Id = 0;
return (S_OK == LineNumber->get_compilandId(&Id)) ? Id : 0;
}
bool DIALineNumber::isStatement() const {
BOOL Statement = 0;
return (S_OK == LineNumber->get_statement(&Statement)) ? Statement : false;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.