当前位置: 首页>>代码示例>>C++>>正文


C++ PassManager::run方法代码示例

本文整理汇总了C++中PassManager::run方法的典型用法代码示例。如果您正苦于以下问题:C++ PassManager::run方法的具体用法?C++ PassManager::run怎么用?C++ PassManager::run使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在PassManager的用法示例。


在下文中一共展示了PassManager::run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: generateObjectFile

/// Optimize merged modules using various IPO passes
bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
                                          std::string &errMsg) {

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

  if (this->determineTarget(errMsg))
    return true;

  Module* mergedModule = _linker.getModule();

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

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

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

  // Add an appropriate DataLayout instance for this module...
  passes.add(new DataLayout(*_target->getDataLayout()));
  passes.add(new TargetTransformInfo(_target->getScalarTargetTransformInfo(),
                                     _target->getVectorTargetTransformInfo()));

  // Enabling internalize here would use its AllButMain variant. It
  // keeps only main if it exists and does nothing for libraries. Instead
  // we create the pass ourselves with the symbol list provided by the linker.
  PassManagerBuilder().populateLTOPassManager(passes, /*Internalize=*/false,
                                              !DisableInline,
                                              DisableGVNLoadPRE);

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

  FunctionPassManager *codeGenPasses = new FunctionPassManager(mergedModule);

  codeGenPasses->add(new DataLayout(*_target->getDataLayout()));

  formatted_raw_ostream Out(out);

  if (_target->addPassesToEmitFile(*codeGenPasses, Out,
                                   TargetMachine::CGFT_ObjectFile)) {
    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();
  delete codeGenPasses;

  return false; // success
}
开发者ID:smowton,项目名称:llpe,代码行数:66,代码来源:LTOCodeGenerator.cpp

示例2: compileModule


//.........这里部分代码省略.........
  Options.UseInitArray = UseInitArray;

  OwningPtr<TargetMachine>
    target(TheTarget->createTargetMachine(TheTriple.getTriple(),
                                          MCPU, FeaturesStr, Options,
                                          RelocModel, CMModel, OLvl));
  assert(target.get() && "Could not allocate target machine!");
  assert(mod && "Should have exited after outputting help!");
  TargetMachine &Target = *target.get();

  if (DisableDotLoc)
    Target.setMCUseLoc(false);

  if (DisableCFI)
    Target.setMCUseCFI(false);

  if (EnableDwarfDirectory)
    Target.setMCUseDwarfDirectory(true);

  if (GenerateSoftFloatCalls)
    FloatABIForCalls = FloatABI::Soft;

  // Disable .loc support for older OS X versions.
  if (TheTriple.isMacOSX() &&
      TheTriple.isMacOSXVersionLT(10, 6))
    Target.setMCUseLoc(false);

  // Figure out where we are going to send the output.
  OwningPtr<tool_output_file> Out
    (GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]));
  if (!Out) return 1;

  // Build up all of the passes that we want to do to the module.
  PassManager PM;

  // Add an appropriate TargetLibraryInfo pass for the module's triple.
  TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
  if (DisableSimplifyLibCalls)
    TLI->disableAllFunctions();
  PM.add(TLI);

  // Add the target data from the target machine, if it exists, or the module.
  if (const DataLayout *TD = Target.getDataLayout())
    PM.add(new DataLayout(*TD));
  else
    PM.add(new DataLayout(mod));

  // Override default to generate verbose assembly.
  Target.setAsmVerbosityDefault(true);

  if (RelaxAll) {
    if (FileType != TargetMachine::CGFT_ObjectFile)
      errs() << argv[0]
             << ": warning: ignoring -mc-relax-all because filetype != obj";
    else
      Target.setMCRelaxAll(true);
  }

  {
    formatted_raw_ostream FOS(Out->os());

    AnalysisID StartAfterID = 0;
    AnalysisID StopAfterID = 0;
    const PassRegistry *PR = PassRegistry::getPassRegistry();
    if (!StartAfter.empty()) {
      const PassInfo *PI = PR->getPassInfo(StartAfter);
      if (!PI) {
        errs() << argv[0] << ": start-after pass is not registered.\n";
        return 1;
      }
      StartAfterID = PI->getTypeInfo();
    }
    if (!StopAfter.empty()) {
      const PassInfo *PI = PR->getPassInfo(StopAfter);
      if (!PI) {
        errs() << argv[0] << ": stop-after pass is not registered.\n";
        return 1;
      }
      StopAfterID = PI->getTypeInfo();
    }

    // Ask the target to add backend passes as necessary.
    if (Target.addPassesToEmitFile(PM, FOS, FileType, NoVerify,
                                   StartAfterID, StopAfterID)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      return 1;
    }

    // Before executing passes, print the final values of the LLVM options.
    cl::PrintOptionValues();

    PM.run(*mod);
  }

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

  return 0;
}
开发者ID:bholt,项目名称:llvm,代码行数:101,代码来源:llc.cpp

示例3: main


