예제 #1
0
bool TeslaVisitor::VisitCallExpr(CallExpr *E) {
    FunctionDecl *F = E->getDirectCallee();
    if (!F) return true;

    StringRef FnName = F->getName();
    if (!FnName.startswith(TESLA_BASE)) return true;

    // TESLA function calls might be inline assertions.
    if (FnName == INLINE_ASSERTION) {
        OwningPtr<Parser> P(Parser::AssertionParser(E, *Context));
        if (!P)
            return false;

        OwningPtr<AutomatonDescription> Description;
        OwningPtr<Usage> Use;
        if (!P->Parse(Description, Use))
            return false;

        Automata.push_back(Description.take());
        Roots.push_back(Use.take());
        return true;
    }

    return true;
}
LLVMSymbolizer::BinaryPair
LLVMSymbolizer::getOrCreateBinary(const std::string &Path) {
  BinaryMapTy::iterator I = BinaryForPath.find(Path);
  if (I != BinaryForPath.end())
    return I->second;
  Binary *Bin = 0;
  Binary *DbgBin = 0;
  OwningPtr<Binary> ParsedBinary;
  OwningPtr<Binary> ParsedDbgBinary;
  if (!error(createBinary(Path, ParsedBinary))) {
    // Check if it's a universal binary.
    Bin = ParsedBinary.take();
    ParsedBinariesAndObjects.push_back(Bin);
    if (Bin->isMachO() || Bin->isMachOUniversalBinary()) {
      // On Darwin we may find DWARF in separate object file in
      // resource directory.
      const std::string &ResourcePath =
          getDarwinDWARFResourceForPath(Path);
      bool ResourceFileExists = false;
      if (!sys::fs::exists(ResourcePath, ResourceFileExists) &&
          ResourceFileExists &&
          !error(createBinary(ResourcePath, ParsedDbgBinary))) {
        DbgBin = ParsedDbgBinary.take();
        ParsedBinariesAndObjects.push_back(DbgBin);
      }
    }
  }
  if (DbgBin == 0)
    DbgBin = Bin;
  BinaryPair Res = std::make_pair(Bin, DbgBin);
  BinaryForPath[Path] = Res;
  return Res;
}
예제 #3
0
llvm::MemoryBuffer *FileManager::
getBufferForFile(const FileEntry *Entry, std::string *ErrorStr) {
  OwningPtr<llvm::MemoryBuffer> Result;
  llvm::error_code ec;

  const char *Filename = Entry->getName();
  // If the file is already open, use the open file descriptor.
  if (Entry->FD != -1) {
    ec = llvm::MemoryBuffer::getOpenFile(Entry->FD, Filename, Result,
                                         Entry->getSize());
    if (ErrorStr)
      *ErrorStr = ec.message();

    close(Entry->FD);
    Entry->FD = -1;
    return Result.take();
  }

  // Otherwise, open the file.

  if (FileSystemOpts.WorkingDir.empty()) {
    ec = llvm::MemoryBuffer::getFile(Filename, Result, Entry->getSize());
    if (ec && ErrorStr)
      *ErrorStr = ec.message();
    return Result.take();
  }

  SmallString<128> FilePath(Entry->getName());
  FixupRelativePath(FilePath);
  ec = llvm::MemoryBuffer::getFile(FilePath.str(), Result, Entry->getSize());
  if (ec && ErrorStr)
    *ErrorStr = ec.message();
  return Result.take();
}
bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
                                               DiagnosticsEngine &Diags,
                                               FileManager &FileMgr,
                                               SourceManager &SourceMgr,
                                               const FrontendOptions &Opts) {
  SrcMgr::CharacteristicKind
    Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;

  if (Input.isBuffer()) {
    SourceMgr.createMainFileIDForMemBuffer(Input.getBuffer(), Kind);
    assert(!SourceMgr.getMainFileID().isInvalid() &&
           "Couldn't establish MainFileID!");
    return true;
  }

  StringRef InputFile = Input.getFile();

  // Figure out where to get and map in the main file.
  if (InputFile != "-") {
    const FileEntry *File = FileMgr.getFile(InputFile);
    if (!File) {
      Diags.Report(diag::err_fe_error_reading) << InputFile;
      return false;
    }

    // The natural SourceManager infrastructure can't currently handle named
    // pipes, but we would at least like to accept them for the main
    // file. Detect them here, read them with the more generic MemoryBuffer
    // function, and simply override their contents as we do for STDIN.
    if (File->isNamedPipe()) {
      OwningPtr<llvm::MemoryBuffer> MB;
      if (llvm::error_code ec = llvm::MemoryBuffer::getFile(InputFile, MB)) {
        Diags.Report(diag::err_cannot_open_file) << InputFile << ec.message();
        return false;
      }

      // Create a new virtual file that will have the correct size.
      File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0);
      SourceMgr.overrideFileContents(File, MB.take());
    }

    SourceMgr.createMainFileID(File, Kind);
  } else {
    OwningPtr<llvm::MemoryBuffer> SB;
    if (llvm::MemoryBuffer::getSTDIN(SB)) {
      // FIXME: Give ec.message() in this diag.
      Diags.Report(diag::err_fe_error_reading_stdin);
      return false;
    }
    const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
                                                   SB->getBufferSize(), 0);
    SourceMgr.createMainFileID(File, Kind);
    SourceMgr.overrideFileContents(File, SB.take());
  }

  assert(!SourceMgr.getMainFileID().isInvalid() &&
         "Couldn't establish MainFileID!");
  return true;
}
예제 #5
0
bool TeslaVisitor::VisitFunctionDecl(FunctionDecl *F) {
    // Only analyse non-deleted definitions (i.e. definitions with bodies).
    if (!F->doesThisDeclarationHaveABody())
        return true;


    // We only parse functions that return __tesla_automaton_description*.
    const Type *RetTy = F->getResultType().getTypePtr();
    if (!RetTy->isPointerType())
        return true;

    QualType Pointee = RetTy->getPointeeType();
    auto TypeID = Pointee.getBaseTypeIdentifier();
    if (!TypeID)
        return true;

    OwningPtr<Parser> P;
    StringRef FnName = F->getName();

    // Build a Parser appropriate to what we're parsing.
    string RetTypeName = TypeID->getName();
    if (RetTypeName == AUTOMATON_DESC)
        P.reset(Parser::AutomatonParser(F, *Context));

    else if ((RetTypeName == AUTOMATON_USAGE) && (FnName != AUTOMATON_USES))
        P.reset(Parser::MappingParser(F, *Context));

    else
        return true;


    // Actually parse the function.
    if (!P)
        return false;

    OwningPtr<AutomatonDescription> Description;
    OwningPtr<Usage> Use;
    if (!P->Parse(Description, Use))
        return false;

    if (Description)
        Automata.push_back(Description.take());

    if (Use)
        Roots.push_back(Use.take());

    return true;
}
예제 #6
0
/// \brief Read the file into _buffer.
error_code
FileNode::readFile(const LinkingContext &ctx, raw_ostream &diagnostics,
                   bool &isYaml) {
  ErrorOr<StringRef> filePath = getPath(ctx);
  if (!filePath &&
      error_code(filePath) == llvm::errc::no_such_file_or_directory)
    return make_error_code(llvm::errc::no_such_file_or_directory);

  // Create a memory buffer
  OwningPtr<llvm::MemoryBuffer> opmb;

  if (error_code ec = llvm::MemoryBuffer::getFileOrSTDIN(*filePath, opmb))
    return ec;

  std::unique_ptr<MemoryBuffer> mb(opmb.take());
  _buffer = std::move(mb);

  if (ctx.logInputFiles())
    diagnostics << _buffer->getBufferIdentifier() << "\n";

  // YAML file is identified by a .objtxt extension
  // FIXME : Identify YAML files by using a magic
  if (filePath->endswith(".objtxt")) {
    if (error_code ec = ctx.getYAMLReader().parseFile(_buffer, _files))
      return ec;
    isYaml = true;
  }
  return error_code::success();
}
예제 #7
0
bool CompilerInstance::InitializeSourceManager(StringRef InputFile,
                                               SrcMgr::CharacteristicKind Kind,
                                               DiagnosticsEngine &Diags,
                                               FileManager &FileMgr,
                                               SourceManager &SourceMgr,
                                               const FrontendOptions &Opts) {
  // Figure out where to get and map in the main file.
  if (InputFile != "-") {
    const FileEntry *File = FileMgr.getFile(InputFile);
    if (!File) {
      Diags.Report(diag::err_fe_error_reading) << InputFile;
      return false;
    }
    SourceMgr.createMainFileID(File, Kind);
  } else {
    OwningPtr<llvm::MemoryBuffer> SB;
    if (llvm::MemoryBuffer::getSTDIN(SB)) {
      // FIXME: Give ec.message() in this diag.
      Diags.Report(diag::err_fe_error_reading_stdin);
      return false;
    }
    const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
                                                   SB->getBufferSize(), 0);
    SourceMgr.createMainFileID(File, Kind);
    SourceMgr.overrideFileContents(File, SB.take());
  }

  assert(!SourceMgr.getMainFileID().isInvalid() &&
         "Couldn't establish MainFileID!");
  return true;
}
예제 #8
0
파일: LTOModule.cpp 프로젝트: Hohahiu/llvm
bool LTOModule::isBitcodeFileForTarget(const char *path,
                                       const char *triplePrefix) {
  OwningPtr<MemoryBuffer> buffer;
  if (MemoryBuffer::getFile(path, buffer))
    return false;
  return isTargetMatch(buffer.take(), triplePrefix);
}
예제 #9
0
const void* LTOCodeGenerator::compile(size_t* length, std::string& errMsg) {
  const char *name;
  if (compile_to_file(&name, errMsg))
    return NULL;

  // remove old buffer if compile() called twice
  delete _nativeObjectFile;

  // read .o file into memory buffer
  OwningPtr<MemoryBuffer> BuffPtr;
  if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
    errMsg = ec.message();
    return NULL;
  }
  _nativeObjectFile = BuffPtr.take();

  // remove temp files
  sys::Path(_nativeObjectPath).eraseFromDisk();

  // return buffer, unless error
  if ( _nativeObjectFile == NULL )
    return NULL;
  *length = _nativeObjectFile->getBufferSize();
  return _nativeObjectFile->getBufferStart();
}
static ASTReader *createASTReader(CompilerInstance &CI,
                                  StringRef pchFile,  
                                  SmallVector<llvm::MemoryBuffer *, 4> &memBufs,
                                  SmallVector<std::string, 4> &bufNames,
                             ASTDeserializationListener *deserialListener = 0) {
  Preprocessor &PP = CI.getPreprocessor();
  OwningPtr<ASTReader> Reader;
  Reader.reset(new ASTReader(PP, CI.getASTContext(), /*isysroot=*/"",
                             /*DisableValidation=*/true));
  for (unsigned ti = 0; ti < bufNames.size(); ++ti) {
    StringRef sr(bufNames[ti]);
    Reader->addInMemoryBuffer(sr, memBufs[ti]);
  }
  Reader->setDeserializationListener(deserialListener);
  switch (Reader->ReadAST(pchFile, serialization::MK_PCH,
                          ASTReader::ARR_None)) {
  case ASTReader::Success:
    // Set the predefines buffer as suggested by the PCH reader.
    PP.setPredefines(Reader->getSuggestedPredefines());
    return Reader.take();

  case ASTReader::Failure:
  case ASTReader::OutOfDate:
  case ASTReader::VersionMismatch:
  case ASTReader::ConfigurationMismatch:
  case ASTReader::HadErrors:
    break;
  }
  return 0;
}
예제 #11
0
파일: GCOV.cpp 프로젝트: 32bitmicro/llvm
/// print -  Print source files with collected line count information.
void FileInfo::print() {
  for (StringMap<LineCounts>::iterator I = LineInfo.begin(), E = LineInfo.end();
       I != E; ++I) {
    StringRef Filename = I->first();
    outs() << Filename << "\n";
    LineCounts &L = LineInfo[Filename];
    OwningPtr<MemoryBuffer> Buff;
    if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
      errs() << Filename << ": " << ec.message() << "\n";
      return;
    }
    StringRef AllLines = Buff.take()->getBuffer();
    for (unsigned i = 0, e = L.size(); i != e; ++i) {
      if (L[i])
        outs() << L[i] << ":\t";
      else
        outs() << " :\t";
      std::pair<StringRef, StringRef> P = AllLines.split('\n');
      if (AllLines != P.first)
        outs() << P.first;
      outs() << "\n";
      AllLines = P.second;
    }
  }
}
예제 #12
0
파일: ARCMT.cpp 프로젝트: CTSRD-TESLA/clang
static CompilerInvocation *
createInvocationForMigration(CompilerInvocation &origCI) {
  OwningPtr<CompilerInvocation> CInvok;
  CInvok.reset(new CompilerInvocation(origCI));
  CInvok->getPreprocessorOpts().ImplicitPCHInclude = std::string();
  CInvok->getPreprocessorOpts().ImplicitPTHInclude = std::string();
  std::string define = getARCMTMacroName();
  define += '=';
  CInvok->getPreprocessorOpts().addMacroDef(define);
  CInvok->getLangOpts()->ObjCAutoRefCount = true;
  CInvok->getLangOpts()->setGC(LangOptions::NonGC);
  CInvok->getDiagnosticOpts().ErrorLimit = 0;
  CInvok->getDiagnosticOpts().PedanticErrors = 0;

  // Ignore -Werror flags when migrating.
  std::vector<std::string> WarnOpts;
  for (std::vector<std::string>::iterator
         I = CInvok->getDiagnosticOpts().Warnings.begin(),
         E = CInvok->getDiagnosticOpts().Warnings.end(); I != E; ++I) {
    if (!StringRef(*I).startswith("error"))
      WarnOpts.push_back(*I);
  }
  WarnOpts.push_back("error=arc-unsafe-retained-assign");
  CInvok->getDiagnosticOpts().Warnings = llvm_move(WarnOpts);

  CInvok->getLangOpts()->ObjCRuntimeHasWeak = HasARCRuntime(origCI);

  return CInvok.take();
}
예제 #13
0
const void* LTOCodeGenerator::compile(size_t* length,
                                      bool disableOpt,
                                      bool disableInline,
                                      bool disableGVNLoadPRE,
                                      std::string& errMsg) {
  const char *name;
  if (!compile_to_file(&name, disableOpt, disableInline, disableGVNLoadPRE,
                       errMsg))
    return NULL;

  // remove old buffer if compile() called twice
  delete NativeObjectFile;

  // read .o file into memory buffer
  OwningPtr<MemoryBuffer> BuffPtr;
  if (error_code ec = MemoryBuffer::getFile(name, BuffPtr, -1, false)) {
    errMsg = ec.message();
    sys::fs::remove(NativeObjectPath);
    return NULL;
  }
  NativeObjectFile = BuffPtr.take();

  // remove temp files
  sys::fs::remove(NativeObjectPath);

  // return buffer, unless error
  if (NativeObjectFile == NULL)
    return NULL;
  *length = NativeObjectFile->getBufferSize();
  return NativeObjectFile->getBufferStart();
}
예제 #14
0
static int printLineInfoForInput() {
  // If we don't have any input files, read from stdin.
  if (!InputFileList.size())
    InputFileList.push_back("-");
  for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
    // Instantiate a dynamic linker.
    TrivialMemoryManager MemMgr;
    RuntimeDyld Dyld(&MemMgr);

    // Load the input memory buffer.
    OwningPtr<MemoryBuffer> InputBuffer;
    OwningPtr<ObjectImage>  LoadedObject;
    if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFileList[i],
                                                     InputBuffer))
      return Error("unable to read input: '" + ec.message() + "'");

    // Load the object file
    LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.take())));
    if (!LoadedObject) {
      return Error(Dyld.getErrorString());
    }

    // Resolve all the relocations we can.
    Dyld.resolveRelocations();

    OwningPtr<DIContext> Context(DIContext::getDWARFContext(LoadedObject->getObjectFile()));

    // Use symbol info to iterate functions in the object.
    error_code ec;
    for (object::symbol_iterator I = LoadedObject->begin_symbols(),
                                 E = LoadedObject->end_symbols();
                          I != E && !ec;
                          I.increment(ec)) {
      object::SymbolRef::Type SymType;
      if (I->getType(SymType)) continue;
      if (SymType == object::SymbolRef::ST_Function) {
        StringRef  Name;
        uint64_t   Addr;
        uint64_t   Size;
        if (I->getName(Name)) continue;
        if (I->getAddress(Addr)) continue;
        if (I->getSize(Size)) continue;

        outs() << "Function: " << Name << ", Size = " << Size << "\n";

        DILineInfoTable Lines = Context->getLineInfoForAddressRange(Addr, Size);
        DILineInfoTable::iterator  Begin = Lines.begin();
        DILineInfoTable::iterator  End = Lines.end();
        for (DILineInfoTable::iterator It = Begin; It != End; ++It) {
          outs() << "  Line info @ " << It->first - Addr << ": "
                 << It->second.getFileName()
                 << ", line:" << It->second.getLine() << "\n";
        }
      }
    }
  }

  return 0;
}
예제 #15
0
파일: llvm_loader.hpp 프로젝트: ivg/bap
error_or<object::Binary> get_binary(const char* data, std::size_t size) {
    StringRef data_ref(data, size);
    MemoryBuffer* buff(MemoryBuffer::getMemBufferCopy(data_ref, "binary"));
    OwningPtr<object::Binary> bin;
    if (error_code ec = createBinary(buff, bin))
        return failure(ec.message());
    return error_or<object::Binary>(bin.take());
}
예제 #16
0
/// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
/// the buffer.
LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
  OwningPtr<MemoryBuffer> buffer;
  if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
    errMsg = ec.message();
    return NULL;
  }
  return makeLTOModule(buffer.take(), errMsg);
}
예제 #17
0
bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
                                            formatted_raw_ostream &Out,
                                            CodeGenFileType FileType,
                                            CodeGenOpt::Level OptLevel,
                                            bool DisableVerify) {
  // Add common CodeGen passes.
  MCContext *Context = 0;
  if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
    return true;
  assert(Context != 0 && "Failed to get MCContext");

  const MCAsmInfo &MAI = *getMCAsmInfo();
  OwningPtr<MCStreamer> AsmStreamer;

  switch (FileType) {
  default: return true;
  case CGFT_AssemblyFile: {
    MCInstPrinter *InstPrinter =
      getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
    AsmStreamer.reset(createAsmStreamer(*Context, Out,
                                        getTargetData()->isLittleEndian(),
                                        getVerboseAsm(), InstPrinter,
                                        /*codeemitter*/0));
    break;
  }
  case CGFT_ObjectFile: {
    // Create the code emitter for the target if it exists.  If not, .o file
    // emission fails.
    MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
    TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
    if (MCE == 0 || TAB == 0)
      return true;
    
    AsmStreamer.reset(createMachOStreamer(*Context, *TAB, Out, MCE));
    break;
  }
  case CGFT_Null:
    // The Null output is intended for use for performance analysis and testing,
    // not real users.
    AsmStreamer.reset(createNullStreamer(*Context));
    break;
  }
  
  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
  FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
  if (Printer == 0)
    return true;
  
  // If successful, createAsmPrinter took ownership of AsmStreamer.
  AsmStreamer.take();
  
  PM.add(Printer);
  
  // Make sure the code model is set.
  setCodeModelForStatic();
  PM.add(createGCInfoDeleter());
  return false;
}
예제 #18
0
static void DumpInput(const StringRef &Filename) {
  OwningPtr<MemoryBuffer> Buff;

  if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
    errs() << Filename << ": " << ec.message() << "\n";
    return;
  }

  OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));

  StringRef DebugInfoSection;
  StringRef DebugAbbrevSection;
  StringRef DebugLineSection;
  StringRef DebugArangesSection;
  StringRef DebugStringSection;

  error_code ec;
  for (ObjectFile::section_iterator i = Obj->begin_sections(),
                                    e = Obj->end_sections();
                                    i != e; i.increment(ec)) {
    StringRef name;
    i->getName(name);
    StringRef data;
    i->getContents(data);

    if (name.startswith("__DWARF,"))
      name = name.substr(8); // Skip "__DWARF," prefix.
    name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
    if (name == "debug_info")
      DebugInfoSection = data;
    else if (name == "debug_abbrev")
      DebugAbbrevSection = data;
    else if (name == "debug_line")
      DebugLineSection = data;
    else if (name == "debug_aranges")
      DebugArangesSection = data;
    else if (name == "debug_str")
      DebugStringSection = data;
  }

  OwningPtr<DIContext> dictx(DIContext::getDWARFContext(/*FIXME*/true,
                                                        DebugInfoSection,
                                                        DebugAbbrevSection,
                                                        DebugArangesSection,
                                                        DebugLineSection,
                                                        DebugStringSection));
  if (Address == -1ULL) {
    outs() << Filename
           << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
    // Dump the complete DWARF structure.
    dictx->dump(outs());
  } else {
    // Print line info for the specified address.
    DILineInfo dli = dictx->getLineInfoForAddress(Address);
    outs() << (dli.getFileName() ? dli.getFileName() : "<unknown>") << ':'
           << dli.getLine() << ':' << dli.getColumn() << '\n';
  }
}
예제 #19
0
/// makeLTOModule - Create an LTOModule. N.B. These methods take ownership of
/// the buffer.
LTOModule *LTOModule::makeLTOModule(const char *path, std::string &errMsg) {
  OwningPtr<MemoryBuffer> buffer;
  if (error_code ec = MemoryBuffer::getFile(path, buffer)) {
    errMsg = ec.message();
    return NULL;
  }
  RandomNumberGenerator::EntropyData.append(path);
  return makeLTOModule(buffer.take(), errMsg);
}
예제 #20
0
llvm::MemoryBuffer *FileManager::
getBufferForFile(StringRef Filename, std::string *ErrorStr) {
  OwningPtr<llvm::MemoryBuffer> Result;
  llvm::error_code ec;
  if (FileSystemOpts.WorkingDir.empty()) {
    ec = llvm::MemoryBuffer::getFile(Filename, Result);
    if (ec && ErrorStr)
      *ErrorStr = ec.message();
    return Result.take();
  }

  SmallString<128> FilePath(Filename);
  FixupRelativePath(FilePath);
  ec = llvm::MemoryBuffer::getFile(FilePath.c_str(), Result);
  if (ec && ErrorStr)
    *ErrorStr = ec.message();
  return Result.take();
}
예제 #21
0
파일: llvm_binary.hpp 프로젝트: jamella/bap
image* create(const char* data, std::size_t size) {
    StringRef data_ref(data, size);
    MemoryBuffer* buff(MemoryBuffer::getMemBufferCopy(data_ref, "binary"));
    OwningPtr<object::Binary> bin;
    if (error_code ec = createBinary(buff, bin))
        llvm_binary_fail(ec);
    std::unique_ptr<object::Binary> binary(bin.take());
    return create(move(binary));
}
예제 #22
0
파일: Main.cpp 프로젝트: otinn/llvm-asan
int TableGenMain(char *argv0, TableGenMainFn *MainFn) {
  RecordKeeper Records;

  try {
    // Parse the input file.
    OwningPtr<MemoryBuffer> File;
    if (error_code ec =
          MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
      errs() << "Could not open input file '" << InputFilename << "': "
             << ec.message() <<"\n";
      return 1;
    }
    MemoryBuffer *F = File.take();

    // Tell SrcMgr about this buffer, which is what TGParser will pick up.
    SrcMgr.AddNewSourceBuffer(F, SMLoc());

    // Record the location of the include directory so that the lexer can find
    // it later.
    SrcMgr.setIncludeDirs(IncludeDirs);

    TGParser Parser(SrcMgr, Records);

    if (Parser.ParseFile())
      return 1;

    std::string Error;
    tool_output_file Out(OutputFilename.c_str(), Error);
    if (!Error.empty()) {
      errs() << argv0 << ": error opening " << OutputFilename
        << ":" << Error << "\n";
      return 1;
    }
    if (!DependFilename.empty())
      if (int Ret = createDependencyFile(Parser, argv0))
        return Ret;

    if (MainFn(Out.os(), Records))
      return 1;

    // Declare success.
    Out.keep();
    return 0;

  } catch (const TGError &Error) {
    PrintError(Error);
  } catch (const std::string &Error) {
    PrintError(Error);
  } catch (const char *Error) {
    PrintError(Error);
  } catch (...) {
    errs() << argv0 << ": Unknown unexpected exception occurred.\n";
  }

  return 1;
}
예제 #23
0
static int executeInput() {
  // Instantiate a dynamic linker.
  TrivialMemoryManager MemMgr;
  RuntimeDyld Dyld(&MemMgr);

  // If we don't have any input files, read from stdin.
  if (!InputFileList.size())
    InputFileList.push_back("-");
  for(unsigned i = 0, e = InputFileList.size(); i != e; ++i) {
    // Load the input memory buffer.
    OwningPtr<MemoryBuffer> InputBuffer;
    OwningPtr<ObjectImage>  LoadedObject;
    if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFileList[i],
                                                     InputBuffer))
      return Error("unable to read input: '" + ec.message() + "'");

    // Load the object file
    LoadedObject.reset(Dyld.loadObject(new ObjectBuffer(InputBuffer.take())));
    if (!LoadedObject) {
      return Error(Dyld.getErrorString());
    }
  }

  // Resolve all the relocations we can.
  Dyld.resolveRelocations();
  // Clear instruction cache before code will be executed.
  MemMgr.invalidateInstructionCache();

  // FIXME: Error out if there are unresolved relocations.

  // Get the address of the entry point (_main by default).
  void *MainAddress = Dyld.getSymbolAddress(EntryPoint);
  if (MainAddress == 0)
    return Error("no definition for '" + EntryPoint + "'");

  // Invalidate the instruction cache for each loaded function.
  for (unsigned i = 0, e = MemMgr.FunctionMemory.size(); i != e; ++i) {
    sys::MemoryBlock &Data = MemMgr.FunctionMemory[i];
    // Make sure the memory is executable.
    std::string ErrorStr;
    sys::Memory::InvalidateInstructionCache(Data.base(), Data.size());
    if (!sys::Memory::setExecutable(Data, &ErrorStr))
      return Error("unable to mark function executable: '" + ErrorStr + "'");
  }

  // Dispatch to _main().
  errs() << "loaded '" << EntryPoint << "' at: " << (void*)MainAddress << "\n";

  int (*Main)(int, const char**) =
    (int(*)(int,const char**)) uintptr_t(MainAddress);
  const char **Argv = new const char*[2];
  // Use the name of the first input object module as argv[0] for the target.
  Argv[0] = InputFileList[0].c_str();
  Argv[1] = 0;
  return Main(1, Argv);
}
예제 #24
0
extern "C" LLVMMemoryBufferRef
LLVMRustCreateMemoryBufferWithContentsOfFile(const char *Path) {
  OwningPtr<MemoryBuffer> buf;
  error_code err = MemoryBuffer::getFile(Path, buf, -1, false);
  if (err) {
      LLVMRustSetLastError(err.message().c_str());
      return NULL;
  }
  return wrap(buf.take());
}
예제 #25
0
// Open the archive and load just the symbol tables
Archive* Archive::OpenAndLoadSymbols(const sys::Path& File,
                                     LLVMContext& C,
                                     std::string* ErrorMessage) {
  OwningPtr<Archive> result ( new Archive(File, C) );
  if (result->mapToMemory(ErrorMessage))
    return NULL;
  if (!result->loadSymbolTable(ErrorMessage))
    return NULL;
  return result.take();
}
예제 #26
0
error_code Archive::Child::getAsBinary(OwningPtr<Binary> &Result) const {
  OwningPtr<Binary> ret;
  OwningPtr<MemoryBuffer> Buff;
  if (error_code ec = getMemoryBuffer(Buff))
    return ec;
  if (error_code ec = createBinary(Buff.take(), ret))
    return ec;
  Result.swap(ret);
  return object_error::success;
}
예제 #27
0
파일: Statistike.cpp 프로젝트: milenavj/LAV
int main(int argc, char **argv) {
  atexit(llvm_shutdown); // Call llvm_shutdown() on exit.
  lav::parseArguments(argc, argv);
  sys::PrintStackTraceOnErrorSignal();

  // Load the bytecode...
//  std::cout << std::endl << "Loading the bytecode..." << std::endl;
  std::string ErrorMsg;

  Module *mainModule = 0;

  OwningPtr<MemoryBuffer> BufferPtr;
  llvm::error_code ec =
      MemoryBuffer::getFileOrSTDIN(InputFileName.c_str(), BufferPtr);
  if (ec) {
    lav::exit_error((std::string) "error loading program '%s': %s" +
                    InputFileName.c_str() + ec.message().c_str());
  }
  mainModule =
      getLazyBitcodeModule(BufferPtr.get(), getGlobalContext(), &ErrorMsg);

  if (mainModule) {
    if (mainModule->MaterializeAllPermanently(&ErrorMsg)) {
      delete mainModule;
      mainModule = 0;
    }
  }
  if (!mainModule)
    lav::exit_error((std::string) "error loading program '%s': %s" +
                    InputFileName.c_str() + ErrorMsg.c_str());

  std::cout << "Loading the bytecode... Completed " << std::endl << std::endl;

  PassManager Passes;
  Passes.add(new llvm::DataLayout(mainModule));
  Passes.add(createFCFGSimplificationPass()); // Clean up after IPCP & DAE
//  Passes.add(createLoopInfoPass()); // 
  Passes.add(llvm::createLoopSimplifyPass());
  Passes.add(lav::createPetljePass()); // 

  if (EnableInline)
    Passes.add(createAllInlinerPass(
        Threshold)); //Inline malo vece funkcije, parametar inlininga od 200 do
                     //milijardu, ako je bez argumenta postavljeno je na
                     //milijardu

  Passes.run(*mainModule);

  Podaci p(mainModule);
  p.UradiPosao();
  BufferPtr.take();
  std::cout << "Finished " << std::endl << std::endl;

  return 0;
}
예제 #28
0
error_code Archive::Child::getAsBinary(OwningPtr<Binary> &Result) const {
  OwningPtr<Binary> ret;
  OwningPtr<MemoryBuffer> Buff;
  if (error_code ec = getMemoryBuffer(Buff))
    return ec;
  ErrorOr<Binary *> BinaryOrErr = createBinary(Buff.take());
  if (error_code EC = BinaryOrErr.getError())
    return EC;
  Result.reset(BinaryOrErr.get());
  return object_error::success;
}
예제 #29
0
파일: IRReader.cpp 프로젝트: drexler/llvm
Module *llvm::ParseIRFile(const std::string &Filename, SMDiagnostic &Err,
                          LLVMContext &Context) {
  OwningPtr<MemoryBuffer> File;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename.c_str(), File)) {
    Err = SMDiagnostic(Filename, SourceMgr::DK_Error,
                       "Could not open input file: " + ec.message());
    return 0;
  }

  return ParseIR(File.take(), Err, Context);
}
예제 #30
0
파일: Archive.cpp 프로젝트: vicioushg/llvm
bool
Archive::mapToMemory(std::string* ErrMsg) {
  OwningPtr<MemoryBuffer> File;
  if (error_code ec = MemoryBuffer::getFile(archPath.c_str(), File)) {
    if (ErrMsg)
      *ErrMsg = ec.message();
    return true;
  }
  mapfile = File.take();
  base = mapfile->getBufferStart();
  return false;
}