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


C++ list::empty方法代码示例

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


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

示例1: autoDetectFromDirectory

CompilationDatabase *autoDetectCompilations(std::string &ErrorMessage) {
  // Auto-detect a compilation database from BuildPath.
  if (BuildPath.getNumOccurrences() > 0)
    return CompilationDatabase::autoDetectFromDirectory(BuildPath,
                                                        ErrorMessage);
  // Try to auto-detect a compilation database from the first source.
  if (!SourcePaths.empty()) {
    if (CompilationDatabase *Compilations =
            CompilationDatabase::autoDetectFromSource(SourcePaths[0],
                                                      ErrorMessage)) {
      // FIXME: just pass SourcePaths[0] once getCompileCommands supports
      // non-absolute paths.
      SmallString<64> Path(SourcePaths[0]);
      llvm::sys::fs::make_absolute(Path);
      std::vector<CompileCommand> Commands =
          Compilations->getCompileCommands(Path);
      // Ignore a detected compilation database that doesn't contain source0
      // since it is probably an unrelated compilation database.
      if (!Commands.empty())
        return Compilations;
    }
    // Reset ErrorMessage since a fix compilation database will be created if
    // it fails to detect one from source.
    ErrorMessage = "";
    // If no compilation database can be detected from source then we create a
    // fixed compilation database with c++11 support.
    std::string CommandLine[] = { "-std=c++11" };
    return new FixedCompilationDatabase(".", CommandLine);
  }

  ErrorMessage = "Could not determine sources to transform";
  return 0;
}
开发者ID:zhongxingzhi,项目名称:clang-refactor,代码行数:33,代码来源:ClangModernize.cpp

示例2: main

int main(int argc, const char **argv) {
  void *MainAddr = (void*) (intptr_t) GetExecutablePath;
  llvm::sys::PrintStackTraceOnErrorSignal(argv[0]);

  std::string
    resourcesPath = CompilerInvocation::GetResourcesPath(argv[0], MainAddr);

  int optargc = 0;
  for (; optargc != argc; ++optargc) {
    if (StringRef(argv[optargc]) == "--args")
      break;
  }
  llvm::cl::ParseCommandLineOptions(optargc, argv, "arcmt-test");

  if (VerifyTransformedFiles) {
    if (ResultFiles.empty()) {
      llvm::cl::PrintHelpMessage();
      return 1;
    }
    return verifyTransformedFiles(ResultFiles);
  }

  if (optargc == argc) {
    llvm::cl::PrintHelpMessage();
    return 1;
  }

  ArrayRef<const char*> Args(argv+optargc+1, argc-optargc-1);

  if (CheckOnly)
    return checkForMigration(resourcesPath, Args);

  return performTransformations(resourcesPath, Args);
}
开发者ID:CSI-LLVM,项目名称:clang,代码行数:34,代码来源:arcmt-test.cpp

示例3: main

int main(int argc, char **argv) {
#if defined(__CYGWIN__)
  // Cygwin clang 3.5.2 with '-O3' generates CRASHING BINARY,
  // if main()'s first function call is passing argv[0].
  std::rand();
#endif
  llvm::cl::ParseCommandLineOptions(argc, argv);

  swift::Demangle::DemangleOptions options;
  options.SynthesizeSugarOnTypes = !DisableSugar;
  if (Simplified)
    options = swift::Demangle::DemangleOptions::SimplifiedUIDemangleOptions();

  if (InputNames.empty()) {
    CompactMode = true;
    return demangleSTDIN(options);
  } else {
    swift::Demangle::Context DCtx;
    for (llvm::StringRef name : InputNames) {
      demangle(llvm::outs(), name, DCtx, options);
      llvm::outs() << '\n';
    }

    return EXIT_SUCCESS;
  }
}
开发者ID:Jnosh,项目名称:swift,代码行数:26,代码来源:swift-demangle.cpp

示例4: main