//.........这里部分代码省略.........
    if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
      AddOptimizationPasses(Passes, *FPasses, 2);
      OptLevelO2 = false;
    }

    if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
      AddOptimizationPasses(Passes, *FPasses, 3);
      OptLevelO3 = false;
    }

    const PassInfo *PassInf = PassList[i];
    Pass *P = 0;
    if (PassInf->getNormalCtor())
      P = PassInf->getNormalCtor()();
    else
      errs() << argv[0] << ": cannot create pass: "
             << PassInf->getPassName() << "\n";
    if (P) {
      PassKind Kind = P->getPassKind();
      addPass(Passes, P);

      if (AnalyzeOnly) {
        switch (Kind) {
        case PT_BasicBlock:
          Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
          break;
        case PT_Region:
          Passes.add(new RegionPassPrinter(PassInf, Out->os()));
          break;
        case PT_Loop:
          Passes.add(new LoopPassPrinter(PassInf, Out->os()));
          break;
        case PT_Function:
          Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
          break;
        case PT_CallGraphSCC:
          Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
          break;
        default:
          Passes.add(new ModulePassPrinter(PassInf, Out->os()));
          break;
        }
      }
    }

    if (PrintEachXForm)
      Passes.add(createPrintModulePass(&errs()));
  }

  // If -std-compile-opts was specified at the end of the pass list, add them.
  if (StandardCompileOpts) {
    AddStandardCompilePasses(Passes);
    StandardCompileOpts = false;
  }

  if (StandardLinkOpts) {
    AddStandardLinkPasses(Passes);
    StandardLinkOpts = false;
  }

  if (OptLevelO1)
    AddOptimizationPasses(Passes, *FPasses, 1);

  if (OptLevelO2)
    AddOptimizationPasses(Passes, *FPasses, 2);

  if (OptLevelO3)
    AddOptimizationPasses(Passes, *FPasses, 3);

  if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
    FPasses->doInitialization();
    for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
      FPasses->run(*F);
    FPasses->doFinalization();
  }

  // Check that the module is well formed on completion of optimization
  if (!NoVerify && !VerifyEach)
    Passes.add(createVerifierPass());

  // Write bitcode or assembly to the output as the last step...
  if (!NoOutput && !AnalyzeOnly) {
    if (OutputAssembly)
      Passes.add(createPrintModulePass(&Out->os()));
    else
      Passes.add(createBitcodeWriterPass(Out->os()));
  }

  // Before executing passes, print the final values of the LLVM options.
  cl::PrintOptionValues();

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

  // Declare success.
  if (!NoOutput || PrintBreakpoints)
    Out->keep();

  return 0;
}
开发者ID:CartBlanche,项目名称:llvm,代码行数:101,代码来源:opt.cpp

示例4: main

int main(int argc, char **argv) {
  // Print a stack trace if we signal out.
  sys::PrintStackTraceOnErrorSignal();
  PrettyStackTraceProgram X(argc, argv);

  LLVMContext &Context = getGlobalContext();
  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
  
  cl::ParseCommandLineOptions(argc, argv, "llvm profile dump decoder\n");

  // Read in the bitcode file...
  std::string ErrorMessage;
  error_code ec;
  Module *M = 0;
  if(DiffMode) {
     ProfileInfoLoader PIL1(argv[0], BitcodeFile);
     ProfileInfoLoader PIL2(argv[0], ProfileDataFile);
     
     ProfileInfoCompare Compare(PIL1,PIL2);
     Compare.run();
     return 0;
  }
  if(Merge != MERGE_NONE) {
     /** argument alignment: 
      *  BitcodeFile ProfileDataFile MergeFile 
      *  output.out  input1.out      other-input.out 
      **/

     // Add the ProfileDataFile arg to MergeFile, it blongs to the MergeFile
     MergeFile.push_back(std::string(ProfileDataFile.getValue()));
     if(MergeFile.size()==0){
        errs()<<"No merge file!";
        return 0;
     }

     //Initialize the ProfileInfoMerge class using one of merge files
     ProfileInfoLoader AHS(argv[0], MergeFile.back());
     ProfileInfoMerge MergeClass(std::string(argv[0]), BitcodeFile, AHS);

     for (std::vector<std::string>::iterator merIt = MergeFile.begin(),
                                             END = MergeFile.end() - 1;
          merIt != END; ++merIt) {
        //errs()<<*merIt<<"\n";
       ProfileInfoLoader THS(argv[0], *merIt);
       MergeClass.addProfileInfo(THS);
     }
     if (Merge == MERGE_SUM) {
       MergeClass.writeTotalFile();
     } else if (Merge == MERGE_AVG) {
       /** avg = sum/N **/
       MergeClass.writeTotalFile(
           std::bind2nd(std::divides<unsigned>(), MergeFile.size()));
     }
     return 0;
  }
#if LLVM_VERSION_MAJOR==3 && LLVM_VERSION_MINOR==4
  OwningPtr<MemoryBuffer> Buffer;
  if (!(ec = MemoryBuffer::getFileOrSTDIN(BitcodeFile, Buffer.get()))) {
     M = ParseBitcodeFile(Buffer.get(), Context, &ErrorMessage);
  } else
     ErrorMessage = ec.message();

#else

  auto Buffer = MemoryBuffer::getFileOrSTDIN(BitcodeFile);
  if (!(ec = Buffer.getError())){
     auto R = parseBitcodeFile(&**Buffer, Context);
     if(R.getError()){
        M = NULL;
        ErrorMessage = R.getError().message();
     }else
        M = R.get();
  } else
     ErrorMessage = ec.message();
#endif
  if (M == 0) {
     errs() << argv[0] << ": " << BitcodeFile << ": "
        << ErrorMessage << "\n";
     return 1;
  }

  // Run the printer pass.
  PassManager PassMgr;
  PassMgr.add(createProfileLoaderPass(ProfileDataFile));

  if(CommMode) {
     PassMgr.add(new ProfileInfoComm());
     PassMgr.run(*M);
     return 0;
  }
  if(Convert){
     Require3rdArg("no output file");
     ProfileInfoWriter PIW(argv[0], MergeFile.front());
     PassMgr.add(new ProfileInfoConverter(PIW));
  }else if(Timing.size() != 0){
     Require3rdArg("no timing source file");
     PassMgr.add(new ProfileTimingPrint(std::move(Timing.getValue()), MergeFile));
  }else{
     // Read the profiling information. This is redundant since we load it again
     // using the standard profile info provider pass, but for now this gives us
//.........这里部分代码省略.........
开发者ID:HaoMengHIT,项目名称:llvm-prof,代码行数:101,代码来源:llvm-prof.cpp

示例5: applyScopeRestrictions

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->getDataLayout());
  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();

  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");
  }

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

  passes.add(createInternalizePass(mustPreserveList));

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

  _scopeRestrictionsDone = true;
}
开发者ID:jcranmer,项目名称:safecode,代码行数:61,代码来源:LTOCodeGenerator.cpp

