本文整理汇总了C++中StringRef::slice方法的典型用法代码示例。如果您正苦于以下问题:C++ StringRef::slice方法的具体用法?C++ StringRef::slice怎么用?C++ StringRef::slice使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类StringRef
的用法示例。
在下文中一共展示了StringRef::slice方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: ApplyOneQAOverride
/// ApplyQAOverride - Apply a list of edits to the input argument lists.
///
/// The input string is a space separate list of edits to perform,
/// they are applied in order to the input argument lists. Edits
/// should be one of the following forms:
///
/// '#': Silence information about the changes to the command line arguments.
///
/// '^': Add FOO as a new argument at the beginning of the command line.
///
/// '+': Add FOO as a new argument at the end of the command line.
///
/// 's/XXX/YYY/': Substitute the regular expression XXX with YYY in the command
/// line.
///
/// 'xOPTION': Removes all instances of the literal argument OPTION.
///
/// 'XOPTION': Removes all instances of the literal argument OPTION,
/// and the following argument.
///
/// 'Ox': Removes all flags matching 'O' or 'O[sz0-9]' and adds 'Ox'
/// at the end of the command line.
///
/// \param OS - The stream to write edit information to.
/// \param Args - The vector of command line arguments.
/// \param Edit - The override command to perform.
/// \param SavedStrings - Set to use for storing string representations.
static void ApplyOneQAOverride(raw_ostream &OS,
SmallVectorImpl<const char*> &Args,
StringRef Edit,
std::set<std::string> &SavedStrings) {
// This does not need to be efficient.
if (Edit[0] == '^') {
const char *Str =
SaveStringInSet(SavedStrings, Edit.substr(1));
OS << "### Adding argument " << Str << " at beginning\n";
Args.insert(Args.begin() + 1, Str);
} else if (Edit[0] == '+') {
const char *Str =
SaveStringInSet(SavedStrings, Edit.substr(1));
OS << "### Adding argument " << Str << " at end\n";
Args.push_back(Str);
} else if (Edit[0] == 's' && Edit[1] == '/' && Edit.endswith("/") &&
Edit.slice(2, Edit.size()-1).find('/') != StringRef::npos) {
StringRef MatchPattern = Edit.substr(2).split('/').first;
StringRef ReplPattern = Edit.substr(2).split('/').second;
ReplPattern = ReplPattern.slice(0, ReplPattern.size()-1);
for (unsigned i = 1, e = Args.size(); i != e; ++i) {
std::string Repl = llvm::Regex(MatchPattern).sub(ReplPattern, Args[i]);
if (Repl != Args[i]) {
OS << "### Replacing '" << Args[i] << "' with '" << Repl << "'\n";
Args[i] = SaveStringInSet(SavedStrings, Repl);
}
}
} else if (Edit[0] == 'x' || Edit[0] == 'X') {
std::string Option = Edit.substr(1, std::string::npos);
for (unsigned i = 1; i < Args.size();) {
if (Option == Args[i]) {
OS << "### Deleting argument " << Args[i] << '\n';
Args.erase(Args.begin() + i);
if (Edit[0] == 'X') {
if (i < Args.size()) {
OS << "### Deleting argument " << Args[i] << '\n';
Args.erase(Args.begin() + i);
} else
OS << "### Invalid X edit, end of command line!\n";
}
} else
++i;
}
} else if (Edit[0] == 'O') {
for (unsigned i = 1; i < Args.size();) {
const char *A = Args[i];
if (A[0] == '-' && A[1] == 'O' &&
(A[2] == '\0' ||
(A[3] == '\0' && (A[2] == 's' || A[2] == 'z' ||
('0' <= A[2] && A[2] <= '9'))))) {
OS << "### Deleting argument " << Args[i] << '\n';
Args.erase(Args.begin() + i);
} else
++i;
}
OS << "### Adding argument " << Edit << " at end\n";
Args.push_back(SaveStringInSet(SavedStrings, '-' + Edit.str()));
} else {
OS << "### Unrecognized edit: " << Edit << "\n";
}
}
示例2: dumpCXXData
//.........这里部分代码省略.........
SymName, TIEntries);
TIs[SymName] = TI;
}
// Catchable type arrays in the MS-ABI start with _CTA or __CTA.
else if (SymName.startswith("_CTA") || SymName.startswith("__CTA")) {
CatchableTypeArray CTA;
CTA.NumEntries =
*reinterpret_cast<const little32_t *>(SymContents.data());
collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
SymName, CTAEntries);
CTAs[SymName] = CTA;
}
// Catchable types in the MS-ABI start with _CT or __CT.
else if (SymName.startswith("_CT") || SymName.startswith("__CT")) {
const little32_t *DataPtr =
reinterpret_cast<const little32_t *>(SymContents.data());
CatchableType CT;
CT.Flags = DataPtr[0];
CT.NonVirtualBaseAdjustmentOffset = DataPtr[2];
CT.VirtualBasePointerOffset = DataPtr[3];
CT.VirtualBaseAdjustmentOffset = DataPtr[4];
CT.Size = DataPtr[5];
StringRef *I = std::begin(CT.Symbols), *E = std::end(CT.Symbols);
collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E);
CTs[SymName] = CT;
}
// Construction vtables in the Itanium ABI start with '_ZTT' or '__ZTT'.
else if (SymName.startswith("_ZTT") || SymName.startswith("__ZTT")) {
collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
SymName, VTTEntries);
}
// Typeinfo names in the Itanium ABI start with '_ZTS' or '__ZTS'.
else if (SymName.startswith("_ZTS") || SymName.startswith("__ZTS")) {
TINames[SymName] = SymContents.slice(0, SymContents.find('\0'));
}
// Vtables in the Itanium ABI start with '_ZTV' or '__ZTV'.
else if (SymName.startswith("_ZTV") || SymName.startswith("__ZTV")) {
collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
SymName, VTableSymEntries);
for (uint64_t SymOffI = 0; SymOffI < SymSize; SymOffI += BytesInAddress) {
auto Key = std::make_pair(SymName, SymOffI);
if (VTableSymEntries.count(Key))
continue;
const char *DataPtr =
SymContents.substr(SymOffI, BytesInAddress).data();
int64_t VData;
if (BytesInAddress == 8)
VData = *reinterpret_cast<const little64_t *>(DataPtr);
else
VData = *reinterpret_cast<const little32_t *>(DataPtr);
VTableDataEntries[Key] = VData;
}
}
// Typeinfo structures in the Itanium ABI start with '_ZTI' or '__ZTI'.
else if (SymName.startswith("_ZTI") || SymName.startswith("__ZTI")) {
// FIXME: Do something with these!
}
}
for (const auto &VFTableEntry : VFTableEntries) {
StringRef VFTableName = VFTableEntry.first.first;
uint64_t Offset = VFTableEntry.first.second;
StringRef SymName = VFTableEntry.second;
outs() << VFTableName << '[' << Offset << "]: " << SymName << '\n';
}
for (const auto &VBTable : VBTables) {
StringRef VBTableName = VBTable.first;
示例3: main
//.........这里部分代码省略.........
}
raw_ostream &OS = outs();
for (int i = 1; i != argc; ++i) {
StringRef Arg = argv[i];
if (Arg.startswith("-")) {
HasAnyOption = true;
if (Arg == "--version") {
OS << PACKAGE_VERSION << '\n';
} else if (Arg == "--prefix") {
OS << ActivePrefix << '\n';
} else if (Arg == "--bindir") {
OS << ActiveBinDir << '\n';
} else if (Arg == "--includedir") {
OS << ActiveIncludeDir << '\n';
} else if (Arg == "--libdir") {
OS << ActiveLibDir << '\n';
} else if (Arg == "--cppflags") {
OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
} else if (Arg == "--cflags") {
OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
} else if (Arg == "--cxxflags") {
OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
} else if (Arg == "--ldflags") {
OS << "-L" << ActiveLibDir << ' ' << LLVM_LDFLAGS
<< ' ' << LLVM_SYSTEM_LIBS << '\n';
} else if (Arg == "--libs") {
PrintLibs = true;
} else if (Arg == "--libnames") {
PrintLibNames = true;
} else if (Arg == "--libfiles") {
PrintLibFiles = true;
} else if (Arg == "--components") {
for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {
OS << ' ';
OS << AvailableComponents[j].Name;
}
OS << '\n';
} else if (Arg == "--targets-built") {
bool First = true;
for (TargetRegistry::iterator I = TargetRegistry::begin(),
E = TargetRegistry::end(); I != E; First = false, ++I) {
if (!First)
OS << ' ';
OS << I->getName();
}
OS << '\n';
} else if (Arg == "--host-target") {
OS << LLVM_DEFAULT_TARGET_TRIPLE << '\n';
} else if (Arg == "--build-mode") {
OS << LLVM_BUILDMODE << '\n';
} else if (Arg == "--obj-root") {
OS << LLVM_OBJ_ROOT << '\n';
} else if (Arg == "--src-root") {
OS << LLVM_SRC_ROOT << '\n';
} else {
usage();
}
} else {
Components.push_back(Arg);
}
}
if (!HasAnyOption)
usage();
if (PrintLibs || PrintLibNames || PrintLibFiles) {
// Construct the list of all the required libraries.
std::vector<StringRef> RequiredLibs;
ComputeLibsForComponents(Components, RequiredLibs);
for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
StringRef Lib = RequiredLibs[i];
if (i)
OS << ' ';
if (PrintLibNames) {
OS << Lib;
} else if (PrintLibFiles) {
OS << ActiveLibDir << '/' << Lib;
} else if (PrintLibs) {
// If this is a typical library name, include it using -l.
if (Lib.startswith("lib") && Lib.endswith(".a")) {
OS << "-l" << Lib.slice(3, Lib.size()-2);
continue;
}
// Otherwise, print the full path.
OS << ActiveLibDir << '/' << Lib;
}
}
OS << '\n';
} else if (!Components.empty()) {
errs() << "llvm-config: error: components given, but unused\n\n";
usage();
}
return 0;
}
示例4: getOffsetOfTrimmedLine
llvm::StringRef swift::ide::getTrimmedTextForLine(unsigned LineIndex,
StringRef Text) {
size_t LineOffset = getOffsetOfTrimmedLine(LineIndex, Text);
size_t LineEnd = Text.find_first_of("\r\n", LineOffset);
return Text.slice(LineOffset, LineEnd);
}
示例5: Error
bool X86ATTAsmParser::
ParseInstruction(StringRef Name, SMLoc NameLoc,
SmallVectorImpl<MCParsedAsmOperand*> &Operands) {
StringRef PatchedName = Name;
// FIXME: Hack to recognize setneb as setne.
if (PatchedName.startswith("set") && PatchedName.endswith("b") &&
PatchedName != "setb" && PatchedName != "setnb")
PatchedName = PatchedName.substr(0, Name.size()-1);
// FIXME: Hack to recognize cmp<comparison code>{ss,sd,ps,pd}.
const MCExpr *ExtraImmOp = 0;
if ((PatchedName.startswith("cmp") || PatchedName.startswith("vcmp")) &&
(PatchedName.endswith("ss") || PatchedName.endswith("sd") ||
PatchedName.endswith("ps") || PatchedName.endswith("pd"))) {
bool IsVCMP = PatchedName.startswith("vcmp");
unsigned SSECCIdx = IsVCMP ? 4 : 3;
unsigned SSEComparisonCode = StringSwitch<unsigned>(
PatchedName.slice(SSECCIdx, PatchedName.size() - 2))
.Case("eq", 0)
.Case("lt", 1)
.Case("le", 2)
.Case("unord", 3)
.Case("neq", 4)
.Case("nlt", 5)
.Case("nle", 6)
.Case("ord", 7)
.Case("eq_uq", 8)
.Case("nge", 9)
.Case("ngt", 0x0A)
.Case("false", 0x0B)
.Case("neq_oq", 0x0C)
.Case("ge", 0x0D)
.Case("gt", 0x0E)
.Case("true", 0x0F)
.Case("eq_os", 0x10)
.Case("lt_oq", 0x11)
.Case("le_oq", 0x12)
.Case("unord_s", 0x13)
.Case("neq_us", 0x14)
.Case("nlt_uq", 0x15)
.Case("nle_uq", 0x16)
.Case("ord_s", 0x17)
.Case("eq_us", 0x18)
.Case("nge_uq", 0x19)
.Case("ngt_uq", 0x1A)
.Case("false_os", 0x1B)
.Case("neq_os", 0x1C)
.Case("ge_oq", 0x1D)
.Case("gt_oq", 0x1E)
.Case("true_us", 0x1F)
.Default(~0U);
if (SSEComparisonCode != ~0U) {
ExtraImmOp = MCConstantExpr::Create(SSEComparisonCode,
getParser().getContext());
if (PatchedName.endswith("ss")) {
PatchedName = IsVCMP ? "vcmpss" : "cmpss";
} else if (PatchedName.endswith("sd")) {
PatchedName = IsVCMP ? "vcmpsd" : "cmpsd";
} else if (PatchedName.endswith("ps")) {
PatchedName = IsVCMP ? "vcmpps" : "cmpps";
} else {
assert(PatchedName.endswith("pd") && "Unexpected mnemonic!");
PatchedName = IsVCMP ? "vcmppd" : "cmppd";
}
}
}
// FIXME: Hack to recognize vpclmul<src1_quadword, src2_quadword>dq
if (PatchedName.startswith("vpclmul")) {
unsigned CLMULQuadWordSelect = StringSwitch<unsigned>(
PatchedName.slice(7, PatchedName.size() - 2))
.Case("lqlq", 0x00) // src1[63:0], src2[63:0]
.Case("hqlq", 0x01) // src1[127:64], src2[63:0]
.Case("lqhq", 0x10) // src1[63:0], src2[127:64]
.Case("hqhq", 0x11) // src1[127:64], src2[127:64]
.Default(~0U);
if (CLMULQuadWordSelect != ~0U) {
ExtraImmOp = MCConstantExpr::Create(CLMULQuadWordSelect,
getParser().getContext());
assert(PatchedName.endswith("dq") && "Unexpected mnemonic!");
PatchedName = "vpclmulqdq";
}
}
Operands.push_back(X86Operand::CreateToken(PatchedName, NameLoc));
if (ExtraImmOp)
Operands.push_back(X86Operand::CreateImm(ExtraImmOp, NameLoc, NameLoc));
// Determine whether this is an instruction prefix.
bool isPrefix =
Name == "lock" || Name == "rep" ||
Name == "repe" || Name == "repz" ||
Name == "repne" || Name == "repnz" ||
Name == "rex64" || Name == "data16";
// This does the actual operand parsing. Don't parse any more if we have a
//.........这里部分代码省略.........
示例6: sub
std::string Regex::sub(StringRef Repl, StringRef String,
std::string *Error) {
SmallVector<StringRef, 8> Matches;
// Reset error, if given.
if (Error && !Error->empty()) *Error = "";
// Return the input if there was no match.
if (!match(String, &Matches))
return String;
// Otherwise splice in the replacement string, starting with the prefix before
// the match.
std::string Res(String.begin(), Matches[0].begin());
// Then the replacement string, honoring possible substitutions.
while (!Repl.empty()) {
// Skip to the next escape.
std::pair<StringRef, StringRef> Split = Repl.split('\\');
// Add the skipped substring.
Res += Split.first;
// Check for terminimation and trailing backslash.
if (Split.second.empty()) {
if (Repl.size() != Split.first.size() &&
Error && Error->empty())
*Error = "replacement string contained trailing backslash";
break;
}
// Otherwise update the replacement string and interpret escapes.
Repl = Split.second;
// FIXME: We should have a StringExtras function for mapping C99 escapes.
switch (Repl[0]) {
// Treat all unrecognized characters as self-quoting.
default:
Res += Repl[0];
Repl = Repl.substr(1);
break;
// Single character escapes.
case 't':
Res += '\t';
Repl = Repl.substr(1);
break;
case 'n':
Res += '\n';
Repl = Repl.substr(1);
break;
// Decimal escapes are backreferences.
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': {
// Extract the backreference number.
StringRef Ref = Repl.slice(0, Repl.find_first_not_of("0123456789"));
Repl = Repl.substr(Ref.size());
unsigned RefValue;
if (!Ref.getAsInteger(10, RefValue) &&
RefValue < Matches.size())
Res += Matches[RefValue];
else if (Error && Error->empty())
*Error = ("invalid backreference string '" + Twine(Ref) + "'").str();
break;
}
}
}
// And finally the suffix.
Res += StringRef(Matches[0].end(), String.end() - Matches[0].end());
return Res;
}
示例7: decodePunycode
bool Punycode::decodePunycode(StringRef InputPunycode,
std::vector<uint32_t> &OutCodePoints) {
OutCodePoints.clear();
OutCodePoints.reserve(InputPunycode.size());
// -- Build the decoded string as UTF32 first because we need random access.
uint32_t n = initial_n;
int i = 0;
int bias = initial_bias;
/// let output = an empty string indexed from 0
// consume all code points before the last delimiter (if there is one)
// and copy them to output,
size_t lastDelimiter = InputPunycode.find_last_of(delimiter);
if (lastDelimiter != StringRef::npos) {
for (char c : InputPunycode.slice(0, lastDelimiter)) {
// fail on any non-basic code point
if (static_cast<unsigned char>(c) > 0x7f)
return true;
OutCodePoints.push_back(c);
}
// if more than zero code points were consumed then consume one more
// (which will be the last delimiter)
InputPunycode =
InputPunycode.slice(lastDelimiter + 1, InputPunycode.size());
}
while (!InputPunycode.empty()) {
int oldi = i;
int w = 1;
for (int k = base; ; k += base) {
// consume a code point, or fail if there was none to consume
if (InputPunycode.empty())
return true;
char codePoint = InputPunycode.front();
InputPunycode = InputPunycode.slice(1, InputPunycode.size());
// let digit = the code point's digit-value, fail if it has none
int digit = digit_index(codePoint);
if (digit < 0)
return true;
i = i + digit * w;
int t = k <= bias ? tmin
: k >= bias + tmax ? tmax
: k - bias;
if (digit < t)
break;
w = w * (base - t);
}
bias = adapt(i - oldi, OutCodePoints.size() + 1, oldi == 0);
n = n + i / (OutCodePoints.size() + 1);
i = i % (OutCodePoints.size() + 1);
// if n is a basic code point then fail
if (n < 0x80)
return true;
// insert n into output at position i
OutCodePoints.insert(OutCodePoints.begin() + i, n);
i++;
}
return true;
}
示例8: normalize
std::string Triple::normalize(StringRef Str) {
// Parse into components.
SmallVector<StringRef, 4> Components;
for (size_t First = 0, Last = 0; Last != StringRef::npos; First = Last + 1) {
Last = Str.find('-', First);
Components.push_back(Str.slice(First, Last));
}
// If the first component corresponds to a known architecture, preferentially
// use it for the architecture. If the second component corresponds to a
// known vendor, preferentially use it for the vendor, etc. This avoids silly
// component movement when a component parses as (eg) both a valid arch and a
// valid os.
ArchType Arch = UnknownArch;
if (Components.size() > 0)
Arch = ParseArch(Components[0]);
VendorType Vendor = UnknownVendor;
if (Components.size() > 1)
Vendor = ParseVendor(Components[1]);
OSType OS = UnknownOS;
if (Components.size() > 2)
OS = ParseOS(Components[2]);
EnvironmentType Environment = UnknownEnvironment;
if (Components.size() > 3)
Environment = ParseEnvironment(Components[3]);
// Note which components are already in their final position. These will not
// be moved.
bool Found[4];
Found[0] = Arch != UnknownArch;
Found[1] = Vendor != UnknownVendor;
Found[2] = OS != UnknownOS;
Found[3] = Environment != UnknownEnvironment;
// If they are not there already, permute the components into their canonical
// positions by seeing if they parse as a valid architecture, and if so moving
// the component to the architecture position etc.
for (unsigned Pos = 0; Pos != array_lengthof(Found); ++Pos) {
if (Found[Pos])
continue; // Already in the canonical position.
for (unsigned Idx = 0; Idx != Components.size(); ++Idx) {
// Do not reparse any components that already matched.
if (Idx < array_lengthof(Found) && Found[Idx])
continue;
// Does this component parse as valid for the target position?
bool Valid = false;
StringRef Comp = Components[Idx];
switch (Pos) {
default:
assert(false && "unexpected component type!");
case 0:
Arch = ParseArch(Comp);
Valid = Arch != UnknownArch;
break;
case 1:
Vendor = ParseVendor(Comp);
Valid = Vendor != UnknownVendor;
break;
case 2:
OS = ParseOS(Comp);
Valid = OS != UnknownOS;
break;
case 3:
Environment = ParseEnvironment(Comp);
Valid = Environment != UnknownEnvironment;
break;
}
if (!Valid)
continue; // Nope, try the next component.
// Move the component to the target position, pushing any non-fixed
// components that are in the way to the right. This tends to give
// good results in the common cases of a forgotten vendor component
// or a wrongly positioned environment.
if (Pos < Idx) {
// Insert left, pushing the existing components to the right. For
// example, a-b-i386 -> i386-a-b when moving i386 to the front.
StringRef CurrentComponent(""); // The empty component.
// Replace the component we are moving with an empty component.
std::swap(CurrentComponent, Components[Idx]);
// Insert the component being moved at Pos, displacing any existing
// components to the right.
for (unsigned i = Pos; !CurrentComponent.empty(); ++i) {
// Skip over any fixed components.
while (i < array_lengthof(Found) && Found[i]) ++i;
// Place the component at the new position, getting the component
// that was at this position - it will be moved right.
std::swap(CurrentComponent, Components[i]);
}
} else if (Pos > Idx) {
// Push right by inserting empty components until the component at Idx
// reaches the target position Pos. For example, pc-a -> -pc-a when
// moving pc to the second position.
do {
// Insert one empty component at Idx.
StringRef CurrentComponent(""); // The empty component.
for (unsigned i = Idx; i < Components.size();) {
// Place the component at the new position, getting the component
//.........这里部分代码省略.........
示例9: if
//.........这里部分代码省略.........
BinPath = InstallPath + "/bin";
IncludePath = InstallPath + "/include";
LibDevicePath = InstallPath + "/nvvm/libdevice";
auto &FS = D.getVFS();
if (!(FS.exists(IncludePath) && FS.exists(BinPath)))
continue;
bool CheckLibDevice = (!NoCudaLib || Candidate.StrictChecking);
if (CheckLibDevice && !FS.exists(LibDevicePath))
continue;
// On Linux, we have both lib and lib64 directories, and we need to choose
// based on our triple. On MacOS, we have only a lib directory.
//
// It's sufficient for our purposes to be flexible: If both lib and lib64
// exist, we choose whichever one matches our triple. Otherwise, if only
// lib exists, we use it.
if (HostTriple.isArch64Bit() && FS.exists(InstallPath + "/lib64"))
LibPath = InstallPath + "/lib64";
else if (FS.exists(InstallPath + "/lib"))
LibPath = InstallPath + "/lib";
else
continue;
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> VersionFile =
FS.getBufferForFile(InstallPath + "/version.txt");
if (!VersionFile) {
// CUDA 7.0 doesn't have a version.txt, so guess that's our version if
// version.txt isn't present.
Version = CudaVersion::CUDA_70;
} else {
Version = ParseCudaVersionFile((*VersionFile)->getBuffer());
}
if (Version >= CudaVersion::CUDA_90) {
// CUDA-9+ uses single libdevice file for all GPU variants.
std::string FilePath = LibDevicePath + "/libdevice.10.bc";
if (FS.exists(FilePath)) {
for (const char *GpuArchName :
{"sm_30", "sm_32", "sm_35", "sm_37", "sm_50", "sm_52", "sm_53",
"sm_60", "sm_61", "sm_62", "sm_70", "sm_72"}) {
const CudaArch GpuArch = StringToCudaArch(GpuArchName);
if (Version >= MinVersionForCudaArch(GpuArch) &&
Version <= MaxVersionForCudaArch(GpuArch))
LibDeviceMap[GpuArchName] = FilePath;
}
}
} else {
std::error_code EC;
for (llvm::sys::fs::directory_iterator LI(LibDevicePath, EC), LE;
!EC && LI != LE; LI = LI.increment(EC)) {
StringRef FilePath = LI->path();
StringRef FileName = llvm::sys::path::filename(FilePath);
// Process all bitcode filenames that look like
// libdevice.compute_XX.YY.bc
const StringRef LibDeviceName = "libdevice.";
if (!(FileName.startswith(LibDeviceName) && FileName.endswith(".bc")))
continue;
StringRef GpuArch = FileName.slice(
LibDeviceName.size(), FileName.find('.', LibDeviceName.size()));
LibDeviceMap[GpuArch] = FilePath.str();
// Insert map entries for specific devices with this compute
// capability. NVCC's choice of the libdevice library version is
// rather peculiar and depends on the CUDA version.
if (GpuArch == "compute_20") {
LibDeviceMap["sm_20"] = FilePath;
LibDeviceMap["sm_21"] = FilePath;
LibDeviceMap["sm_32"] = FilePath;
} else if (GpuArch == "compute_30") {
LibDeviceMap["sm_30"] = FilePath;
if (Version < CudaVersion::CUDA_80) {
LibDeviceMap["sm_50"] = FilePath;
LibDeviceMap["sm_52"] = FilePath;
LibDeviceMap["sm_53"] = FilePath;
}
LibDeviceMap["sm_60"] = FilePath;
LibDeviceMap["sm_61"] = FilePath;
LibDeviceMap["sm_62"] = FilePath;
} else if (GpuArch == "compute_35") {
LibDeviceMap["sm_35"] = FilePath;
LibDeviceMap["sm_37"] = FilePath;
} else if (GpuArch == "compute_50") {
if (Version >= CudaVersion::CUDA_80) {
LibDeviceMap["sm_50"] = FilePath;
LibDeviceMap["sm_52"] = FilePath;
LibDeviceMap["sm_53"] = FilePath;
}
}
}
}
// Check that we have found at least one libdevice that we can link in if
// -nocudalib hasn't been specified.
if (LibDeviceMap.empty() && !NoCudaLib)
continue;
IsValid = true;
break;
}
}
示例10: determineConstantNamePrefix
//.........这里部分代码省略.........
if (ec == ecEnd)
return;
// Determine whether the given enumerator is non-deprecated and has no
// specifically-provided name.
auto isNonDeprecatedWithoutCustomName = [](
const clang::EnumConstantDecl *elem) -> bool {
if (elem->hasAttr<clang::SwiftNameAttr>())
return false;
clang::VersionTuple maxVersion{~0U, ~0U, ~0U};
switch (elem->getAvailability(nullptr, maxVersion)) {
case clang::AR_Available:
case clang::AR_NotYetIntroduced:
for (auto attr : elem->attrs()) {
if (auto annotate = dyn_cast<clang::AnnotateAttr>(attr)) {
if (annotate->getAnnotation() == "swift1_unavailable")
return false;
}
if (auto avail = dyn_cast<clang::AvailabilityAttr>(attr)) {
if (avail->getPlatform()->getName() == "swift")
return false;
}
}
return true;
case clang::AR_Deprecated:
case clang::AR_Unavailable:
return false;
}
};
// Move to the first non-deprecated enumerator, or non-swift_name'd
// enumerator, if present.
auto firstNonDeprecated =
std::find_if(ec, ecEnd, isNonDeprecatedWithoutCustomName);
bool hasNonDeprecated = (firstNonDeprecated != ecEnd);
if (hasNonDeprecated) {
ec = firstNonDeprecated;
} else {
// Advance to the first case without a custom name, deprecated or not.
while (ec != ecEnd && (*ec)->hasAttr<clang::SwiftNameAttr>())
++ec;
if (ec == ecEnd) {
return;
}
}
// Compute the common prefix.
StringRef commonPrefix = (*ec)->getName();
bool followedByNonIdentifier = false;
for (++ec; ec != ecEnd; ++ec) {
// Skip deprecated or swift_name'd enumerators.
const clang::EnumConstantDecl *elem = *ec;
if (hasNonDeprecated) {
if (!isNonDeprecatedWithoutCustomName(elem))
continue;
} else {
if (elem->hasAttr<clang::SwiftNameAttr>())
continue;
}
commonPrefix = getCommonWordPrefix(commonPrefix, elem->getName(),
followedByNonIdentifier);
if (commonPrefix.empty())
break;
}
if (!commonPrefix.empty()) {
StringRef checkPrefix = commonPrefix;
// Account for the 'kConstant' naming convention on enumerators.
if (checkPrefix[0] == 'k') {
bool canDropK;
if (checkPrefix.size() >= 2)
canDropK = clang::isUppercase(checkPrefix[1]);
else
canDropK = !followedByNonIdentifier;
if (canDropK)
checkPrefix = checkPrefix.drop_front();
}
// Don't use importFullName() here, we want to ignore the swift_name
// and swift_private attributes.
StringRef enumNameStr = decl->getName();
StringRef commonWithEnum = getCommonPluralPrefix(checkPrefix, enumNameStr);
size_t delta = commonPrefix.size() - checkPrefix.size();
// Account for the 'EnumName_Constant' convention on enumerators.
if (commonWithEnum.size() < checkPrefix.size() &&
checkPrefix[commonWithEnum.size()] == '_' && !followedByNonIdentifier) {
delta += 1;
}
commonPrefix = commonPrefix.slice(0, commonWithEnum.size() + delta);
}
constantNamePrefix = ctx.AllocateCopy(commonPrefix);
}
示例11: main
//.........这里部分代码省略.........
} else if (Arg == "--libdir") {
OS << ActiveLibDir << '\n';
} else if (Arg == "--cppflags") {
OS << ActiveIncludeOption << ' ' << LLVM_CPPFLAGS << '\n';
} else if (Arg == "--cflags") {
OS << ActiveIncludeOption << ' ' << LLVM_CFLAGS << '\n';
} else if (Arg == "--cxxflags") {
OS << ActiveIncludeOption << ' ' << LLVM_CXXFLAGS << '\n';
} else if (Arg == "--ldflags") {
OS << "-L" << ActiveLibDir << ' ' << LLVM_LDFLAGS << '\n';
} else if (Arg == "--system-libs") {
PrintSystemLibs = true;
} else if (Arg == "--libs") {
PrintLibs = true;
} else if (Arg == "--libnames") {
PrintLibNames = true;
} else if (Arg == "--libfiles") {
PrintLibFiles = true;
} else if (Arg == "--components") {
for (unsigned j = 0; j != array_lengthof(AvailableComponents); ++j) {
// Only include non-installed components when in a development tree.
if (!AvailableComponents[j].IsInstalled && !IsInDevelopmentTree)
continue;
OS << ' ';
OS << AvailableComponents[j].Name;
}
OS << '\n';
} else if (Arg == "--targets-built") {
OS << LLVM_TARGETS_BUILT << '\n';
} else if (Arg == "--host-target") {
OS << Triple::normalize(LLVM_DEFAULT_TARGET_TRIPLE) << '\n';
} else if (Arg == "--build-mode") {
OS << build_mode << '\n';
} else if (Arg == "--assertion-mode") {
#if defined(NDEBUG)
OS << "OFF\n";
#else
OS << "ON\n";
#endif
} else if (Arg == "--obj-root") {
OS << ActivePrefix << '\n';
} else if (Arg == "--src-root") {
OS << LLVM_SRC_ROOT << '\n';
} else {
usage();
}
} else {
Components.push_back(Arg);
}
}
if (!HasAnyOption)
usage();
if (PrintLibs || PrintLibNames || PrintLibFiles || PrintSystemLibs) {
// If no components were specified, default to "all".
if (Components.empty())
Components.push_back("all");
// Construct the list of all the required libraries.
std::vector<StringRef> RequiredLibs;
ComputeLibsForComponents(Components, RequiredLibs,
/*IncludeNonInstalled=*/IsInDevelopmentTree);
if (PrintLibs || PrintLibNames || PrintLibFiles) {
for (unsigned i = 0, e = RequiredLibs.size(); i != e; ++i) {
StringRef Lib = RequiredLibs[i];
if (i)
OS << ' ';
if (PrintLibNames) {
OS << Lib;
} else if (PrintLibFiles) {
OS << ActiveLibDir << '/' << Lib;
} else if (PrintLibs) {
// If this is a typical library name, include it using -l.
if (Lib.startswith("lib") && Lib.endswith(".a")) {
OS << "-l" << Lib.slice(3, Lib.size()-2);
continue;
}
// Otherwise, print the full path.
OS << ActiveLibDir << '/' << Lib;
}
}
OS << '\n';
}
// Print SYSTEM_LIBS after --libs.
// FIXME: Each LLVM component may have its dependent system libs.
if (PrintSystemLibs)
OS << LLVM_SYSTEM_LIBS << '\n';
} else if (!Components.empty()) {
errs() << "llvm-config: error: components given, but unused\n\n";
usage();
}
return 0;
}
示例12: verifyFile
/// \brief After the file has been processed, check to see if we got all of
/// the expected diagnostics and check to see if there were any unexpected
/// ones.
bool DiagnosticVerifier::verifyFile(unsigned BufferID,
bool shouldAutoApplyFixes) {
using llvm::SMLoc;
const SourceLoc BufferStartLoc = SM.getLocForBufferStart(BufferID);
CharSourceRange EntireRange = SM.getRangeForBuffer(BufferID);
StringRef InputFile = SM.extractText(EntireRange);
StringRef BufferName = SM.getIdentifierForBuffer(BufferID);
// Queue up all of the diagnostics, allowing us to sort them and emit them in
// file order.
std::vector<llvm::SMDiagnostic> Errors;
unsigned PrevExpectedContinuationLine = 0;
std::vector<ExpectedDiagnosticInfo> ExpectedDiagnostics;
auto addError = [&](const char *Loc, std::string message,
ArrayRef<llvm::SMFixIt> FixIts = {}) {
auto loc = SourceLoc(SMLoc::getFromPointer(Loc));
auto diag = SM.GetMessage(loc, llvm::SourceMgr::DK_Error, message,
{}, FixIts);
Errors.push_back(diag);
};
// Scan the memory buffer looking for expected-note/warning/error.
for (size_t Match = InputFile.find("expected-");
Match != StringRef::npos; Match = InputFile.find("expected-", Match+1)) {
// Process this potential match. If we fail to process it, just move on to
// the next match.
StringRef MatchStart = InputFile.substr(Match);
const char *DiagnosticLoc = MatchStart.data();
llvm::SourceMgr::DiagKind ExpectedClassification;
if (MatchStart.startswith("expected-note")) {
ExpectedClassification = llvm::SourceMgr::DK_Note;
MatchStart = MatchStart.substr(strlen("expected-note"));
} else if (MatchStart.startswith("expected-warning")) {
ExpectedClassification = llvm::SourceMgr::DK_Warning;
MatchStart = MatchStart.substr(strlen("expected-warning"));
} else if (MatchStart.startswith("expected-error")) {
ExpectedClassification = llvm::SourceMgr::DK_Error;
MatchStart = MatchStart.substr(strlen("expected-error"));
} else
continue;
// Skip any whitespace before the {{.
MatchStart = MatchStart.substr(MatchStart.find_first_not_of(" \t"));
size_t TextStartIdx = MatchStart.find("{{");
if (TextStartIdx == StringRef::npos) {
addError(MatchStart.data(),
"expected {{ in expected-warning/note/error line");
continue;
}
int LineOffset = 0;
if (TextStartIdx > 0 && MatchStart[0] == '@') {
if (MatchStart[1] != '+' && MatchStart[1] != '-') {
addError(MatchStart.data(), "expected '+'/'-' for line offset");
continue;
}
StringRef Offs;
if (MatchStart[1] == '+')
Offs = MatchStart.slice(2, TextStartIdx).rtrim();
else
Offs = MatchStart.slice(1, TextStartIdx).rtrim();
size_t SpaceIndex = Offs.find(' ');
if (SpaceIndex != StringRef::npos && SpaceIndex < TextStartIdx) {
size_t Delta = Offs.size() - SpaceIndex;
MatchStart = MatchStart.substr(TextStartIdx - Delta);
TextStartIdx = Delta;
Offs = Offs.slice(0, SpaceIndex);
} else {
MatchStart = MatchStart.substr(TextStartIdx);
TextStartIdx = 0;
}
if (Offs.getAsInteger(10, LineOffset)) {
addError(MatchStart.data(), "expected line offset before '{{'");
continue;
}
}
ExpectedDiagnosticInfo Expected(DiagnosticLoc, ExpectedClassification);
unsigned Count = 1;
if (TextStartIdx > 0) {
StringRef CountStr = MatchStart.substr(0, TextStartIdx).trim();
if (CountStr == "*") {
Expected.mayAppear = true;
} else {
if (CountStr.getAsInteger(10, Count)) {
addError(MatchStart.data(), "expected match count before '{{'");
continue;
//.........这里部分代码省略.........