int main(int argc, char **argv) {
  llvm::cl::ParseCommandLineOptions(argc, argv, "clang-wpa");
  FileManager FileMgr;
  std::vector<ASTUnit*> ASTUnits;

  if (InputFilenames.empty())
    return 0;

  DiagnosticOptions DiagOpts;
  llvm::IntrusiveRefCntPtr<Diagnostic> Diags
    = CompilerInstance::createDiagnostics(DiagOpts, argc, argv);
  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
    const std::string &InFile = InputFilenames[i];
    llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromPCHFile(InFile, Diags));
    if (!AST)
      return 1;

    ASTUnits.push_back(AST.take());
  }

  llvm::OwningPtr<CallGraph> CG;
  CG.reset(new CallGraph());

  for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i)
    CG->addTU(ASTUnits[i]->getASTContext());

  CG->ViewCallGraph();
}
开发者ID:jhoush,项目名称:dist-clang,代码行数:28,代码来源:clang-wpa.cpp

示例5: main

int main(int argc, char **argv) {
#if defined(__CYGWIN__)
  // Cygwin clang 3.5.2 with '-O3' generates CRASHING BINARY,
  // if main()'s first function call is passing argv[0].
  std::rand();
#endif  
  llvm::cl::ParseCommandLineOptions(argc, argv);

  swift::Demangle::DemangleOptions options;
  options.SynthesizeSugarOnTypes = !DisableSugar;
  if (Simplified)
    options = swift::Demangle::DemangleOptions::SimplifiedUIDemangleOptions();

  if (InputNames.empty()) {
    CompactMode = true;
    auto input = llvm::MemoryBuffer::getSTDIN();
    if (!input) {
      llvm::errs() << input.getError().message() << '\n';
      return EXIT_FAILURE;
    }
    llvm::StringRef inputContents = input.get()->getBuffer();

    // This doesn't handle Unicode symbols, but maybe that's okay.
    llvm::Regex maybeSymbol("_T[_a-zA-Z0-9$]+");
    llvm::SmallVector<llvm::StringRef, 1> matches;
    while (maybeSymbol.match(inputContents, &matches)) {
      llvm::outs() << substrBefore(inputContents, matches.front());
      demangle(llvm::outs(), matches.front(), options);
      inputContents = substrAfter(inputContents, matches.front());
    }
    llvm::outs() << inputContents;

  } else {
    for (llvm::StringRef name : InputNames) {
      demangle(llvm::outs(), name, options);
      llvm::outs() << '\n';
    }
  }

  return EXIT_SUCCESS;
}
开发者ID:007Indian,项目名称:swift,代码行数:41,代码来源:swift-demangle.cpp

示例6: main

int main(int argc, char **argv) {
  llvm::cl::ParseCommandLineOptions(argc-2, argv, "callgraph");

  FileManager FileMgr;
  std::vector<ASTUnit*> ASTUnits;

  if (InputFilenames.empty())
    return 0;

  TextDiagnosticBuffer DiagClient;

  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
    const std::string &InFile = InputFilenames[i];

    std::string ErrMsg;
    llvm::OwningPtr<ASTUnit> AST;
    clang::Diagnostic diagnostic;

    AST.reset(ASTUnit::LoadFromPCHFile(InFile,diagnostic,false,true));

    if (!AST) {
      llvm::errs() << "[" << InFile << "] error: " << ErrMsg << '\n';
      return 1;
    }

    ASTUnits.push_back(AST.take());
  }

  llvm::OwningPtr<CallGraph> CG;
  CG.reset(new CallGraph());

  for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i){
    CG->addTU(ASTUnits[i]->getASTContext());

  }

  //std::cout<<"ajuns aici\n";
  std::cout<<"start = "<<argv[argc-2]<<"\n";
  std::cout<<"end = "<<argv[argc-1]<<"\n";

  std::vector<ProcessGraph *> pg1;
  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
		const std::string &InFile = InputFilenames[i];
		Splitter splitter(InFile);

		// std::cout << "begin1\n";
		if (!splitter.hasErrors()) {
		//	 std::cout << "begin2\n";
			splitter.splitFiles(i == 0, i == 0 ? "hw" : "sw");
		//	 std::cout << "begin3\n";
			std::vector<ProcessGraph *> *pg = splitter.getConfigs();
			if (pg->size() != 0) {
				if (pg->size() != 1) {
					std::cout << "Error :(too many)/none config functions\n";
					exit(-1);
				}
				pg1 = *pg;
			}
			/*Partitioner p(ProcessGraph *pg, int populationSize, int maxIter,unsigned int maxLUTS,
			 unsigned int maxSLICES);
			 */

		}
		// std::cout << "end1\n";
	}


	GraphDataAppender gda(pg1[0], "/home/Silviu/workspace/big_test");
	Partitioner p(pg1[0], 400, 400,false,argv[argc-2],argv[argc-1]);
	bool *bestSolution = p.getBestSolution();
	ProcessGraph *pgc = pg1[0];
	std::cout<<pgc->getMaxLUTS()<<" "<<pgc->getMaxSLICES()<<"\n";
	for (int i=0; i<pgc->getNumVertices(); i++){
		ProcessGraphNode *pgn = pgc->lookupGraphNode(i);
		std::cout<<pgn->getName()<<":\n";
		VertexData vd = pgn->getVertexData();
		std::cout << vd.hadrwareExecutionTime << "\n";
		std::cout << vd.communicationTime << "\n";
		std::cout << vd.softwareExecutionTime << "\n";
		std::cout << vd.LUTS << "\n";
		std::cout << vd.SLICES << "\n";
	}

	std::cout<<"Solutia partitionarii:\n";
	for (int i=0; i<pgc->getNumVertices(); i++){
		std::cout<<pgc->lookupGraphNode(i)->getName()<<" :"<<(bestSolution[i] == HARDWARE ? "Hardware" : "Software") << "\n";
	}

}
开发者ID:aaasz,项目名称:SHP,代码行数:89,代码来源:callgraph.cpp