示例6: generateObjectFile

/// Optimize merged modules using various IPO passes
bool LTOCodeGenerator::generateObjectFile(raw_ostream &out,
        bool DisableOpt,
        bool DisableInline,
        bool DisableGVNLoadPRE,
        std::string &errMsg) {
    if (!this->determineTarget(errMsg))
        return false;

    Module *mergedModule = IRLinker.getModule();

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

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

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

    // Add an appropriate DataLayout instance for this module...
    mergedModule->setDataLayout(TargetMach->getDataLayout());
    passes.add(new DataLayoutPass(mergedModule));

    // Add appropriate TargetLibraryInfo for this module.
    passes.add(new TargetLibraryInfo(Triple(TargetMach->getTargetTriple())));

    TargetMach->addAnalysisPasses(passes);

    // Enabling internalize here would use its AllButMain variant. It
    // keeps only main if it exists and does nothing for libraries. Instead
    // we create the pass ourselves with the symbol list provided by the linker.
    if (!DisableOpt)
        PassManagerBuilder().populateLTOPassManager(passes,
                /*Internalize=*/false,
                !DisableInline,
                DisableGVNLoadPRE);

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

    PassManager codeGenPasses;

    codeGenPasses.add(new DataLayoutPass(mergedModule));

    formatted_raw_ostream Out(out);

    // If the bitcode files contain ARC code and were compiled with optimization,
    // the ObjCARCContractPass must be run, so do it unconditionally here.
    codeGenPasses.add(createObjCARCContractPass());

    if (TargetMach->addPassesToEmitFile(codeGenPasses, Out,
                                        TargetMachine::CGFT_ObjectFile)) {
        errMsg = "target file type not supported";
        return false;
    }

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

    // Run the code generator, and write assembly file
    codeGenPasses.run(*mergedModule);

    return true;
}
开发者ID:KurSh,项目名称:llvm,代码行数:67,代码来源:LTOCodeGenerator.cpp

示例7: compileModule


//.........这里部分代码省略.........
  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (OptLevel) {
  default:
    errs() << argv[0] << ": invalid optimization level.\n";
    return 1;
  case ' ': break;
  case '0': OLvl = CodeGenOpt::None; break;
  case '1': OLvl = CodeGenOpt::Less; break;
  case '2': OLvl = CodeGenOpt::Default; break;
  case '3': OLvl = CodeGenOpt::Aggressive; break;
  }

  TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
  Options.DisableIntegratedAS = NoIntegratedAssembler;
  Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
  Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
  Options.MCOptions.AsmVerbose = AsmVerbose;

  std::unique_ptr<TargetMachine> Target(
      TheTarget->createTargetMachine(TheTriple.getTriple(), MCPU, FeaturesStr,
                                     Options, RelocModel, CMModel, OLvl));
  assert(Target && "Could not allocate target machine!");

  // If we don't have a module then just exit now. We do this down
  // here since the CPU/Feature help is underneath the target machine
  // creation.
  if (SkipModule)
    return 0;

  assert(M && "Should have exited if we didn't have a module!");

  if (GenerateSoftFloatCalls)
    FloatABIForCalls = FloatABI::Soft;

  // Figure out where we are going to send the output.
  std::unique_ptr<tool_output_file> Out =
      GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
  if (!Out) return 1;

  // Build up all of the passes that we want to do to the module.
  PassManager PM;

  // Add an appropriate TargetLibraryInfo pass for the module's triple.
  TargetLibraryInfo *TLI = new TargetLibraryInfo(TheTriple);
  if (DisableSimplifyLibCalls)
    TLI->disableAllFunctions();
  PM.add(TLI);

  // Add the target data from the target machine, if it exists, or the module.
  if (const DataLayout *DL = Target->getSubtargetImpl()->getDataLayout())
    M->setDataLayout(DL);
  PM.add(new DataLayoutPass());

  if (RelaxAll.getNumOccurrences() > 0 &&
      FileType != TargetMachine::CGFT_ObjectFile)
    errs() << argv[0]
             << ": warning: ignoring -mc-relax-all because filetype != obj";

  {
    formatted_raw_ostream FOS(Out->os());

    AnalysisID StartAfterID = nullptr;
    AnalysisID StopAfterID = nullptr;
    const PassRegistry *PR = PassRegistry::getPassRegistry();
    if (!StartAfter.empty()) {
      const PassInfo *PI = PR->getPassInfo(StartAfter);
      if (!PI) {
        errs() << argv[0] << ": start-after pass is not registered.\n";
        return 1;
      }
      StartAfterID = PI->getTypeInfo();
    }
    if (!StopAfter.empty()) {
      const PassInfo *PI = PR->getPassInfo(StopAfter);
      if (!PI) {
        errs() << argv[0] << ": stop-after pass is not registered.\n";
        return 1;
      }
      StopAfterID = PI->getTypeInfo();
    }

    // Ask the target to add backend passes as necessary.
    if (Target->addPassesToEmitFile(PM, FOS, FileType, NoVerify,
                                    StartAfterID, StopAfterID)) {
      errs() << argv[0] << ": target does not support generation of this"
             << " file type!\n";
      return 1;
    }

    // Before executing passes, print the final values of the LLVM options.
    cl::PrintOptionValues();

    PM.run(*M);
  }

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

  return 0;
}
开发者ID:IamSpid3r,项目名称:cheerp-llvm,代码行数:101,代码来源:llc.cpp

