Esempio n. 1
0
void CopyBinary(const ELFObjectFile<ELF64LE> &ObjFile) {
  std::unique_ptr<FileOutputBuffer> Buffer;
  std::unique_ptr<Object<ELF64LE>> Obj;
  if (!OutputFormat.empty() && OutputFormat != "binary")
    error("invalid output format '" + OutputFormat + "'");

  if (!OutputFormat.empty() && OutputFormat == "binary")
    Obj = llvm::make_unique<BinaryObject<ELF64LE>>(ObjFile);
  else
    Obj = llvm::make_unique<ELFObject<ELF64LE>>(ObjFile);
  Obj->finalize();
  ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
      FileOutputBuffer::create(OutputFilename, Obj->totalSize(),
                               FileOutputBuffer::F_executable);
  if (BufferOrErr.getError())
    error("failed to open " + OutputFilename);
  else
    Buffer = std::move(*BufferOrErr);
  std::error_code EC;
  if (EC)
    report_fatal_error(EC.message());
  Obj->write(*Buffer);
  if (auto EC = Buffer->commit())
    reportError(OutputFilename, EC);
}
Esempio n. 2
0
static bool doImportingForModule(Module &M, const ModuleSummaryIndex *Index) {
  if (SummaryFile.empty() && !Index)
    report_fatal_error("error: -function-import requires -summary-file or "
                       "file from frontend\n");
  std::unique_ptr<ModuleSummaryIndex> IndexPtr;
  if (!SummaryFile.empty()) {
    if (Index)
      report_fatal_error("error: -summary-file and index from frontend\n");
    Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
        getModuleSummaryIndexForFile(SummaryFile);
    if (!IndexPtrOrErr) {
      logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
                            "Error loading file '" + SummaryFile + "': ");
      return false;
    }
    IndexPtr = std::move(*IndexPtrOrErr);
    Index = IndexPtr.get();
  }

  // First step is collecting the import list.
  FunctionImporter::ImportMapTy ImportList;
  ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
                                    ImportList);

  // Conservatively mark all internal values as promoted. This interface is
  // only used when doing importing via the function importing pass. The pass
  // is only enabled when testing importing via the 'opt' tool, which does
  // not do the ThinLink that would normally determine what values to promote.
  for (auto &I : *Index) {
    for (auto &S : I.second) {
      if (GlobalValue::isLocalLinkage(S->linkage()))
        S->setLinkage(GlobalValue::ExternalLinkage);
    }
  }

  // Next we need to promote to global scope and rename any local values that
  // are potentially exported to other modules.
  if (renameModuleForThinLTO(M, *Index, nullptr)) {
    errs() << "Error renaming module\n";
    return false;
  }

  // Perform the import now.
  auto ModuleLoader = [&M](StringRef Identifier) {
    return loadFile(Identifier, M.getContext());
  };
  FunctionImporter Importer(*Index, ModuleLoader);
  Expected<bool> Result = Importer.importFunctions(
      M, ImportList, !DontForceImportReferencedDiscardableSymbols);

  // FIXME: Probably need to propagate Errors through the pass manager.
  if (!Result) {
    logAllUnhandledErrors(Result.takeError(), errs(),
                          "Error importing module: ");
    return false;
  }

  return *Result;
}
Esempio n. 3
0
ExecutionEngine * JIT_to_ExecutionEngine (Module * m) {

    InitializeNativeTarget();
    InitializeNativeTargetAsmPrinter();
    InitializeNativeTargetAsmParser();

    PassRegistry * Registry = PassRegistry::getPassRegistry();
    initializeCore(*Registry);
    initializeCodeGen(*Registry);
    initializeLowerIntrinsicsPass(*Registry);

    std::string errMessage;
    EngineBuilder builder{std::unique_ptr<Module>(m)};
    builder.setErrorStr(&errMessage);
    builder.setMCPU(sys::getHostCPUName());
    TargetOptions opts = InitTargetOptionsFromCodeGenFlags();
    builder.setTargetOptions(opts);
    CodeGenOpt::Level optLevel = CodeGenOpt::Level::None;
    switch (OptLevel) {
        case '0': optLevel = CodeGenOpt::None; break;
        case '1': optLevel = CodeGenOpt::Less; break;
        case '2': optLevel = CodeGenOpt::Default; break;
        case '3': optLevel = CodeGenOpt::Aggressive; break;
        default: errs() << OptLevel << " is an invalid optimization level.\n";
    }
    builder.setOptLevel(optLevel);

    if ((strncmp(lGetSystemISA(), "avx2", 4) == 0)) {
        std::vector<std::string> attrs;
        attrs.push_back("avx2");
        builder.setMAttrs(attrs);
    }
    // builder.selectTarget();

    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
        if (IROutputFilename.empty()) {
            m->dump();
        } else {
            std::error_code error;
            llvm::raw_fd_ostream out(IROutputFilename, error, sys::fs::OpenFlags::F_None);
            m->print(out, nullptr);
        }
    }

    ExecutionEngine * engine = builder.create();
    ICGrepObjectCache * cache = nullptr;
    if (engine == nullptr) {
        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
    }
    if (EnableObjectCache) {
        if (ObjectCacheDir.empty())
            // Default is $HOME/.cache/icgrep
            cache = new ICGrepObjectCache();
        else
            cache = new ICGrepObjectCache(ObjectCacheDir);
        engine->setObjectCache(cache);
    }
    return engine;
}
Esempio n. 4
0
//===----------------------------------------------------------------------===//
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.

  cl::ParseCommandLineOptions(argc, argv, "llvm coverage tool\n");

  std::string ErrorInfo;
  raw_fd_ostream OS(OutputFile.c_str(), ErrorInfo);
  if (!ErrorInfo.empty())
    errs() << ErrorInfo << "\n";

  GCOVFile GF;
  if (InputGCNO.empty())
    errs() << " " << argv[0] << ": No gcov input file!\n";

  OwningPtr<MemoryBuffer> GCNO_Buff;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCNO, GCNO_Buff)) {
    errs() << InputGCNO << ": " << ec.message() << "\n";
    return 1;
  }
  GCOVBuffer GCNO_GB(GCNO_Buff.get());
  if (!GF.read(GCNO_GB)) {
    errs() << "Invalid .gcno File!\n";
    return 1;
  }

  if (!InputGCDA.empty()) {
    OwningPtr<MemoryBuffer> GCDA_Buff;
    if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputGCDA, GCDA_Buff)) {
      errs() << InputGCDA << ": " << ec.message() << "\n";
      return 1;
    }
    GCOVBuffer GCDA_GB(GCDA_Buff.get());
    if (!GF.read(GCDA_GB)) {
      errs() << "Invalid .gcda File!\n";
      return 1;
    }
  }


  if (DumpGCOV)
    GF.dump();

  FileInfo FI;
  GF.collectLineCounts(FI);
  FI.print(OS, InputGCNO, InputGCDA);
  return 0;
}
Esempio n. 5
0
static const Target *getTarget(const ObjectFile *Obj) {
  // Figure out the target triple.
  Triple TheTriple("unknown-unknown-unknown");
  if (TripleName.empty()) {
  if (Obj) {
    TheTriple.setArch(Triple::ArchType(Obj->getArch()));
    // TheTriple defaults to ELF, and COFF doesn't have an environment:
    // the best we can do here is indicate that it is mach-o.
    if (Obj->isMachO())
      TheTriple.setObjectFormat(Triple::MachO);
  }
  } else {
    TheTriple.setTriple(TripleName);
  }

  // Get the Target.
  std::string Error;
  const Target *TheTarget = TargetRegistry::lookupTarget("", TheTriple, Error);
  if (!TheTarget) {
    errs() << ToolName << ": " << Error;
    return 0;
  }

  // Update the triple name and return the found target.
  TripleName = TheTriple.getTriple();
  return TheTarget;
}
Esempio n. 6
0
static void WriteOutputFile(const Module *M) {
  // Infer the output filename if needed.
  if (OutputFilename.empty()) {
    if (InputFilename == "-") {
      OutputFilename = "-";
    } else {
      StringRef IFN = InputFilename;
      OutputFilename = (IFN.endswith(".ll") ? IFN.drop_back(3) : IFN).str();
      OutputFilename += ".bc";
    }
  }

  std::error_code EC;
  std::unique_ptr<ToolOutputFile> Out(
      new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
  if (EC) {
    errs() << EC.message() << '\n';
    exit(1);
  }

  if (Force || !CheckBitcodeOutputToConsole(Out->os(), true))
    WriteBitcodeToFile(*M, Out->os(), PreserveBitcodeUseListOrder, nullptr,
                       EmitModuleHash);

  // Declare success.
  Out->keep();
}
Esempio n. 7
0
/// Create a combined index file from the input IR files and write it.
///
/// This is meant to enable testing of ThinLTO combined index generation,
/// currently available via the gold plugin via -thinlto.
static int createCombinedFunctionIndex(StringRef Command) {
  FunctionInfoIndex CombinedIndex;
  uint64_t NextModuleId = 0;
  for (auto &Filename : InputFilenames) {
    ErrorOr<std::unique_ptr<FunctionInfoIndex>> IndexOrErr =
        getFunctionIndexForFile(Filename, diagnosticHandler);
    if (std::error_code EC = IndexOrErr.getError()) {
      std::string Error = EC.message();
      errs() << Command << ": error loading file '" << Filename
             << "': " << Error << "\n";
      return 1;
    }
    std::unique_ptr<FunctionInfoIndex> Index = std::move(IndexOrErr.get());
    // Skip files without a function summary.
    if (!Index)
      continue;
    CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
  }
  std::error_code EC;
  assert(!OutputFilename.empty());
  raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
                    sys::fs::OpenFlags::F_None);
  if (EC) {
    errs() << Command << ": error opening the file '" << OutputFilename
           << ".thinlto.bc': " << EC.message() << "\n";
    return 1;
  }
  WriteFunctionSummaryToFile(CombinedIndex, OS);
  OS.close();
  return 0;
}
Esempio n. 8
0
static unsigned Choose(unsigned n) {
  ensure(n > 0);
  ++Depth;
  if (!Fuzz) {
    if (RT) {
      ensure(Depth <= 99);
      setpri();
    }
    for (unsigned i = 0; i < (n - 1); ++i) {
      int ret = ::fork();
      ensure(ret != -1);
      if (ret == 0) {
        Id = Shmem->NextId.fetch_add(1);
        Choices += std::to_string(i) + " ";
        return i;
      }
      if (RT)
        ensure(0 == sem_wait(&Shmem->sem));
      else
        ::wait(0);
    }
    Choices += std::to_string(n - 1) + " ";
    return n - 1;
  } else if (!ForcedChoiceStr.empty()) {
    static unsigned Choice = 0;
    return ForcedChoices[Choice++];
  } else {
    unsigned i = rand() % n;
    Choices += std::to_string(i) + " ";
    return i;
  }
}
Esempio n. 9
0
int main(int argc, const char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  cl::ParseCommandLineOptions(argc, argv);

  std::unique_ptr<CompilationDatabase> Compilations(
      FixedCompilationDatabase::loadFromCommandLine(argc, argv));
  if (!Compilations) {  // Couldn't find a compilation DB from the command line
    std::string ErrorMessage;
    Compilations.reset(
      !BuildPath.empty() ?
        CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage) :
        CompilationDatabase::autoDetectFromSource(SourcePaths[0], ErrorMessage)
      );

    // Still no compilation DB? - bail.
    if (!Compilations)
      llvm::report_fatal_error(ErrorMessage);
  }

  ClangTool Tool(*Compilations, SourcePaths);
  InstContext IC;
  ExprBuilderContext EBC;
  CandidateMap CandMap;
  std::vector<std::unique_ptr<llvm::Module>> OwnedMods;
  std::unique_ptr<FrontendActionFactory> Factory(CreateExtractorActionFactory(
      getGlobalContext(), IC, EBC, OwnedMods, CandMap));
  Tool.run(Factory.get());

  std::unique_ptr<Solver> S = GetSolverFromArgs();
  return SolveCandidateMap(llvm::outs(), CandMap, S.get()) ? 0 : 1;
}
Esempio n. 10
0
/// Create a combined index file from the input IR files and write it.
///
/// This is meant to enable testing of ThinLTO combined index generation,
/// currently available via the gold plugin via -thinlto.
static int createCombinedFunctionIndex(StringRef Command) {
  LLVMContext Context;
  FunctionInfoIndex CombinedIndex;
  uint64_t NextModuleId = 0;
  for (auto &Filename : InputFilenames) {
    std::string Error;
    std::unique_ptr<FunctionInfoIndex> Index =
        getFunctionIndexForFile(Filename, Error, Context);
    if (!Index) {
      errs() << Command << ": error loading file '" << Filename
             << "': " << Error << "\n";
      return 1;
    }
    CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
  }
  std::error_code EC;
  assert(!OutputFilename.empty());
  raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
                    sys::fs::OpenFlags::F_None);
  if (EC) {
    errs() << Command << ": error opening the file '" << OutputFilename
           << ".thinlto.bc': " << EC.message() << "\n";
    return 1;
  }
  WriteFunctionSummaryToFile(CombinedIndex, OS);
  OS.close();
  return 0;
}
Esempio n. 11
0
CommonOptionsParser::CommonOptionsParser(
    int &argc, const char **argv, cl::OptionCategory &Category,
    llvm::cl::NumOccurrencesFlag OccurrencesFlag, const char *Overview) {
  static cl::opt<bool> Help("h", cl::desc("Alias for -help"), cl::Hidden);

  static cl::opt<std::string> BuildPath("p", cl::desc("Build path"),
                                        cl::Optional, cl::cat(Category));

  static cl::list<std::string> SourcePaths(
      cl::Positional, cl::desc("<source0> [... <sourceN>]"), OccurrencesFlag,
      cl::cat(Category));

  static cl::list<std::string> ArgsAfter(
      "extra-arg",
      cl::desc("Additional argument to append to the compiler command line"),
      cl::cat(Category));

  static cl::list<std::string> ArgsBefore(
      "extra-arg-before",
      cl::desc("Additional argument to prepend to the compiler command line"),
      cl::cat(Category));

  cl::HideUnrelatedOptions(Category);

  std::string ErrorMessage;
  Compilations =
      FixedCompilationDatabase::loadFromCommandLine(argc, argv, ErrorMessage);
  if (!Compilations && !ErrorMessage.empty())
    llvm::errs() << ErrorMessage;
  cl::ParseCommandLineOptions(argc, argv, Overview);
  cl::PrintOptionValues();

  SourcePathList = SourcePaths;
  if ((OccurrencesFlag == cl::ZeroOrMore || OccurrencesFlag == cl::Optional) &&
      SourcePathList.empty())
    return;
  if (!Compilations) {
    if (!BuildPath.empty()) {
      Compilations =
          CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage);
    } else {
      Compilations = CompilationDatabase::autoDetectFromSource(SourcePaths[0],
                                                               ErrorMessage);
    }
    if (!Compilations) {
      llvm::errs() << "Error while trying to load a compilation database:\n"
                   << ErrorMessage << "Running without flags.\n";
      Compilations.reset(
          new FixedCompilationDatabase(".", std::vector<std::string>()));
    }
  }
  auto AdjustingCompilations =
      llvm::make_unique<ArgumentsAdjustingCompilations>(
          std::move(Compilations));
  AdjustingCompilations->appendArgumentsAdjuster(
      getInsertArgumentAdjuster(ArgsBefore, ArgumentInsertPosition::BEGIN));
  AdjustingCompilations->appendArgumentsAdjuster(
      getInsertArgumentAdjuster(ArgsAfter, ArgumentInsertPosition::END));
  Compilations = std::move(AdjustingCompilations);
}
Esempio n. 12
0
bool CheerpWritePass::runOnModule(Module& M)
{
  cheerp::PointerAnalyzer &PA = getAnalysis<cheerp::PointerAnalyzer>();
  cheerp::GlobalDepsAnalyzer &GDA = getAnalysis<cheerp::GlobalDepsAnalyzer>();
  cheerp::Registerize &registerize = getAnalysis<cheerp::Registerize>();
  cheerp::SourceMapGenerator* sourceMapGenerator = NULL;
  if (!SourceMap.empty())
  {
    std::string ErrorString;
    sourceMapGenerator = new cheerp::SourceMapGenerator(SourceMap, SourceMapPrefix, M.getContext(), ErrorString);
    if (!ErrorString.empty())
    {
       // An error occurred opening the source map file, bail out
       delete sourceMapGenerator;
       llvm::report_fatal_error(ErrorString.c_str(), false);
       return false;
    }
  }
  PA.fullResolve();
  PA.computeConstantOffsets(M);
  registerize.assignRegisters(M, PA);
  cheerp::CheerpWriter writer(M, Out, PA, registerize, GDA, sourceMapGenerator, PrettyCode, NoRegisterize, !NoNativeJavaScriptMath, !NoJavaScriptMathImul);
  writer.makeJS();
  delete sourceMapGenerator;
  return false;
}
Esempio n. 13
0
static void runSpecificPasses(StringRef Binary, llvm::Module *M,
                              llvm::TargetMachine *TM,
                              llvm::Triple &ModuleTriple) {
  llvm::legacy::PassManager Passes;
  llvm::TargetLibraryInfoImpl TLII(ModuleTriple);
  Passes.add(new TargetLibraryInfoWrapperPass(TLII));

  const llvm::DataLayout &DL = M->getDataLayout();
  if (DL.isDefault() && !DefaultDataLayout.empty()) {
    M->setDataLayout(DefaultDataLayout);
  }

  // Add internal analysis passes from the target machine.
  Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
                                                     : TargetIRAnalysis()));

  for (const llvm::PassInfo *PassInfo : PassList) {
    llvm::Pass *P = nullptr;
    if (PassInfo->getTargetMachineCtor())
      P = PassInfo->getTargetMachineCtor()(TM);
    else if (PassInfo->getNormalCtor())
      P = PassInfo->getNormalCtor()();
    else
      errs() << Binary << ": cannot create pass: "******"\n";
    if (P) {
      addPass(Passes, P);
    }
  }

  // Do it.
  Passes.run(*M);
}
Esempio n. 14
0
int main(int argc, char **argv) {
  // Init LLVM, call llvm_shutdown() on exit, parse args, etc.
  llvm::PrettyStackTraceProgram X(argc, argv);
  cl::ParseCommandLineOptions(argc, argv, "llvm codegen stress-tester\n");
  llvm_shutdown_obj Y;

  std::auto_ptr<Module> M(new Module("/tmp/autogen.bc", getGlobalContext()));
  Function *F = GenEmptyFunction(M.get());
  FillFunction(F);
  IntroduceControlFlow(F);

  // Figure out what stream we are supposed to write to...
  OwningPtr<tool_output_file> Out;
  // Default to standard output.
  if (OutputFilename.empty())
    OutputFilename = "-";

  std::string ErrorInfo;
  Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
                                 raw_fd_ostream::F_Binary));
  if (!ErrorInfo.empty()) {
    errs() << ErrorInfo << '\n';
    return 1;
  }

  PassManager Passes;
  Passes.add(createVerifierPass());
  Passes.add(createPrintModulePass(&Out->os()));
  Passes.run(*M.get());
  Out->keep();

  return 0;
}
Esempio n. 15
0
static void WriteOutputFile(const Module *M) {
  // Infer the output filename if needed.
  if (OutputFilename.empty()) {
    if (InputFilename == "-") {
      OutputFilename = "-";
    } else {
      std::string IFN = InputFilename;
      int Len = IFN.length();
      if (IFN[Len-3] == '.' && IFN[Len-2] == 'l' && IFN[Len-1] == 'l') {
        // Source ends in .ll
        OutputFilename = std::string(IFN.begin(), IFN.end()-3);
      } else {
        OutputFilename = IFN;   // Append a .bc to it
      }
      OutputFilename += ".bc";
    }
  }

  std::error_code EC;
  std::unique_ptr<tool_output_file> Out(
      new tool_output_file(OutputFilename, EC, sys::fs::F_None));
  if (EC) {
    errs() << EC.message() << '\n';
    exit(1);
  }

  if (Force || !CheckBitcodeOutputToConsole(Out->os(), true))
    WriteBitcodeToFile(M, Out->os(), PreserveBitcodeUseListOrder);

  // Declare success.
  Out->keep();
}
Esempio n. 16
0
InternalizePass::InternalizePass(bool OnlyHidden)
  : ModulePass(ID), OnlyHidden(OnlyHidden) {
  initializeInternalizePassPass(*PassRegistry::getPassRegistry());
  if (!APIFile.empty())           // If a filename is specified, use it.
    LoadFile(APIFile.c_str());
  ExternalNames.insert(APIList.begin(), APIList.end());
}
Esempio n. 17
0
int main(int argc, const char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  std::unique_ptr<CompilationDatabase> Compilations(
      FixedCompilationDatabase::loadFromCommandLine(argc, argv));
  cl::ParseCommandLineOptions(argc, argv);
  if (!Compilations) {  // Couldn't find a compilation DB from the command line
    std::string ErrorMessage;
    Compilations.reset(
      !BuildPath.empty() ?
        CompilationDatabase::autoDetectFromDirectory(BuildPath, ErrorMessage) :
        CompilationDatabase::autoDetectFromSource(SourcePaths[0], ErrorMessage)
      );

//  Still no compilation DB? - bail.
    if (!Compilations)
      llvm::report_fatal_error(ErrorMessage);
    }
  RefactoringTool Tool(*Compilations, SourcePaths);
  ast_matchers::MatchFinder Finder;
  ToolTemplateCallback Callback(&Tool.getReplacements());

// TODO: Put your matchers here.
// Use Finder.addMatcher(...) to define the patterns in the AST that you
// want to match against. You are not limited to just one matcher!

  return Tool.run(newFrontendActionFactory(&Finder));
}
PassManagerBuilder::PassManagerBuilder() {
    OptLevel = 2;
    SizeLevel = 0;
    LibraryInfo = nullptr;
    Inliner = nullptr;
    DisableTailCalls = false;
    DisableUnitAtATime = false;
    DisableUnrollLoops = false;
    BBVectorize = RunBBVectorization;
    SLPVectorize = RunSLPVectorization;
    LoopVectorize = RunLoopVectorization;
    RerollLoops = RunLoopRerolling;
    LoadCombine = RunLoadCombine;
    DisableGVNLoadPRE = false;
    VerifyInput = false;
    VerifyOutput = false;
    StripDebug = false;
    MergeFunctions = false;
    
    // Initialization of the global cryptographically
    // secure pseudo-random generator
    if(!AesSeed.empty()) {
        llvm::cryptoutils->prng_seed(AesSeed.c_str());
    }
}
Esempio n. 19
0
/*
 * method importInitialStates
 *
 * Here we read the file specified by RAFilename and initialize the
 * abstract states of the selected nodes in the graph.
 */