示例7: main

int main(int argc, const char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  Transforms TransformManager;
  ReplacementHandling ReplacementHandler;

  TransformManager.registerTransforms();

  // Hide all options we don't define ourselves. Move pre-defined 'help',
  // 'help-list', and 'version' to our general category.
  llvm::StringMap<cl::Option*> Options;
  cl::getRegisteredOptions(Options);
  const cl::OptionCategory **CategoryEnd =
      VisibleCategories + llvm::array_lengthof(VisibleCategories);
  for (llvm::StringMap<cl::Option *>::iterator I = Options.begin(),
                                               E = Options.end();
       I != E; ++I) {
    if (I->first() == "help" || I->first() == "version" ||
        I->first() == "help-list")
      I->second->setCategory(GeneralCategory);
    else if (std::find(VisibleCategories, CategoryEnd, I->second->Category) ==
             CategoryEnd)
      I->second->setHiddenFlag(cl::ReallyHidden);
  }
  cl::SetVersionPrinter(&printVersion);

  // Parse options and generate compilations.
  std::unique_ptr<CompilationDatabase> Compilations(
      FixedCompilationDatabase::loadFromCommandLine(argc, argv));
  cl::ParseCommandLineOptions(argc, argv);

  // Populate the ModifiableFiles structure.
  GlobalOptions.ModifiableFiles.readListFromString(IncludePaths, ExcludePaths);
  GlobalOptions.ModifiableFiles.readListFromFile(IncludeFromFile,
                                                 ExcludeFromFile);

  if (!Compilations) {
    std::string ErrorMessage;
    Compilations.reset(autoDetectCompilations(ErrorMessage));
    if (!Compilations) {
      llvm::errs() << llvm::sys::path::filename(argv[0]) << ": " << ErrorMessage
                   << "\n";
      return 1;
    }
  }

  // Populate source files.
  std::vector<std::string> Sources;
  if (!SourcePaths.empty()) {
    // Use only files that are not explicitly excluded.
    std::remove_copy_if(SourcePaths.begin(), SourcePaths.end(),
                        std::back_inserter(Sources),
                        isFileExplicitlyExcludedPredicate);
  } else {
    if (GlobalOptions.ModifiableFiles.isIncludeListEmpty()) {
      llvm::errs() << llvm::sys::path::filename(argv[0])
                   << ": Use -include to indicate which files of "
                   << "the compilatiion database to transform.\n";
      return 1;
    }
    // Use source paths from the compilation database.
    // We only transform files that are explicitly included.
    Sources = Compilations->getAllFiles();
    std::vector<std::string>::iterator E = std::remove_if(
        Sources.begin(), Sources.end(), isFileNotIncludedPredicate);
    Sources.erase(E, Sources.end());
  }

  // check if line ranges are just applyed to single files
  if ( !LineRanges.empty() && Sources.size() > 1 ){
     llvm::errs() << "error: -line can only be used for single file.\n";
     return 1;
  }

  // add the line ranges to the sources 
  if ( !LineRanges.empty() ){
  }

  if (Sources.empty()) {
    llvm::errs() << llvm::sys::path::filename(argv[0])
                 << ": Could not determine sources to transform.\n";
    return 1;
  }

  // Enable timming.
  GlobalOptions.EnableTiming = TimingDirectoryName.getNumOccurrences() > 0;

  bool CmdSwitchError = false;
  CompilerVersions RequiredVersions =
      handleSupportedCompilers(argv[0], CmdSwitchError);
  if (CmdSwitchError)
    return 1;

  TransformManager.createSelectedTransforms(GlobalOptions, RequiredVersions);

  if (TransformManager.begin() == TransformManager.end()) {
    if (SupportedCompilers.empty())
      llvm::errs() << llvm::sys::path::filename(argv[0])
                   << ": no selected transforms\n";
    else
      llvm::errs() << llvm::sys::path::filename(argv[0])
//.........这里部分代码省略.........
开发者ID:zhongxingzhi,项目名称:clang-refactor,代码行数:101,代码来源:ClangModernize.cpp

示例8: main

int main(int argc, char **argv) {
  llvm::cl::ParseCommandLineOptions(argc, argv, "clang-wpa");
  std::vector<ASTUnit*> ASTUnits;

  Program Prog;
  Indexer Idxer(Prog);

  if (InputFilenames.empty())
    return 0;

  DiagnosticOptions DiagOpts;
  llvm::IntrusiveRefCntPtr<Diagnostic> Diags
    = CompilerInstance::createDiagnostics(DiagOpts, argc, argv);
  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
    const std::string &InFile = InputFilenames[i];
    llvm::OwningPtr<ASTUnit> AST(ASTUnit::LoadFromASTFile(InFile, Diags));
    if (!AST)
      return 1;

    ASTUnits.push_back(AST.take());
  }

  if (ViewCallGraph) {
    llvm::OwningPtr<CallGraph> CG;
    CG.reset(new CallGraph(Prog));

    for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i)
      CG->addTU(ASTUnits[i]->getASTContext());

    CG->ViewCallGraph();
    return 0;
  }

  if (AnalyzeFunction.empty())
    return 0;

  // Feed all ASTUnits to the Indexer.
  for (unsigned i = 0, e = ASTUnits.size(); i != e; ++i) {
    ASTUnitTU *TU = new ASTUnitTU(ASTUnits[i]);
    Idxer.IndexAST(TU);
  }

  Entity Ent = Entity::get(AnalyzeFunction, Prog);
  FunctionDecl *FD;
  TranslationUnit *TU;
  llvm::tie(FD, TU) = Idxer.getDefinitionFor(Ent);

  if (!FD)
    return 0;

  // Create an analysis engine.
  Preprocessor &PP = TU->getPreprocessor();

  // Hard code options for now.
  AnalysisManager AMgr(TU->getASTContext(), PP.getDiagnostics(),
                       PP.getLangOptions(), /* PathDiagnostic */ 0,
                       CreateRegionStoreManager,
                       CreateRangeConstraintManager, &Idxer,
                       /* MaxNodes */ 300000, /* MaxLoop */ 3,
                       /* VisualizeEG */ false, /* VisualizeEGUbi */ false,
                       /* PurgeDead */ true, /* EagerlyAssume */ false,
                       /* TrimGraph */ false, /* InlineCall */ true, 
                       /* UseUnoptimizedCFG */ false);

  GRTransferFuncs* TF = MakeCFRefCountTF(AMgr.getASTContext(), /*GC*/false,
                                         AMgr.getLangOptions());
  GRExprEngine Eng(AMgr, TF);

  Eng.ExecuteWorkList(AMgr.getStackFrame(FD, TU), AMgr.getMaxNodes());
  
  return 0;
}
开发者ID:CPFL,项目名称:guc,代码行数:72,代码来源:clang-wpa.cpp