示例8: compileInternal

static int compileInternal(const char *input, int optimize, int optsize,
                           const char *argv0,
                           raw_fd_ostream *fd, CompilerInstance &Clang)
{
  std::string ErrMsg;
  LLVMContext &Context = getGlobalContext();
  std::auto_ptr<Module> M;

  MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(input, &ErrMsg);
  if (!Buffer) {
    errs() << "Could not open temp input file '" << input << "'\n";
    return 2;
  }
  M.reset(ParseBitcodeFile(Buffer, Context, &ErrMsg));
  delete Buffer;
  if (M.get() == 0) {
    errs() << "Cannot parse temp input file '" << input << "'" << ErrMsg << "\n";
    return 2;
  }

  // FIXME: Remove TargetData!
  //XXX  M->setTargetTriple("");
  //XXX  M->setDataLayout("");

  // TODO: let clang handle these
  PassManager Passes;
  FunctionPassManager *FPasses = NULL;
  if (optimize) {
    FPasses = new FunctionPassManager(M.get());
//    FPasses->add(new TargetData(M.get()));//XXX
    createStandardFunctionPasses(FPasses, optimize);
  }
//  Passes.add(new TargetData(M.get()));//XXX
  unsigned threshold = optsize ? 75 : optimize > 2 ? 275 : 225;
  createStandardModulePasses(&Passes, optimize,
                             optsize,
                             true,
                             optimize > 1 && !optsize,
                             false,
                             false,
                             optimize > 1 ?
                             createFunctionInliningPass(threshold) :
                             createAlwaysInlinerPass());
  if (optimize) {
    FPasses->doInitialization();
    for (Module::iterator I = M.get()->begin(), E = M.get()->end();
         I != E; ++I)
      FPasses->run(*I);
    Passes.add(createVerifierPass());
    Passes.run(*M.get());
  }

  std::string Err2;
  //TODO: directly construct our target
  const Target *TheTarget =
    TargetRegistry::lookupTarget("clambc-generic-generic", Err2);
  if (TheTarget == 0) {
    errs() << argv0 << ": error auto-selecting target for module '"
      << Err2 << "'.  Please use the -march option to explicitly "
      << "pick a target.\n";
    return 1;
  }
  std::auto_ptr<TargetMachine> 
    Target(TheTarget->createTargetMachine("clambc-generic-generic", ""));
  //TODO: send it to the -o specified on cmdline
  // Figure out where we are going to send the output...
  formatted_raw_ostream *Out2 =
    new formatted_raw_ostream(*fd, formatted_raw_ostream::DELETE_STREAM);
  if (Out2 == 0) return 2;

  CodeGenOpt::Level OLvl = CodeGenOpt::Default;
  switch (optimize) {
  case 0: OLvl = CodeGenOpt::None; break;
  case 3: OLvl = CodeGenOpt::Aggressive; break;
  default: break;
  }

  PassManager PM;
  PM.add(new TargetData(M.get()));//XXX
  if (Target->addPassesToEmitWholeFile(PM, *Out2, TargetMachine::CGFT_AssemblyFile, OLvl)) {
      errs() << argv0<< ": target does not support generation of this"
             << " file type!\n";
      if (Out2 != &fouts()) delete Out2;
      // And the Out file is empty and useless, so remove it now.
//      sys::Path(OutputFilename).eraseFromDisk();
      return 2;
  }
  PM.run(*M.get());
  delete Out2;
  return 0;
}
开发者ID:amitamitamitamit,项目名称:clamav-bytecode-compiler,代码行数:91,代码来源:driver.cpp

示例9: dynamicInlinerForOpenOSR

