Example #1
0
void 
ASTResultSynthesizer::MaybeRecordPersistentType(TypeDecl *D)
{
    if (!D->getIdentifier())
        return;
    
    StringRef name = D->getName();
    
    if (name.size() == 0 || name[0] != '$')
        return;
    
    lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));

    ConstString name_cs(name.str().c_str());
    
    if (log)
        log->Printf ("Recording persistent type %s\n", name_cs.GetCString());
    
    Decl *D_scratch = m_target.GetClangASTImporter()->DeportDecl(m_target.GetScratchClangASTContext()->getASTContext(), 
                                                                 m_ast_context,
                                                                 D);
    
    if (TypeDecl *TypeDecl_scratch = dyn_cast<TypeDecl>(D_scratch))
        m_target.GetPersistentVariables().RegisterPersistentType(name_cs, TypeDecl_scratch);
}
TestModuleFileExtension::Reader::Reader(ModuleFileExtension *Ext,
                                        const llvm::BitstreamCursor &InStream)
  : ModuleFileExtensionReader(Ext), Stream(InStream)
{
  // Read the extension block.
  SmallVector<uint64_t, 4> Record;
  while (true) {
    llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
    switch (Entry.Kind) {
    case llvm::BitstreamEntry::SubBlock:
    case llvm::BitstreamEntry::EndBlock:
    case llvm::BitstreamEntry::Error:
      return;

    case llvm::BitstreamEntry::Record:
      break;
    }

    Record.clear();
    StringRef Blob;
    unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
    switch (RecCode) {
    case FIRST_EXTENSION_RECORD_ID: {
      StringRef Message = Blob.substr(0, Record[0]);
      fprintf(stderr, "Read extension block message: %s\n",
              Message.str().c_str());
      break;
    }
    }
  }
}
Example #3
0
void clang::AttachHeaderIncludeGen(Preprocessor &PP, bool ShowAllHeaders,
                                   StringRef OutputPath, bool ShowDepth,
                                   bool MSStyle) {
  raw_ostream *OutputFile = MSStyle ? &llvm::outs() : &llvm::errs();
  bool OwnsOutputFile = false;

  // Open the output file, if used.
  if (!OutputPath.empty()) {
    std::string Error;
    llvm::raw_fd_ostream *OS = new llvm::raw_fd_ostream(
        OutputPath.str().c_str(), Error,
        llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
    if (!Error.empty()) {
      PP.getDiagnostics().Report(
        clang::diag::warn_fe_cc_print_header_failure) << Error;
      delete OS;
    } else {
      OS->SetUnbuffered();
      OS->SetUseAtomicWrites(true);
      OutputFile = OS;
      OwnsOutputFile = true;
    }
  }

  PP.addPPCallbacks(new HeaderIncludesCallback(&PP, ShowAllHeaders,
                                               OutputFile, OwnsOutputFile,
                                               ShowDepth, MSStyle));
}
void IdentifierNamingCheck::checkMacro(SourceManager &SourceMgr,
                                       const Token &MacroNameTok,
                                       const MacroInfo *MI) {
  if (!NamingStyles[SK_MacroDefinition])
    return;

  StringRef Name = MacroNameTok.getIdentifierInfo()->getName();
  const NamingStyle &Style = *NamingStyles[SK_MacroDefinition];
  if (matchesStyle(Name, Style))
    return;

  std::string KindName =
      fixupWithCase(StyleNames[SK_MacroDefinition], CT_LowerCase);
  std::replace(KindName.begin(), KindName.end(), '_', ' ');

  std::string Fixup = fixupWithStyle(Name, Style);
  if (StringRef(Fixup).equals(Name)) {
    if (!IgnoreFailedSplit) {
      DEBUG(
          llvm::dbgs() << MacroNameTok.getLocation().printToString(SourceMgr)
                       << llvm::format(": unable to split words for %s '%s'\n",
                                       KindName.c_str(), Name.str().c_str()));
    }
  } else {
    NamingCheckId ID(MI->getDefinitionLoc(), Name);
    NamingCheckFailure &Failure = NamingCheckFailures[ID];
    SourceRange Range(MacroNameTok.getLocation(), MacroNameTok.getEndLoc());

    Failure.Fixup = std::move(Fixup);
    Failure.KindName = std::move(KindName);
    addUsage(NamingCheckFailures, ID, Range);
  }
}
Example #5
0
static std::string getFullArchName(uint32_t Flags) {
  StringRef Arch = getArchName(Flags);
  StringRef Mach = getMachName(Flags);
  if (Mach.empty())
    return Arch.str();
  return (Arch + " (" + Mach + ")").str();
}
Example #6
0
bool ModuleInfo::getNameFromSymbolTable(SymbolRef::Type Type, uint64_t Address,
                                        std::string &Name, uint64_t &Addr,
                                        uint64_t &Size) const {
  assert(Module);
  error_code ec;
  for (symbol_iterator si = Module->begin_symbols(),
                       se = Module->end_symbols();
                       si != se; si.increment(ec)) {
    if (error(ec)) return false;
    uint64_t SymbolAddress;
    uint64_t SymbolSize;
    SymbolRef::Type SymbolType;
    if (error(si->getAddress(SymbolAddress)) ||
        SymbolAddress == UnknownAddressOrSize) continue;
    if (error(si->getSize(SymbolSize)) ||
        SymbolSize == UnknownAddressOrSize) continue;
    if (error(si->getType(SymbolType))) continue;
    // FIXME: If a function has alias, there are two entries in symbol table
    // with same address size. Make sure we choose the correct one.
    if (SymbolAddress <= Address && Address < SymbolAddress + SymbolSize &&
        SymbolType == Type) {
      StringRef SymbolName;
      if (error(si->getName(SymbolName))) continue;
      Name = SymbolName.str();
      Addr = SymbolAddress;
      Size = SymbolSize;
      return true;
    }
  }
  return false;
}
Example #7
0
void DumpModuleInfoAction::ExecuteAction() {
  // Set up the output file.
  std::unique_ptr<llvm::raw_fd_ostream> OutFile;
  StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
  if (!OutputFileName.empty() && OutputFileName != "-") {
    std::error_code EC;
    OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
                                           llvm::sys::fs::F_Text));
  }
  llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();

  Out << "Information for module file '" << getCurrentFile() << "':\n";
  auto &FileMgr = getCompilerInstance().getFileManager();
  auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
  StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
  bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
                Magic[2] == 'C' && Magic[3] == 'H');
  Out << "  Module format: " << (IsRaw ? "raw" : "obj") << "\n";

  Preprocessor &PP = getCompilerInstance().getPreprocessor();
  DumpModuleInfoListener Listener(Out);
  HeaderSearchOptions &HSOpts =
      PP.getHeaderSearchInfo().getHeaderSearchOpts();
  ASTReader::readASTFileControlBlock(
      getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
      /*FindModuleFileExtensions=*/true, Listener,
      HSOpts.ModulesValidateDiagnosticOptions);
}
Example #8
0
// This is for use when debugging LTO.
static void saveBCFile(Module &M, StringRef Suffix) {
  std::error_code EC;
  raw_fd_ostream OS(Config->OutputFile.str() + Suffix.str(), EC,
                    sys::fs::OpenFlags::F_None);
  check(EC);
  WriteBitcodeToFile(&M, OS, /* ShouldPreserveUseListOrder */ true);
}
Example #9
0
std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, 
                                         types::ID InputType) const {
  switch (getTriple().getArch()) {
  default:
    return getTripleString();

  case llvm::Triple::arm:
  case llvm::Triple::thumb: {
    // FIXME: Factor into subclasses.
    llvm::Triple Triple = getTriple();

    // Thumb2 is the default for V7 on Darwin.
    //
    // FIXME: Thumb should just be another -target-feaure, not in the triple.
    StringRef Suffix =
      getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple));
    bool ThumbDefault = Suffix.startswith("v6m") ||
      (Suffix.startswith("v7") && getTriple().isOSDarwin());
    std::string ArchName = "arm";

    // Assembly files should start in ARM mode.
    if (InputType != types::TY_PP_Asm &&
        Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault))
      ArchName = "thumb";
    Triple.setArchName(ArchName + Suffix.str());

    return Triple.getTriple();
  }
  }
}
Example #10
0
const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
  std::string MArch;
  if (!Arch.empty())
    MArch = Arch;
  else
    MArch = Triple.getArchName();
  MArch = StringRef(MArch).split("+").first.lower();

  // Handle -march=native.
  if (MArch == "native") {
    std::string CPU = llvm::sys::getHostCPUName();
    if (CPU != "generic") {
      // Translate the native cpu into the architecture suffix for that CPU.
      StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
      // If there is no valid architecture suffix for this CPU we don't know how
      // to handle it, so return no architecture.
      if (Suffix.empty())
        MArch = "";
      else
        MArch = std::string("arm") + Suffix.str();
    }
  }

  return MArch;
}
Example #11
0
void ARMSubtarget::resetSubtargetFeatures(StringRef CPU, StringRef FS) {
  if (CPUString.empty())
    CPUString = "generic";

  // Insert the architecture feature derived from the target triple into the
  // feature string. This is important for setting features that are implied
  // based on the architecture version.
  std::string ArchFS = ARM_MC::ParseARMTriple(TargetTriple.getTriple(),
                                              CPUString);
  if (!FS.empty()) {
    if (!ArchFS.empty())
      ArchFS = ArchFS + "," + FS.str();
    else
      ArchFS = FS;
  }
  ParseSubtargetFeatures(CPUString, ArchFS);

  // Thumb2 implies at least V6T2. FIXME: Fix tests to explicitly specify a
  // ARM version or CPU and then remove this.
  if (!HasV6T2Ops && hasThumb2())
    HasV4TOps = HasV5TOps = HasV5TEOps = HasV6Ops = HasV6T2Ops = true;

  // Keep a pointer to static instruction cost data for the specified CPU.
  SchedModel = getSchedModelForCPU(CPUString);

  // Initialize scheduling itinerary for the specified CPU.
  InstrItins = getInstrItineraryForCPU(CPUString);

  if ((TargetTriple.getTriple().find("eabi") != std::string::npos) ||
      (isTargetIOS() && isMClass()))
    // FIXME: We might want to separate AAPCS and EABI. Some systems, e.g.
    // Darwin-EABI conforms to AACPS but not the rest of EABI.
    TargetABI = ARM_ABI_AAPCS;

  if (isAAPCS_ABI())
    stackAlignment = 8;

  if (!isTargetIOS())
    UseMovt = hasV6T2Ops();
  else {
    IsR9Reserved = ReserveR9 | !HasV6Ops;
    UseMovt = DarwinUseMOVT && hasV6T2Ops();
    SupportsTailCall = !getTargetTriple().isOSVersionLT(5, 0);
  }

  if (!isThumb() || hasThumb2())
    PostRAScheduler = true;

  // v6+ may or may not support unaligned mem access depending on the system
  // configuration.
  if (!StrictAlign && hasV6Ops() && isTargetDarwin())
    AllowsUnalignedMem = true;

  // NEON f32 ops are non-IEEE 754 compliant. Darwin is ok with it by default.
  uint64_t Bits = getFeatureBits();
  if ((Bits & ARM::ProcA5 || Bits & ARM::ProcA8) && // Where this matters
      (Options.UnsafeFPMath || isTargetDarwin()))
    UseNEONForSinglePrecisionFP = true;
}
Example #12
0
std::pair<ModuleFile *, bool>
ModuleManager::addModule(StringRef FileName, ModuleKind Type,
                         SourceLocation ImportLoc, ModuleFile *ImportedBy,
                         unsigned Generation, std::string &ErrorStr) {
  const FileEntry *Entry = FileMgr.getFile(FileName);
  if (!Entry && FileName != "-") {
    ErrorStr = "file not found";
    return std::make_pair(static_cast<ModuleFile*>(0), false);
  }
  
  // Check whether we already loaded this module, before 
  ModuleFile *&ModuleEntry = Modules[Entry];
  bool NewModule = false;
  if (!ModuleEntry) {
    // Allocate a new module.
    ModuleFile *New = new ModuleFile(Type, Generation);
    New->Index = Chain.size();
    New->FileName = FileName.str();
    New->File = Entry;
    New->ImportLoc = ImportLoc;
    Chain.push_back(New);
    NewModule = true;
    ModuleEntry = New;

    // Load the contents of the module
    if (llvm::MemoryBuffer *Buffer = lookupBuffer(FileName)) {
      // The buffer was already provided for us.
      assert(Buffer && "Passed null buffer");
      New->Buffer.reset(Buffer);
    } else {
      // Open the AST file.
      llvm::error_code ec;
      if (FileName == "-") {
        ec = llvm::MemoryBuffer::getSTDIN(New->Buffer);
        if (ec)
          ErrorStr = ec.message();
      } else
        New->Buffer.reset(FileMgr.getBufferForFile(FileName, &ErrorStr));
      
      if (!New->Buffer)
        return std::make_pair(static_cast<ModuleFile*>(0), false);
    }
    
    // Initialize the stream
    New->StreamFile.init((const unsigned char *)New->Buffer->getBufferStart(),
                         (const unsigned char *)New->Buffer->getBufferEnd());     }
  
  if (ImportedBy) {
    ModuleEntry->ImportedBy.insert(ImportedBy);
    ImportedBy->Imports.insert(ModuleEntry);
  } else {
    if (!ModuleEntry->DirectlyImported)
      ModuleEntry->ImportLoc = ImportLoc;
    
    ModuleEntry->DirectlyImported = true;
  }
  
  return std::make_pair(ModuleEntry, NewModule);
}
Example #13
0
Acceptor::Acceptor(std::unique_ptr<Socket> &&listener_socket,
                   StringRef name,
                   const LocalSocketIdFunc &local_socket_id)
    : m_listener_socket_up(std::move(listener_socket)),
      m_name(name.str()),
      m_local_socket_id(local_socket_id)
{
}
void VariableNamingRule::ValidateFieldDeclaration(StringRef name,
        AccessSpecifier access,
        SourceLocation location,
        SourceManager& sourceManager)
{
    if (access == AS_public)
    {
        if (! boost::regex_match(name.begin(), name.end(), m_publicFieldNamePattern))
        {
            m_context.outputPrinter->PrintRuleViolation(
                "variable naming",
                Severity::Style,
                boost::str(boost::format("Public field '%s' should be named in camelCase style")
                           % name.str()),
                location,
                sourceManager);
        }
    }
    else if (access == AS_protected || access == AS_private)
    {
        if (! boost::regex_match(name.begin(), name.end(), m_privateOrProtectedFieldNamePattern))
        {
            std::string which = (access == AS_protected) ? "Protected" : "Private";
            m_context.outputPrinter->PrintRuleViolation(
                "variable naming",
                Severity::Style,
                boost::str(boost::format("%s field '%s' should be named in m_camelCase style")
                           % which
                           % name.str()),
                location,
                sourceManager);
        }
        else if (boost::regex_match(name.begin(), name.end(), m_deprecatedFieldNamePattern))
        {
            std::string which = (access == AS_protected) ? "Protected" : "Private";
            m_context.outputPrinter->PrintRuleViolation(
                "variable naming",
                Severity::Style,
                boost::str(boost::format("%s field '%s' is named in a style that is deprecated")
                           % which
                           % name.str()),
                location,
                sourceManager);
        }
    }
}
Example #15
0
std::string convert_to_slash(StringRef path, Style style) {
  if (real_style(style) != Style::windows)
    return path;

  std::string s = path.str();
  std::replace(s.begin(), s.end(), '\\', '/');
  return s;
}
Example #16
0
void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
                    CrashReportInfo *CrashInfo) const {
  // Always quote the exe.
  OS << ' ';
  printArg(OS, Executable, /*Quote=*/true);

  llvm::ArrayRef<const char *> Args = Arguments;
  llvm::SmallVector<const char *, 128> ArgsRespFile;
  if (ResponseFile != nullptr) {
    buildArgvForResponseFile(ArgsRespFile);
    Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
  }

  bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
  for (size_t i = 0, e = Args.size(); i < e; ++i) {
    const char *const Arg = Args[i];

    if (CrashInfo) {
      if (int Skip = skipArgs(Arg, HaveCrashVFS)) {
        i += Skip - 1;
        continue;
      }
      auto Found = std::find_if(InputFilenames.begin(), InputFilenames.end(),
                                [&Arg](StringRef IF) { return IF == Arg; });
      if (Found != InputFilenames.end() &&
          (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
        // Replace the input file name with the crashinfo's file name.
        OS << ' ';
        StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
        printArg(OS, ShortName.str().c_str(), Quote);
        continue;
      }
    }

    OS << ' ';
    printArg(OS, Arg, Quote);
  }

  if (CrashInfo && HaveCrashVFS) {
    OS << ' ';
    printArg(OS, "-ivfsoverlay", Quote);
    OS << ' ';
    printArg(OS, CrashInfo->VFSPath.str().c_str(), Quote);
  }

  if (ResponseFile != nullptr) {
    OS << "\n Arguments passed via response file:\n";
    writeResponseFile(OS);
    // Avoiding duplicated newline terminator, since FileLists are
    // newline-separated.
    if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
      OS << "\n";
    OS << " (end of response file)";
  }

  OS << Terminator;
}
PCHGenerator::PCHGenerator(const Preprocessor &PP,
                           StringRef OutputFile,
                           clang::Module *Module,
                           StringRef isysroot,
                           raw_ostream *OS)
  : PP(PP), OutputFile(OutputFile), Module(Module), 
    isysroot(isysroot.str()), Out(OS), 
    SemaPtr(0), Stream(Buffer), Writer(Stream) {
}
Example #18
0
/// Helpers
void Strator::StratorWorker::printLocation(const Instruction& inst){
	MDNode *node = inst.getDebugLoc().getAsMDNode(inst.getContext());
	DILocation loc(node);
	unsigned line = loc.getLineNumber();
	StringRef file = loc.getFilename();
	// StringRef dir = loc.getDirectory();
	cerr << "Location: " << endl;
	cerr << file.str() << ", line: " << line << endl;
}
DiagnosticBuilder ClangTidyContext::diag(StringRef CheckName,
                                         SourceLocation Loc,
                                         StringRef Description) {
  unsigned ID = DiagEngine->getDiagnosticIDs()->getCustomDiagID(
      DiagnosticIDs::Warning, Description);
  if (CheckNamesByDiagnosticID.count(ID) == 0)
    CheckNamesByDiagnosticID.insert(std::make_pair(ID, CheckName.str()));
  return DiagEngine->Report(Loc, ID);
}
Example #20
0
PCHGenerator::PCHGenerator(const Preprocessor &PP, StringRef OutputFile,
                           clang::Module *Module, StringRef isysroot,
                           std::shared_ptr<PCHBuffer> Buffer,
                           bool AllowASTWithErrors)
    : PP(PP), OutputFile(OutputFile), Module(Module), isysroot(isysroot.str()),
      SemaPtr(nullptr), Buffer(Buffer), Stream(Buffer->Data), Writer(Stream),
      AllowASTWithErrors(AllowASTWithErrors) {
  Buffer->IsComplete = false;
}
Example #21
0
bool DebugIR::updateExtension(StringRef NewExtension) {
  size_t dot = Filename.find_last_of(".");
  if (dot == std::string::npos)
    return false;

  Filename.erase(dot);
  Filename += NewExtension.str();
  return true;
}
Example #22
0
static std::string getErrorString(const Twine &Message, StringRef Whence,
                                  bool Warning) {
  std::string Str = (Warning ? "warning" : "error");
  Str += ": ";
  if (!Whence.empty())
    Str += Whence.str() + ": ";
  Str += Message.str() + "\n";
  return Str;
}
Example #23
0
bool Transform::handleBeginSource(CompilerInstance &CI, StringRef Filename) {
  CurrentSource = Filename;

  if (Options().EnableTiming) {
    Timings.push_back(std::make_pair(Filename.str(), llvm::TimeRecord()));
    Timings.back().second -= llvm::TimeRecord::getCurrentTime(true);
  }
  return true;
}
Example #24
0
static std::string
sd_getClassNameFromMD(llvm::MDNode* mdNode, unsigned operandNo = 0) {
//  llvm::MDTuple* mdTuple = dyn_cast<llvm::MDTuple>(mdNode);
//  assert(mdTuple);
  llvm::MDTuple* mdTuple = cast<llvm::MDTuple>(mdNode);
  assert(mdTuple->getNumOperands() > operandNo + 1);

//  llvm::MDNode* nameMdNode = dyn_cast<llvm::MDNode>(mdTuple->getOperand(operandNo).get());
//  assert(nameMdNode);
  llvm::MDNode* nameMdNode = cast<llvm::MDNode>(mdTuple->getOperand(operandNo).get());

//  llvm::MDString* mdStr = dyn_cast<llvm::MDString>(nameMdNode->getOperand(0));
//  assert(mdStr);
  llvm::MDString* mdStr = cast<llvm::MDString>(nameMdNode->getOperand(0));

  StringRef strRef = mdStr->getString();
  assert(sd_isVtableName_ref(strRef));

//  llvm::MDNode* gvMd = dyn_cast<llvm::MDNode>(mdTuple->getOperand(operandNo+1).get());
  llvm::MDNode* gvMd = cast<llvm::MDNode>(mdTuple->getOperand(operandNo+1).get());

//  SmallString<256> OutName;
//  llvm::raw_svector_ostream Out(OutName);
//  gvMd->print(Out, CURR_MODULE);
//  Out.flush();

  llvm::ConstantAsMetadata* vtblConsMd = dyn_cast_or_null<ConstantAsMetadata>(gvMd->getOperand(0).get());
  if (vtblConsMd == NULL) {
//    llvm::MDNode* tmpnode = dyn_cast<llvm::MDNode>(gvMd);
//    llvm::MDString* tmpstr = dyn_cast<llvm::MDString>(tmpnode->getOperand(0));
//    assert(tmpstr->getString() == "NO_VTABLE");

    return strRef.str();
  }

//  llvm::GlobalVariable* vtbl = dyn_cast<llvm::GlobalVariable>(vtblConsMd->getValue());
//  assert(vtbl);
  llvm::GlobalVariable* vtbl = cast<llvm::GlobalVariable>(vtblConsMd->getValue());

  StringRef vtblNameRef = vtbl->getName();
  assert(vtblNameRef.startswith(strRef));

  return vtblNameRef.str();
}
// This method allows an ArchiveMember to be replaced with the data for a
// different file, presumably as an update to the member. It also makes sure
// the flags are reset correctly.
bool ArchiveMember::replaceWith(StringRef newFile, std::string* ErrMsg) {
    if (!sys::fs::exists(newFile)) {
        if (ErrMsg)
            *ErrMsg = "Can not replace an archive member with a non-existent file";
        return true;
    }

    data = 0;
    path = newFile.str();

    // SVR4 symbol tables have an empty name
    if (path == ARFILE_SVR4_SYMTAB_NAME)
        flags |= SVR4SymbolTableFlag;
    else
        flags &= ~SVR4SymbolTableFlag;

    // BSD4.4 symbol tables have a special name
    if (path == ARFILE_BSD4_SYMTAB_NAME)
        flags |= BSD4SymbolTableFlag;
    else
        flags &= ~BSD4SymbolTableFlag;

    // String table name
    if (path == ARFILE_STRTAB_NAME)
        flags |= StringTableFlag;
    else
        flags &= ~StringTableFlag;

    // If it has a slash or its over 15 chars then its a long filename format
    if (path.length() > 15)
        flags |= HasLongFilenameFlag;
    else
        flags &= ~HasLongFilenameFlag;

    // Get the status info
    sys::fs::file_status Status;
    if (sys::fs::status(path, Status))
        return true;

    User = Status.getUser();
    Group = Status.getGroup();
    Mode = Status.permissions();
    ModTime = Status.getLastModificationTime();
    Size = Status.getSize();

    // Determine what kind of file it is.
    sys::fs::file_magic magic = sys::fs::file_magic::unknown;
    if (sys::fs::identify_magic(path, magic))
        return true;
    if (magic == sys::fs::file_magic::bitcode)
        flags |= BitcodeFlag;
    else
        flags &= ~BitcodeFlag;

    return false;
}
Example #26
0
std::string ModuleFile::Dependency::getPrettyPrintedPath() const {
  StringRef pathWithoutScope = RawPath;
  if (isScoped()) {
    size_t splitPoint = pathWithoutScope.find_last_of('\0');
    pathWithoutScope = pathWithoutScope.slice(0, splitPoint);
  }
  std::string output = pathWithoutScope.str();
  std::replace(output.begin(), output.end(), '\0', '.');
  return output;
}
Example #27
0
static std::vector<std::string>
getSyntaxOnlyToolArgs(const std::vector<std::string> &ExtraArgs,
                      StringRef FileName) {
  std::vector<std::string> Args;
  Args.push_back("clang-tool");
  Args.push_back("-fsyntax-only");
  Args.insert(Args.end(), ExtraArgs.begin(), ExtraArgs.end());
  Args.push_back(FileName.str());
  return Args;
}
Example #28
0
bool Option::error(const Twine &Message, StringRef ArgName) {
  if (ArgName.data() == 0) ArgName = ArgStr;
  if (ArgName.empty())
    std::cerr << HelpStr;  // Be nice for positional arguments
  else
    std::cerr << "for the -" << ArgName.str();

  std::cerr << " option: " << Message.str() << "\n";
  return true;
}
// On function prologue, the stack is created by decrementing
// its pointer. Once decremented, all references are done with positive
// offset from the stack/frame pointer, using StackGrowsUp enables
// an easier handling.
// Using CodeModel::Large enables different CALL behavior.
MipsTargetMachine::MipsTargetMachine(const Target &T, const Triple &TT,
                                     StringRef CPU, StringRef FS,
                                     const TargetOptions &Options,
                                     Optional<Reloc::Model> RM,
                                     CodeModel::Model CM, CodeGenOpt::Level OL,
                                     bool isLittle)
    : LLVMTargetMachine(T, computeDataLayout(TT, CPU, Options, isLittle), TT,
                        CPU, FS, Options, getEffectiveRelocModel(CM, RM), CM,
                        OL),
      isLittle(isLittle), TLOF(llvm::make_unique<MipsTargetObjectFile>()),
      ABI(MipsABIInfo::computeTargetABI(TT, CPU, Options.MCOptions)),
      Subtarget(nullptr), DefaultSubtarget(TT, CPU, FS, isLittle, *this),
      NoMips16Subtarget(TT, CPU, FS.empty() ? "-mips16" : FS.str() + ",-mips16",
                        isLittle, *this),
      Mips16Subtarget(TT, CPU, FS.empty() ? "+mips16" : FS.str() + ",+mips16",
                      isLittle, *this) {
  Subtarget = &DefaultSubtarget;
  initAsmInfo();
}
Example #30
0
void DwarfCompileUnit::addGlobalNameForTypeUnit(StringRef Name,
                                                const DIScope *Context) {
  if (!hasDwarfPubSections())
    return;
  std::string FullName = getParentContextString(Context) + Name.str();
  // Insert, allowing the entry to remain as-is if it's already present
  // This way the CU-level type DIE is preferred over the "can't describe this
  // type as a unit offset because it's not really in the CU at all, it's only
  // in a type unit"
  GlobalNames.insert(std::make_pair(std::move(FullName), &getUnitDie()));
}