示例9: llvm_manager

int
main(int argc, char* argv[])
{
    llvm::llvm_shutdown_obj llvm_manager(false);

    cl::SetVersionPrinter(&PrintVersion);
    cl::ParseCommandLineOptions(argc, argv);

    if (show_help)
        cl::PrintHelpMessage();

    if (show_license)
    {
        for (std::size_t i=0; i<sizeof(license_msg)/sizeof(license_msg[0]); i++)
            llvm::outs() << license_msg[i] << '\n';
        return EXIT_SUCCESS;
    }

    if (show_info)
    {
        llvm::outs() << full_version << '\n';
        list_module<yasm::ObjectFormatModule>();
        return EXIT_SUCCESS;
    }

    yasm::OffsetDiagnosticPrinter diag_printer(llvm::errs());
    yasm::Diagnostic diags(&diag_printer);
    yasm::SourceManager source_mgr(diags);
    diags.setSourceManager(&source_mgr);
    diag_printer.setPrefix("yobjdump");

    // Load standard modules
    if (!yasm::LoadStandardPlugins())
    {
        diags.Report(yasm::diag::fatal_standard_modules);
        return EXIT_FAILURE;
    }

    if (show_all_headers)
    {
        show_file_headers = true;
        show_section_headers = true;
        show_private_headers = true;
        show_relocs = true;
        show_symbols = true;
    }

    // Determine input filename and open input file.
    if (in_filenames.empty())
    {
        diags.Report(yasm::diag::fatal_no_input_files);
        return EXIT_FAILURE;
    }

    int retval = EXIT_SUCCESS;

    for (std::vector<std::string>::const_iterator i=in_filenames.begin(),
         end=in_filenames.end(); i != end; ++i)
    {
        try
        {
            if (DoDump(*i, source_mgr, diags) != EXIT_SUCCESS)
                retval = EXIT_FAILURE;
        }
        catch (std::out_of_range& err)
        {
            llvm::errs() << *i << ": "
                << "out of range error while reading (corrupt file?)\n";
            retval = EXIT_FAILURE;
        }
    }
    return retval;
}
开发者ID:PeterJohnson,项目名称:yasm-nextgen,代码行数:73,代码来源:yobjdump.cpp