void* MCJITHelper::dynamicInlinerForOpenOSR(Function* F1, Instruction* OSRSrc, void* extra, void* profDataAddr) {
    DynamicInlinerInfo* inlineInfo = (DynamicInlinerInfo*) extra;
    MCJITHelper* TheHelper = inlineInfo->TheHelper;
    bool verbose = TheHelper->verbose;

    assert(OSRSrc->getParent()->getParent() == F1 && "MCJIT messed up the objects");

    if (verbose) {
        std::cerr << "Value for F1 is " << F1 << std::endl;
        std::cerr << "Value for OSRSrc is " << OSRSrc << std::endl;
        std::cerr << "Value for extra is " << extra << std::endl;
        std::cerr << "Value for profDataAddr is " << profDataAddr << std::endl;
    }

    std::pair<Function*, StateMap*> identityPair = StateMap::generateIdentityMapping(F1);

    Function* F2 = identityPair.first;
    StateMap* M = identityPair.second;

    Value* valToInlineInF2 = M->getCorrespondingOneToOneValue(inlineInfo->valToInline);

    Instruction* OSRSrcInF2 = cast<Instruction>(M->getCorrespondingOneToOneValue(OSRSrc));
    assert (OSRSrcInF2 != nullptr && "TODO cannot find corresponding OSRSrc in temporary F2");
    if (OSRLibrary::removeOSRPoint(*OSRSrcInF2) && verbose) {
        std::cerr << "OSR point removed after cloning F1" << std::endl;
    }

    Instruction* LPad = M->getLandingPad(OSRSrc);

    StateMap* M_F2toOSRContFun;
    LivenessAnalysis LA(F1);
    std::vector<Value*>* valuesToPass = OSRLibrary::getLiveValsVecAtInstr(OSRSrc, LA);
    std::string OSRDestFunName = (F2->getName().str()).append("OSRCont");
    Function* OSRContFun = OSRLibrary::genContinuationFunc(TheHelper->Context,
            *F1, *F2, *OSRSrc, *LPad, *valuesToPass, *M, &OSRDestFunName, verbose, &M_F2toOSRContFun);

    Value* valToInline = M_F2toOSRContFun->getCorrespondingOneToOneValue(valToInlineInF2);
    assert (valToInline != nullptr && "broken state map for continuation function");

    delete valuesToPass;
    delete F2;
    delete M;
    delete M_F2toOSRContFun;

    // create a module for generated code
    std::string modForJITName = "OpenOSRDynInline";
    modForJITName.append(OSRDestFunName);
    std::unique_ptr<Module> modForJIT = llvm::make_unique<Module>(modForJITName, TheHelper->Context);
    Module* modForJIT_ptr = modForJIT.get();

    // determine which function is called
    uint64_t calledFun = (uint64_t)profDataAddr;

    std::cerr << "Address of invoked function: " << calledFun << std::endl;
    Function* funToInline = nullptr;
    for (AddrSymPair &pair: TheHelper->CompiledFunAddrTable) {
        if (pair.first == calledFun) {
            std::string &FunName = pair.second;
            funToInline = TheHelper->getFunction(FunName);
            break;
        }
    }

    Function* myFunToInline = nullptr;
    if (funToInline == nullptr) {
        std::cerr << "Sorry, I could not determine which function was called!" << std::endl;
    } else {
        std::cerr << "Function being inlined: " << funToInline->getName().str() << std::endl;
        ValueToValueMapTy VMap;
        myFunToInline = CloneFunction(funToInline, VMap, false, nullptr);
        myFunToInline->addFnAttr(Attribute::AlwaysInline);
        myFunToInline->setLinkage(Function::LinkageTypes::PrivateLinkage);
        modForJIT_ptr->getFunctionList().push_back(myFunToInline);
        OSRLibrary::fixUsesOfFunctionsAndGlobals(funToInline, myFunToInline);
        for (Value::use_iterator UI = valToInline->use_begin(),
                UE = valToInline->use_end(); UI != UE; ) {
            Use &U = *(UI++);
            if (CallInst* CI = dyn_cast<CallInst>(U.getUser())) {
                if (CI->getParent()->getParent() != OSRContFun) continue;
                if (verbose) {
                    raw_os_ostream errStream(std::cerr);
                    std::cerr << "Updating instruction ";
                    CI->print(errStream);
                    std::cerr << std::endl;
                }
                U.set(myFunToInline);
            }
        }
    }

    modForJIT_ptr->getFunctionList().push_back(OSRContFun);
    verifyFunction(*OSRContFun, &outs());

    // remove dead code & inline when possible
    FunctionPassManager FPM(modForJIT_ptr);
    FPM.add(createCFGSimplificationPass());
    FPM.doInitialization();
    FPM.run(*OSRContFun);

    if (funToInline != nullptr) {
//.........这里部分代码省略.........
开发者ID:chubbymaggie,项目名称:tinyvm,代码行数:101,代码来源:MCJITHelper.cpp

示例10: compile_module_to_string

// TODO: factor this into a C++ core function, and a thin OCaml C wrapper
CAMLprim value compile_module_to_string(LLVMModuleRef modref) {
#ifndef __arm__
    Module &mod = *llvm::unwrap(modref);
    LLVMContext &ctx = mod.getContext();
    
    // TODO: streamline this - don't initialize anything but PTX
    LLVMInitializeNVPTXTargetInfo();
    LLVMInitializeNVPTXTarget();
    LLVMInitializeNVPTXTargetMC();
    LLVMInitializeNVPTXAsmPrinter();

    // DISABLED - hooked in here to force PrintBeforeAll option - seems to be the only way?
    /*char* argv[] = { "llc", "-print-before-all" };*/
    /*int argc = sizeof(argv)/sizeof(char*);*/
    /*cl::ParseCommandLineOptions(argc, argv, "Halide PTX internal compiler\n");*/

    // Set up TargetTriple
    mod.setTargetTriple(Triple::normalize("nvptx64--"));
    Triple TheTriple(mod.getTargetTriple());
    
    // Allocate target machine
    const std::string MArch = "nvptx64";
    const std::string MCPU = "sm_20";
    const Target* TheTarget = 0;
    
    std::string errStr;
    TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), errStr);
    assert(TheTarget);

    TargetOptions Options;
    Options.LessPreciseFPMADOption = true;
    Options.PrintMachineCode = false;
    Options.NoFramePointerElim = false;
    Options.NoFramePointerElimNonLeaf = false;
    //Options.NoExcessFPPrecision = false;
    Options.AllowFPOpFusion = FPOpFusion::Fast;
    Options.UnsafeFPMath = true;
    Options.NoInfsFPMath = false;
    Options.NoNaNsFPMath = false;
    Options.HonorSignDependentRoundingFPMathOption = false;
    Options.UseSoftFloat = false;
    /* if (FloatABIForCalls != FloatABI::Default) */
        /* Options.FloatABIType = FloatABIForCalls; */
    Options.NoZerosInBSS = false;
    Options.JITExceptionHandling = false;
    Options.JITEmitDebugInfo = false;
    Options.JITEmitDebugInfoToDisk = false;
    Options.GuaranteedTailCallOpt = false;
    Options.StackAlignmentOverride = 0;
    Options.RealignStack = true;
    // Options.DisableJumpTables = false;
    Options.TrapFuncName = "";
    Options.EnableSegmentedStacks = false;

    CodeGenOpt::Level OLvl = CodeGenOpt::Default;

    const std::string FeaturesStr = "";
    std::auto_ptr<TargetMachine>
        target(TheTarget->createTargetMachine(TheTriple.getTriple(),
                                              MCPU, FeaturesStr, Options,
                                              llvm::Reloc::Default,
                                              llvm::CodeModel::Default,
                                              OLvl));
    assert(target.get() && "Could not allocate target machine!");
    TargetMachine &Target = *target.get();

    // Set up passes
    PassManager PM;
    // Add the target data from the target machine
    PM.add(new TargetData(*Target.getTargetData()));

    // Inlining functions is essential to PTX
    PM.add(createAlwaysInlinerPass());

    // Override default to generate verbose assembly.
    Target.setAsmVerbosityDefault(true);

    // Output string stream
    std::string outstr;
    raw_string_ostream outs(outstr);
    formatted_raw_ostream ostream(outs);

    // Ask the target to add backend passes as necessary.
    bool fail = Target.addPassesToEmitFile(PM, ostream,
                                           TargetMachine::CGFT_AssemblyFile,
                                           true);
    assert(!fail);

    PM.run(mod);

    ostream.flush();
    std::string& out = outs.str();
    return copy_string(out.c_str());
#else
    return caml_copy_string("NOT IMPLEMENTED ON ARM: compile_module_to_string");
#endif //disable on ARM
}
开发者ID:damianfral,项目名称:Halide,代码行数:98,代码来源:cllutil.c

