示例#1
1
文件: sc.cpp 项目: otinn/safecode
static void addStaticGEPCheckingPass(PassManager & Passes) {
#if 0
	switch (SCConfig.staticCheckType()) {
		case SAFECodeConfiguration::ABC_CHECK_NONE:
			Passes.add(new ArrayBoundsCheckDummy());
			break;
		case SAFECodeConfiguration::ABC_CHECK_LOCAL:
#if 0
      if (SCConfig.getPAType() == SAFECodeConfiguration::PA_APA) {
        Passes.add(new ArrayBoundsCheckStruct());
      }
#endif
			Passes.add(new ArrayBoundsCheckLocal());
			break;
		case SAFECodeConfiguration::ABC_CHECK_FULL:
#if 0
      if (SCConfig.getPAType() == SAFECodeConfiguration::PA_APA) {
        Passes.add(new ArrayBoundsCheckStruct());
      }
#endif
#if 0
			Passes.add(new ArrayBoundsCheck());
#else
			assert (0 && "Omega pass is not working right now!");
#endif
			break;
	}
#endif
}
示例#2
0
文件: codegen.cpp 项目: yukunxie/cats
/* Compile the AST into a module */
void CodeGenContext::generateCode(NBlock& root)
{
	//std::cout << "Generating code...\n";

	/* Create the top level interpreter function to call as entry */
	vector<Type*> argTypes;
	FunctionType *ftype = FunctionType::get(Type::getVoidTy(getGlobalContext()), makeArrayRef(argTypes), false);
	mainFunction = Function::Create(ftype, GlobalValue::InternalLinkage, "main", module);
	BasicBlock *bblock = BasicBlock::Create(getGlobalContext(), "entry", mainFunction, 0);

	currentFunction = mainFunction;

	/* Push a new variable/block context */
	pushBlock(bblock);
	root.codeGen(*this); /* emit bytecode for the toplevel block */
	ReturnInst::Create(getGlobalContext(), bblock);
	popBlock();

	/* Print the bytecode in a human-readable format
	   to see if our program compiled properly
	 */
	//std::cout << "Code is generated.\n";
	PassManager pm;
	pm.add(createPrintModulePass(outs()));
	pm.run(*module);
}
示例#3
0
//adapted from LLVM's C interface "LLVMTargetMachineEmitToFile"
bool llvmutil_emitobjfile(Module * Mod, TargetMachine * TM, const char * Filename, std::string * ErrorMessage) {

    PassManager pass;

    llvmutil_addtargetspecificpasses(&pass, TM);
    
    TargetMachine::CodeGenFileType ft = TargetMachine::CGFT_ObjectFile;
    
    raw_fd_ostream dest(Filename, *ErrorMessage, raw_fd_ostream::F_Binary);
    formatted_raw_ostream destf(dest);
    if (!ErrorMessage->empty()) {
        return true;
    }

    if (TM->addPassesToEmitFile(pass, destf, ft)) {
        *ErrorMessage = "addPassesToEmitFile";
        return true;
    }

    pass.run(*Mod);
    destf.flush();
    dest.flush();

    return false;
}
示例#4
0
void SingleImplPass::run_pass(DexStoresVector& stores, ConfigFiles& cfg, PassManager& mgr) {
  auto scope = build_class_scope(stores);
  ClassHierarchy ch = build_type_hierarchy(scope);
  int max_steps = 0;
  size_t previous_invoke_intf_count = s_invoke_intf_count;
  removed_count = 0;
  while (true) {
    DEBUG_ONLY size_t scope_size = scope.size();
    TypeToTypes intfs_to_classes;
    TypeSet intfs;
    build_type_maps(scope, intfs_to_classes, intfs);
    TypeMap single_impl;
    collect_single_impl(intfs_to_classes, single_impl);

    std::unique_ptr<SingleImplAnalysis> single_impls =
        SingleImplAnalysis::analyze(
            scope, stores, single_impl, intfs, m_pass_config);
    auto optimized = optimize(
        std::move(single_impls), ch, scope, m_pass_config);
    if (optimized == 0 || ++max_steps >= MAX_PASSES) break;
    removed_count += optimized;
    assert(scope_size > scope.size());
  }

  TRACE(INTF, 1, "Removed interfaces %ld\n", removed_count);
  TRACE(INTF, 1,
          "Updated invoke-interface to invoke-virtual %ld\n",
          s_invoke_intf_count - previous_invoke_intf_count);

  mgr.incr_metric(METRIC_REMOVED_INTERFACES, removed_count);
  mgr.incr_metric(METRIC_INVOKE_INT_TO_VIRT,
                  s_invoke_intf_count - previous_invoke_intf_count);

  post_dexen_changes(scope, stores);
}
示例#5
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;
}
示例#6
0
void AccessMarkingPass::run_pass(DexStoresVector& stores,
                                 ConfigFiles& /* conf */,
                                 PassManager& pm) {
  auto scope = build_class_scope(stores);
  ClassHierarchy ch = build_type_hierarchy(scope);
  SignatureMap sm = build_signature_map(ch);
  if (m_finalize_classes) {
    auto n_classes_final = mark_classes_final(scope, ch);
    pm.incr_metric("finalized_classes", n_classes_final);
    TRACE(ACCESS, 1, "Finalized %lu classes\n", n_classes_final);
  }
  if (m_finalize_methods) {
    auto n_methods_final = mark_methods_final(scope, ch);
    pm.incr_metric("finalized_methods", n_methods_final);
    TRACE(ACCESS, 1, "Finalized %lu methods\n", n_methods_final);
  }
  if (m_finalize_fields) {
    auto n_fields_final = mark_fields_final(scope);
    pm.incr_metric("finalized_fields", n_fields_final);
    TRACE(ACCESS, 1, "Finalized %lu fields\n", n_fields_final);
  }
  auto candidates = devirtualize(sm);
  auto dmethods = direct_methods(scope);
  candidates.insert(candidates.end(), dmethods.begin(), dmethods.end());
  if (m_privatize_methods) {
    auto privates = find_private_methods(scope, candidates);
    fix_call_sites_private(scope, privates);
    mark_methods_private(privates);
    pm.incr_metric("privatized_methods", privates.size());
    TRACE(ACCESS, 1, "Privatized %lu methods\n", privates.size());
  }
}
示例#7
0
void minipascal::CodeGenContext::generateCode(minipascal::Node* root)
{
	vector<llvm::Type*> argTypes;
	FunctionType *ftype = FunctionType::get(llvm::Type::getVoidTy(getGlobalContext()), makeArrayRef(argTypes), false);
	Function* mainfunc = Function::Create(ftype, GlobalValue::InternalLinkage, "main", mmodule);
	BasicBlock* mainblock = BasicBlock::Create(getGlobalContext(), "entry", mainfunc, 0);
		
	pushFunction(mainfunc);
	pushBlock(mainblock);
	// root->print();
	root->codeGen(*this);
	// printConstVal();
	// printTypeDefs();
	// printVarTypes();
	// printLocalVal();

	ReturnInst::Create(getGlobalContext(), currentBlock());
	popBlock();

	mmodule->dump();

	cout << "write to file out.ll start\n";
	string errorstr("Can not open the file");
	raw_fd_ostream outfile("out.ll", errorstr, 0);
  	verifyModule(*mmodule, PrintMessageAction);
  	PassManager passman;
  	passman.add(createPrintModulePass(&outfile));
  	passman.run(*mmodule);

	// WriteBitcodeToFile(mmodule, outfile);
	cout << "write to file out.ll end\n";
}
示例#8
0
extern "C" void LLVMRustWriteOutputFile(LLVMPassManagerRef PMR,
                                        LLVMModuleRef M,
                                        const char *triple,
                                        const char *path,
                                        TargetMachine::CodeGenFileType FileType,
                                        CodeGenOpt::Level OptLevel) {

  // Set compilation options.
  llvm::NoFramePointerElim = true;

  InitializeAllTargets();
  InitializeAllAsmPrinters();
  InitializeAllAsmParsers();
  TargetMachine::setRelocationModel(Reloc::PIC_);
  std::string Err;
  const Target *TheTarget = TargetRegistry::lookupTarget(triple, Err);
  std::string FeaturesStr;
  std::string Trip(triple);
  std::string CPUStr = llvm::sys::getHostCPUName();
  TargetMachine *Target = TheTarget->createTargetMachine(Trip, CPUStr, FeaturesStr);
  bool NoVerify = false;
  PassManager *PM = unwrap<PassManager>(PMR);
  std::string ErrorInfo;
  raw_fd_ostream OS(path, ErrorInfo,
                    raw_fd_ostream::F_Binary);
  formatted_raw_ostream FOS(OS);

  bool foo = Target->addPassesToEmitFile(*PM, FOS, FileType, OptLevel,
                                         NoVerify);
  assert(!foo);
  (void)foo;
  PM->run(*unwrap(M));
  delete Target;
}
示例#9
0
文件: Driver.cpp 项目: sas/lld
/// This is where the link is actually performed.
bool Driver::link(LinkingContext &ctx, raw_ostream &diagnostics) {
  if (ctx.getNodes().empty())
    return false;

  for (std::unique_ptr<Node> &ie : ctx.getNodes())
    if (FileNode *node = dyn_cast<FileNode>(ie.get()))
      ctx.getTaskGroup().spawn([node] { node->getFile()->parse(); });

  std::vector<std::unique_ptr<File>> internalFiles;
  ctx.createInternalFiles(internalFiles);
  for (auto i = internalFiles.rbegin(), e = internalFiles.rend(); i != e; ++i) {
    auto &members = ctx.getNodes();
    members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
  }

  // Give target a chance to add files.
  std::vector<std::unique_ptr<File>> implicitFiles;
  ctx.createImplicitFiles(implicitFiles);
  for (auto i = implicitFiles.rbegin(), e = implicitFiles.rend(); i != e; ++i) {
    auto &members = ctx.getNodes();
    members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
  }

  // Give target a chance to postprocess input files.
  // Mach-O uses this chance to move all object files before library files.
  // ELF adds specific undefined symbols resolver.
  ctx.finalizeInputFiles();

  // Do core linking.
  ScopedTask resolveTask(getDefaultDomain(), "Resolve");
  Resolver resolver(ctx);
  if (!resolver.resolve()) {
    ctx.getTaskGroup().sync();
    return false;
  }
  std::unique_ptr<SimpleFile> merged = resolver.resultFile();
  resolveTask.end();

  // Run passes on linked atoms.
  ScopedTask passTask(getDefaultDomain(), "Passes");
  PassManager pm;
  ctx.addPasses(pm);
  if (std::error_code ec = pm.runOnFile(*merged)) {
    diagnostics << "Failed to write file '" << ctx.outputPath()
                << "': " << ec.message() << "\n";
    return false;
  }

  passTask.end();

  // Give linked atoms to Writer to generate output file.
  ScopedTask writeTask(getDefaultDomain(), "Write");
  if (std::error_code ec = ctx.writeFile(*merged)) {
    diagnostics << "Failed to write file '" << ctx.outputPath()
                << "': " << ec.message() << "\n";
    return false;
  }

  return true;
}
static void AddTargetTranslationPass(PassManager &PM) {
  ExpandVAArgPass *VAArgPass = NULL;
  ReplaceUnwindHeaderSizePass *UnwindPass = NULL;

  if (ArchName == "arm") {
    VAArgPass = createARMExpandVAArgPass();
    UnwindPass = createARMReplaceUnwindHeaderSizePass();
  } else if (ArchName == "x86") {
    VAArgPass = createX86ExpandVAArgPass();
    UnwindPass = createX86ReplaceUnwindHeaderSizePass();
  } else if (ArchName == "mips") {
    VAArgPass = createMipsExpandVAArgPass();
    UnwindPass = createMipsReplaceUnwindHeaderSizePass();
  } else if (ArchName == "arm64") {
    VAArgPass = createArm64ExpandVAArgPass();
    UnwindPass = createX86ReplaceUnwindHeaderSizePass();  // the same as x86
  } else if (ArchName == "x86_64") {
    VAArgPass = createX86_64ExpandVAArgPass();
    UnwindPass = createX86ReplaceUnwindHeaderSizePass();  // the same as x86
  } else if (ArchName == "mips64") {
    VAArgPass = createMips64ExpandVAArgPass();
    UnwindPass = createX86ReplaceUnwindHeaderSizePass();  // the same as x86
  } else {
    errs() << "'" << ArchName << "' is not supported!\n";
    exit(1);
  }

  // Add target specific pass
  PM.add(new DataLayoutPass());
  if (VAArgPass)
    PM.add(VAArgPass);
  if (UnwindPass)
    PM.add(UnwindPass);
}
int main(int argc, char **argv) {
  if (argc < 2) {
    errs() << "Usage: " << argv[0] << " <IR file>\n";
    return 1;
  }

  // Parse the input LLVM IR file into a module.
  SMDiagnostic Err;
  std::unique_ptr<Module> Mod(parseIRFile(argv[1], Err, getGlobalContext()));
  if (!Mod) {
    Err.print(argv[0], errs());
    return 1;
  }

  // Create a function declarations for _tidx, _tidy, _tidz
  FunctionType *TidFuncTy =
      FunctionType::get(Type::getInt32Ty(Mod->getContext()), false);
  Function *Tidx = Function::Create(TidFuncTy, GlobalValue::InternalLinkage,
                                    "_tidx", Mod.get());
  Function *Tidy = Function::Create(TidFuncTy, GlobalValue::InternalLinkage,
                                    "_tidy", Mod.get());
  Function *Tidz = Function::Create(TidFuncTy, GlobalValue::InternalLinkage,
                                    "_tidz", Mod.get());

  // Create a pass manager and fill it with the passes we want to run.
  PassManager PM;
  PM.add(new ReplaceThreadIdxRefs(Tidx, Tidy, Tidz));
  PM.run(*Mod);

  outs() << "Dumping the module after the pass has run:\n";
  Mod->dump();

  return 0;
}
示例#12
0
void MipsLinkingContext::addPasses(PassManager &pm) {
    auto pass = createMipsRelocationPass(*this);
    if (pass)
        pm.add(std::move(pass));
    ELFLinkingContext::addPasses(pm);
    pm.add(llvm::make_unique<elf::MipsCtorsOrderPass>());
}
示例#13
0
bool LLVMOptimizeModule(LLVMModuleRef Mod) {
    Module* M = unwrap(Mod);

  // Create a PassManager to hold and optimize the collection of passes we are
  // about to build.
  PassManager Passes;

  // Add an appropriate TargetLibraryInfo pass for the module's triple.
  TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));

  // Add an appropriate DataLayout instance for this module.
  // const std::string &ModuleDataLayout = M->getDataLayout();
  // if (!ModuleDataLayout.empty()) {
  //   DataLayout *TD = NULL; // new DataLayout(ModuleDataLayout);
  //   Passes.add(TD);
  // }


  Passes.add(createVerifierPass());  // Verify that input is correct

  // -std-compile-opts adds the same module passes as -O3.
  PassManagerBuilder Builder;
  Builder.Inliner = createFunctionInliningPass();
  Builder.OptLevel = 3;
  Builder.populateModulePassManager(Passes);


  // Now that we have all of the passes ready, run them.
  bool change = Passes.run(*M);

  return change;
}
示例#14
0
void LTOCodeGenerator::applyScopeRestrictions() {
  if (ScopeRestrictionsDone)
    return;
  Module *mergedModule = Linker.getModule();

  // Start off with a verification pass.
  PassManager passes;
  passes.add(createVerifierPass());

  // mark which symbols can not be internalized
  Mangler Mangler(TargetMach);
  std::vector<const char*> MustPreserveList;
  SmallPtrSet<GlobalValue*, 8> AsmUsed;
  std::vector<StringRef> Libcalls;
  TargetLibraryInfo TLI(Triple(TargetMach->getTargetTriple()));
  accumulateAndSortLibcalls(Libcalls, TLI, TargetMach->getTargetLowering());

  for (Module::iterator f = mergedModule->begin(),
         e = mergedModule->end(); f != e; ++f)
    applyRestriction(*f, Libcalls, MustPreserveList, AsmUsed, Mangler);
  for (Module::global_iterator v = mergedModule->global_begin(),
         e = mergedModule->global_end(); v !=  e; ++v)
    applyRestriction(*v, Libcalls, MustPreserveList, AsmUsed, Mangler);
  for (Module::alias_iterator a = mergedModule->alias_begin(),
         e = mergedModule->alias_end(); a != e; ++a)
    applyRestriction(*a, Libcalls, MustPreserveList, AsmUsed, Mangler);

  GlobalVariable *LLVMCompilerUsed =
    mergedModule->getGlobalVariable("llvm.compiler.used");
  findUsedValues(LLVMCompilerUsed, AsmUsed);
  if (LLVMCompilerUsed)
    LLVMCompilerUsed->eraseFromParent();

  if (!AsmUsed.empty()) {
    llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(Context);
    std::vector<Constant*> asmUsed2;
    for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = AsmUsed.begin(),
           e = AsmUsed.end(); i !=e; ++i) {
      GlobalValue *GV = *i;
      Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
      asmUsed2.push_back(c);
    }

    llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
    LLVMCompilerUsed =
      new llvm::GlobalVariable(*mergedModule, ATy, false,
                               llvm::GlobalValue::AppendingLinkage,
                               llvm::ConstantArray::get(ATy, asmUsed2),
                               "llvm.compiler.used");

    LLVMCompilerUsed->setSection("llvm.metadata");
  }

  passes.add(createInternalizePass(MustPreserveList));

  // apply scope restrictions
  passes.run(*mergedModule);

  ScopeRestrictionsDone = true;
}
示例#15
0
void LTOCodeGenerator::applyScopeRestrictions() {
  if (_scopeRestrictionsDone) return;
  Module *mergedModule = _linker.getModule();

  // Start off with a verification pass.
  PassManager passes;
  passes.add(createVerifierPass());

  // mark which symbols can not be internalized 
  if (!_mustPreserveSymbols.empty()) {
    MCContext Context(*_target->getMCAsmInfo(), NULL);
    Mangler mangler(Context, *_target->getTargetData());
    std::vector<const char*> mustPreserveList;
    for (Module::iterator f = mergedModule->begin(),
         e = mergedModule->end(); f != e; ++f) {
      if (!f->isDeclaration() &&
          _mustPreserveSymbols.count(mangler.getNameWithPrefix(f)))
        mustPreserveList.push_back(::strdup(f->getNameStr().c_str()));
    }
    for (Module::global_iterator v = mergedModule->global_begin(), 
         e = mergedModule->global_end(); v !=  e; ++v) {
      if (!v->isDeclaration() &&
          _mustPreserveSymbols.count(mangler.getNameWithPrefix(v)))
        mustPreserveList.push_back(::strdup(v->getNameStr().c_str()));
    }
    passes.add(createInternalizePass(mustPreserveList));
  }
  
  // apply scope restrictions
  passes.run(*mergedModule);
  
  _scopeRestrictionsDone = true;
}
示例#16
0
void CodeGenContext::generateCode(NBlock& root)
{
	std::cout << "Generating code...\n";

	vector<Type*> argTypes;
	FunctionType* ftype = FunctionType::get(Type::getVoidTy(getGlobalContext()), makeArrayRef(argTypes), false);
	mainFunction = Function::Create(ftype, GlobalValue::InternalLinkage, "main", module);
	BasicBlock* bblock = BasicBlock::Create(getGlobalContext(), "entry", mainFunction, 0);

	pushBlock(bblock);
	root.codeGen(*this);
	ReturnInst::Create(getGlobalContext(), bblock);
	popBlock();

	std::cout << "Code generation complete.\n";

	PassManager pm;
	pm.add(createPrintModulePass(outs()));
	pm.run(*module);

	//Pass* printer = createPrintModulePass(outs());
	//ModulePassManager pm;
	//pm.addPass(printer);
	//pm.run(module);
}
示例#17
0
int
main (int argc, char **argv, const char **env) {
  // This boilerplate provides convenient stack traces and clean LLVM exit
  // handling. It also initializes the built in support for convenient
  // command line option handling.
  sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram X{argc, argv};
  llvm_shutdown_obj shutdown;
  cl::ParseCommandLineOptions(argc, argv);

  // Construct an IR file from the filename passed on the command line.
  LLVMContext &context = getGlobalContext();
  SMDiagnostic err;
  unique_ptr<Module> module = parseIRFile(inPath.getValue(), err, context);

  if (!module.get()) {
    errs() << "Error reading bitcode file.\n";
    err.print(argv[0], errs());
    return -1;
  }

  // Build up all of the passes that we want to run on the module.
  PassManager pm;
  pm.add(new callgraphs::CallGraphPass);
  pm.add(new callgraphs::WeightedCallGraphPass);
  pm.add(new CallGraphPrinter<callgraphs::WeightedCallGraphPass>(outs()));
  pm.run(*module);

  return 0;
}
示例#18
0
extern "C" void
LLVMRustRunRestrictionPass(LLVMModuleRef M, char **symbols, size_t len) {
    PassManager passes;
    ArrayRef<const char*> ref(symbols, len);
    passes.add(llvm::createInternalizePass(ref));
    passes.run(*unwrap(M));
}
bool LTOCodeGenerator::writeMergedModules(const char *path,
                                          std::string &errMsg) {
  if (!determineTarget(errMsg))
    return false;

  // Run the verifier on the merged modules.
  PassManager passes;
  passes.add(createVerifierPass());
  passes.run(*_linker.getModule());

  // create output file
  std::string ErrInfo;
  tool_output_file Out(path, ErrInfo, sys::fs::F_Binary);
  if (!ErrInfo.empty()) {
    errMsg = "could not open bitcode file for writing: ";
    errMsg += path;
    return false;
  }

  // write bitcode to it
  WriteBitcodeToFile(_linker.getModule(), Out.os());
  Out.os().close();

  if (Out.os().has_error()) {
    errMsg = "could not write bitcode file: ";
    errMsg += path;
    Out.os().clear_error();
    return false;
  }

  Out.keep();
  return true;
}
示例#20
0
extern "C" void LLVMRustWriteOutputFile(LLVMPassManagerRef PMR,
                                        LLVMModuleRef M,
                                        const char *triple,
                                        const char *path,
                                        LLVMCodeGenFileType FileType) {

  // Set compilation options.
  llvm::UnwindTablesMandatory = true;
  llvm::NoFramePointerElim = true;

  InitializeAllTargets();
  InitializeAllAsmPrinters();
  InitializeAllAsmParsers();
  TargetMachine::setRelocationModel(Reloc::PIC_);
  std::string Err;
  const Target *TheTarget = TargetRegistry::lookupTarget(triple, Err);
  std::string FeaturesStr;
  TargetMachine *Target = TheTarget->createTargetMachine(triple, FeaturesStr);
  bool NoVerify = false;
  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  PassManager *PM = unwrap<PassManager>(PMR);
  std::string ErrorInfo;
  raw_fd_ostream OS(path, ErrorInfo,
                    raw_fd_ostream::F_Binary);
  formatted_raw_ostream FOS(OS);
  TargetMachine::CodeGenFileType FileType2 =
    static_cast<TargetMachine::CodeGenFileType>(FileType);

  bool foo = Target->addPassesToEmitFile(*PM, FOS, FileType2, OLvl, NoVerify);
  assert(!foo);
  (void)foo;
  PM->run(*unwrap(M));
  delete Target;
}
示例#21
0
void outputLLVM(llvm::Module &module, raw_pwrite_stream &os) {
	PassManager pm;
	addOptPasses(pm);
	pm.add(createPrintModulePass(os));
	pm.run(module);
	os.flush();
}
示例#22
0
void LTOCodeGenerator::applyScopeRestrictions() {
  if (_scopeRestrictionsDone) return;
  Module *mergedModule = _linker.getModule();

  // Start off with a verification pass.
  PassManager passes;
  passes.add(createVerifierPass());

  // mark which symbols can not be internalized
  MCContext Context(*_target->getMCAsmInfo(), *_target->getRegisterInfo(),NULL);
  Mangler mangler(Context, *_target->getTargetData());
  std::vector<const char*> mustPreserveList;
  SmallPtrSet<GlobalValue*, 8> asmUsed;

  for (Module::iterator f = mergedModule->begin(),
         e = mergedModule->end(); f != e; ++f)
    applyRestriction(*f, mustPreserveList, asmUsed, mangler);
  for (Module::global_iterator v = mergedModule->global_begin(),
         e = mergedModule->global_end(); v !=  e; ++v)
    applyRestriction(*v, mustPreserveList, asmUsed, mangler);
  for (Module::alias_iterator a = mergedModule->alias_begin(),
         e = mergedModule->alias_end(); a != e; ++a)
    applyRestriction(*a, mustPreserveList, asmUsed, mangler);

  GlobalVariable *LLVMCompilerUsed =
    mergedModule->getGlobalVariable("llvm.compiler.used");
  findUsedValues(LLVMCompilerUsed, asmUsed);
  if (LLVMCompilerUsed)
    LLVMCompilerUsed->eraseFromParent();

  llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(_context);
  std::vector<Constant*> asmUsed2;
  for (SmallPtrSet<GlobalValue*, 16>::const_iterator i = asmUsed.begin(),
         e = asmUsed.end(); i !=e; ++i) {
    GlobalValue *GV = *i;
    Constant *c = ConstantExpr::getBitCast(GV, i8PTy);
    asmUsed2.push_back(c);
  }

  llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, asmUsed2.size());
  LLVMCompilerUsed =
    new llvm::GlobalVariable(*mergedModule, ATy, false,
                             llvm::GlobalValue::AppendingLinkage,
                             llvm::ConstantArray::get(ATy, asmUsed2),
                             "llvm.compiler.used");

  LLVMCompilerUsed->setSection("llvm.metadata");

  // Add prerequisite passes needed by SAFECode
  PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/ false,
                                              !DisableInline);

  passes.add(createInternalizePass(mustPreserveList));

  // apply scope restrictions
  passes.run(*mergedModule);

  _scopeRestrictionsDone = true;
}
示例#23
0
/// Optimize merged modules using various IPO passes
bool LTOCodeGenerator::generateAssemblyCode(raw_ostream& out,
                                            std::string& errMsg)
{
    if ( this->determineTarget(errMsg) ) 
        return true;

    // mark which symbols can not be internalized 
    this->applyScopeRestrictions();

    Module* mergedModule = _linker.getModule();

    // if options were requested, set them
    if ( !_codegenOptions.empty() )
        cl::ParseCommandLineOptions(_codegenOptions.size(), 
                                    const_cast<char **>(&_codegenOptions[0]));

    // Instantiate the pass manager to organize the passes.
    PassManager passes;

    // Start off with a verification pass.
    passes.add(createVerifierPass());

    // Add an appropriate TargetData instance for this module...
    passes.add(new TargetData(*_target->getTargetData()));
    
    createStandardLTOPasses(&passes, /*Internalize=*/ false, !DisableInline,
                            /*VerifyEach=*/ false);

    // Make sure everything is still good.
    passes.add(createVerifierPass());

    FunctionPassManager* codeGenPasses = new FunctionPassManager(mergedModule);

    codeGenPasses->add(new TargetData(*_target->getTargetData()));

    formatted_raw_ostream Out(out);

    if (_target->addPassesToEmitFile(*codeGenPasses, Out,
                                     TargetMachine::CGFT_AssemblyFile,
                                     CodeGenOpt::Aggressive)) {
      errMsg = "target file type not supported";
      return true;
    }

    // Run our queue of passes all at once now, efficiently.
    passes.run(*mergedModule);

    // Run the code generator, and write assembly file
    codeGenPasses->doInitialization();

    for (Module::iterator
           it = mergedModule->begin(), e = mergedModule->end(); it != e; ++it)
      if (!it->isDeclaration())
        codeGenPasses->run(*it);

    codeGenPasses->doFinalization();

    return false; // success
}
示例#24
0
void PECOFFLinkingContext::addPasses(PassManager &pm) {
  pm.add(llvm::make_unique<pecoff::PDBPass>(*this));
  pm.add(llvm::make_unique<pecoff::EdataPass>(*this));
  pm.add(llvm::make_unique<pecoff::IdataPass>(*this));
  pm.add(llvm::make_unique<pecoff::OrderPass>());
  pm.add(llvm::make_unique<pecoff::LoadConfigPass>(*this));
  pm.add(llvm::make_unique<pecoff::InferSubsystemPass>(*this));
}
示例#25
0
int main(int argc, char**argv) {
    Module* Mod = makeLLVMModule();
    verifyModule(*Mod, PrintMessageAction);
    PassManager PM;
    PM.add(createPrintModulePass(&outs()));
    PM.run(*Mod);
    return 0;
}
示例#26
0
文件: main.cpp 项目: pb2bee/llvm-demo
static void
countStaticCalls(Module &m) {
  // Build up all of the passes that we want to run on the module.
  PassManager pm;
  pm.add(new callcounter::StaticCallCounter());
  pm.add(new StaticCountPrinter(outs()));
  pm.run(m);
}
示例#27
0
// A utility function that adds a pass to the pass manager but will also add
// a verifier pass after if we're supposed to verify.
static inline void addPass(PassManager &PM, Pass *P) {
  // Add the pass to the pass manager...
  PM.add(P);

  // If we are verifying all of the intermediate steps, add the verifier...
  if (VerifyEach)
    PM.add(createVerifierPass());
}
示例#28
0
extern "C" bool
LLVMRustWriteOutputFile(LLVMPassManagerRef PMR,
                        LLVMModuleRef M,
                        const char *triple,
                        const char *feature,
                        const char *path,
                        TargetMachine::CodeGenFileType FileType,
                        CodeGenOpt::Level OptLevel,
      bool EnableSegmentedStacks) {

  LLVMRustInitializeTargets();

  // Initializing the command-line options more than once is not
  // allowed. So, check if they've already been initialized.
  // (This could happen if we're being called from rustpkg, for
  // example.)
  if (!EnableARMEHABI) {
    int argc = 3;
    const char* argv[] = {"rustc", "-arm-enable-ehabi",
        "-arm-enable-ehabi-descriptors"};
    cl::ParseCommandLineOptions(argc, argv);
  }

  TargetOptions Options;
  Options.NoFramePointerElim = true;
  Options.EnableSegmentedStacks = EnableSegmentedStacks;
  Options.FixedStackSegmentSize = 2 * 1024 * 1024;  // XXX: This is too big.

  PassManager *PM = unwrap<PassManager>(PMR);

  std::string Err;
  std::string Trip(Triple::normalize(triple));
  std::string FeaturesStr(feature);
  std::string CPUStr("generic");
  const Target *TheTarget = TargetRegistry::lookupTarget(Trip, Err);
  TargetMachine *Target =
    TheTarget->createTargetMachine(Trip, CPUStr, FeaturesStr,
           Options, Reloc::PIC_,
           CodeModel::Default, OptLevel);
  Target->addAnalysisPasses(*PM);

  bool NoVerify = false;
  std::string ErrorInfo;
  raw_fd_ostream OS(path, ErrorInfo,
                    raw_fd_ostream::F_Binary);
  if (ErrorInfo != "") {
    LLVMRustError = ErrorInfo.c_str();
    return false;
  }
  formatted_raw_ostream FOS(OS);

  bool foo = Target->addPassesToEmitFile(*PM, FOS, FileType, NoVerify);
  assert(!foo);
  (void)foo;
  PM->run(*unwrap(M));
  delete Target;
  return true;
}
示例#29
0
文件: Lint.cpp 项目: jhoush/dist-llvm
/// lintModule - Check a module for errors, printing messages on stderr.
/// Return true if the module is corrupt.
///
void llvm::lintModule(const Module &M, std::string *ErrorInfo) {
  PassManager PM;
  Lint *V = new Lint();
  PM.add(V);
  PM.run(const_cast<Module&>(M));

  if (ErrorInfo)
    *ErrorInfo = V->MessagesStr.str();
}
示例#30
0
文件: toobj.cpp 项目: GameFusion/ldc
// based on llc code, University of Illinois Open Source License
static void codegenModule(llvm::TargetMachine &Target, llvm::Module& m,
    llvm::raw_fd_ostream& out, llvm::TargetMachine::CodeGenFileType fileType)
{
    using namespace llvm;

    // Create a PassManager to hold and optimize the collection of passes we are
    // about to build.
#if LDC_LLVM_VER >= 307
    legacy::
#endif
    PassManager Passes;

#if LDC_LLVM_VER >= 307
    // The DataLayout is already set at the module (in module.cpp,
    // method Module::genLLVMModule())
    // FIXME: Introduce new command line switch default-data-layout to
    // override the module data layout
#elif LDC_LLVM_VER == 306
    Passes.add(new DataLayoutPass());
#elif LDC_LLVM_VER == 305
    if (const DataLayout *DL = Target.getDataLayout())
        Passes.add(new DataLayoutPass(*DL));
    else
        Passes.add(new DataLayoutPass(&m));
#elif LDC_LLVM_VER >= 302
    if (const DataLayout *DL = Target.getDataLayout())
        Passes.add(new DataLayout(*DL));
    else
        Passes.add(new DataLayout(&m));
#else
    if (const TargetData *TD = Target.getTargetData())
        Passes.add(new TargetData(*TD));
    else
        Passes.add(new TargetData(&m));
#endif

#if LDC_LLVM_VER >= 307
    // Add internal analysis passes from the target machine.
    Passes.add(createTargetTransformInfoWrapperPass(Target.getTargetIRAnalysis()));
#elif LDC_LLVM_VER >= 303
    Target.addAnalysisPasses(Passes);
#endif

#if LDC_LLVM_VER < 307
    llvm::formatted_raw_ostream fout(out);
#endif
    if (Target.addPassesToEmitFile(Passes,
#if LDC_LLVM_VER >= 307
            out,
#else
            fout,
#endif
            fileType, codeGenOptLevel()))
        llvm_unreachable("no support for asm output");

    Passes.run(m);
}