示例10: main

/**

Most of the main program is pieced together from examples on the web. We are doing the following.

-# Creating lists of include directories, defines, and input files from the command line arguments.
-# Initializing the compiler to read C++ code, and setting the compiler to think we are creating
   code for the default target architecture.
-# Creating the necessary source and file managers as well as the preprocessor.
-# Adding search directories and creating #define statements for -D command line arguments.
-# Telling clang to use our ICGASTConsumer as an ASTConsumer.
-# Parse the input file.

*/
int main( int argc , char * argv[] ) {

#if (__clang_major__ >= 6) || ((__clang_major__ == 3) && (__clang_minor__ >= 5))
    clang::TargetOptions to;
#elif (__clang_major__ == 3) && (__clang_minor__ >= 3)
    clang::TargetOptions * to = new clang::TargetOptions() ;
#else
    clang::TargetOptions to;
#endif
    clang::CompilerInstance ci;

    /* Gather all of the command line arguments into lists of include directories, defines, and input files.
       All other arguments will be ignored. */
    llvm::cl::SetVersionPrinter(ICG_version) ;
    llvm::cl::ParseCommandLineOptions(argc , argv) ;

    if ( ! validAttributesVersion(attr_version) ) {
        return -1 ;
    }

/*
    if ( show_units ) {
        list_units() ;
        return 0 ;
    }
*/

    if ( input_file_names.empty() ) {
        std::cerr << "No header file specified" << std::endl ;
        return 1 ;
    }

    ci.createDiagnostics();
    clang::DiagnosticOptions & diago = ci.getDiagnosticOpts() ;
    diago.ShowColors = 1 ;
    ci.getDiagnostics().setIgnoreAllWarnings(true) ;
#if ( GCC_MAJOR == 4 ) && ( GCC_MINOR <= 2 )
    ci.getDiagnostics().setSuppressAllDiagnostics() ;
#endif

    // Set all of the defaults to c++
    clang::CompilerInvocation::setLangDefaults(ci.getLangOpts() , clang::IK_CXX) ;
    ci.getLangOpts().CXXExceptions = true ;

    // Activate C++11 parsing
    ci.getLangOpts().CPlusPlus11 = true ;

    // Set the default target architecture
#if (__clang_major__ >= 6) || (__clang_major__ == 3) && (__clang_minor__ >= 5)
    to.Triple = llvm::sys::getDefaultTargetTriple();
#elif (__clang_major__ == 3) && (__clang_minor__ >= 3)
    to->Triple = llvm::sys::getDefaultTargetTriple();
#else
    to.Triple = llvm::sys::getDefaultTargetTriple();
#endif

#if (__clang_major__ >= 6) || (__clang_major__ == 3) && (__clang_minor__ >= 5)
    std::shared_ptr<clang::TargetOptions> shared_to  = std::make_shared<clang::TargetOptions>(to) ;
    clang::TargetInfo *pti = clang::TargetInfo::CreateTargetInfo(ci.getDiagnostics(), shared_to);
#else
    clang::TargetInfo *pti = clang::TargetInfo::CreateTargetInfo(ci.getDiagnostics(), to);
#endif
    ci.setTarget(pti);

    // Create all of the necessary managers.
    ci.createFileManager();
    ci.createSourceManager(ci.getFileManager());
#if (__clang_major__ >= 6) || (__clang_major__ == 3) && (__clang_minor__ >= 5)
    ci.createPreprocessor(clang::TU_Complete);
#else
    ci.createPreprocessor();
#endif

    clang::HeaderSearch & hs = ci.getPreprocessor().getHeaderSearchInfo() ;
    clang::HeaderSearchOptions & hso = ci.getHeaderSearchOpts() ;
    clang::Preprocessor & pp = ci.getPreprocessor() ;

    // Add all of the include directories to the preprocessor
    HeaderSearchDirs hsd(hs , hso , pp, sim_services_flag) ;
    hsd.addSearchDirs ( include_dirs ) ;

    // Tell the preprocessor to use its default predefines
    clang::PreprocessorOptions & ppo = ci.getPreprocessorOpts() ;
    ppo.UsePredefines = true;
#if (__clang_major__ == 3) && (__clang_minor__ >= 8)
    pp.getBuiltinInfo().initializeBuiltins(pp.getIdentifierTable(), pp.getLangOpts());
#else
//.........这里部分代码省略.........
开发者ID:E-LLP,项目名称:trick,代码行数:101,代码来源:main.cpp

示例11: main

int main(int argc, char **argv) {
  INITIALIZE_LLVM(argc, argv);

  llvm::cl::ParseCommandLineOptions(argc, argv, "Swift SIL Extractor\n");

  CompilerInvocation Invocation;

  Invocation.setMainExecutablePath(llvm::sys::fs::getMainExecutable(
      argv[0], reinterpret_cast<void *>(&anchorForGetMainExecutable)));

  // Give the context the list of search paths to use for modules.
  Invocation.setImportSearchPaths(ImportPaths);
  // Set the SDK path and target if given.
  if (SDKPath.getNumOccurrences() == 0) {
    const char *SDKROOT = getenv("SDKROOT");
    if (SDKROOT)
      SDKPath = SDKROOT;
  }
  if (!SDKPath.empty())
    Invocation.setSDKPath(SDKPath);
  if (!Triple.empty())
    Invocation.setTargetTriple(Triple);
  if (!ResourceDir.empty())
    Invocation.setRuntimeResourcePath(ResourceDir);
  Invocation.getClangImporterOptions().ModuleCachePath = ModuleCachePath;
  Invocation.setParseStdlib();
  Invocation.getLangOptions().DisableAvailabilityChecking = true;
  Invocation.getLangOptions().EnableAccessControl = false;
  Invocation.getLangOptions().EnableObjCAttrRequiresFoundation = false;

  // Load the input file.
  llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
      llvm::MemoryBuffer::getFileOrSTDIN(InputFilename);
  if (!FileBufOrErr) {
    fprintf(stderr, "Error! Failed to open file: %s\n", InputFilename.c_str());
    exit(-1);
  }

  // If it looks like we have an AST, set the source file kind to SIL and the
  // name of the module to the file's name.
  Invocation.addInputBuffer(FileBufOrErr.get().get());

  serialization::ExtendedValidationInfo extendedInfo;
  auto result = serialization::validateSerializedAST(
      FileBufOrErr.get()->getBuffer(), &extendedInfo);
  bool HasSerializedAST = result.status == serialization::Status::Valid;

  if (HasSerializedAST) {
    const StringRef Stem = ModuleName.size()
                               ? StringRef(ModuleName)
                               : llvm::sys::path::stem(InputFilename);
    Invocation.setModuleName(Stem);
    Invocation.setInputKind(InputFileKind::IFK_Swift_Library);
  } else {
    Invocation.setModuleName("main");
    Invocation.setInputKind(InputFileKind::IFK_SIL);
  }

  SILOptions &SILOpts = Invocation.getSILOptions();
  SILOpts.AssumeUnqualifiedOwnershipWhenParsing =
      AssumeUnqualifiedOwnershipWhenParsing;

  CompilerInstance CI;
  PrintingDiagnosticConsumer PrintDiags;
  CI.addDiagnosticConsumer(&PrintDiags);

  if (CI.setup(Invocation))
    return 1;
  CI.performSema();

  // If parsing produced an error, don't run any passes.
  if (CI.getASTContext().hadError())
    return 1;

  // Load the SIL if we have a module. We have to do this after SILParse
  // creating the unfortunate double if statement.
  if (HasSerializedAST) {
    assert(!CI.hasSILModule() &&
           "performSema() should not create a SILModule.");
    CI.setSILModule(
        SILModule::createEmptyModule(CI.getMainModule(), CI.getSILOptions()));
    std::unique_ptr<SerializedSILLoader> SL = SerializedSILLoader::create(
        CI.getASTContext(), CI.getSILModule(), nullptr);

    if (extendedInfo.isSIB())
      SL->getAllForModule(CI.getMainModule()->getName(), nullptr);
    else
      SL->getAll();
  }

  if (CommandLineFunctionNames.empty() && FunctionNameFile.empty())
    return CI.getASTContext().hadError();

  // For efficient usage, we separate our names into two separate sorted
  // lists, one of managled names, and one of unmangled names.
  std::vector<std::string> Names;
  getFunctionNames(Names);

  // First partition our function names into mangled/demangled arrays.
  auto FirstDemangledName = std::partition(
//.........这里部分代码省略.........
开发者ID:apple,项目名称:swift,代码行数:101,代码来源:SILFunctionExtractor.cpp

示例12: main

int main(int argc, const char **argv) {
    llvm::sys::PrintStackTraceOnErrorSignal();
    Transforms TransformManager;
    ReplacementHandling ReplacementHandler;

    TransformManager.registerTransforms();

    // Hide all options we don't define ourselves. Move pre-defined 'help',
    // 'help-list', and 'version' to our general category.
    llvm::StringMap<cl::Option*> Options;
    cl::getRegisteredOptions(Options);
    const cl::OptionCategory **CategoryEnd =
        VisibleCategories + llvm::array_lengthof(VisibleCategories);
    for (llvm::StringMap<cl::Option *>::iterator I = Options.begin(),
            E = Options.end();
            I != E; ++I) {
        if (I->first() == "help" || I->first() == "version" ||
                I->first() == "help-list")
            I->second->setCategory(GeneralCategory);
        else if (std::find(VisibleCategories, CategoryEnd, I->second->Category) ==
                 CategoryEnd)
            I->second->setHiddenFlag(cl::ReallyHidden);
    }
    cl::SetVersionPrinter(&printVersion);

    // Parse options and generate compilations.
    std::unique_ptr<CompilationDatabase> Compilations(
        FixedCompilationDatabase::loadFromCommandLine(argc, argv));
    cl::ParseCommandLineOptions(argc, argv);

    // Populate the ModifiableFiles structure.
    GlobalOptions.ModifiableFiles.readListFromString(IncludePaths, ExcludePaths);
    GlobalOptions.ModifiableFiles.readListFromFile(IncludeFromFile,
            ExcludeFromFile);

    if (!Compilations) {
        std::string ErrorMessage;
        Compilations = autoDetectCompilations(ErrorMessage);
        if (!Compilations) {
            llvm::errs() << llvm::sys::path::filename(argv[0]) << ": " << ErrorMessage
                         << "\n";
            return 1;
        }
    }

    // Populate source files.
    std::vector<std::string> Sources;
    if (!SourcePaths.empty()) {
        // Use only files that are not explicitly excluded.
        std::remove_copy_if(SourcePaths.begin(), SourcePaths.end(),
                            std::back_inserter(Sources),
                            isFileExplicitlyExcludedPredicate);
    } else {
        if (GlobalOptions.ModifiableFiles.isIncludeListEmpty()) {
            llvm::errs() << llvm::sys::path::filename(argv[0])
                         << ": Use -include to indicate which files of "
                         << "the compilatiion database to transform.\n";
            return 1;
        }
        // Use source paths from the compilation database.
        // We only transform files that are explicitly included.
        Sources = Compilations->getAllFiles();
        std::vector<std::string>::iterator E = std::remove_if(
                Sources.begin(), Sources.end(), isFileNotIncludedPredicate);
        Sources.erase(E, Sources.end());
    }



    // check if line ranges are just applyed to single files
    if ( !LineRanges.empty() && Sources.size() > 1 ) {
        llvm::errs() << "error: -line can only be used for single file.\n";
        return 1;
    }

    // add the line ranges to the sources
    if ( !LineRanges.empty() ) {
    }


    std::string filename;
    int line_begin, column_begin;
    int line_end, column_end;

    if ( Target.getNumOccurrences() ) {
        // TODO parse the target data
        std::stringstream sstr(Target);
        char separator;
        sstr >>
             line_begin >> separator >>
             column_begin >> separator >>
             line_end >> separator >>
             column_end >> separator >> filename;

        llvm::errs() << filename << " " << line_begin << "-" <<
                     column_begin << ":" << line_end << "-" << column_end << "\n";

        // store it in the Transform object
    }
开发者ID:realincubus,项目名称:clang-refactor,代码行数:99,代码来源:ClangModernize.cpp

示例13: main

int main(int argc, char *argv[]) {
  llvm::cl::SetVersionPrinter(PrintVersion);
  llvm::cl::ParseCommandLineOptions(argc, argv, "CFG to LLVM");

  auto context = llvm::make_unique<llvm::LLVMContext>();

  if (OS.empty()) {
    if (ListSupported || ListUnsupported) {
      OS = "linux"; // just need something
    }
    else {
      std::cerr << "-os must be specified" << std::endl;
      return EXIT_FAILURE;
    }
  }

  if (!(ListSupported || ListUnsupported || ListCFGFunctions) && EntryPoints.empty()) {
    std::cerr
        << "-entrypoint must be specified" << std::endl;
        return EXIT_FAILURE;
  }

  if (!InitArch(context.get(), OS, Arch)) {
    std::cerr
        << "Cannot initialize for arch " << Arch
        << " and OS " << OS << std::endl;
    return EXIT_FAILURE;
  }

  auto M = CreateModule(context.get());
  if (!M) {
    return EXIT_FAILURE;
  }

  auto triple = M->getTargetTriple();

  if (ListSupported || ListUnsupported) {
    ListArchSupportedInstructions(triple, llvm::outs(), ListSupported, ListUnsupported);
    return EXIT_SUCCESS;
  }

  if (InputFilename.empty()) {
    std::cerr
        << "Must specify an input file." << std::endl;
    return EXIT_FAILURE;
  }

  //reproduce NativeModule from CFG input argument
  try {
    std::unique_ptr<NativeModule> mod(ReadProtoBuf(InputFilename));
    if (!mod) {
      std::cerr << "Unable to read module from CFG" << std::endl;
      return EXIT_FAILURE;
    }

    if (ListCFGFunctions) {
      PrintCFGFunctionList(mod.get(), Arch);
      return EXIT_SUCCESS;
    }

    //make sure the entry point list is correct before we start lifting the code
    const std::vector<NativeEntrySymbol> &module_entry_points = mod->getEntryPoints();

    for (const auto &entry_point : EntryPoints) {
      auto it = std::find_if(
        module_entry_points.begin(),
        module_entry_points.end(),

        [&entry_point](const NativeEntrySymbol &symbol) -> bool {
          return (symbol.getName() == entry_point);
        }
      );

      if (it == module_entry_points.end()) {
          std::cerr << "The following entry point could not be found: \"" << entry_point << "\". Aborting..." << std::endl;
          return EXIT_FAILURE;
      }
    }

    //now, convert it to an LLVM module
    ArchInitAttachDetach(M);

    if (!LiftCodeIntoModule(mod.get(), M)) {
      std::cerr << "Failure to convert to LLVM module!" << std::endl;
      return EXIT_FAILURE;
    }

    std::set<VA> entry_point_pcs;
    for (const auto &entry_point_name : EntryPoints) {
      auto entry_pc = FindSymbolInModule(mod.get(), entry_point_name);
      assert(entry_pc != static_cast<VA>( -1));

      std::cerr << "Adding entry point: " << entry_point_name << std::endl
                << entry_point_name << " is implemented by sub_" << std::hex
                << entry_pc << std::endl;

      if ( !ArchAddEntryPointDriver(M, entry_point_name, entry_pc)) {
        return EXIT_FAILURE;
      }

//.........这里部分代码省略.........
开发者ID:kumarak,项目名称:mcsema,代码行数:101,代码来源:Lift.cpp


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