示例11: main

// main - Entry point for the sc compiler.
//
int main(int argc, char **argv) {

  cl::ParseCommandLineOptions(argc, argv, " llvm system compiler\n");
  sys::PrintStackTraceOnErrorSignal();

  // Load the module to be compiled...
  std::auto_ptr<Module> M;
  std::string ErrorMessage;
  if (MemoryBuffer *Buffer
      = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
    M.reset(ParseBitcodeFile(Buffer, getGlobalContext(), &ErrorMessage));
    delete Buffer;
  }

  if (M.get() == 0) {
    std::cerr << argv[0] << ": bytecode didn't read correctly.\n";
    return 1;
  }

  // Build up all of the passes that we want to do to the module...
  PassManager Passes;

  Passes.add(new TargetData(M.get()));

  // Currently deactiviated
  Passes.add(new TypeChecks());
  if(EnableTypeSafetyOpts)
    Passes.add(new TypeChecksOpt());

  // Verify the final result
  Passes.add(createVerifierPass());

  // Figure out where we are going to send the output...
  raw_fd_ostream *Out = 0;
  std::string error;
  if (OutputFilename != "") {
    if (OutputFilename != "-") {
      // Specified an output filename?
      if (!Force && std::ifstream(OutputFilename.c_str())) {
        // If force is not specified, make sure not to overwrite a file!
        std::cerr << argv[0] << ": error opening '" << OutputFilename
          << "': file exists!\n"
          << "Use -f command line argument to force output\n";
        return 1;
      }
      Out = new raw_fd_ostream (OutputFilename.c_str(), error);

      // Make sure that the Out file gets unlinked from the disk if we get a
      // SIGINT
      sys::RemoveFileOnSignal(sys::Path(OutputFilename));
    } else {
      Out = new raw_stdout_ostream();
    }
  } else {
    if (InputFilename == "-") {
      OutputFilename = "-";
      Out = new raw_stdout_ostream();
    } else {
      OutputFilename = GetFileNameRoot(InputFilename);

      OutputFilename += ".abc.bc";
    }

    if (!Force && std::ifstream(OutputFilename.c_str())) {
      // If force is not specified, make sure not to overwrite a file!
      std::cerr << argv[0] << ": error opening '" << OutputFilename
        << "': file exists!\n"
        << "Use -f command line argument to force output\n";
      return 1;
    }

    Out = new raw_fd_ostream(OutputFilename.c_str(), error);
    if (error.length()) {
      std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
      delete Out;
      return 1;
    }

    // Make sure that the Out file gets unlinked from the disk if we get a
    // SIGINT
    sys::RemoveFileOnSignal(sys::Path(OutputFilename));
  }

  // Add the writing of the output file to the list of passes
  Passes.add (createBitcodeWriterPass(*Out));

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

  // Delete the ostream
  delete Out;

  return 0;
}
开发者ID:brills,项目名称:pfpa,代码行数:96,代码来源:tc.cpp

示例12: main