void llvm::RangeAnalysis::importInitialStates(ModuleLookup& M){

	if(RAFilename.empty()) return;

	ifstream File;
	File.open(RAFilename.c_str(), ifstream::in);

	std::string line;
	while (std::getline(File, line))
	{
		std::size_t tam = line.size();
		std::size_t pos = line.find_first_of("|");
		std::string FunctionName = line.substr(0, pos);

		line = line.substr(pos+1, tam-pos-1);
		tam = line.size();
		pos = line.find_first_of("|");
		std::string ValueName = line.substr(0, pos);

		std::string RangeString = line.substr(pos+1, tam-pos);

		if(Value* V = M.getValueByName(FunctionName, ValueName)) {

			if(GraphNode* G = depGraph->findNode(V)){
				initial_state[G] = Range(RangeString);
			}
		}
	}

	File.close();
}
Esempio n. 20
0
static tool_output_file *GetOutputStream(const char *TargetName,
                                         Triple::OSType OS,
                                         const char *ProgName) {
  // If we don't yet have an output filename, make one.
  if (OutputFilename.empty()) {
    if (InputFilename == "-")
      OutputFilename = "-";
    else {
      OutputFilename = GetFileNameRoot(InputFilename);

      switch (FileType) {
      case TargetMachine::CGFT_AssemblyFile:
        if (TargetName[0] == 'c') {
          if (TargetName[1] == 0)
            OutputFilename += ".cbe.c";
          else if (TargetName[1] == 'p' && TargetName[2] == 'p')
            OutputFilename += ".cpp";
          else
            OutputFilename += ".s";
        } else
          OutputFilename += ".s";
        break;
      case TargetMachine::CGFT_ObjectFile:
        if (OS == Triple::Win32)
          OutputFilename += ".obj";
        else
          OutputFilename += ".o";
        break;
      case TargetMachine::CGFT_Null:
        OutputFilename += ".null";
        break;
      }
    }
  }

  // Decide if we need "binary" output.
  bool Binary = false;
  switch (FileType) {
  case TargetMachine::CGFT_AssemblyFile:
    break;
  case TargetMachine::CGFT_ObjectFile:
  case TargetMachine::CGFT_Null:
    Binary = true;
    break;
  }

  // Open the file.
  std::string error;
  unsigned OpenFlags = 0;
  if (Binary) OpenFlags |= raw_fd_ostream::F_Binary;
  tool_output_file *FDOut = new tool_output_file(OutputFilename.c_str(), error,
                                                 OpenFlags);
  if (!error.empty()) {
    errs() << error << '\n';
    delete FDOut;
    return 0;
  }

  return FDOut;
}
Esempio n. 21
0
int main(int argc, char **argv) {
  cl::ParseCommandLineOptions(argc, argv);
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  if (OutputFilename.empty())
    OutputFilename = "-";

  std::string ErrorInfo;
  std::unique_ptr<tool_output_file> Out(
      new tool_output_file(OutputFilename.c_str(), ErrorInfo, sys::fs::F_None));
  if (!ErrorInfo.empty()) {
    errs() << ErrorInfo << '\n';
    return 1;
  }

  std::unique_ptr<MemoryBuffer> Buf;
  if (MemoryBuffer::getFileOrSTDIN(Input, Buf))
    return 1;

  int Res = 1;
  if (Format == YOF_COFF)
    Res = yaml2coff(Out->os(), Buf.get());
  else if (Format == YOF_ELF)
    Res = yaml2elf(Out->os(), Buf.get());
  else
    errs() << "Not yet implemented\n";

  if (Res == 0)
    Out->keep();

  return Res;
}
Esempio n. 22
0
static void WriteOutputFile(const Module *M) {
  // Infer the output filename if needed.
  if (OutputFilename.empty()) {
    if (InputFilename == "-") {
      OutputFilename = "-";
    } else {
      std::string IFN = InputFilename;
      int Len = IFN.length();
      if (IFN[Len-3] == '.' && IFN[Len-2] == 'l' && IFN[Len-1] == 'l') {
        // Source ends in .ll
        OutputFilename = std::string(IFN.begin(), IFN.end()-3);
      } else {
        OutputFilename = IFN;   // Append a .bc to it
      }
      OutputFilename += ".bc";
    }
  }

  std::string ErrorInfo;
  OwningPtr<tool_output_file> Out
  (new tool_output_file(OutputFilename.c_str(), ErrorInfo,
                        raw_fd_ostream::F_Binary));
  if (!ErrorInfo.empty()) {
    errs() << ErrorInfo << '\n';
    exit(1);
  }

  if (Force || !CheckBitcodeOutputToConsole(Out->os(), true))
    WriteBitcodeToFile(M, Out->os());

  // Declare success.
  Out->keep();
}
Esempio n. 23
0
InternalizePass::InternalizePass(bool AllButMain)
  : ModulePass(ID), AllButMain(AllButMain){
  initializeInternalizePassPass(*PassRegistry::getPassRegistry());
  if (!APIFile.empty())           // If a filename is specified, use it.
    LoadFile(APIFile.c_str());
  if (!APIList.empty())           // If a list is specified, use it as well.
    ExternalNames.insert(APIList.begin(), APIList.end());
}
Esempio n. 24
0
void MachineBlockFrequencyInfo::calculate(
    const MachineFunction &F, const MachineBranchProbabilityInfo &MBPI,
    const MachineLoopInfo &MLI) {
  if (!MBFI)
    MBFI.reset(new ImplType);
  MBFI->calculate(F, MBPI, MLI);
  if (ViewMachineBlockFreqPropagationDAG != GVDT_None &&
      (ViewBlockFreqFuncName.empty() ||
       F.getName().equals(ViewBlockFreqFuncName))) {
    view("MachineBlockFrequencyDAGS." + F.getName());
  }
  if (PrintMachineBlockFreq &&
      (PrintBlockFreqFuncName.empty() ||
       F.getName().equals(PrintBlockFreqFuncName))) {
    MBFI->print(dbgs());
  }
}
Esempio n. 25
0
void BlockFrequencyInfo::calculate(const Function &F,
                                   const BranchProbabilityInfo &BPI,
                                   const LoopInfo &LI) {
  if (!BFI)
    BFI.reset(new ImplType);
  BFI->calculate(F, BPI, LI);
  if (ViewBlockFreqPropagationDAG != GVDT_None &&
      (ViewBlockFreqFuncName.empty() ||
       F.getName().equals(ViewBlockFreqFuncName))) {
    view();
  }
  if (PrintBlockFreq &&
      (PrintBlockFreqFuncName.empty() ||
       F.getName().equals(PrintBlockFreqFuncName))) {
    print(dbgs());
  }
}
Esempio n. 26
0
// Helper function to handle -of, -od, etc.
static void initFromString(char*& dest, const cl::opt<std::string>& src) {
    dest = 0;
    if (src.getNumOccurrences() != 0) {
        if (src.empty())
            error("Expected argument to '-%s'", src.ArgStr);
        dest = mem.strdup(src.c_str());
    }
}
Esempio n. 27
0
int llvm::TableGenMain(char *argv0, TableGenMainFn *MainFn) {
  RecordKeeper Records;

  // Parse the input file.
  ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
      MemoryBuffer::getFileOrSTDIN(InputFilename);
  if (std::error_code EC = FileOrErr.getError())
    return reportError(argv0, "Could not open input file '" + InputFilename +
                                  "': " + EC.message() + "\n");

  // Tell SrcMgr about this buffer, which is what TGParser will pick up.
  SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());

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

  TGParser Parser(SrcMgr, MacroNames, Records);

  if (Parser.ParseFile())
    return 1;

  // Write output to memory.
  std::string OutString;
  raw_string_ostream Out(OutString);
  if (MainFn(Out, Records))
    return 1;

  // Always write the depfile, even if the main output hasn't changed.
  // If it's missing, Ninja considers the output dirty.  If this was below
  // the early exit below and someone deleted the .inc.d file but not the .inc
  // file, tablegen would never write the depfile.
  if (!DependFilename.empty()) {
    if (int Ret = createDependencyFile(Parser, argv0))
      return Ret;
  }

  // Only updates the real output file if there are any differences.
  // This prevents recompilation of all the files depending on it if there
  // aren't any.
  if (auto ExistingOrErr = MemoryBuffer::getFile(OutputFilename))
    if (std::move(ExistingOrErr.get())->getBuffer() == Out.str())
      return 0;

  std::error_code EC;
  ToolOutputFile OutFile(OutputFilename, EC, sys::fs::F_Text);
  if (EC)
    return reportError(argv0, "error opening " + OutputFilename + ":" +
                                  EC.message() + "\n");
  OutFile.os() << Out.str();

  if (ErrorsPrinted > 0)
    return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");

  // Declare success.
  OutFile.keep();
  return 0;
}
Esempio n. 28
0
bool DynamicGiri::runOnModule(Module &M) {
  // Get references to other passes used by this pass.
  bbNumPass = &getAnalysis<QueryBasicBlockNumbers>();
  lsNumPass = &getAnalysis<QueryLoadStoreNumbers>();

  // Open the trace file and get ready to start using it.
  Trace = new TraceFile(TraceFilename, bbNumPass, lsNumPass);

  // FIXME:
  //  This code should not be here.  It should be in a separate pass that
  //  queries this pass as an analysis pass.

  if (!StartOfSliceLoc.empty()) {
    // User specified the line number of the source code. This is very useful
    // if the user won't bother to dive into the IR of the program. We compare
    // the file name and the loc with all the instructions of the module. Note
    // that there will be more than one instruction in this case, and we'll
    // treat the *last* one of them as the criterion.
    std::ifstream StartOfSlice(StartOfSliceLoc);
    if (!StartOfSlice.is_open()) {
      errs() << "Error opening criterion file: " << StartOfSliceLoc << "\n";
      return false;
    }
    std::string StartFilename;
    unsigned StartLoc = 0;
    while (StartOfSlice >> StartFilename >> StartLoc) {
      if (StartLoc == 0) {
        errs() << "Error reading criterion file: " << StartOfSliceLoc << "\n";
        break;
      }
      dbgs() << "Start slicing Filename:Loc is defined as "
             << StartFilename << ":" << StartLoc << "\n";

      Instruction *Criterion = nullptr;
      for (Module::iterator F = M.begin(); F != M.end(); ++F)
        for (inst_iterator I = inst_begin(F); I != inst_end(F); ++I)
          if (MDNode *N = I->getMetadata("dbg")) { 
            DILocation l(N);
            if (l.getFilename().str() == StartFilename &&
                l.getLineNumber() == StartLoc) {
              Criterion = &*I;
              DEBUG(dbgs() << "Found instruction matching the LoC: ");
              DEBUG(Criterion->dump());
            }
          }

      if (Criterion != nullptr) {
        std::set<Value *> Slice;
        std::unordered_set<DynValue> DynSlice;
        std::set<DynValue *> DataFlowGraph;
        getBackwardsSlice(Criterion, Slice, DynSlice, DataFlowGraph);
        printBackwardsSlice(Criterion, Slice, DynSlice, DataFlowGraph);
      } else
        errs() << "Didin't find the starting instruction to slice.\n";
      StartLoc = 0; // reset the LoC for error checking of while
    }
    StartOfSlice.close();
  } else if (!StartOfSliceInst.empty()) {
Esempio n. 29
0
int main(int argc, char **argv) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal(argv[0]);
  PrettyStackTraceProgram X(argc, argv);

  LLVMContext Context;
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.

  Context.setDiagnosticHandler(diagnosticHandler, argv[0]);

  cl::ParseCommandLineOptions(argc, argv, "llvm .bc -> .ll disassembler\n");

  Expected<std::unique_ptr<Module>> MOrErr = openInputFile(Context);
  if (!MOrErr) {
    handleAllErrors(MOrErr.takeError(), [&](ErrorInfoBase &EIB) {
      errs() << argv[0] << ": ";
      EIB.log(errs());
      errs() << '\n';
    });
    return 1;
  }
  std::unique_ptr<Module> M = std::move(*MOrErr);

  // Just use stdout.  We won't actually print anything on it.
  if (DontPrint)
    OutputFilename = "-";

  if (OutputFilename.empty()) { // Unspecified output, infer it.
    if (InputFilename == "-") {
      OutputFilename = "-";
    } else {
      StringRef IFN = InputFilename;
      OutputFilename = (IFN.endswith(".bc") ? IFN.drop_back(3) : IFN).str();
      OutputFilename += ".ll";
    }
  }

  std::error_code EC;
  std::unique_ptr<tool_output_file> Out(
      new tool_output_file(OutputFilename, EC, sys::fs::F_None));
  if (EC) {
    errs() << EC.message() << '\n';
    return 1;
  }

  std::unique_ptr<AssemblyAnnotationWriter> Annotator;
  if (ShowAnnotations)
    Annotator.reset(new CommentWriter());

  // All that llvm-dis does is write the assembly to a file.
  if (!DontPrint)
    M->print(Out->os(), Annotator.get(), PreserveAssemblyUseListOrder);

  // Declare success.
  Out->keep();

  return 0;
}
int main(int argc, char **argv) {

  sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram X(argc, argv);

  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
  LLVMContext &Context = getGlobalContext();

  cl::ParseCommandLineOptions(argc, argv, "Bitcode translation tool\n");

  int input_fd = open(InputFilename.c_str(), O_RDONLY);

  unsigned char *wrapper = NULL;
  const char *bitcode = NULL;

  // Read bitcode wrapper
  size_t bitcode_size = 0;
  size_t wrapper_size = ReadBitcodeWrapper(input_fd, &wrapper, bitcode_size);

  // Read bitcode
  bitcode = (const char*) calloc(1, bitcode_size);
  size_t nread = read(input_fd, (void*) bitcode, bitcode_size);
  if (nread != bitcode_size) {
    errs() << "Could not read bitcode\n";
    return 1;
  }

  // Translate bitcode
  std::string BCString;
  TranslateBitcode(bitcode, bitcode_size, BCString, Context);

  // Update bitcode size
  WriteInt32(wrapper, 12, BCString.length());

  // Default to input filename
  if (OutputFilename.empty())
    OutputFilename = InputFilename;

  // Output stripped bitcode
  std::error_code EC;
  tool_output_file Out(OutputFilename.c_str(), EC, sys::fs::F_None);
  if (EC) {
    errs() << EC.message() << '\n';
    return 1;
  }

  Out.os().write((const char *) wrapper, wrapper_size);
  Out.os().write(BCString.c_str(), BCString.length());
  Out.keep();

  // Clean up
  free((void *) wrapper);
  free((void *) bitcode);
  close(input_fd);

  return 0;
}