本文整理汇总了C++中SourceMgr类的典型用法代码示例。如果您正苦于以下问题:C++ SourceMgr类的具体用法?C++ SourceMgr怎么用?C++ SourceMgr使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SourceMgr类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
int main(int ac, char **av)
{
SourceMgr SrcMgr;
//LLVMInitializeX86TargetInfo();
llvm::InitializeAllTargetInfos();
//LLVMInitializeX86AsmParser();
llvm::InitializeAllTargetMCs();
//LLVMInitializeX86TargetMC();
llvm::InitializeAllAsmParsers();
//LLVMInitializeX86AsmParser();
llvm::InitializeAllDisassemblers();
//LLVMInitializeX86Disassembler();
// arg0:
// llvm::Target encapsulating the "x86_64-apple-darwin14.5.0" information
// see /lib/Support/Triple.cpp for the details
//spec = llvm::sys::getDefaultTargetTriple();
//std::string machSpec = "x86_64-apple-windows"; // will produce a COFF
//std::string machSpec = "x86_64-apple-darwin14.5.0"; // will produce a Mach-O
std::string machSpec = "arm-none-none-eabi"; //
//std::string machSpec = "x86_64-apple-darwin";
//std::string machSpec = "x86_64-thumb-linux-gnu";
//std::string machSpec = "x86_64-unknown-linux-gnu";
printf("machine spec: %s\n", machSpec.c_str());
machSpec = Triple::normalize(machSpec);
printf("machine spec (normalized): %s\n", machSpec.c_str());
Triple TheTriple(machSpec);
// Get the target specific parser.
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(/*arch*/"", TheTriple, Error);
if (!TheTarget) {
errs() << Error;
return -1;
}
machSpec = TheTriple.getTriple();
printf("machine spec (returned): %s\n", machSpec.c_str());
printf("Target.getName(): %s\n", TheTarget->getName());
printf("Target.getShortDescription(): %s\n", TheTarget->getShortDescription());
/* from the target we get almost everything */
std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(machSpec));
std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, machSpec));
std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); /* describes target instruction set */
MCSubtargetInfo *STI = TheTarget->createMCSubtargetInfo(machSpec, "", ""); /* subtarget instr set */
MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, machSpec, /* specific CPU */ "");
// arg0:
// llvm::SourceMgr (Support/SourceMgr.h) that holds assembler source
// has vector of llvm::SrcBuffer encaps (Support/MemoryBuffer.h) and vector of include dirs
//std::string asmSrc = ".org 0x100, 0xAA\nfoo:\nxor %eax, %ebx\npush %rbp\njmp foo\nrdtsc\n";
//std::string asmSrc = ".text\n" "ldr pc, data_foo\n" "\n" "data_foo:\n" " .int 0x8\n" "\n" "loop:\n" "b loop\n";
//std::string asmSrc = ".text\n" "mov r2, r1\n";
std::string asmSrc = ".text\n" "ldr pc, data_foo\n" "data_foo:\n" ".int 0x8\n" "loop:\n" "b loop\n";
std::unique_ptr<MemoryBuffer> memBuf = MemoryBuffer::getMemBuffer(asmSrc);
SrcMgr.AddNewSourceBuffer(std::move(memBuf), SMLoc());
// arg1: the machine code context
MCObjectFileInfo MOFI;
MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
MOFI.InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default, Ctx);
// this is the assembler interface
// -methods per .s statements (emit bytes, handle directive, etc.)
// -remembers current section
// -implementations that write a .s, or .o in various formats
//
// 1. the output stream ... a formatted_raw_ostream wraps a raw_ostream to provide
// tracking of line and column position for padding and shit
//
// but raw_ostream is abstract and is implemented by raw_fd_ostream, raw_string_ostream, etc.
/* output stream:
raw_svector_ostream is a raw_pwrite_stream is a raw_ostream
since a SmallString is SmallVector (svector) we can use this and
retrieve bytes later with its .data() method */
SmallString<1024> smallString;
raw_svector_ostream rso(smallString);
/* code emitter needs 1) instruction set info 2) register info */
MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
MCStreamer *as = TheTarget->createMCObjectStreamer(
TheTriple, /* Triple */
Ctx, /* the MCContext */
*MAB, /* the AsmBackend, (fixups, relaxation, objs and elfs) */
rso, /* output stream raw_pwrite_stream */
CE, /* code emitter */
*STI, /* subtarget info */
true, /* relax all fixups */
true, /* incremental linker compatible */
false /* DWARFMustBeAtTheEnd */
);
std::string abi = "none";
//.........这里部分代码省略.........
示例2: ParsePattern
bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM) {
PatternLoc = SMLoc::getFromPointer(PatternStr.data());
// Ignore trailing whitespace.
while (!PatternStr.empty() &&
(PatternStr.back() == ' ' || PatternStr.back() == '\t'))
PatternStr = PatternStr.substr(0, PatternStr.size()-1);
// Check that there is something on the line.
if (PatternStr.empty()) {
SM.PrintMessage(PatternLoc, "found empty check string with prefix '" +
CheckPrefix+":'", "error");
return true;
}
// Check to see if this is a fixed string, or if it has regex pieces.
if (PatternStr.size() < 2 ||
(PatternStr.find("{{") == StringRef::npos &&
PatternStr.find("[[") == StringRef::npos)) {
FixedStr = PatternStr;
return false;
}
// Paren value #0 is for the fully matched string. Any new parenthesized
// values add from their.
unsigned CurParen = 1;
// Otherwise, there is at least one regex piece. Build up the regex pattern
// by escaping scary characters in fixed strings, building up one big regex.
while (!PatternStr.empty()) {
// RegEx matches.
if (PatternStr.size() >= 2 &&
PatternStr[0] == '{' && PatternStr[1] == '{') {
// Otherwise, this is the start of a regex match. Scan for the }}.
size_t End = PatternStr.find("}}");
if (End == StringRef::npos) {
SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
"found start of regex string with no end '}}'", "error");
return true;
}
if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
return true;
PatternStr = PatternStr.substr(End+2);
continue;
}
// Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
// (or some other regex) and assigns it to the FileCheck variable 'foo'. The
// second form is [[foo]] which is a reference to foo. The variable name
// itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
// it. This is to catch some common errors.
if (PatternStr.size() >= 2 &&
PatternStr[0] == '[' && PatternStr[1] == '[') {
// Verify that it is terminated properly.
size_t End = PatternStr.find("]]");
if (End == StringRef::npos) {
SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
"invalid named regex reference, no ]] found", "error");
return true;
}
StringRef MatchStr = PatternStr.substr(2, End-2);
PatternStr = PatternStr.substr(End+2);
// Get the regex name (e.g. "foo").
size_t NameEnd = MatchStr.find(':');
StringRef Name = MatchStr.substr(0, NameEnd);
if (Name.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
"invalid name in named regex: empty name", "error");
return true;
}
// Verify that the name is well formed.
for (unsigned i = 0, e = Name.size(); i != e; ++i)
if (Name[i] != '_' &&
(Name[i] < 'a' || Name[i] > 'z') &&
(Name[i] < 'A' || Name[i] > 'Z') &&
(Name[i] < '0' || Name[i] > '9')) {
SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
"invalid name in named regex", "error");
return true;
}
// Name can't start with a digit.
if (isdigit(Name[0])) {
SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
"invalid name in named regex", "error");
return true;
}
// Handle [[foo]].
if (NameEnd == StringRef::npos) {
VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
continue;
}
//.........这里部分代码省略.........
示例3: ReadCheckFile
/// ReadCheckFile - Read the check file, which specifies the sequence of
/// expected strings. The strings are added to the CheckStrings vector.
static bool ReadCheckFile(SourceMgr &SM,
std::vector<CheckString> &CheckStrings) {
// Open the check file, and tell SourceMgr about it.
std::string ErrorStr;
MemoryBuffer *F =
MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
if (F == 0) {
errs() << "Could not open check file '" << CheckFilename << "': "
<< ErrorStr << '\n';
return true;
}
// If we want to canonicalize whitespace, strip excess whitespace from the
// buffer containing the CHECK lines.
if (!NoCanonicalizeWhiteSpace)
F = CanonicalizeInputFile(F);
SM.AddNewSourceBuffer(F, SMLoc());
// Find all instances of CheckPrefix followed by : in the file.
StringRef Buffer = F->getBuffer();
std::vector<std::pair<SMLoc, Pattern> > NotMatches;
while (1) {
// See if Prefix occurs in the memory buffer.
Buffer = Buffer.substr(Buffer.find(CheckPrefix));
// If we didn't find a match, we're done.
if (Buffer.empty())
break;
const char *CheckPrefixStart = Buffer.data();
// When we find a check prefix, keep track of whether we find CHECK: or
// CHECK-NEXT:
bool IsCheckNext = false, IsCheckNot = false;
// Verify that the : is present after the prefix.
if (Buffer[CheckPrefix.size()] == ':') {
Buffer = Buffer.substr(CheckPrefix.size()+1);
} else if (Buffer.size() > CheckPrefix.size()+6 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+7);
IsCheckNext = true;
} else if (Buffer.size() > CheckPrefix.size()+5 &&
memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
Buffer = Buffer.substr(CheckPrefix.size()+6);
IsCheckNot = true;
} else {
Buffer = Buffer.substr(1);
continue;
}
// Okay, we found the prefix, yay. Remember the rest of the line, but
// ignore leading and trailing whitespace.
Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
// Scan ahead to the end of line.
size_t EOL = Buffer.find_first_of("\n\r");
// Remember the location of the start of the pattern, for diagnostics.
SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
// Parse the pattern.
Pattern P;
if (P.ParsePattern(Buffer.substr(0, EOL), SM))
return true;
Buffer = Buffer.substr(EOL);
// Verify that CHECK-NEXT lines have at least one CHECK line before them.
if (IsCheckNext && CheckStrings.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
"found '"+CheckPrefix+"-NEXT:' without previous '"+
CheckPrefix+ ": line", "error");
return true;
}
// Handle CHECK-NOT.
if (IsCheckNot) {
NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
P));
continue;
}
// Okay, add the string we captured to the output vector and move on.
CheckStrings.push_back(CheckString(P,
PatternLoc,
IsCheckNext));
std::swap(NotMatches, CheckStrings.back().NotStrings);
}
if (CheckStrings.empty()) {
errs() << "error: no check strings found with prefix '" << CheckPrefix
<< ":'\n";
//.........这里部分代码省略.........
示例4: assert
/// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
InlineAsm::AsmDialect Dialect) const {
assert(!Str.empty() && "Can't emit empty inline asm block");
// Remember if the buffer is nul terminated or not so we can avoid a copy.
bool isNullTerminated = Str.back() == 0;
if (isNullTerminated)
Str = Str.substr(0, Str.size()-1);
// If the output streamer does not have mature MC support or the integrated
// assembler has been disabled, just emit the blob textually.
// Otherwise parse the asm and emit it via MC support.
// This is useful in case the asm parser doesn't handle something but the
// system assembler does.
const MCAsmInfo *MCAI = TM.getMCAsmInfo();
assert(MCAI && "No MCAsmInfo");
if (!MCAI->useIntegratedAssembler() &&
!OutStreamer.isIntegratedAssemblerRequired()) {
OutStreamer.EmitRawText(Str);
emitInlineAsmEnd(TM.getSubtarget<MCSubtargetInfo>(), 0);
return;
}
SourceMgr SrcMgr;
SrcMgrDiagInfo DiagInfo;
// If the current LLVMContext has an inline asm handler, set it in SourceMgr.
LLVMContext &LLVMCtx = MMI->getModule()->getContext();
bool HasDiagHandler = false;
if (LLVMCtx.getInlineAsmDiagnosticHandler() != 0) {
// If the source manager has an issue, we arrange for srcMgrDiagHandler
// to be invoked, getting DiagInfo passed into it.
DiagInfo.LocInfo = LocMDNode;
DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
HasDiagHandler = true;
}
MemoryBuffer *Buffer;
if (isNullTerminated)
Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
else
Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
// Tell SrcMgr about this buffer, it takes ownership of the buffer.
SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
std::unique_ptr<MCAsmParser> Parser(
createMCAsmParser(SrcMgr, OutContext, OutStreamer, *MAI));
// Initialize the parser with a fresh subtarget info. It is better to use a
// new STI here because the parser may modify it and we do not want those
// modifications to persist after parsing the inlineasm. The modifications
// made by the parser will be seen by the code emitters because it passes
// the current STI down to the EncodeInstruction() method.
std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
// Preserve a copy of the original STI because the parser may modify it. For
// example, when switching between arm and thumb mode. If the target needs to
// emit code to return to the original state it can do so in
// emitInlineAsmEnd().
MCSubtargetInfo STIOrig = *STI;
std::unique_ptr<MCTargetAsmParser> TAP(
TM.getTarget().createMCAsmParser(*STI, *Parser, *MII));
if (!TAP)
report_fatal_error("Inline asm not supported by this streamer because"
" we don't have an asm parser for this target\n");
Parser->setAssemblerDialect(Dialect);
Parser->setTargetParser(*TAP.get());
// Don't implicitly switch to the text section before the asm.
int Res = Parser->Run(/*NoInitialTextSection*/ true,
/*NoFinalize*/ true);
emitInlineAsmEnd(STIOrig, STI.get());
if (Res && !HasDiagHandler)
report_fatal_error("Error parsing inline asm\n");
}
示例5: main
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets and assembly printers/parsers.
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmParsers();
llvm::InitializeAllDisassemblers();
// Register the target printer for --version.
cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
TripleName = Triple::normalize(TripleName);
setDwarfDebugFlags(argc, argv);
setDwarfDebugProducer();
const char *ProgName = argv[0];
const Target *TheTarget = GetTarget(ProgName);
if (!TheTarget)
return 1;
OwningPtr<MemoryBuffer> BufferPtr;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
errs() << ProgName << ": " << ec.message() << '\n';
return 1;
}
MemoryBuffer *Buffer = BufferPtr.take();
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
// Record the location of the include directories so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(IncludeDirs);
llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
assert(MRI && "Unable to create target register info!");
llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
assert(MAI && "Unable to create target asm info!");
// FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
// MCObjectFileInfo needs a MCContext reference in order to initialize itself.
OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
if (SaveTempLabels)
Ctx.setAllowTemporaryLabels(false);
Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
if (!DwarfDebugFlags.empty())
Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
if (!DwarfDebugProducer.empty())
Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
if (!DebugCompilationDir.empty())
Ctx.setCompilationDir(DebugCompilationDir);
if (!MainFileName.empty())
Ctx.setMainFileName(MainFileName);
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
if (MAttrs.size()) {
SubtargetFeatures Features;
for (unsigned i = 0; i != MAttrs.size(); ++i)
Features.AddFeature(MAttrs[i]);
FeaturesStr = Features.getString();
}
OwningPtr<tool_output_file> Out(GetOutputStream());
if (!Out)
return 1;
formatted_raw_ostream FOS(Out->os());
OwningPtr<MCStreamer> Str;
OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
OwningPtr<MCSubtargetInfo>
STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
MCInstPrinter *IP = NULL;
if (FileType == OFT_AssemblyFile) {
IP =
TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
MCCodeEmitter *CE = 0;
MCAsmBackend *MAB = 0;
if (ShowEncoding) {
CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
}
bool UseCFI = !DisableCFI;
Str.reset(TheTarget->createAsmStreamer(
Ctx, FOS, /*asmverbose*/ true, UseCFI,
//.........这里部分代码省略.........
示例6: ExecuteAssembler
static bool ExecuteAssembler(AssemblerInvocation &Opts,
DiagnosticsEngine &Diags) {
// Get the target specific parser.
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
if (!TheTarget)
return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
if (std::error_code EC = Buffer.getError()) {
Error = EC.message();
return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
}
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
// Record the location of the include directories so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(Opts.IncludePaths);
std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
assert(MRI && "Unable to create target register info!");
std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
assert(MAI && "Unable to create target asm info!");
// Ensure MCAsmInfo initialization occurs before any use, otherwise sections
// may be created with a combination of default and explicit settings.
MAI->setCompressDebugSections(Opts.CompressDebugSections);
MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
if (Opts.OutputPath.empty())
Opts.OutputPath = "-";
std::unique_ptr<raw_fd_ostream> FDOS =
getOutputStream(Opts.OutputPath, Diags, IsBinary);
if (!FDOS)
return true;
std::unique_ptr<raw_fd_ostream> DwoOS;
if (!Opts.SplitDwarfFile.empty())
DwoOS = getOutputStream(Opts.SplitDwarfFile, Diags, IsBinary);
// FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
// MCObjectFileInfo needs a MCContext reference in order to initialize itself.
std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
bool PIC = false;
if (Opts.RelocationModel == "static") {
PIC = false;
} else if (Opts.RelocationModel == "pic") {
PIC = true;
} else {
assert(Opts.RelocationModel == "dynamic-no-pic" &&
"Invalid PIC model!");
PIC = false;
}
MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
if (Opts.SaveTemporaryLabels)
Ctx.setAllowTemporaryLabels(false);
if (Opts.GenDwarfForAssembly)
Ctx.setGenDwarfForAssembly(true);
if (!Opts.DwarfDebugFlags.empty())
Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
if (!Opts.DwarfDebugProducer.empty())
Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
if (!Opts.DebugCompilationDir.empty())
Ctx.setCompilationDir(Opts.DebugCompilationDir);
if (!Opts.DebugPrefixMap.empty())
for (const auto &KV : Opts.DebugPrefixMap)
Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
if (!Opts.MainFileName.empty())
Ctx.setMainFileName(StringRef(Opts.MainFileName));
Ctx.setDwarfVersion(Opts.DwarfVersion);
// Build up the feature string from the target feature list.
std::string FS;
if (!Opts.Features.empty()) {
FS = Opts.Features[0];
for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
FS += "," + Opts.Features[i];
}
std::unique_ptr<MCStreamer> Str;
std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
std::unique_ptr<MCSubtargetInfo> STI(
TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
raw_pwrite_stream *Out = FDOS.get();
std::unique_ptr<buffer_ostream> BOS;
//.........这里部分代码省略.........
示例7: MRI
int Disassembler::disassemble(const Target &T,
const std::string &Triple,
MCSubtargetInfo &STI,
MCStreamer &Streamer,
MemoryBuffer &Buffer,
SourceMgr &SM,
raw_ostream &Out) {
std::unique_ptr<const MCRegisterInfo> MRI(T.createMCRegInfo(Triple));
if (!MRI) {
errs() << "error: no register info for target " << Triple << "\n";
return -1;
}
std::unique_ptr<const MCAsmInfo> MAI(T.createMCAsmInfo(*MRI, Triple));
if (!MAI) {
errs() << "error: no assembly info for target " << Triple << "\n";
return -1;
}
// Set up the MCContext for creating symbols and MCExpr's.
MCContext Ctx(MAI.get(), MRI.get(), nullptr);
std::unique_ptr<const MCDisassembler> DisAsm(
T.createMCDisassembler(STI, Ctx));
if (!DisAsm) {
errs() << "error: no disassembler for target " << Triple << "\n";
return -1;
}
// Set up initial section manually here
Streamer.InitSections(false);
bool ErrorOccurred = false;
// Convert the input to a vector for disassembly.
ByteArrayTy ByteArray;
StringRef Str = Buffer.getBuffer();
bool InAtomicBlock = false;
while (SkipToToken(Str)) {
ByteArray.first.clear();
ByteArray.second.clear();
if (Str[0] == '[') {
if (InAtomicBlock) {
SM.PrintMessage(SMLoc::getFromPointer(Str.data()), SourceMgr::DK_Error,
"nested atomic blocks make no sense");
ErrorOccurred = true;
}
InAtomicBlock = true;
Str = Str.drop_front();
continue;
} else if (Str[0] == ']') {
if (!InAtomicBlock) {
SM.PrintMessage(SMLoc::getFromPointer(Str.data()), SourceMgr::DK_Error,
"attempt to close atomic block without opening");
ErrorOccurred = true;
}
InAtomicBlock = false;
Str = Str.drop_front();
continue;
}
// It's a real token, get the bytes and emit them
ErrorOccurred |= ByteArrayFromString(ByteArray, Str, SM);
if (!ByteArray.first.empty())
ErrorOccurred |= PrintInsts(*DisAsm, ByteArray, SM, Out, Streamer,
InAtomicBlock, STI);
}
if (InAtomicBlock) {
SM.PrintMessage(SMLoc::getFromPointer(Str.data()), SourceMgr::DK_Error,
"unclosed atomic block");
ErrorOccurred = true;
}
return ErrorOccurred;
}
示例8: AsLexInput
static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
raw_ostream &OS) {
AsmLexer Lexer(MAI);
Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
bool Error = false;
while (Lexer.Lex().isNot(AsmToken::Eof)) {
const AsmToken &Tok = Lexer.getTok();
switch (Tok.getKind()) {
default:
SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
"unknown token");
Error = true;
break;
case AsmToken::Error:
Error = true; // error already printed.
break;
case AsmToken::Identifier:
OS << "identifier: " << Lexer.getTok().getString();
break;
case AsmToken::Integer:
OS << "int: " << Lexer.getTok().getString();
break;
case AsmToken::Real:
OS << "real: " << Lexer.getTok().getString();
break;
case AsmToken::String:
OS << "string: " << Lexer.getTok().getString();
break;
case AsmToken::Amp: OS << "Amp"; break;
case AsmToken::AmpAmp: OS << "AmpAmp"; break;
case AsmToken::At: OS << "At"; break;
case AsmToken::Caret: OS << "Caret"; break;
case AsmToken::Colon: OS << "Colon"; break;
case AsmToken::Comma: OS << "Comma"; break;
case AsmToken::Dollar: OS << "Dollar"; break;
case AsmToken::Dot: OS << "Dot"; break;
case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
case AsmToken::Eof: OS << "Eof"; break;
case AsmToken::Equal: OS << "Equal"; break;
case AsmToken::EqualEqual: OS << "EqualEqual"; break;
case AsmToken::Exclaim: OS << "Exclaim"; break;
case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
case AsmToken::Greater: OS << "Greater"; break;
case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
case AsmToken::Hash: OS << "Hash"; break;
case AsmToken::LBrac: OS << "LBrac"; break;
case AsmToken::LCurly: OS << "LCurly"; break;
case AsmToken::LParen: OS << "LParen"; break;
case AsmToken::Less: OS << "Less"; break;
case AsmToken::LessEqual: OS << "LessEqual"; break;
case AsmToken::LessGreater: OS << "LessGreater"; break;
case AsmToken::LessLess: OS << "LessLess"; break;
case AsmToken::Minus: OS << "Minus"; break;
case AsmToken::Percent: OS << "Percent"; break;
case AsmToken::Pipe: OS << "Pipe"; break;
case AsmToken::PipePipe: OS << "PipePipe"; break;
case AsmToken::Plus: OS << "Plus"; break;
case AsmToken::RBrac: OS << "RBrac"; break;
case AsmToken::RCurly: OS << "RCurly"; break;
case AsmToken::RParen: OS << "RParen"; break;
case AsmToken::Slash: OS << "Slash"; break;
case AsmToken::Star: OS << "Star"; break;
case AsmToken::Tilde: OS << "Tilde"; break;
case AsmToken::PercentCall16:
OS << "PercentCall16";
break;
case AsmToken::PercentCall_Hi:
OS << "PercentCall_Hi";
break;
case AsmToken::PercentCall_Lo:
OS << "PercentCall_Lo";
break;
case AsmToken::PercentDtprel_Hi:
OS << "PercentDtprel_Hi";
break;
case AsmToken::PercentDtprel_Lo:
OS << "PercentDtprel_Lo";
break;
case AsmToken::PercentGot:
OS << "PercentGot";
break;
case AsmToken::PercentGot_Disp:
OS << "PercentGot_Disp";
break;
case AsmToken::PercentGot_Hi:
OS << "PercentGot_Hi";
break;
case AsmToken::PercentGot_Lo:
OS << "PercentGot_Lo";
break;
case AsmToken::PercentGot_Ofst:
OS << "PercentGot_Ofst";
break;
case AsmToken::PercentGot_Page:
OS << "PercentGot_Page";
//.........这里部分代码省略.........
示例9: ExecuteAssembler
static bool ExecuteAssembler(AssemblerInvocation &Opts,
DiagnosticsEngine &Diags) {
// Get the target specific parser.
std::string Error;
const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
if (!TheTarget) {
Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
return false;
}
OwningPtr<MemoryBuffer> BufferPtr;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
Error = ec.message();
Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
return false;
}
MemoryBuffer *Buffer = BufferPtr.take();
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
// Record the location of the include directories so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(Opts.IncludePaths);
OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
assert(MRI && "Unable to create target register info!");
OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
assert(MAI && "Unable to create target asm info!");
bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
if (!Out)
return false;
// FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
// MCObjectFileInfo needs a MCContext reference in order to initialize itself.
OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
// FIXME: Assembler behavior can change with -static.
MOFI->InitMCObjectFileInfo(Opts.Triple,
Reloc::Default, CodeModel::Default, Ctx);
if (Opts.SaveTemporaryLabels)
Ctx.setAllowTemporaryLabels(false);
if (Opts.GenDwarfForAssembly)
Ctx.setGenDwarfForAssembly(true);
if (!Opts.DwarfDebugFlags.empty())
Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
if (!Opts.DwarfDebugProducer.empty())
Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
if (!Opts.DebugCompilationDir.empty())
Ctx.setCompilationDir(Opts.DebugCompilationDir);
if (!Opts.MainFileName.empty())
Ctx.setMainFileName(StringRef(Opts.MainFileName));
// Build up the feature string from the target feature list.
std::string FS;
if (!Opts.Features.empty()) {
FS = Opts.Features[0];
for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
FS += "," + Opts.Features[i];
}
OwningPtr<MCStreamer> Str;
OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
OwningPtr<MCSubtargetInfo>
STI(TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
// FIXME: There is a bit of code duplication with addPassesToEmitFile.
if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
MCInstPrinter *IP =
TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
*STI);
MCCodeEmitter *CE = 0;
MCAsmBackend *MAB = 0;
if (Opts.ShowEncoding) {
CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU);
}
Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
/*useLoc*/ true,
/*useCFI*/ true,
/*useDwarfDirectory*/ true,
IP, CE, MAB,
Opts.ShowInst));
} else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
Str.reset(createNullStreamer(Ctx));
} else {
assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
"Invalid file type!");
MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
Opts.CPU);
Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,
CE, Opts.RelaxAll,
Opts.NoExecStack));
//.........这里部分代码省略.........
示例10: assert
/// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
InlineAsm::AsmDialect Dialect) const {
assert(!Str.empty() && "Can't emit empty inline asm block");
// Remember if the buffer is nul terminated or not so we can avoid a copy.
bool isNullTerminated = Str.back() == 0;
if (isNullTerminated)
Str = Str.substr(0, Str.size()-1);
// If the output streamer is actually a .s file, just emit the blob textually.
// This is useful in case the asm parser doesn't handle something but the
// system assembler does.
if (OutStreamer.hasRawTextSupport()) {
OutStreamer.EmitRawText(Str);
return;
}
SourceMgr SrcMgr;
SrcMgrDiagInfo DiagInfo;
// If the current LLVMContext has an inline asm handler, set it in SourceMgr.
LLVMContext &LLVMCtx = MMI->getModule()->getContext();
bool HasDiagHandler = false;
if (LLVMCtx.getInlineAsmDiagnosticHandler() != 0) {
// If the source manager has an issue, we arrange for srcMgrDiagHandler
// to be invoked, getting DiagInfo passed into it.
DiagInfo.LocInfo = LocMDNode;
DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
HasDiagHandler = true;
}
MemoryBuffer *Buffer;
if (isNullTerminated)
Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
else
Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
// Tell SrcMgr about this buffer, it takes ownership of the buffer.
SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
OutContext, OutStreamer,
*MAI));
// FIXME: It would be nice if we can avoid createing a new instance of
// MCSubtargetInfo here given TargetSubtargetInfo is available. However,
// we have to watch out for asm directives which can change subtarget
// state. e.g. .code 16, .code 32.
OwningPtr<MCSubtargetInfo>
STI(TM.getTarget().createMCSubtargetInfo(TM.getTargetTriple(),
TM.getTargetCPU(),
TM.getTargetFeatureString()));
OwningPtr<MCTargetAsmParser>
TAP(TM.getTarget().createMCAsmParser(*STI, *Parser, *MII));
if (!TAP)
report_fatal_error("Inline asm not supported by this streamer because"
" we don't have an asm parser for this target\n");
Parser->setAssemblerDialect(Dialect);
Parser->setTargetParser(*TAP.get());
// Don't implicitly switch to the text section before the asm.
int Res = Parser->Run(/*NoInitialTextSection*/ true,
/*NoFinalize*/ true);
if (Res && !HasDiagHandler)
report_fatal_error("Error parsing inline asm\n");
}
示例11: ExecuteAssembler
static bool ExecuteAssembler(AssemblerInvocation &Opts,
DiagnosticsEngine &Diags) {
// Get the target specific parser.
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
if (!TheTarget)
return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
if (std::error_code EC = Buffer.getError()) {
Error = EC.message();
return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
}
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
// Record the location of the include directories so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(Opts.IncludePaths);
std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
assert(MRI && "Unable to create target register info!");
std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
assert(MAI && "Unable to create target asm info!");
// Ensure MCAsmInfo initialization occurs before any use, otherwise sections
// may be created with a combination of default and explicit settings.
if (Opts.CompressDebugSections)
MAI->setCompressDebugSections(true);
bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
std::unique_ptr<formatted_raw_ostream> Out(
GetOutputStream(Opts, Diags, IsBinary));
if (!Out)
return true;
// FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
// MCObjectFileInfo needs a MCContext reference in order to initialize itself.
std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
// FIXME: Assembler behavior can change with -static.
MOFI->InitMCObjectFileInfo(Opts.Triple,
Reloc::Default, CodeModel::Default, Ctx);
if (Opts.SaveTemporaryLabels)
Ctx.setAllowTemporaryLabels(false);
if (Opts.GenDwarfForAssembly)
Ctx.setGenDwarfForAssembly(true);
if (!Opts.DwarfDebugFlags.empty())
Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
if (!Opts.DwarfDebugProducer.empty())
Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
if (!Opts.DebugCompilationDir.empty())
Ctx.setCompilationDir(Opts.DebugCompilationDir);
if (!Opts.MainFileName.empty())
Ctx.setMainFileName(StringRef(Opts.MainFileName));
Ctx.setDwarfVersion(Opts.DwarfVersion);
// Build up the feature string from the target feature list.
std::string FS;
if (!Opts.Features.empty()) {
FS = Opts.Features[0];
for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
FS += "," + Opts.Features[i];
}
std::unique_ptr<MCStreamer> Str;
std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
std::unique_ptr<MCSubtargetInfo> STI(
TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
// FIXME: There is a bit of code duplication with addPassesToEmitFile.
if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
MCInstPrinter *IP =
TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
*STI);
MCCodeEmitter *CE = nullptr;
MCAsmBackend *MAB = nullptr;
if (Opts.ShowEncoding) {
CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU);
}
Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
/*useDwarfDirectory*/ true,
IP, CE, MAB,
Opts.ShowInst));
} else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
Str.reset(createNullStreamer(Ctx));
} else {
assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
"Invalid file type!");
MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
//.........这里部分代码省略.........
示例12: assert
// Parse inline ASM and collect the list of symbols that are not defined in
// the current module. This is inspired from IRObjectFile.
void IRObjectFile::CollectAsmUndefinedRefs(
const Triple &TT, StringRef InlineAsm,
function_ref<void(StringRef, BasicSymbolRef::Flags)> AsmUndefinedRefs) {
if (InlineAsm.empty())
return;
std::string Err;
const Target *T = TargetRegistry::lookupTarget(TT.str(), Err);
assert(T && T->hasMCAsmParser());
std::unique_ptr<MCRegisterInfo> MRI(T->createMCRegInfo(TT.str()));
if (!MRI)
return;
std::unique_ptr<MCAsmInfo> MAI(T->createMCAsmInfo(*MRI, TT.str()));
if (!MAI)
return;
std::unique_ptr<MCSubtargetInfo> STI(
T->createMCSubtargetInfo(TT.str(), "", ""));
if (!STI)
return;
std::unique_ptr<MCInstrInfo> MCII(T->createMCInstrInfo());
if (!MCII)
return;
MCObjectFileInfo MOFI;
MCContext MCCtx(MAI.get(), MRI.get(), &MOFI);
MOFI.InitMCObjectFileInfo(TT, /*PIC*/ false, CodeModel::Default, MCCtx);
RecordStreamer Streamer(MCCtx);
T->createNullTargetStreamer(Streamer);
std::unique_ptr<MemoryBuffer> Buffer(MemoryBuffer::getMemBuffer(InlineAsm));
SourceMgr SrcMgr;
SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
std::unique_ptr<MCAsmParser> Parser(
createMCAsmParser(SrcMgr, MCCtx, Streamer, *MAI));
MCTargetOptions MCOptions;
std::unique_ptr<MCTargetAsmParser> TAP(
T->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
if (!TAP)
return;
Parser->setTargetParser(*TAP);
if (Parser->Run(false))
return;
for (auto &KV : Streamer) {
StringRef Key = KV.first();
RecordStreamer::State Value = KV.second;
uint32_t Res = BasicSymbolRef::SF_None;
switch (Value) {
case RecordStreamer::NeverSeen:
llvm_unreachable("NeverSeen should have been replaced earlier");
case RecordStreamer::DefinedGlobal:
Res |= BasicSymbolRef::SF_Global;
break;
case RecordStreamer::Defined:
break;
case RecordStreamer::Global:
case RecordStreamer::Used:
Res |= BasicSymbolRef::SF_Undefined;
Res |= BasicSymbolRef::SF_Global;
break;
case RecordStreamer::DefinedWeak:
Res |= BasicSymbolRef::SF_Weak;
Res |= BasicSymbolRef::SF_Global;
break;
case RecordStreamer::UndefinedWeak:
Res |= BasicSymbolRef::SF_Weak;
Res |= BasicSymbolRef::SF_Undefined;
}
AsmUndefinedRefs(Key, BasicSymbolRef::Flags(Res));
}
}
示例13: main
int main(int argc, char **argv) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal(argv[0]);
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
// Initialize targets and assembly printers/parsers.
llvm::InitializeAllTargetInfos();
llvm::InitializeAllTargetMCs();
llvm::InitializeAllAsmParsers();
llvm::InitializeAllDisassemblers();
// Register the target printer for --version.
cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
TripleName = Triple::normalize(TripleName);
setDwarfDebugFlags(argc, argv);
setDwarfDebugProducer();
const char *ProgName = argv[0];
const Target *TheTarget = GetTarget(ProgName);
if (!TheTarget)
return 1;
// Now that GetTarget() has (potentially) replaced TripleName, it's safe to
// construct the Triple object.
Triple TheTriple(TripleName);
ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
MemoryBuffer::getFileOrSTDIN(InputFilename);
if (std::error_code EC = BufferPtr.getError()) {
errs() << InputFilename << ": " << EC.message() << '\n';
return 1;
}
MemoryBuffer *Buffer = BufferPtr->get();
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
// Record the location of the include directories so that the lexer can find
// it later.
SrcMgr.setIncludeDirs(IncludeDirs);
std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
assert(MRI && "Unable to create target register info!");
std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
assert(MAI && "Unable to create target asm info!");
MAI->setRelaxELFRelocations(RelaxELFRel);
if (CompressDebugSections != DebugCompressionType::None) {
if (!zlib::isAvailable()) {
errs() << ProgName
<< ": build tools with zlib to enable -compress-debug-sections";
return 1;
}
MAI->setCompressDebugSections(CompressDebugSections);
}
MAI->setPreserveAsmComments(PreserveComments);
// FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
// MCObjectFileInfo needs a MCContext reference in order to initialize itself.
MCObjectFileInfo MOFI;
MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx);
if (SaveTempLabels)
Ctx.setAllowTemporaryLabels(false);
Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
// Default to 4 for dwarf version.
unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
if (DwarfVersion < 2 || DwarfVersion > 5) {
errs() << ProgName << ": Dwarf version " << DwarfVersion
<< " is not supported." << '\n';
return 1;
}
Ctx.setDwarfVersion(DwarfVersion);
if (!DwarfDebugFlags.empty())
Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
if (!DwarfDebugProducer.empty())
Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
if (!DebugCompilationDir.empty())
Ctx.setCompilationDir(DebugCompilationDir);
else {
// If no compilation dir is set, try to use the current directory.
SmallString<128> CWD;
if (!sys::fs::current_path(CWD))
Ctx.setCompilationDir(CWD);
}
if (!MainFileName.empty())
Ctx.setMainFileName(MainFileName);
// Package up features to be passed to target/subtarget
std::string FeaturesStr;
//.........这里部分代码省略.........
示例14: ParseFile
static bool ParseFile(const std::string &Filename,
const std::vector<std::string> &IncludeDirs,
SmallVectorImpl<std::string> &OutputFiles) {
ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
MemoryBuffer::getFileOrSTDIN(Filename);
if (std::error_code EC = MBOrErr.getError()) {
llvm::errs() << "Could not open input file '" << Filename << "': "
<< EC.message() <<"\n";
return true;
}
std::unique_ptr<llvm::MemoryBuffer> MB = std::move(MBOrErr.get());
// Record the location of the include directory so that the lexer can find it
// later.
SourceMgr SrcMgr;
SrcMgr.setIncludeDirs(IncludeDirs);
// Tell SrcMgr about this buffer, which is what Parser will pick up.
SrcMgr.AddNewSourceBuffer(std::move(MB), llvm::SMLoc());
LangOptions Opts;
Opts.DefaultReal8 = DefaultReal8;
Opts.DefaultDouble8 = DefaultDouble8;
Opts.DefaultInt8 = DefaultInt8;
Opts.ReturnComments = ReturnComments;
if(!FreeForm && !FixedForm) {
llvm::StringRef Ext = llvm::sys::path::extension(Filename);
if(Ext.equals_lower(".f")) {
Opts.FixedForm = 1;
Opts.FreeForm = 0;
}
} else if(FixedForm) {
Opts.FixedForm = 1;
Opts.FreeForm = 0;
}
TextDiagnosticPrinter TDP(SrcMgr);
DiagnosticsEngine Diag(new DiagnosticIDs,&SrcMgr, &TDP, false);
// Chain in -verify checker, if requested.
if(RunVerifier)
Diag.setClient(new VerifyDiagnosticConsumer(Diag));
ASTContext Context(SrcMgr, Opts);
Sema SA(Context, Diag);
Parser P(SrcMgr, Opts, Diag, SA);
Diag.getClient()->BeginSourceFile(Opts, &P.getLexer());
P.ParseProgramUnits();
Diag.getClient()->EndSourceFile();
// Dump
if(PrintAST || DumpAST) {
auto Dumper = CreateASTDumper("");
Dumper->HandleTranslationUnit(Context);
delete Dumper;
}
// Emit
if(!SyntaxOnly && !Diag.hadErrors()) {
flang::TargetOptions TargetOptions;
TargetOptions.Triple = TargetTriple.empty()? llvm::sys::getDefaultTargetTriple() :
TargetTriple;
TargetOptions.CPU = llvm::sys::getHostCPUName();
auto CG = CreateLLVMCodeGen(Diag, Filename == ""? std::string("module") : Filename,
CodeGenOptions(), TargetOptions, llvm::getGlobalContext());
CG->Initialize(Context);
CG->HandleTranslationUnit(Context);
BackendAction BA = Backend_EmitObj;
if(EmitASM) BA = Backend_EmitAssembly;
if(EmitLLVM) BA = Backend_EmitLL;
const llvm::Target *TheTarget = 0;
std::string Err;
TheTarget = llvm::TargetRegistry::lookupTarget(TargetOptions.Triple, Err);
CodeGenOpt::Level TMOptLevel = CodeGenOpt::Default;
switch(OptLevel) {
case 0: TMOptLevel = CodeGenOpt::None; break;
case 3: TMOptLevel = CodeGenOpt::Aggressive; break;
}
llvm::TargetOptions Options;
auto TM = TheTarget->createTargetMachine(TargetOptions.Triple, TargetOptions.CPU, "", Options,
Reloc::Default, CodeModel::Default,
TMOptLevel);
if(!(EmitLLVM && OptLevel == 0)) {
auto TheModule = CG->GetModule();
auto PM = new llvm::legacy::PassManager();
//llvm::legacy::FunctionPassManager *FPM = new llvm::legacy::FunctionPassManager(TheModule);
//FPM->add(new DataLayoutPass());
//PM->add(new llvm::DataLayoutPass());
//TM->addAnalysisPasses(*PM);
PM->add(createPromoteMemoryToRegisterPass());
PassManagerBuilder PMBuilder;
PMBuilder.OptLevel = OptLevel;
PMBuilder.SizeLevel = 0;
//.........这里部分代码省略.........
示例15: parseMCMarkup
static void parseMCMarkup(StringRef Filename) {
OwningPtr<MemoryBuffer> BufferPtr;
if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, BufferPtr)) {
errs() << ToolName << ": " << ec.message() << '\n';
return;
}
MemoryBuffer *Buffer = BufferPtr.take();
SourceMgr SrcMgr;
// Tell SrcMgr about this buffer, which is what the parser will pick up.
SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
StringRef InputSource = Buffer->getBuffer();
MarkupLexer Lex(InputSource);
MarkupParser Parser(Lex, SrcMgr);
SmallVector<MarkupTag, 4> TagStack;
for (int CurChar = Lex.getNextChar();
CurChar != EOF;
CurChar = Lex.getNextChar()) {
switch (CurChar) {
case '<': {
// A "<<" is output as a literal '<' and does not start a markup tag.
if (Lex.peekNextChar() == '<') {
(void)Lex.getNextChar();
break;
}
// Parse the markup entry.
TagStack.push_back(Parser.parseTag());
// Do any special handling for the start of a tag.
processStartTag(TagStack.back());
continue;
}
case '>': {
SMLoc Loc = SMLoc::getFromPointer(Lex.getPosition() - 1);
// A ">>" is output as a literal '>' and does not end a markup tag.
if (Lex.peekNextChar() == '>') {
(void)Lex.getNextChar();
break;
}
// Close out the innermost tag.
if (TagStack.empty())
Parser.FatalError(Loc, "'>' without matching '<'");
// Do any special handling for the end of a tag.
processEndTag(TagStack.back());
TagStack.pop_back();
continue;
}
default:
break;
}
// For anything else, just echo the character back out.
if (!DumpTags && CurChar != EOF)
outs() << (char)CurChar;
}
// If there are any unterminated markup tags, issue diagnostics for them.
while (!TagStack.empty()) {
MarkupTag &Tag = TagStack.back();
SrcMgr.PrintMessage(Tag.getLoc(), SourceMgr::DK_Error,
"unterminated markup tag");
TagStack.pop_back();
}
}