int main(int argc, char* argv[])
{
   if(argc < 2)
   {
      cerr << "Usage: " << argv[0] << " bf_file" << endl;
      return -1;
   }
   ifstream sourceFile(argv[1]);
   string line, source;
   while(getline(sourceFile, line)) source += line;

   // Setup a module and engine for JIT-ing
   std::string error;
   InitializeNativeTarget();

   Module* module = new Module("bfcode", getGlobalContext());

   InitializeNativeTarget();
   LLVMLinkInJIT();
   ExecutionEngine *engine = EngineBuilder(module)
      .setErrorStr(&error)
      .setOptLevel(CodeGenOpt::Aggressive)
      .create();
   if(!engine)
   {
      cout << "No engine created: " << error << endl;
      return -1;
   }

   module->setDataLayout(engine->getTargetData()->getStringRepresentation());

   // Compile the BF to IR
   cout << "Parsing… " << flush;
   Function* func = makeFunc(module, source.c_str());
   cout << "done" << endl;

   {
       ofstream dst("out.ll");
       raw_os_ostream rawdst(dst);
       rawdst << *module;
   }

   // Run optimization passes
   cout << "Optimizing… " << flush;

   PassManagerBuilder PMBuilder;

   FunctionPassManager pm(module);
   PMBuilder.populateFunctionPassManager(pm);
   pm.add(new TargetData(*(engine->getTargetData())));
   pm.add(createVerifierPass());

   // Eliminate simple loops such as [>>++<<-]
   pm.add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
   pm.add(createLICMPass());                 // Hoist loop invariants
   pm.add(createPromoteMemoryToRegisterPass());
   pm.add(createIndVarSimplifyPass());       // Canonicalize indvars
   pm.add(createLoopDeletionPass());         // Delete dead loops
   pm.add(createConstantPropagationPass());  // Propagate constants
   pm.add(new CondProp);                     // Propagate conditionals

   // Simplify code
   for(int repeat=0; repeat < 3; repeat++)
   {
      pm.add(createPromoteMemoryToRegisterPass());
      pm.add(createGVNPass());                  // Remove redundancies
      pm.add(createSCCPPass());                 // Constant prop with SCCP
      pm.add(createLoopDeletionPass());
      pm.add(createLoopUnrollPass());
      pm.add(createCFGSimplificationPass());    // Merge & remove BBs
      pm.add(createInstructionCombiningPass());
      pm.add(createConstantPropagationPass());  // Propagate constants
      pm.add(createAggressiveDCEPass());        // Delete dead instructions
      pm.add(createCFGSimplificationPass());    // Merge & remove BBs
      pm.add(createDeadStoreEliminationPass()); // Delete dead stores
      pm.add(createMemCpyOptPass());            // Combine multiple stores into memset's
      //pm.add(new PutCharAggregatePass);
   }

   pm.add(createPromoteMemoryToRegisterPass());

   // Process
   foreach (Function& f, *module)
       if (!f.isDeclaration)
           pm.run(f);

   PassManager pmm;

   PMBuilder.populateModulePassManager(pmm);
   pmm.add(createConstantMergePass());
   pmm.add(createGlobalOptimizerPass());
   pmm.add(createGlobalDCEPass());
   pmm.add(createIPConstantPropagationPass());
   pmm.run(*module);

   foreach (Function& f, *module)
       if (!f.isDeclaration)
           pm.run(f);
   pmm.run(*module);

//.........这里部分代码省略.........
开发者ID:muggenhor,项目名称:brainfuck-vm,代码行数:101,代码来源:bf-llvm.cpp

示例13: main


//.........这里部分代码省略.........


  // a separate stream
  std::unique_ptr<tool_output_file>  fdesOut;
  std::unique_ptr<tool_output_file> OutC;
  // do the samething for FIFO description
  if (NoOutput) {
    if (!OutputFIFOFilename.empty())
      errs() << "WARNING: The -fdes (fifo des filename) option is ignored when\n"
                "the --disable-output option is used.\n";
    if(!OutputCFileName.empty())
      errs() << "WARNING: The -ocfile (synthesiziable c filename) option is ignored when\n"
                  "the --disable-output option is used.\n";

  } else {
    // Default to standard output.
    if (OutputFIFOFilename.empty())
      OutputFIFOFilename = "-";

    std::error_code EC;
    fdesOut.reset(new tool_output_file(OutputFIFOFilename, EC, sys::fs::F_None));
    if (EC) {
      errs() << EC.message() << '\n';
      return 1;
    }


    if(!OutputCFileName.empty())
    {
        std::error_code EC_c;
        OutC.reset(new tool_output_file(OutputCFileName, EC_c, sys::fs::F_None));
        if (EC_c) {
          errs() << EC_c.message() << '\n';
          return 1;
        }
    }



  }




  PassManager Passes;
  // we will need two passes
  // the first pass is to generate multiple function from a single function
  // the second pass is to generate the synthesizable C version for each generated function

  Passes.add(llvm::createDecoupleInsSccPass(!NoControlFlowDup));

  Passes.add(llvm::createDecoupleMemAccessPass(Burst));

  Passes.add(createPrintModulePass(Out->os()));
  if(!OutputCFileName.empty())
  {
    errs()<<"added cprint pass\n";
    Passes.add(llvm::createGenSynthCPass(OutC->os(),GenerateCPUMode));
  }

  //PartitionGen* pg = new PartitionGen(Out->os(),fdesOut->os(),NoControlFlowDup,GenerateCPUMode);

  //Passes.add(pg );
  // Create a new optimization pass for each one specified on the command line
  /*for (unsigned i = 0; i < PassList.size(); ++i) {
    // Check to see if -std-compile-opts was specified before this option.  If
    // so, handle it.
    const PassInfo *PassInf = PassList[i];
    Pass *P = 0;
    if (PassInf->getNormalCtor())
      P = PassInf->getNormalCtor()();
    else
      errs() << argv[0] << ": cannot create pass: "
             << PassInf->getPassName() << "\n";
    if (P) {
      PassKind Kind = P->getPassKind();
      addPass(Passes, P);
    }
  }*/

  // Before executing passes, print the final values of the LLVM options.
  cl::PrintOptionValues();

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




  // Declare success.
  if (!NoOutput )
  {
    Out->keep();
    if (!OutputFIFOFilename.empty())
        fdesOut->keep();
    if(!OutputCFileName.empty())
        OutC->keep();
  }
  return 0;
}
开发者ID:sycinf,项目名称:ArchSyn,代码行数:101,代码来源:decoupmem.cpp

示例14: ldc_optimize_module

//////////////////////////////////////////////////////////////////////////////////////////
// This function runs optimization passes based on command line arguments.
// Returns true if any optimization passes were invoked.
bool ldc_optimize_module(llvm::Module* m)
{
    // Create a PassManager to hold and optimize the collection of
    // per-module passes we are about to build.
    PassManager mpm;

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

    // The -disable-simplify-libcalls flag actually disables all builtin optzns.
    if (disableSimplifyLibCalls)
        tli->disableAllFunctions();
    mpm.add(tli);

    // Add an appropriate TargetData instance for this module.
#if LDC_LLVM_VER >= 302
    mpm.add(new DataLayout(m));
#else
    mpm.add(new TargetData(m));
#endif

    // Also set up a manager for the per-function passes.
    FunctionPassManager fpm(m);
#if LDC_LLVM_VER >= 302
    fpm.add(new DataLayout(m));
#else
    fpm.add(new TargetData(m));
#endif

    // If the -strip-debug command line option was specified, add it before
    // anything else.
    if (stripDebug)
        mpm.add(createStripSymbolsPass(true));

    bool defaultsAdded = false;
    // Create a new optimization pass for each one specified on the command line
    for (unsigned i = 0; i < passList.size(); ++i) {
        if (optimizeLevel && optimizeLevel.getPosition() < passList.getPosition(i)) {
            addOptimizationPasses(mpm, fpm, optLevel(), sizeLevel());
            defaultsAdded = true;
        }

        const PassInfo *passInf = passList[i];
        Pass *pass = 0;
        if (passInf->getNormalCtor())
            pass = passInf->getNormalCtor()();
        else {
            const char* arg = passInf->getPassArgument(); // may return null
            if (arg)
                error("Can't create pass '-%s' (%s)", arg, pass->getPassName());
            else
                error("Can't create pass (%s)", pass->getPassName());
            llvm_unreachable("pass creation failed");
        }
        if (pass) {
            addPass(mpm, pass);
        }
    }

    // Add the default passes for the specified optimization level.
    if (!defaultsAdded)
        addOptimizationPasses(mpm, fpm, optLevel(), sizeLevel());

    // Run per-function passes.
    fpm.doInitialization();
    for (llvm::Module::iterator F = m->begin(), E = m->end(); F != E; ++F)
        fpm.run(*F);
    fpm.doFinalization();

    // Run per-module passes.
    mpm.run(*m);

    // Verify the resulting module.
    verifyModule(m);

    // Report that we run some passes.
    return true;
}
开发者ID:NilsBossung,项目名称:ldc,代码行数:81,代码来源:optimizer.cpp

示例15: main


//.........这里部分代码省略.........
  for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
    GlobalValue *GV = M->getFunction(ExtractFuncs[i]);
    if (!GV) {
      errs() << argv[0] << ": program doesn't contain function named '"
             << ExtractFuncs[i] << "'!\n";
      return 1;
    }
    GVs.insert(GV);
  }
  // Extract functions via regular expression matching.
  for (size_t i = 0, e = ExtractRegExpFuncs.size(); i != e; ++i) {
    std::string Error;
    StringRef RegExStr = ExtractRegExpFuncs[i];
    Regex RegEx(RegExStr);
    if (!RegEx.isValid(Error)) {
      errs() << argv[0] << ": '" << ExtractRegExpFuncs[i] << "' "
        "invalid regex: " << Error;
    }
    bool match = false;
    for (Module::iterator F = M->begin(), E = M->end(); F != E;
         F++) {
      if (RegEx.match(F->getName())) {
        GVs.insert(&*F);
        match = true;
      }
    }
    if (!match) {
      errs() << argv[0] << ": program doesn't contain global named '"
             << ExtractRegExpFuncs[i] << "'!\n";
      return 1;
    }
  }

  // Materialize requisite global values.
  if (!DeleteFn)
    for (size_t i = 0, e = GVs.size(); i != e; ++i) {
      GlobalValue *GV = GVs[i];
      if (GV->isMaterializable()) {
        std::string ErrInfo;
        if (GV->Materialize(&ErrInfo)) {
          errs() << argv[0] << ": error reading input: " << ErrInfo << "\n";
          return 1;
        }
      }
    }
  else {
    // Deleting. Materialize every GV that's *not* in GVs.
    SmallPtrSet<GlobalValue *, 8> GVSet(GVs.begin(), GVs.end());
    for (auto &G : M->globals()) {
      if (!GVSet.count(&G) && G.isMaterializable()) {
        std::string ErrInfo;
        if (G.Materialize(&ErrInfo)) {
          errs() << argv[0] << ": error reading input: " << ErrInfo << "\n";
          return 1;
        }
      }
    }
    for (auto &F : *M) {
      if (!GVSet.count(&F) && F.isMaterializable()) {
        std::string ErrInfo;
        if (F.Materialize(&ErrInfo)) {
          errs() << argv[0] << ": error reading input: " << ErrInfo << "\n";
          return 1;
        }
      }
    }
  }

  // In addition to deleting all other functions, we also want to spiff it
  // up a little bit.  Do this now.
  PassManager Passes;
  Passes.add(new DataLayoutPass(M.get())); // Use correct DataLayout

  std::vector<GlobalValue*> Gvs(GVs.begin(), GVs.end());

  Passes.add(createGVExtractionPass(Gvs, DeleteFn));
  if (!DeleteFn)
    Passes.add(createGlobalDCEPass());           // Delete unreachable globals
  Passes.add(createStripDeadDebugInfoPass());    // Remove dead debug info
  Passes.add(createStripDeadPrototypesPass());   // Remove dead func decls

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

  if (OutputAssembly)
    Passes.add(createPrintModulePass(Out.os()));
  else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
    Passes.add(createBitcodeWriterPass(Out.os()));

  Passes.run(*M.get());

  // Declare success.
  Out.keep();

  return 0;
}
开发者ID:NextGenIntelligence,项目名称:llvm,代码行数:101,代码来源:llvm-extract.cpp


注:本文中的PassManager::run方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。