Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/MacroInfo.cpp
//===--- MacroInfo.cpp - Information about #defined identifiers -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the MacroInfo interface. // //===----------------------------------------------------------------------===// #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" using namespace clang; MacroInfo::MacroInfo(SourceLocation DefLoc) : Location(DefLoc), ArgumentList(nullptr), NumArguments(0), IsDefinitionLengthCached(false), IsFunctionLike(false), IsC99Varargs(false), IsGNUVarargs(false), IsBuiltinMacro(false), HasCommaPasting(false), IsDisabled(false), IsUsed(false), IsAllowRedefinitionsWithoutWarning(false), IsWarnIfUnused(false), FromASTFile(false), UsedForHeaderGuard(false) { } unsigned MacroInfo::getDefinitionLengthSlow(SourceManager &SM) const { assert(!IsDefinitionLengthCached); IsDefinitionLengthCached = true; if (ReplacementTokens.empty()) return (DefinitionLength = 0); const Token &firstToken = ReplacementTokens.front(); const Token &lastToken = ReplacementTokens.back(); SourceLocation macroStart = firstToken.getLocation(); SourceLocation macroEnd = lastToken.getLocation(); assert(macroStart.isValid() && macroEnd.isValid()); assert((macroStart.isFileID() || firstToken.is(tok::comment)) && "Macro defined in macro?"); assert((macroEnd.isFileID() || lastToken.is(tok::comment)) && "Macro defined in macro?"); std::pair<FileID, unsigned> startInfo = SM.getDecomposedExpansionLoc(macroStart); std::pair<FileID, unsigned> endInfo = SM.getDecomposedExpansionLoc(macroEnd); assert(startInfo.first == endInfo.first && "Macro definition spanning multiple FileIDs ?"); assert(startInfo.second <= endInfo.second); DefinitionLength = endInfo.second - startInfo.second; DefinitionLength += lastToken.getLength(); return DefinitionLength; } /// \brief Return true if the specified macro definition is equal to /// this macro in spelling, arguments, and whitespace. /// /// \param Syntactically if true, the macro definitions can be identical even /// if they use different identifiers for the function macro parameters. /// Otherwise the comparison is lexical and this implements the rules in /// C99 6.10.3. bool MacroInfo::isIdenticalTo(const MacroInfo &Other, Preprocessor &PP, bool Syntactically) const { bool Lexically = !Syntactically; // Check # tokens in replacement, number of args, and various flags all match. if (ReplacementTokens.size() != Other.ReplacementTokens.size() || getNumArgs() != Other.getNumArgs() || isFunctionLike() != Other.isFunctionLike() || isC99Varargs() != Other.isC99Varargs() || isGNUVarargs() != Other.isGNUVarargs()) return false; if (Lexically) { // Check arguments. for (arg_iterator I = arg_begin(), OI = Other.arg_begin(), E = arg_end(); I != E; ++I, ++OI) if (*I != *OI) return false; } // Check all the tokens. for (unsigned i = 0, e = ReplacementTokens.size(); i != e; ++i) { const Token &A = ReplacementTokens[i]; const Token &B = Other.ReplacementTokens[i]; if (A.getKind() != B.getKind()) return false; // If this isn't the first first token, check that the whitespace and // start-of-line characteristics match. if (i != 0 && (A.isAtStartOfLine() != B.isAtStartOfLine() || A.hasLeadingSpace() != B.hasLeadingSpace())) return false; // If this is an identifier, it is easy. if (A.getIdentifierInfo() || B.getIdentifierInfo()) { if (A.getIdentifierInfo() == B.getIdentifierInfo()) continue; if (Lexically) return false; // With syntactic equivalence the parameter names can be different as long // as they are used in the same place. int AArgNum = getArgumentNum(A.getIdentifierInfo()); if (AArgNum == -1) return false; if (AArgNum != Other.getArgumentNum(B.getIdentifierInfo())) return false; continue; } // Otherwise, check the spelling. if (PP.getSpelling(A) != PP.getSpelling(B)) return false; } return true; } void MacroInfo::dump() const { llvm::raw_ostream &Out = llvm::errs(); // FIXME: Dump locations. Out << "MacroInfo " << this; if (IsBuiltinMacro) Out << " builtin"; if (IsDisabled) Out << " disabled"; if (IsUsed) Out << " used"; if (IsAllowRedefinitionsWithoutWarning) Out << " allow_redefinitions_without_warning"; if (IsWarnIfUnused) Out << " warn_if_unused"; if (FromASTFile) Out << " imported"; if (UsedForHeaderGuard) Out << " header_guard"; Out << "\n #define <macro>"; if (IsFunctionLike) { Out << "("; for (unsigned I = 0; I != NumArguments; ++I) { if (I) Out << ", "; Out << ArgumentList[I]->getName(); } if (IsC99Varargs || IsGNUVarargs) { if (NumArguments && IsC99Varargs) Out << ", "; Out << "..."; } Out << ")"; } for (const Token &Tok : ReplacementTokens) { Out << " "; if (const char *Punc = tok::getPunctuatorSpelling(Tok.getKind())) Out << Punc; else if (const char *Kwd = tok::getKeywordSpelling(Tok.getKind())) Out << Kwd; else if (Tok.is(tok::identifier)) Out << Tok.getIdentifierInfo()->getName(); else if (Tok.isLiteral() && Tok.getLiteralData()) Out << StringRef(Tok.getLiteralData(), Tok.getLength()); else Out << Tok.getName(); } } MacroDirective::DefInfo MacroDirective::getDefinition() { MacroDirective *MD = this; SourceLocation UndefLoc; Optional<bool> isPublic; for (; MD; MD = MD->getPrevious()) { if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) return DefInfo(DefMD, UndefLoc, !isPublic.hasValue() || isPublic.getValue()); if (UndefMacroDirective *UndefMD = dyn_cast<UndefMacroDirective>(MD)) { UndefLoc = UndefMD->getLocation(); continue; } VisibilityMacroDirective *VisMD = cast<VisibilityMacroDirective>(MD); if (!isPublic.hasValue()) isPublic = VisMD->isPublic(); } return DefInfo(nullptr, UndefLoc, !isPublic.hasValue() || isPublic.getValue()); } const MacroDirective::DefInfo MacroDirective::findDirectiveAtLoc(SourceLocation L, SourceManager &SM) const { assert(L.isValid() && "SourceLocation is invalid."); for (DefInfo Def = getDefinition(); Def; Def = Def.getPreviousDefinition()) { if (Def.getLocation().isInvalid() || // For macros defined on the command line. SM.isBeforeInTranslationUnit(Def.getLocation(), L)) return (!Def.isUndefined() || SM.isBeforeInTranslationUnit(L, Def.getUndefLocation())) ? Def : DefInfo(); } return DefInfo(); } void MacroDirective::dump() const { llvm::raw_ostream &Out = llvm::errs(); switch (getKind()) { case MD_Define: Out << "DefMacroDirective"; break; case MD_Undefine: Out << "UndefMacroDirective"; break; case MD_Visibility: Out << "VisibilityMacroDirective"; break; } Out << " " << this; // FIXME: Dump SourceLocation. if (auto *Prev = getPrevious()) Out << " prev " << Prev; if (IsFromPCH) Out << " from_pch"; if (isa<VisibilityMacroDirective>(this)) Out << (IsPublic ? " public" : " private"); if (auto *DMD = dyn_cast<DefMacroDirective>(this)) { if (auto *Info = DMD->getInfo()) { Out << "\n "; Info->dump(); } } Out << "\n"; } ModuleMacro *ModuleMacro::create(Preprocessor &PP, Module *OwningModule, IdentifierInfo *II, MacroInfo *Macro, ArrayRef<ModuleMacro *> Overrides) { void *Mem = PP.getPreprocessorAllocator().Allocate( sizeof(ModuleMacro) + sizeof(ModuleMacro *) * Overrides.size(), llvm::alignOf<ModuleMacro>()); return new (Mem) ModuleMacro(OwningModule, II, Macro, Overrides); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/PTHLexer.cpp
//===--- PTHLexer.cpp - Lex from a token stream ---------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PTHLexer interface. // //===----------------------------------------------------------------------===// #include "clang/Lex/PTHLexer.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemStatCache.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/TokenKinds.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/PTHManager.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/EndianStream.h" #include "llvm/Support/MemoryBuffer.h" #include <memory> #include <system_error> using namespace clang; static const unsigned StoredTokenSize = 1 + 1 + 2 + 4 + 4; //===----------------------------------------------------------------------===// // PTHLexer methods. //===----------------------------------------------------------------------===// PTHLexer::PTHLexer(Preprocessor &PP, FileID FID, const unsigned char *D, const unsigned char *ppcond, PTHManager &PM) : PreprocessorLexer(&PP, FID), TokBuf(D), CurPtr(D), LastHashTokPtr(nullptr), PPCond(ppcond), CurPPCondPtr(ppcond), PTHMgr(PM) { FileStartLoc = PP.getSourceManager().getLocForStartOfFile(FID); } bool PTHLexer::Lex(Token& Tok) { //===--------------------------------------==// // Read the raw token data. //===--------------------------------------==// using namespace llvm::support; // Shadow CurPtr into an automatic variable. const unsigned char *CurPtrShadow = CurPtr; // Read in the data for the token. unsigned Word0 = endian::readNext<uint32_t, little, aligned>(CurPtrShadow); uint32_t IdentifierID = endian::readNext<uint32_t, little, aligned>(CurPtrShadow); uint32_t FileOffset = endian::readNext<uint32_t, little, aligned>(CurPtrShadow); tok::TokenKind TKind = (tok::TokenKind) (Word0 & 0xFF); Token::TokenFlags TFlags = (Token::TokenFlags) ((Word0 >> 8) & 0xFF); uint32_t Len = Word0 >> 16; CurPtr = CurPtrShadow; //===--------------------------------------==// // Construct the token itself. //===--------------------------------------==// Tok.startToken(); Tok.setKind(TKind); Tok.setFlag(TFlags); assert(!LexingRawMode); Tok.setLocation(FileStartLoc.getLocWithOffset(FileOffset)); Tok.setLength(Len); // Handle identifiers. if (Tok.isLiteral()) { Tok.setLiteralData((const char*) (PTHMgr.SpellingBase + IdentifierID)); } else if (IdentifierID) { MIOpt.ReadToken(); IdentifierInfo *II = PTHMgr.GetIdentifierInfo(IdentifierID-1); Tok.setIdentifierInfo(II); // Change the kind of this identifier to the appropriate token kind, e.g. // turning "for" into a keyword. Tok.setKind(II->getTokenID()); if (II->isHandleIdentifierCase()) return PP->HandleIdentifier(Tok); return true; } //===--------------------------------------==// // Process the token. //===--------------------------------------==// if (TKind == tok::eof) { // Save the end-of-file token. EofToken = Tok; assert(!ParsingPreprocessorDirective); assert(!LexingRawMode); return LexEndOfFile(Tok); } if (TKind == tok::hash && Tok.isAtStartOfLine()) { LastHashTokPtr = CurPtr - StoredTokenSize; assert(!LexingRawMode); PP->HandleDirective(Tok); return false; } if (TKind == tok::eod) { assert(ParsingPreprocessorDirective); ParsingPreprocessorDirective = false; return true; } MIOpt.ReadToken(); return true; } bool PTHLexer::LexEndOfFile(Token &Result) { // If we hit the end of the file while parsing a preprocessor directive, // end the preprocessor directive first. The next token returned will // then be the end of file. if (ParsingPreprocessorDirective) { ParsingPreprocessorDirective = false; // Done parsing the "line". return true; // Have a token. } assert(!LexingRawMode); // If we are in a #if directive, emit an error. while (!ConditionalStack.empty()) { if (PP->getCodeCompletionFileLoc() != FileStartLoc) PP->Diag(ConditionalStack.back().IfLoc, diag::err_pp_unterminated_conditional); ConditionalStack.pop_back(); } // Finally, let the preprocessor handle this. return PP->HandleEndOfFile(Result); } // FIXME: We can just grab the last token instead of storing a copy // into EofToken. void PTHLexer::getEOF(Token& Tok) { assert(EofToken.is(tok::eof)); Tok = EofToken; } void PTHLexer::DiscardToEndOfLine() { assert(ParsingPreprocessorDirective && ParsingFilename == false && "Must be in a preprocessing directive!"); // We assume that if the preprocessor wishes to discard to the end of // the line that it also means to end the current preprocessor directive. ParsingPreprocessorDirective = false; // Skip tokens by only peeking at their token kind and the flags. // We don't need to actually reconstruct full tokens from the token buffer. // This saves some copies and it also reduces IdentifierInfo* lookup. const unsigned char* p = CurPtr; while (1) { // Read the token kind. Are we at the end of the file? tok::TokenKind x = (tok::TokenKind) (uint8_t) *p; if (x == tok::eof) break; // Read the token flags. Are we at the start of the next line? Token::TokenFlags y = (Token::TokenFlags) (uint8_t) p[1]; if (y & Token::StartOfLine) break; // Skip to the next token. p += StoredTokenSize; } CurPtr = p; } /// SkipBlock - Used by Preprocessor to skip the current conditional block. bool PTHLexer::SkipBlock() { using namespace llvm::support; assert(CurPPCondPtr && "No cached PP conditional information."); assert(LastHashTokPtr && "No known '#' token."); const unsigned char *HashEntryI = nullptr; uint32_t TableIdx; do { // Read the token offset from the side-table. uint32_t Offset = endian::readNext<uint32_t, little, aligned>(CurPPCondPtr); // Read the target table index from the side-table. TableIdx = endian::readNext<uint32_t, little, aligned>(CurPPCondPtr); // Compute the actual memory address of the '#' token data for this entry. HashEntryI = TokBuf + Offset; // Optmization: "Sibling jumping". #if...#else...#endif blocks can // contain nested blocks. In the side-table we can jump over these // nested blocks instead of doing a linear search if the next "sibling" // entry is not at a location greater than LastHashTokPtr. if (HashEntryI < LastHashTokPtr && TableIdx) { // In the side-table we are still at an entry for a '#' token that // is earlier than the last one we saw. Check if the location we would // stride gets us closer. const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2); assert(NextPPCondPtr >= CurPPCondPtr); // Read where we should jump to. const unsigned char *HashEntryJ = TokBuf + endian::readNext<uint32_t, little, aligned>(NextPPCondPtr); if (HashEntryJ <= LastHashTokPtr) { // Jump directly to the next entry in the side table. HashEntryI = HashEntryJ; TableIdx = endian::readNext<uint32_t, little, aligned>(NextPPCondPtr); CurPPCondPtr = NextPPCondPtr; } } } while (HashEntryI < LastHashTokPtr); assert(HashEntryI == LastHashTokPtr && "No PP-cond entry found for '#'"); assert(TableIdx && "No jumping from #endifs."); // Update our side-table iterator. const unsigned char* NextPPCondPtr = PPCond + TableIdx*(sizeof(uint32_t)*2); assert(NextPPCondPtr >= CurPPCondPtr); CurPPCondPtr = NextPPCondPtr; // Read where we should jump to. HashEntryI = TokBuf + endian::readNext<uint32_t, little, aligned>(NextPPCondPtr); uint32_t NextIdx = endian::readNext<uint32_t, little, aligned>(NextPPCondPtr); // By construction NextIdx will be zero if this is a #endif. This is useful // to know to obviate lexing another token. bool isEndif = NextIdx == 0; // This case can occur when we see something like this: // // #if ... // /* a comment or nothing */ // #elif // // If we are skipping the first #if block it will be the case that CurPtr // already points 'elif'. Just return. if (CurPtr > HashEntryI) { assert(CurPtr == HashEntryI + StoredTokenSize); // Did we reach a #endif? If so, go ahead and consume that token as well. if (isEndif) CurPtr += StoredTokenSize * 2; else LastHashTokPtr = HashEntryI; return isEndif; } // Otherwise, we need to advance. Update CurPtr to point to the '#' token. CurPtr = HashEntryI; // Update the location of the last observed '#'. This is useful if we // are skipping multiple blocks. LastHashTokPtr = CurPtr; // Skip the '#' token. assert(((tok::TokenKind)*CurPtr) == tok::hash); CurPtr += StoredTokenSize; // Did we reach a #endif? If so, go ahead and consume that token as well. if (isEndif) { CurPtr += StoredTokenSize * 2; } return isEndif; } SourceLocation PTHLexer::getSourceLocation() { // getSourceLocation is not on the hot path. It is used to get the location // of the next token when transitioning back to this lexer when done // handling a #included file. Just read the necessary data from the token // data buffer to construct the SourceLocation object. // NOTE: This is a virtual function; hence it is defined out-of-line. using namespace llvm::support; const unsigned char *OffsetPtr = CurPtr + (StoredTokenSize - 4); uint32_t Offset = endian::readNext<uint32_t, little, aligned>(OffsetPtr); return FileStartLoc.getLocWithOffset(Offset); } //===----------------------------------------------------------------------===// // PTH file lookup: map from strings to file data. //===----------------------------------------------------------------------===// /// PTHFileLookup - This internal data structure is used by the PTHManager /// to map from FileEntry objects managed by FileManager to offsets within /// the PTH file. namespace { class PTHFileData { const uint32_t TokenOff; const uint32_t PPCondOff; public: PTHFileData(uint32_t tokenOff, uint32_t ppCondOff) : TokenOff(tokenOff), PPCondOff(ppCondOff) {} uint32_t getTokenOffset() const { return TokenOff; } uint32_t getPPCondOffset() const { return PPCondOff; } }; class PTHFileLookupCommonTrait { public: typedef std::pair<unsigned char, const char*> internal_key_type; typedef unsigned hash_value_type; typedef unsigned offset_type; static hash_value_type ComputeHash(internal_key_type x) { return llvm::HashString(x.second); } static std::pair<unsigned, unsigned> ReadKeyDataLength(const unsigned char*& d) { using namespace llvm::support; unsigned keyLen = (unsigned)endian::readNext<uint16_t, little, unaligned>(d); unsigned dataLen = (unsigned) *(d++); return std::make_pair(keyLen, dataLen); } static internal_key_type ReadKey(const unsigned char* d, unsigned) { unsigned char k = *(d++); // Read the entry kind. return std::make_pair(k, (const char*) d); } }; } // end anonymous namespace class PTHManager::PTHFileLookupTrait : public PTHFileLookupCommonTrait { public: typedef const FileEntry* external_key_type; typedef PTHFileData data_type; static internal_key_type GetInternalKey(const FileEntry* FE) { return std::make_pair((unsigned char) 0x1, FE->getName()); } static bool EqualKey(internal_key_type a, internal_key_type b) { return a.first == b.first && strcmp(a.second, b.second) == 0; } static PTHFileData ReadData(const internal_key_type& k, const unsigned char* d, unsigned) { assert(k.first == 0x1 && "Only file lookups can match!"); using namespace llvm::support; uint32_t x = endian::readNext<uint32_t, little, unaligned>(d); uint32_t y = endian::readNext<uint32_t, little, unaligned>(d); return PTHFileData(x, y); } }; class PTHManager::PTHStringLookupTrait { public: typedef uint32_t data_type; typedef const std::pair<const char*, unsigned> external_key_type; typedef external_key_type internal_key_type; typedef uint32_t hash_value_type; typedef unsigned offset_type; static bool EqualKey(const internal_key_type& a, const internal_key_type& b) { return (a.second == b.second) ? memcmp(a.first, b.first, a.second) == 0 : false; } static hash_value_type ComputeHash(const internal_key_type& a) { return llvm::HashString(StringRef(a.first, a.second)); } // This hopefully will just get inlined and removed by the optimizer. static const internal_key_type& GetInternalKey(const external_key_type& x) { return x; } static std::pair<unsigned, unsigned> ReadKeyDataLength(const unsigned char*& d) { using namespace llvm::support; return std::make_pair( (unsigned)endian::readNext<uint16_t, little, unaligned>(d), sizeof(uint32_t)); } static std::pair<const char*, unsigned> ReadKey(const unsigned char* d, unsigned n) { assert(n >= 2 && d[n-1] == '\0'); return std::make_pair((const char*) d, n-1); } static uint32_t ReadData(const internal_key_type& k, const unsigned char* d, unsigned) { using namespace llvm::support; return endian::readNext<uint32_t, little, unaligned>(d); } }; //===----------------------------------------------------------------------===// // PTHManager methods. //===----------------------------------------------------------------------===// PTHManager::PTHManager( std::unique_ptr<const llvm::MemoryBuffer> buf, std::unique_ptr<PTHFileLookup> fileLookup, const unsigned char *idDataTable, std::unique_ptr<IdentifierInfo *[], llvm::FreeDeleter> perIDCache, std::unique_ptr<PTHStringIdLookup> stringIdLookup, unsigned numIds, const unsigned char *spellingBase, const char *originalSourceFile) : Buf(std::move(buf)), PerIDCache(std::move(perIDCache)), FileLookup(std::move(fileLookup)), IdDataTable(idDataTable), StringIdLookup(std::move(stringIdLookup)), NumIds(numIds), PP(nullptr), SpellingBase(spellingBase), OriginalSourceFile(originalSourceFile) {} PTHManager::~PTHManager() { } static void InvalidPTH(DiagnosticsEngine &Diags, const char *Msg) { Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0")) << Msg; } PTHManager *PTHManager::Create(StringRef file, DiagnosticsEngine &Diags) { // Memory map the PTH file. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileOrErr = llvm::MemoryBuffer::getFile(file); if (!FileOrErr) { // FIXME: Add ec.message() to this diag. Diags.Report(diag::err_invalid_pth_file) << file; return nullptr; } std::unique_ptr<llvm::MemoryBuffer> File = std::move(FileOrErr.get()); using namespace llvm::support; // Get the buffer ranges and check if there are at least three 32-bit // words at the end of the file. const unsigned char *BufBeg = (const unsigned char*)File->getBufferStart(); const unsigned char *BufEnd = (const unsigned char*)File->getBufferEnd(); // Check the prologue of the file. if ((BufEnd - BufBeg) < (signed)(sizeof("cfe-pth") + 4 + 4) || memcmp(BufBeg, "cfe-pth", sizeof("cfe-pth")) != 0) { Diags.Report(diag::err_invalid_pth_file) << file; return nullptr; } // Read the PTH version. const unsigned char *p = BufBeg + (sizeof("cfe-pth")); unsigned Version = endian::readNext<uint32_t, little, aligned>(p); if (Version < PTHManager::Version) { InvalidPTH(Diags, Version < PTHManager::Version ? "PTH file uses an older PTH format that is no longer supported" : "PTH file uses a newer PTH format that cannot be read"); return nullptr; } // Compute the address of the index table at the end of the PTH file. const unsigned char *PrologueOffset = p; if (PrologueOffset >= BufEnd) { Diags.Report(diag::err_invalid_pth_file) << file; return nullptr; } // Construct the file lookup table. This will be used for mapping from // FileEntry*'s to cached tokens. const unsigned char* FileTableOffset = PrologueOffset + sizeof(uint32_t)*2; const unsigned char *FileTable = BufBeg + endian::readNext<uint32_t, little, aligned>(FileTableOffset); if (!(FileTable > BufBeg && FileTable < BufEnd)) { Diags.Report(diag::err_invalid_pth_file) << file; return nullptr; // FIXME: Proper error diagnostic? } std::unique_ptr<PTHFileLookup> FL(PTHFileLookup::Create(FileTable, BufBeg)); // Warn if the PTH file is empty. We still want to create a PTHManager // as the PTH could be used with -include-pth. if (FL->isEmpty()) InvalidPTH(Diags, "PTH file contains no cached source data"); // Get the location of the table mapping from persistent ids to the // data needed to reconstruct identifiers. const unsigned char* IDTableOffset = PrologueOffset + sizeof(uint32_t)*0; const unsigned char *IData = BufBeg + endian::readNext<uint32_t, little, aligned>(IDTableOffset); if (!(IData >= BufBeg && IData < BufEnd)) { Diags.Report(diag::err_invalid_pth_file) << file; return nullptr; } // Get the location of the hashtable mapping between strings and // persistent IDs. const unsigned char* StringIdTableOffset = PrologueOffset + sizeof(uint32_t)*1; const unsigned char *StringIdTable = BufBeg + endian::readNext<uint32_t, little, aligned>(StringIdTableOffset); if (!(StringIdTable >= BufBeg && StringIdTable < BufEnd)) { Diags.Report(diag::err_invalid_pth_file) << file; return nullptr; } std::unique_ptr<PTHStringIdLookup> SL( PTHStringIdLookup::Create(StringIdTable, BufBeg)); // Get the location of the spelling cache. const unsigned char* spellingBaseOffset = PrologueOffset + sizeof(uint32_t)*3; const unsigned char *spellingBase = BufBeg + endian::readNext<uint32_t, little, aligned>(spellingBaseOffset); if (!(spellingBase >= BufBeg && spellingBase < BufEnd)) { Diags.Report(diag::err_invalid_pth_file) << file; return nullptr; } // Get the number of IdentifierInfos and pre-allocate the identifier cache. uint32_t NumIds = endian::readNext<uint32_t, little, aligned>(IData); // Pre-allocate the persistent ID -> IdentifierInfo* cache. We use calloc() // so that we in the best case only zero out memory once when the OS returns // us new pages. std::unique_ptr<IdentifierInfo *[], llvm::FreeDeleter> PerIDCache; if (NumIds) { PerIDCache.reset((IdentifierInfo **)calloc(NumIds, sizeof(PerIDCache[0]))); if (!PerIDCache) { InvalidPTH(Diags, "Could not allocate memory for processing PTH file"); return nullptr; } } // Compute the address of the original source file. const unsigned char* originalSourceBase = PrologueOffset + sizeof(uint32_t)*4; unsigned len = endian::readNext<uint16_t, little, unaligned>(originalSourceBase); if (!len) originalSourceBase = nullptr; // Create the new PTHManager. return new PTHManager(std::move(File), std::move(FL), IData, std::move(PerIDCache), std::move(SL), NumIds, spellingBase, (const char *)originalSourceBase); } IdentifierInfo* PTHManager::LazilyCreateIdentifierInfo(unsigned PersistentID) { using namespace llvm::support; // Look in the PTH file for the string data for the IdentifierInfo object. const unsigned char* TableEntry = IdDataTable + sizeof(uint32_t)*PersistentID; const unsigned char *IDData = (const unsigned char *)Buf->getBufferStart() + endian::readNext<uint32_t, little, aligned>(TableEntry); assert(IDData < (const unsigned char*)Buf->getBufferEnd()); // Allocate the object. std::pair<IdentifierInfo,const unsigned char*> *Mem = Alloc.Allocate<std::pair<IdentifierInfo,const unsigned char*> >(); Mem->second = IDData; assert(IDData[0] != '\0'); IdentifierInfo *II = new ((void*) Mem) IdentifierInfo(); // Store the new IdentifierInfo in the cache. PerIDCache[PersistentID] = II; assert(II->getNameStart() && II->getNameStart()[0] != '\0'); return II; } IdentifierInfo* PTHManager::get(StringRef Name) { // Double check our assumption that the last character isn't '\0'. assert(Name.empty() || Name.back() != '\0'); PTHStringIdLookup::iterator I = StringIdLookup->find(std::make_pair(Name.data(), Name.size())); if (I == StringIdLookup->end()) // No identifier found? return nullptr; // Match found. Return the identifier! assert(*I > 0); return GetIdentifierInfo(*I-1); } PTHLexer *PTHManager::CreateLexer(FileID FID) { const FileEntry *FE = PP->getSourceManager().getFileEntryForID(FID); if (!FE) return nullptr; using namespace llvm::support; // Lookup the FileEntry object in our file lookup data structure. It will // return a variant that indicates whether or not there is an offset within // the PTH file that contains cached tokens. PTHFileLookup::iterator I = FileLookup->find(FE); if (I == FileLookup->end()) // No tokens available? return nullptr; const PTHFileData& FileData = *I; const unsigned char *BufStart = (const unsigned char *)Buf->getBufferStart(); // Compute the offset of the token data within the buffer. const unsigned char* data = BufStart + FileData.getTokenOffset(); // Get the location of pp-conditional table. const unsigned char* ppcond = BufStart + FileData.getPPCondOffset(); uint32_t Len = endian::readNext<uint32_t, little, aligned>(ppcond); if (Len == 0) ppcond = nullptr; assert(PP && "No preprocessor set yet!"); return new PTHLexer(*PP, FID, data, ppcond, *this); } //===----------------------------------------------------------------------===// // 'stat' caching. //===----------------------------------------------------------------------===// namespace { class PTHStatData { public: const bool HasData; uint64_t Size; time_t ModTime; llvm::sys::fs::UniqueID UniqueID; bool IsDirectory; PTHStatData(uint64_t Size, time_t ModTime, llvm::sys::fs::UniqueID UniqueID, bool IsDirectory) : HasData(true), Size(Size), ModTime(ModTime), UniqueID(UniqueID), IsDirectory(IsDirectory) {} PTHStatData() : HasData(false) {} }; class PTHStatLookupTrait : public PTHFileLookupCommonTrait { public: typedef const char* external_key_type; // const char* typedef PTHStatData data_type; static internal_key_type GetInternalKey(const char *path) { // The key 'kind' doesn't matter here because it is ignored in EqualKey. return std::make_pair((unsigned char) 0x0, path); } static bool EqualKey(internal_key_type a, internal_key_type b) { // When doing 'stat' lookups we don't care about the kind of 'a' and 'b', // just the paths. return strcmp(a.second, b.second) == 0; } static data_type ReadData(const internal_key_type& k, const unsigned char* d, unsigned) { if (k.first /* File or Directory */) { bool IsDirectory = true; if (k.first == 0x1 /* File */) { IsDirectory = false; d += 4 * 2; // Skip the first 2 words. } using namespace llvm::support; uint64_t File = endian::readNext<uint64_t, little, unaligned>(d); uint64_t Device = endian::readNext<uint64_t, little, unaligned>(d); llvm::sys::fs::UniqueID UniqueID(Device, File); time_t ModTime = endian::readNext<uint64_t, little, unaligned>(d); uint64_t Size = endian::readNext<uint64_t, little, unaligned>(d); return data_type(Size, ModTime, UniqueID, IsDirectory); } // Negative stat. Don't read anything. return data_type(); } }; } // end anonymous namespace namespace clang { class PTHStatCache : public FileSystemStatCache { typedef llvm::OnDiskChainedHashTable<PTHStatLookupTrait> CacheTy; CacheTy Cache; public: PTHStatCache(PTHManager::PTHFileLookup &FL) : Cache(FL.getNumBuckets(), FL.getNumEntries(), FL.getBuckets(), FL.getBase()) {} LookupResult getStat(const char *Path, FileData &Data, bool isFile, std::unique_ptr<vfs::File> *F, vfs::FileSystem &FS) override { // Do the lookup for the file's data in the PTH file. CacheTy::iterator I = Cache.find(Path); // If we don't get a hit in the PTH file just forward to 'stat'. if (I == Cache.end()) return statChained(Path, Data, isFile, F, FS); const PTHStatData &D = *I; if (!D.HasData) return CacheMissing; Data.Name = Path; Data.Size = D.Size; Data.ModTime = D.ModTime; Data.UniqueID = D.UniqueID; Data.IsDirectory = D.IsDirectory; Data.IsNamedPipe = false; Data.InPCH = true; return CacheExists; } }; } std::unique_ptr<FileSystemStatCache> PTHManager::createStatCache() { return llvm::make_unique<PTHStatCache>(*FileLookup); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/HLSLMacroExpander.cpp
//===--- HLSLMacroExpander.cpp - Standalone Macro expansion -----*- C++ -*-===// // // // HLSLMacroExpander.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the MacroExpander class. // //===----------------------------------------------------------------------===// #include "clang/Lex/HLSLMacroExpander.h" #include "clang/Basic/SourceLocation.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/ModuleMap.h" #include "clang/Lex/PPCallbacks.h" #include "clang/Lex/PTHLexer.h" #include "clang/Lex/PTHManager.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" #include "clang/Lex/TokenLexer.h" #include "llvm/ADT/StringRef.h" #include "dxc/Support/Global.h" using namespace clang; using namespace llvm; using namespace hlsl; MacroExpander::MacroExpander(Preprocessor &PP_, unsigned options) : PP(PP_), m_expansionFileId(), m_stripQuotes(false) { if (options & STRIP_QUOTES) m_stripQuotes = true; // The preprocess requires a file to be on the lexing stack when we // call ExpandMacro. We add an empty in-memory buffer that we use // just for expanding macros. std::unique_ptr<llvm::MemoryBuffer> SB = llvm::MemoryBuffer::getMemBuffer("", "<hlsl-semantic-defines>"); if (!SB) { DXASSERT(false, "Cannot create macro expansion source buffer"); throw hlsl::Exception(DXC_E_MACRO_EXPANSION_FAILURE); } // Unfortunately, there is no api in the SourceManager to lookup a // previously added file, so we have to add the empty file every time // we expand macros. We could modify source manager to get/set the // macro file id similar to the one we have for getPreambleFileID. // Macros should only be expanded once (if needed for a root signature) // or twice (for semantic defines) so adding an empty file every time // is probably not a big deal. m_expansionFileId = PP.getSourceManager().createFileID(std::move(SB)); if (m_expansionFileId.isInvalid()) { DXASSERT(false, "Could not create FileID for macro expnasion?"); throw hlsl::Exception(DXC_E_MACRO_EXPANSION_FAILURE); } } // Simple struct to hold a data/length pair. struct LiteralData { const char *Data; unsigned Length; }; // Get the literal data from a literal token. // If stripQuotes flag is true the quotes (and string literal type) will // be removed from the data and only the raw string literal value will be // returned. static LiteralData GetLiteralData(const Token &Tok, bool stripQuotes) { if (!tok::isStringLiteral(Tok.getKind())) return LiteralData{Tok.getLiteralData(), Tok.getLength()}; unsigned start_offset = 0; unsigned end_offset = 0; switch (Tok.getKind()) { case tok::string_literal: start_offset = 1; end_offset = 1; break; // "foo" case tok::wide_string_literal: start_offset = 2; end_offset = 1; break; // L"foo" case tok::utf8_string_literal: start_offset = 3; end_offset = 1; break; // u8"foo" case tok::utf16_string_literal: start_offset = 2; end_offset = 1; break; // u"foo" case tok::utf32_string_literal: start_offset = 2; end_offset = 1; break; // U"foo" default: break; } unsigned length = Tok.getLength() - (start_offset + end_offset); if (length > Tok.getLength()) { // Check for unsigned underflow. DXASSERT(false, "string literal quote count is wrong?"); start_offset = 0; length = Tok.getLength(); } return LiteralData{Tok.getLiteralData() + start_offset, length}; } // Print leading spaces if needed by the token. // Take care when stripping string literal quoates that we do not add extra // spaces to the output. static bool ShouldPrintLeadingSpace(const Token &Tok, const Token &PrevTok, bool stripQuotes) { if (!Tok.hasLeadingSpace()) return false; // Token has leading spaces, but the previous token was a sting literal // and we are stripping quotes to paste the strings together so do not // add a space between the string literal values. if (tok::isStringLiteral(PrevTok.getKind()) && stripQuotes) return false; return true; } // Macro expansion implementation. // We re-lex the macro using the preprocessors lexer. bool MacroExpander::ExpandMacro(MacroInfo *pMacro, std::string *out) { if (!pMacro || !out) return false; MacroInfo &macro = *pMacro; // Initialize the token from the macro definition location. Token Tok; bool failed = PP.getRawToken(macro.getDefinitionLoc(), Tok); if (failed) return false; // Start the lexing process. Use an outer file to make the preprocessor happy. PP.EnterSourceFile( m_expansionFileId, nullptr, PP.getSourceManager().getLocForStartOfFile(m_expansionFileId)); PP.EnterMacro(Tok, macro.getDefinitionEndLoc(), &macro, nullptr); PP.Lex(Tok); llvm::raw_string_ostream OS(*out); // Keep track of previous token to print spaces correctly. Token PrevTok; PrevTok.startToken(); // Lex all the tokens from the macro and add them to the output. while (!Tok.is(tok::eof)) { if (ShouldPrintLeadingSpace(Tok, PrevTok, m_stripQuotes)) { OS << ' '; } if (IdentifierInfo *II = Tok.getIdentifierInfo()) { OS << II->getName(); } else if (Tok.isLiteral() && !Tok.needsCleaning() && Tok.getLiteralData()) { LiteralData literalData = GetLiteralData(Tok, m_stripQuotes); OS.write(literalData.Data, literalData.Length); } else { std::string S = PP.getSpelling(Tok); OS.write(&S[0], S.size()); } PrevTok = Tok; PP.Lex(Tok); } return true; } // Search for the macro info by the given name. MacroInfo *MacroExpander::FindMacroInfo(clang::Preprocessor &PP, StringRef macroName) { // Lookup macro identifier. IdentifierInfo *ii = PP.getIdentifierInfo(macroName); if (!ii) return nullptr; // Lookup macro info. return PP.getMacroInfo(ii); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/ModuleMap.cpp
//===--- ModuleMap.cpp - Describe the layout of modules ---------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the ModuleMap implementation, which describes the layout // of a module as it relates to headers. // //===----------------------------------------------------------------------===// #include "clang/Lex/ModuleMap.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/LiteralSupport.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <stdlib.h> #if defined(LLVM_ON_UNIX) #include <limits.h> #endif using namespace clang; // // /////////////////////////////////////////////////////////////////////////////// Module::ExportDecl ModuleMap::resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved, bool Complain) const { // We may have just a wildcard. if (Unresolved.Id.empty()) { assert(Unresolved.Wildcard && "Invalid unresolved export"); return Module::ExportDecl(nullptr, true); } // Resolve the module-id. Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain); if (!Context) return Module::ExportDecl(); return Module::ExportDecl(Context, Unresolved.Wildcard); } Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const { // Find the starting module. Module *Context = lookupModuleUnqualified(Id[0].first, Mod); if (!Context) { if (Complain) Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified) << Id[0].first << Mod->getFullModuleName(); return nullptr; } // Dig into the module path. for (unsigned I = 1, N = Id.size(); I != N; ++I) { Module *Sub = lookupModuleQualified(Id[I].first, Context); if (!Sub) { if (Complain) Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified) << Id[I].first << Context->getFullModuleName() << SourceRange(Id[0].second, Id[I-1].second); return nullptr; } Context = Sub; } return Context; } ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target, HeaderSearch &HeaderInfo) : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target), HeaderInfo(HeaderInfo), BuiltinIncludeDir(nullptr), CompilingModule(nullptr), SourceModule(nullptr), NumCreatedModules(0) { #ifdef MS_SUPPORT_VARIABLE_LANGOPTS MMapLangOpts.LineComment = true; #endif } ModuleMap::~ModuleMap() { for (llvm::StringMap<Module *>::iterator I = Modules.begin(), IEnd = Modules.end(); I != IEnd; ++I) { delete I->getValue(); } } void ModuleMap::setTarget(const TargetInfo &Target) { assert((!this->Target || this->Target == &Target) && "Improper target override"); this->Target = &Target; } /// \brief "Sanitize" a filename so that it can be used as an identifier. static StringRef sanitizeFilenameAsIdentifier(StringRef Name, SmallVectorImpl<char> &Buffer) { if (Name.empty()) return Name; if (!isValidIdentifier(Name)) { // If we don't already have something with the form of an identifier, // create a buffer with the sanitized name. Buffer.clear(); if (isDigit(Name[0])) Buffer.push_back('_'); Buffer.reserve(Buffer.size() + Name.size()); for (unsigned I = 0, N = Name.size(); I != N; ++I) { if (isIdentifierBody(Name[I])) Buffer.push_back(Name[I]); else Buffer.push_back('_'); } Name = StringRef(Buffer.data(), Buffer.size()); } while (llvm::StringSwitch<bool>(Name) #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true) #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true) #include "clang/Basic/TokenKinds.def" .Default(false)) { if (Name.data() != Buffer.data()) Buffer.append(Name.begin(), Name.end()); Buffer.push_back('_'); Name = StringRef(Buffer.data(), Buffer.size()); } return Name; } /// \brief Determine whether the given file name is the name of a builtin /// header, supplied by Clang to replace, override, or augment existing system /// headers. static bool isBuiltinHeader(StringRef FileName) { return llvm::StringSwitch<bool>(FileName) .Case("float.h", true) .Case("iso646.h", true) .Case("limits.h", true) .Case("stdalign.h", true) .Case("stdarg.h", true) .Case("stdbool.h", true) .Case("stddef.h", true) .Case("stdint.h", true) .Case("tgmath.h", true) .Case("unwind.h", true) .Default(false); } ModuleMap::HeadersMap::iterator ModuleMap::findKnownHeader(const FileEntry *File) { HeadersMap::iterator Known = Headers.find(File); if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps && Known == Headers.end() && File->getDir() == BuiltinIncludeDir && isBuiltinHeader(llvm::sys::path::filename(File->getName()))) { HeaderInfo.loadTopLevelSystemModules(); return Headers.find(File); } return Known; } ModuleMap::KnownHeader ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File, SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) { if (UmbrellaDirs.empty()) return KnownHeader(); const DirectoryEntry *Dir = File->getDir(); assert(Dir && "file in no directory"); // Note: as an egregious but useful hack we use the real path here, because // frameworks moving from top-level frameworks to embedded frameworks tend // to be symlinked from the top-level location to the embedded location, // and we need to resolve lookups as if we had found the embedded location. StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir); // Keep walking up the directory hierarchy, looking for a directory with // an umbrella header. do { auto KnownDir = UmbrellaDirs.find(Dir); if (KnownDir != UmbrellaDirs.end()) return KnownHeader(KnownDir->second, NormalHeader); IntermediateDirs.push_back(Dir); // Retrieve our parent path. DirName = llvm::sys::path::parent_path(DirName); if (DirName.empty()) break; // Resolve the parent path to a directory entry. Dir = SourceMgr.getFileManager().getDirectory(DirName); } while (Dir); return KnownHeader(); } static bool violatesPrivateInclude(Module *RequestingModule, const FileEntry *IncFileEnt, ModuleMap::ModuleHeaderRole Role, Module *RequestedModule) { bool IsPrivateRole = Role & ModuleMap::PrivateHeader; #ifndef NDEBUG if (IsPrivateRole) { // Check for consistency between the module header role // as obtained from the lookup and as obtained from the module. // This check is not cheap, so enable it only for debugging. bool IsPrivate = false; SmallVectorImpl<Module::Header> *HeaderList[] = { &RequestedModule->Headers[Module::HK_Private], &RequestedModule->Headers[Module::HK_PrivateTextual]}; for (auto *Hs : HeaderList) IsPrivate |= std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) { return H.Entry == IncFileEnt; }) != Hs->end(); assert((!IsPrivateRole || IsPrivate) && "inconsistent headers and roles"); } #endif return IsPrivateRole && // FIXME: Should we map RequestingModule to its top-level module here // too? This check is redundant with the isSubModuleOf check in // diagnoseHeaderInclusion. RequestedModule->getTopLevelModule() != RequestingModule; } static Module *getTopLevelOrNull(Module *M) { return M ? M->getTopLevelModule() : nullptr; } void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule, SourceLocation FilenameLoc, StringRef Filename, const FileEntry *File) { // No errors for indirect modules. This may be a bit of a problem for modules // with no source files. if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule)) return; if (RequestingModule) resolveUses(RequestingModule, /*Complain=*/false); bool Excluded = false; Module *Private = nullptr; Module *NotUsed = nullptr; HeadersMap::iterator Known = findKnownHeader(File); if (Known != Headers.end()) { for (const KnownHeader &Header : Known->second) { // If 'File' is part of 'RequestingModule' we can definitely include it. if (Header.getModule() && Header.getModule()->isSubModuleOf(RequestingModule)) return; // Remember private headers for later printing of a diagnostic. if (violatesPrivateInclude(RequestingModule, File, Header.getRole(), Header.getModule())) { Private = Header.getModule(); continue; } // If uses need to be specified explicitly, we are only allowed to return // modules that are explicitly used by the requesting module. if (RequestingModule && LangOpts.ModulesDeclUse && !RequestingModule->directlyUses(Header.getModule())) { NotUsed = Header.getModule(); continue; } // We have found a module that we can happily use. return; } Excluded = true; } // We have found a header, but it is private. if (Private) { Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module) << Filename; return; } // We have found a module, but we don't use it. if (NotUsed) { Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module) << RequestingModule->getFullModuleName() << Filename; return; } if (Excluded || isHeaderInUmbrellaDirs(File)) return; // At this point, only non-modular includes remain. if (LangOpts.ModulesStrictDeclUse) { Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module) << RequestingModule->getFullModuleName() << Filename; } else if (RequestingModule) { diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ? diag::warn_non_modular_include_in_framework_module : diag::warn_non_modular_include_in_module; Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName(); } } static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New, const ModuleMap::KnownHeader &Old) { // Prefer a public header over a private header. if ((New.getRole() & ModuleMap::PrivateHeader) != (Old.getRole() & ModuleMap::PrivateHeader)) return !(New.getRole() & ModuleMap::PrivateHeader); // Prefer a non-textual header over a textual header. if ((New.getRole() & ModuleMap::TextualHeader) != (Old.getRole() & ModuleMap::TextualHeader)) return !(New.getRole() & ModuleMap::TextualHeader); // Don't have a reason to choose between these. Just keep the first one. return false; } ModuleMap::KnownHeader ModuleMap::findModuleForHeader(const FileEntry *File) { auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader { if (R.getRole() & ModuleMap::TextualHeader) return ModuleMap::KnownHeader(); return R; }; HeadersMap::iterator Known = findKnownHeader(File); if (Known != Headers.end()) { ModuleMap::KnownHeader Result; // Iterate over all modules that 'File' is part of to find the best fit. for (KnownHeader &H : Known->second) { // Prefer a header from the current module over all others. if (H.getModule()->getTopLevelModule() == CompilingModule) return MakeResult(H); // Cannot use a module if it is unavailable. if (!H.getModule()->isAvailable()) continue; if (!Result || isBetterKnownHeader(H, Result)) Result = H; } return MakeResult(Result); } SmallVector<const DirectoryEntry *, 2> SkippedDirs; KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs); if (H) { Module *Result = H.getModule(); // Search up the module stack until we find a module with an umbrella // directory. Module *UmbrellaModule = Result; while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent) UmbrellaModule = UmbrellaModule->Parent; if (UmbrellaModule->InferSubmodules) { const FileEntry *UmbrellaModuleMap = getModuleMapFileForUniquing(UmbrellaModule); // Infer submodules for each of the directories we found between // the directory of the umbrella header and the directory where // the actual header is located. bool Explicit = UmbrellaModule->InferExplicitSubmodules; for (unsigned I = SkippedDirs.size(); I != 0; --I) { // Find or create the module that corresponds to this directory name. SmallString<32> NameBuf; StringRef Name = sanitizeFilenameAsIdentifier( llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf); Result = findOrCreateModule(Name, Result, /*IsFramework=*/false, Explicit).first; InferredModuleAllowedBy[Result] = UmbrellaModuleMap; Result->IsInferred = true; // Associate the module and the directory. UmbrellaDirs[SkippedDirs[I-1]] = Result; // If inferred submodules export everything they import, add a // wildcard to the set of exports. if (UmbrellaModule->InferExportWildcard && Result->Exports.empty()) Result->Exports.push_back(Module::ExportDecl(nullptr, true)); } // Infer a submodule with the same name as this header file. SmallString<32> NameBuf; StringRef Name = sanitizeFilenameAsIdentifier( llvm::sys::path::stem(File->getName()), NameBuf); Result = findOrCreateModule(Name, Result, /*IsFramework=*/false, Explicit).first; InferredModuleAllowedBy[Result] = UmbrellaModuleMap; Result->IsInferred = true; Result->addTopHeader(File); // If inferred submodules export everything they import, add a // wildcard to the set of exports. if (UmbrellaModule->InferExportWildcard && Result->Exports.empty()) Result->Exports.push_back(Module::ExportDecl(nullptr, true)); } else { // Record each of the directories we stepped through as being part of // the module we found, since the umbrella header covers them all. for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I) UmbrellaDirs[SkippedDirs[I]] = Result; } Headers[File].push_back(KnownHeader(Result, NormalHeader)); // If a header corresponds to an unavailable module, don't report // that it maps to anything. if (!Result->isAvailable()) return KnownHeader(); return MakeResult(Headers[File].back()); } return KnownHeader(); } bool ModuleMap::isHeaderInUnavailableModule(const FileEntry *Header) const { return isHeaderUnavailableInModule(Header, nullptr); } bool ModuleMap::isHeaderUnavailableInModule(const FileEntry *Header, const Module *RequestingModule) const { HeadersMap::const_iterator Known = Headers.find(Header); if (Known != Headers.end()) { for (SmallVectorImpl<KnownHeader>::const_iterator I = Known->second.begin(), E = Known->second.end(); I != E; ++I) { if (I->isAvailable() && (!RequestingModule || I->getModule()->isSubModuleOf(RequestingModule))) return false; } return true; } const DirectoryEntry *Dir = Header->getDir(); SmallVector<const DirectoryEntry *, 2> SkippedDirs; StringRef DirName = Dir->getName(); auto IsUnavailable = [&](const Module *M) { return !M->isAvailable() && (!RequestingModule || M->isSubModuleOf(RequestingModule)); }; // Keep walking up the directory hierarchy, looking for a directory with // an umbrella header. do { llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir = UmbrellaDirs.find(Dir); if (KnownDir != UmbrellaDirs.end()) { Module *Found = KnownDir->second; if (IsUnavailable(Found)) return true; // Search up the module stack until we find a module with an umbrella // directory. Module *UmbrellaModule = Found; while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent) UmbrellaModule = UmbrellaModule->Parent; if (UmbrellaModule->InferSubmodules) { for (unsigned I = SkippedDirs.size(); I != 0; --I) { // Find or create the module that corresponds to this directory name. SmallString<32> NameBuf; StringRef Name = sanitizeFilenameAsIdentifier( llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf); Found = lookupModuleQualified(Name, Found); if (!Found) return false; if (IsUnavailable(Found)) return true; } // Infer a submodule with the same name as this header file. SmallString<32> NameBuf; StringRef Name = sanitizeFilenameAsIdentifier( llvm::sys::path::stem(Header->getName()), NameBuf); Found = lookupModuleQualified(Name, Found); if (!Found) return false; } return IsUnavailable(Found); } SkippedDirs.push_back(Dir); // Retrieve our parent path. DirName = llvm::sys::path::parent_path(DirName); if (DirName.empty()) break; // Resolve the parent path to a directory entry. Dir = SourceMgr.getFileManager().getDirectory(DirName); } while (Dir); return false; } Module *ModuleMap::findModule(StringRef Name) const { llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name); if (Known != Modules.end()) return Known->getValue(); return nullptr; } Module *ModuleMap::lookupModuleUnqualified(StringRef Name, Module *Context) const { for(; Context; Context = Context->Parent) { if (Module *Sub = lookupModuleQualified(Name, Context)) return Sub; } return findModule(Name); } Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{ if (!Context) return findModule(Name); return Context->findSubmodule(Name); } std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit) { // Try to find an existing module with this name. if (Module *Sub = lookupModuleQualified(Name, Parent)) return std::make_pair(Sub, false); // Create a new module with this name. Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework, IsExplicit, NumCreatedModules++); if (LangOpts.CurrentModule == Name) { SourceModule = Result; SourceModuleName = Name; } if (!Parent) { Modules[Name] = Result; if (!LangOpts.CurrentModule.empty() && !CompilingModule && Name == LangOpts.CurrentModule) { CompilingModule = Result; } } return std::make_pair(Result, true); } /// \brief For a framework module, infer the framework against which we /// should link. static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir, FileManager &FileMgr) { assert(Mod->IsFramework && "Can only infer linking for framework modules"); assert(!Mod->isSubFramework() && "Can only infer linking for top-level frameworks"); SmallString<128> LibName; LibName += FrameworkDir->getName(); llvm::sys::path::append(LibName, Mod->Name); if (FileMgr.getFile(LibName)) { Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name, /*IsFramework=*/true)); } } Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir, bool IsSystem, Module *Parent) { Attributes Attrs; Attrs.IsSystem = IsSystem; return inferFrameworkModule(FrameworkDir, Attrs, Parent); } Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir, Attributes Attrs, Module *Parent) { // Note: as an egregious but useful hack we use the real path here, because // we might be looking at an embedded framework that symlinks out to a // top-level framework, and we need to infer as if we were naming the // top-level framework. StringRef FrameworkDirName = SourceMgr.getFileManager().getCanonicalName(FrameworkDir); // In case this is a case-insensitive filesystem, use the canonical // directory name as the ModuleName, since modules are case-sensitive. // FIXME: we should be able to give a fix-it hint for the correct spelling. SmallString<32> ModuleNameStorage; StringRef ModuleName = sanitizeFilenameAsIdentifier( llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage); // Check whether we've already found this module. if (Module *Mod = lookupModuleQualified(ModuleName, Parent)) return Mod; FileManager &FileMgr = SourceMgr.getFileManager(); // If the framework has a parent path from which we're allowed to infer // a framework module, do so. const FileEntry *ModuleMapFile = nullptr; if (!Parent) { // Determine whether we're allowed to infer a module map. bool canInfer = false; if (llvm::sys::path::has_parent_path(FrameworkDirName)) { // Figure out the parent path. StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName); if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) { // Check whether we have already looked into the parent directory // for a module map. llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator inferred = InferredDirectories.find(ParentDir); if (inferred == InferredDirectories.end()) { // We haven't looked here before. Load a module map, if there is // one. bool IsFrameworkDir = Parent.endswith(".framework"); if (const FileEntry *ModMapFile = HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) { parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir); inferred = InferredDirectories.find(ParentDir); } if (inferred == InferredDirectories.end()) inferred = InferredDirectories.insert( std::make_pair(ParentDir, InferredDirectory())).first; } if (inferred->second.InferModules) { // We're allowed to infer for this directory, but make sure it's okay // to infer this particular module. StringRef Name = llvm::sys::path::stem(FrameworkDirName); canInfer = std::find(inferred->second.ExcludedModules.begin(), inferred->second.ExcludedModules.end(), Name) == inferred->second.ExcludedModules.end(); Attrs.IsSystem |= inferred->second.Attrs.IsSystem; Attrs.IsExternC |= inferred->second.Attrs.IsExternC; Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive; ModuleMapFile = inferred->second.ModuleMapFile; } } } // If we're not allowed to infer a framework module, don't. if (!canInfer) return nullptr; } else ModuleMapFile = getModuleMapFileForUniquing(Parent); // Look for an umbrella header. SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName()); llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h"); const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName); // FIXME: If there's no umbrella header, we could probably scan the // framework to load *everything*. But, it's not clear that this is a good // idea. if (!UmbrellaHeader) return nullptr; Module *Result = new Module(ModuleName, SourceLocation(), Parent, /*IsFramework=*/true, /*IsExplicit=*/false, NumCreatedModules++); InferredModuleAllowedBy[Result] = ModuleMapFile; Result->IsInferred = true; if (LangOpts.CurrentModule == ModuleName) { SourceModule = Result; SourceModuleName = ModuleName; } Result->IsSystem |= Attrs.IsSystem; Result->IsExternC |= Attrs.IsExternC; Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive; Result->Directory = FrameworkDir; if (!Parent) Modules[ModuleName] = Result; // umbrella header "umbrella-header-name" // // The "Headers/" component of the name is implied because this is // a framework module. setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h"); // export * Result->Exports.push_back(Module::ExportDecl(nullptr, true)); // module * { export * } Result->InferSubmodules = true; Result->InferExportWildcard = true; // Look for subframeworks. std::error_code EC; SmallString<128> SubframeworksDirName = StringRef(FrameworkDir->getName()); llvm::sys::path::append(SubframeworksDirName, "Frameworks"); llvm::sys::path::native(SubframeworksDirName); for (llvm::sys::fs::directory_iterator Dir(SubframeworksDirName, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { if (!StringRef(Dir->path()).endswith(".framework")) continue; if (const DirectoryEntry *SubframeworkDir = FileMgr.getDirectory(Dir->path())) { // Note: as an egregious but useful hack, we use the real path here and // check whether it is actually a subdirectory of the parent directory. // This will not be the case if the 'subframework' is actually a symlink // out to a top-level framework. StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir); bool FoundParent = false; do { // Get the parent directory name. SubframeworkDirName = llvm::sys::path::parent_path(SubframeworkDirName); if (SubframeworkDirName.empty()) break; if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) { FoundParent = true; break; } } while (true); if (!FoundParent) continue; // FIXME: Do we want to warn about subframeworks without umbrella headers? inferFrameworkModule(SubframeworkDir, Attrs, Result); } } // If the module is a top-level framework, automatically link against the // framework. if (!Result->isSubFramework()) { inferFrameworkLink(Result, FrameworkDir, FileMgr); } return Result; } void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader, Twine NameAsWritten) { Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader)); Mod->Umbrella = UmbrellaHeader; Mod->UmbrellaAsWritten = NameAsWritten.str(); UmbrellaDirs[UmbrellaHeader->getDir()] = Mod; } void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir, Twine NameAsWritten) { Mod->Umbrella = UmbrellaDir; Mod->UmbrellaAsWritten = NameAsWritten.str(); UmbrellaDirs[UmbrellaDir] = Mod; } static Module::HeaderKind headerRoleToKind(ModuleMap::ModuleHeaderRole Role) { switch ((int)Role) { default: llvm_unreachable("unknown header role"); case ModuleMap::NormalHeader: return Module::HK_Normal; case ModuleMap::PrivateHeader: return Module::HK_Private; case ModuleMap::TextualHeader: return Module::HK_Textual; case ModuleMap::PrivateHeader | ModuleMap::TextualHeader: return Module::HK_PrivateTextual; } } void ModuleMap::addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role) { if (!(Role & TextualHeader)) { bool isCompilingModuleHeader = Mod->getTopLevelModule() == CompilingModule; HeaderInfo.MarkFileModuleHeader(Header.Entry, Role, isCompilingModuleHeader); } Headers[Header.Entry].push_back(KnownHeader(Mod, Role)); Mod->Headers[headerRoleToKind(Role)].push_back(std::move(Header)); } void ModuleMap::excludeHeader(Module *Mod, Module::Header Header) { // Add this as a known header so we won't implicitly add it to any // umbrella directory module. // FIXME: Should we only exclude it from umbrella modules within the // specified module? (void) Headers[Header.Entry]; Mod->Headers[Module::HK_Excluded].push_back(std::move(Header)); } const FileEntry * ModuleMap::getContainingModuleMapFile(const Module *Module) const { if (Module->DefinitionLoc.isInvalid()) return nullptr; return SourceMgr.getFileEntryForID( SourceMgr.getFileID(Module->DefinitionLoc)); } const FileEntry *ModuleMap::getModuleMapFileForUniquing(const Module *M) const { if (M->IsInferred) { assert(InferredModuleAllowedBy.count(M) && "missing inferred module map"); return InferredModuleAllowedBy.find(M)->second; } return getContainingModuleMapFile(M); } void ModuleMap::setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap) { assert(M->IsInferred && "module not inferred"); InferredModuleAllowedBy[M] = ModMap; } void ModuleMap::dump() { llvm::errs() << "Modules:"; for (llvm::StringMap<Module *>::iterator M = Modules.begin(), MEnd = Modules.end(); M != MEnd; ++M) M->getValue()->print(llvm::errs(), 2); llvm::errs() << "Headers:"; for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end(); H != HEnd; ++H) { llvm::errs() << " \"" << H->first->getName() << "\" -> "; for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(), E = H->second.end(); I != E; ++I) { if (I != H->second.begin()) llvm::errs() << ","; llvm::errs() << I->getModule()->getFullModuleName(); } llvm::errs() << "\n"; } } bool ModuleMap::resolveExports(Module *Mod, bool Complain) { auto Unresolved = std::move(Mod->UnresolvedExports); Mod->UnresolvedExports.clear(); for (auto &UE : Unresolved) { Module::ExportDecl Export = resolveExport(Mod, UE, Complain); if (Export.getPointer() || Export.getInt()) Mod->Exports.push_back(Export); else Mod->UnresolvedExports.push_back(UE); } return !Mod->UnresolvedExports.empty(); } bool ModuleMap::resolveUses(Module *Mod, bool Complain) { auto Unresolved = std::move(Mod->UnresolvedDirectUses); Mod->UnresolvedDirectUses.clear(); for (auto &UDU : Unresolved) { Module *DirectUse = resolveModuleId(UDU, Mod, Complain); if (DirectUse) Mod->DirectUses.push_back(DirectUse); else Mod->UnresolvedDirectUses.push_back(UDU); } return !Mod->UnresolvedDirectUses.empty(); } bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) { auto Unresolved = std::move(Mod->UnresolvedConflicts); Mod->UnresolvedConflicts.clear(); for (auto &UC : Unresolved) { if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) { Module::Conflict Conflict; Conflict.Other = OtherMod; Conflict.Message = UC.Message; Mod->Conflicts.push_back(Conflict); } else Mod->UnresolvedConflicts.push_back(UC); } return !Mod->UnresolvedConflicts.empty(); } Module *ModuleMap::inferModuleFromLocation(FullSourceLoc Loc) { if (Loc.isInvalid()) return nullptr; // Use the expansion location to determine which module we're in. FullSourceLoc ExpansionLoc = Loc.getExpansionLoc(); if (!ExpansionLoc.isFileID()) return nullptr; const SourceManager &SrcMgr = Loc.getManager(); FileID ExpansionFileID = ExpansionLoc.getFileID(); while (const FileEntry *ExpansionFile = SrcMgr.getFileEntryForID(ExpansionFileID)) { // Find the module that owns this header (if any). if (Module *Mod = findModuleForHeader(ExpansionFile).getModule()) return Mod; // No module owns this header, so look up the inclusion chain to see if // any included header has an associated module. SourceLocation IncludeLoc = SrcMgr.getIncludeLoc(ExpansionFileID); if (IncludeLoc.isInvalid()) return nullptr; ExpansionFileID = SrcMgr.getFileID(IncludeLoc); } return nullptr; } //----------------------------------------------------------------------------// // Module map file parser //----------------------------------------------------------------------------// namespace clang { /// \brief A token in a module map file. struct MMToken { enum TokenKind { Comma, ConfigMacros, Conflict, EndOfFile, HeaderKeyword, Identifier, Exclaim, ExcludeKeyword, ExplicitKeyword, ExportKeyword, ExternKeyword, FrameworkKeyword, LinkKeyword, ModuleKeyword, Period, PrivateKeyword, UmbrellaKeyword, UseKeyword, RequiresKeyword, Star, StringLiteral, TextualKeyword, LBrace, RBrace, LSquare, RSquare } Kind; unsigned Location; unsigned StringLength; const char *StringData; void clear() { Kind = EndOfFile; Location = 0; StringLength = 0; StringData = nullptr; } bool is(TokenKind K) const { return Kind == K; } SourceLocation getLocation() const { return SourceLocation::getFromRawEncoding(Location); } StringRef getString() const { return StringRef(StringData, StringLength); } }; class ModuleMapParser { Lexer &L; SourceManager &SourceMgr; /// \brief Default target information, used only for string literal /// parsing. const TargetInfo *Target; DiagnosticsEngine &Diags; ModuleMap &Map; /// \brief The current module map file. const FileEntry *ModuleMapFile; /// \brief The directory that file names in this module map file should /// be resolved relative to. const DirectoryEntry *Directory; /// \brief The directory containing Clang-supplied headers. const DirectoryEntry *BuiltinIncludeDir; /// \brief Whether this module map is in a system header directory. bool IsSystem; /// \brief Whether an error occurred. bool HadError; /// \brief Stores string data for the various string literals referenced /// during parsing. llvm::BumpPtrAllocator StringData; /// \brief The current token. MMToken Tok; /// \brief The active module. Module *ActiveModule; /// \brief Consume the current token and return its location. SourceLocation consumeToken(); /// \brief Skip tokens until we reach the a token with the given kind /// (or the end of the file). void skipUntil(MMToken::TokenKind K); typedef SmallVector<std::pair<std::string, SourceLocation>, 2> ModuleId; bool parseModuleId(ModuleId &Id); void parseModuleDecl(); void parseExternModuleDecl(); void parseRequiresDecl(); void parseHeaderDecl(clang::MMToken::TokenKind, SourceLocation LeadingLoc); void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc); void parseExportDecl(); void parseUseDecl(); void parseLinkDecl(); void parseConfigMacros(); void parseConflict(); void parseInferredModuleDecl(bool Framework, bool Explicit); typedef ModuleMap::Attributes Attributes; bool parseOptionalAttributes(Attributes &Attrs); public: explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr, const TargetInfo *Target, DiagnosticsEngine &Diags, ModuleMap &Map, const FileEntry *ModuleMapFile, const DirectoryEntry *Directory, const DirectoryEntry *BuiltinIncludeDir, bool IsSystem) : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map), ModuleMapFile(ModuleMapFile), Directory(Directory), BuiltinIncludeDir(BuiltinIncludeDir), IsSystem(IsSystem), HadError(false), ActiveModule(nullptr) { Tok.clear(); consumeToken(); } bool parseModuleMapFile(); }; } SourceLocation ModuleMapParser::consumeToken() { retry: SourceLocation Result = Tok.getLocation(); Tok.clear(); Token LToken; L.LexFromRawLexer(LToken); Tok.Location = LToken.getLocation().getRawEncoding(); switch (LToken.getKind()) { case tok::raw_identifier: { StringRef RI = LToken.getRawIdentifier(); Tok.StringData = RI.data(); Tok.StringLength = RI.size(); Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI) .Case("config_macros", MMToken::ConfigMacros) .Case("conflict", MMToken::Conflict) .Case("exclude", MMToken::ExcludeKeyword) .Case("explicit", MMToken::ExplicitKeyword) .Case("export", MMToken::ExportKeyword) .Case("extern", MMToken::ExternKeyword) .Case("framework", MMToken::FrameworkKeyword) .Case("header", MMToken::HeaderKeyword) .Case("link", MMToken::LinkKeyword) .Case("module", MMToken::ModuleKeyword) .Case("private", MMToken::PrivateKeyword) .Case("requires", MMToken::RequiresKeyword) .Case("textual", MMToken::TextualKeyword) .Case("umbrella", MMToken::UmbrellaKeyword) .Case("use", MMToken::UseKeyword) .Default(MMToken::Identifier); break; } case tok::comma: Tok.Kind = MMToken::Comma; break; case tok::eof: Tok.Kind = MMToken::EndOfFile; break; case tok::l_brace: Tok.Kind = MMToken::LBrace; break; case tok::l_square: Tok.Kind = MMToken::LSquare; break; case tok::period: Tok.Kind = MMToken::Period; break; case tok::r_brace: Tok.Kind = MMToken::RBrace; break; case tok::r_square: Tok.Kind = MMToken::RSquare; break; case tok::star: Tok.Kind = MMToken::Star; break; case tok::exclaim: Tok.Kind = MMToken::Exclaim; break; case tok::string_literal: { if (LToken.hasUDSuffix()) { Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl); HadError = true; goto retry; } // Parse the string literal. LangOptions LangOpts; StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target); if (StringLiteral.hadError) goto retry; // Copy the string literal into our string data allocator. unsigned Length = StringLiteral.GetStringLength(); char *Saved = StringData.Allocate<char>(Length + 1); memcpy(Saved, StringLiteral.GetString().data(), Length); Saved[Length] = 0; // Form the token. Tok.Kind = MMToken::StringLiteral; Tok.StringData = Saved; Tok.StringLength = Length; break; } case tok::comment: goto retry; default: Diags.Report(LToken.getLocation(), diag::err_mmap_unknown_token); HadError = true; goto retry; } return Result; } void ModuleMapParser::skipUntil(MMToken::TokenKind K) { unsigned braceDepth = 0; unsigned squareDepth = 0; do { switch (Tok.Kind) { case MMToken::EndOfFile: return; case MMToken::LBrace: if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) return; ++braceDepth; break; case MMToken::LSquare: if (Tok.is(K) && braceDepth == 0 && squareDepth == 0) return; ++squareDepth; break; case MMToken::RBrace: if (braceDepth > 0) --braceDepth; else if (Tok.is(K)) return; break; case MMToken::RSquare: if (squareDepth > 0) --squareDepth; else if (Tok.is(K)) return; break; default: if (braceDepth == 0 && squareDepth == 0 && Tok.is(K)) return; break; } consumeToken(); } while (true); } /// \brief Parse a module-id. /// /// module-id: /// identifier /// identifier '.' module-id /// /// \returns true if an error occurred, false otherwise. bool ModuleMapParser::parseModuleId(ModuleId &Id) { Id.clear(); do { if (Tok.is(MMToken::Identifier) || Tok.is(MMToken::StringLiteral)) { Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation())); consumeToken(); } else { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name); return true; } if (!Tok.is(MMToken::Period)) break; consumeToken(); } while (true); return false; } namespace { /// \brief Enumerates the known attributes. enum AttributeKind { /// \brief An unknown attribute. AT_unknown, /// \brief The 'system' attribute. AT_system, /// \brief The 'extern_c' attribute. AT_extern_c, /// \brief The 'exhaustive' attribute. AT_exhaustive }; } /// \brief Parse a module declaration. /// /// module-declaration: /// 'extern' 'module' module-id string-literal /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt] /// { module-member* } /// /// module-member: /// requires-declaration /// header-declaration /// submodule-declaration /// export-declaration /// link-declaration /// /// submodule-declaration: /// module-declaration /// inferred-submodule-declaration void ModuleMapParser::parseModuleDecl() { assert(Tok.is(MMToken::ExplicitKeyword) || Tok.is(MMToken::ModuleKeyword) || Tok.is(MMToken::FrameworkKeyword) || Tok.is(MMToken::ExternKeyword)); if (Tok.is(MMToken::ExternKeyword)) { parseExternModuleDecl(); return; } // Parse 'explicit' or 'framework' keyword, if present. SourceLocation ExplicitLoc; bool Explicit = false; bool Framework = false; // Parse 'explicit' keyword, if present. if (Tok.is(MMToken::ExplicitKeyword)) { ExplicitLoc = consumeToken(); Explicit = true; } // Parse 'framework' keyword, if present. if (Tok.is(MMToken::FrameworkKeyword)) { consumeToken(); Framework = true; } // Parse 'module' keyword. if (!Tok.is(MMToken::ModuleKeyword)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); consumeToken(); HadError = true; return; } consumeToken(); // 'module' keyword // If we have a wildcard for the module name, this is an inferred submodule. // Parse it. if (Tok.is(MMToken::Star)) return parseInferredModuleDecl(Framework, Explicit); // Parse the module name. ModuleId Id; if (parseModuleId(Id)) { HadError = true; return; } if (ActiveModule) { if (Id.size() > 1) { Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id) << SourceRange(Id.front().second, Id.back().second); HadError = true; return; } } else if (Id.size() == 1 && Explicit) { // Top-level modules can't be explicit. Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level); Explicit = false; ExplicitLoc = SourceLocation(); HadError = true; } Module *PreviousActiveModule = ActiveModule; if (Id.size() > 1) { // This module map defines a submodule. Go find the module of which it // is a submodule. ActiveModule = nullptr; const Module *TopLevelModule = nullptr; for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) { if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) { if (I == 0) TopLevelModule = Next; ActiveModule = Next; continue; } if (ActiveModule) { Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified) << Id[I].first << ActiveModule->getTopLevelModule()->getFullModuleName(); } else { Diags.Report(Id[I].second, diag::err_mmap_expected_module_name); } HadError = true; return; } if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) { assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) && "submodule defined in same file as 'module *' that allowed its " "top-level module"); Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile); } } StringRef ModuleName = Id.back().first; SourceLocation ModuleNameLoc = Id.back().second; // Parse the optional attribute list. Attributes Attrs; parseOptionalAttributes(Attrs); // Parse the opening brace. if (!Tok.is(MMToken::LBrace)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace) << ModuleName; HadError = true; return; } SourceLocation LBraceLoc = consumeToken(); // Determine whether this (sub)module has already been defined. if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) { if (Existing->DefinitionLoc.isInvalid() && !ActiveModule) { // Skip the module definition. skipUntil(MMToken::RBrace); if (Tok.is(MMToken::RBrace)) consumeToken(); else { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); HadError = true; } return; } Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition) << ModuleName; Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition); // Skip the module definition. skipUntil(MMToken::RBrace); if (Tok.is(MMToken::RBrace)) consumeToken(); HadError = true; return; } // Start defining this module. ActiveModule = Map.findOrCreateModule(ModuleName, ActiveModule, Framework, Explicit).first; ActiveModule->DefinitionLoc = ModuleNameLoc; if (Attrs.IsSystem || IsSystem) ActiveModule->IsSystem = true; if (Attrs.IsExternC) ActiveModule->IsExternC = true; ActiveModule->Directory = Directory; bool Done = false; do { switch (Tok.Kind) { case MMToken::EndOfFile: case MMToken::RBrace: Done = true; break; case MMToken::ConfigMacros: parseConfigMacros(); break; case MMToken::Conflict: parseConflict(); break; case MMToken::ExplicitKeyword: case MMToken::ExternKeyword: case MMToken::FrameworkKeyword: case MMToken::ModuleKeyword: parseModuleDecl(); break; case MMToken::ExportKeyword: parseExportDecl(); break; case MMToken::UseKeyword: parseUseDecl(); break; case MMToken::RequiresKeyword: parseRequiresDecl(); break; case MMToken::TextualKeyword: parseHeaderDecl(MMToken::TextualKeyword, consumeToken()); break; case MMToken::UmbrellaKeyword: { SourceLocation UmbrellaLoc = consumeToken(); if (Tok.is(MMToken::HeaderKeyword)) parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc); else parseUmbrellaDirDecl(UmbrellaLoc); break; } case MMToken::ExcludeKeyword: parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken()); break; case MMToken::PrivateKeyword: parseHeaderDecl(MMToken::PrivateKeyword, consumeToken()); break; case MMToken::HeaderKeyword: parseHeaderDecl(MMToken::HeaderKeyword, consumeToken()); break; case MMToken::LinkKeyword: parseLinkDecl(); break; default: Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member); consumeToken(); break; } } while (!Done); if (Tok.is(MMToken::RBrace)) consumeToken(); else { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); HadError = true; } // If the active module is a top-level framework, and there are no link // libraries, automatically link against the framework. if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() && ActiveModule->LinkLibraries.empty()) { inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager()); } // If the module meets all requirements but is still unavailable, mark the // whole tree as unavailable to prevent it from building. if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement && ActiveModule->Parent) { ActiveModule->getTopLevelModule()->markUnavailable(); ActiveModule->getTopLevelModule()->MissingHeaders.append( ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end()); } // We're done parsing this module. Pop back to the previous module. ActiveModule = PreviousActiveModule; } /// \brief Parse an extern module declaration. /// /// extern module-declaration: /// 'extern' 'module' module-id string-literal void ModuleMapParser::parseExternModuleDecl() { assert(Tok.is(MMToken::ExternKeyword)); SourceLocation ExternLoc = consumeToken(); // 'extern' keyword // Parse 'module' keyword. if (!Tok.is(MMToken::ModuleKeyword)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); consumeToken(); HadError = true; return; } consumeToken(); // 'module' keyword // Parse the module name. ModuleId Id; if (parseModuleId(Id)) { HadError = true; return; } // Parse the referenced module map file name. if (!Tok.is(MMToken::StringLiteral)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file); HadError = true; return; } std::string FileName = Tok.getString(); consumeToken(); // filename StringRef FileNameRef = FileName; SmallString<128> ModuleMapFileName; if (llvm::sys::path::is_relative(FileNameRef)) { ModuleMapFileName += Directory->getName(); llvm::sys::path::append(ModuleMapFileName, FileName); FileNameRef = ModuleMapFileName; } if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef)) Map.parseModuleMapFile( File, /*IsSystem=*/false, Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd ? Directory : File->getDir(), ExternLoc); } /// \brief Parse a requires declaration. /// /// requires-declaration: /// 'requires' feature-list /// /// feature-list: /// feature ',' feature-list /// feature /// /// feature: /// '!'[opt] identifier void ModuleMapParser::parseRequiresDecl() { assert(Tok.is(MMToken::RequiresKeyword)); // Parse 'requires' keyword. consumeToken(); // Parse the feature-list. do { bool RequiredState = true; if (Tok.is(MMToken::Exclaim)) { RequiredState = false; consumeToken(); } if (!Tok.is(MMToken::Identifier)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature); HadError = true; return; } // Consume the feature name. std::string Feature = Tok.getString(); consumeToken(); // Add this feature. ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts, *Map.Target); if (!Tok.is(MMToken::Comma)) break; // Consume the comma. consumeToken(); } while (true); } /// \brief Append to \p Paths the set of paths needed to get to the /// subframework in which the given module lives. static void appendSubframeworkPaths(Module *Mod, SmallVectorImpl<char> &Path) { // Collect the framework names from the given module to the top-level module. SmallVector<StringRef, 2> Paths; for (; Mod; Mod = Mod->Parent) { if (Mod->IsFramework) Paths.push_back(Mod->Name); } if (Paths.empty()) return; // Add Frameworks/Name.framework for each subframework. for (unsigned I = Paths.size() - 1; I != 0; --I) llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework"); } /// \brief Parse a header declaration. /// /// header-declaration: /// 'textual'[opt] 'header' string-literal /// 'private' 'textual'[opt] 'header' string-literal /// 'exclude' 'header' string-literal /// 'umbrella' 'header' string-literal /// /// FIXME: Support 'private textual header'. void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken, SourceLocation LeadingLoc) { // We've already consumed the first token. ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader; if (LeadingToken == MMToken::PrivateKeyword) { Role = ModuleMap::PrivateHeader; // 'private' may optionally be followed by 'textual'. if (Tok.is(MMToken::TextualKeyword)) { LeadingToken = Tok.Kind; consumeToken(); } } if (LeadingToken == MMToken::TextualKeyword) Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader); if (LeadingToken != MMToken::HeaderKeyword) { if (!Tok.is(MMToken::HeaderKeyword)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) << (LeadingToken == MMToken::PrivateKeyword ? "private" : LeadingToken == MMToken::ExcludeKeyword ? "exclude" : LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella"); return; } consumeToken(); } // Parse the header name. if (!Tok.is(MMToken::StringLiteral)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) << "header"; HadError = true; return; } Module::UnresolvedHeaderDirective Header; Header.FileName = Tok.getString(); Header.FileNameLoc = consumeToken(); // Check whether we already have an umbrella. if (LeadingToken == MMToken::UmbrellaKeyword && ActiveModule->Umbrella) { Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash) << ActiveModule->getFullModuleName(); HadError = true; return; } // Look for this file. const FileEntry *File = nullptr; const FileEntry *BuiltinFile = nullptr; SmallString<128> RelativePathName; if (llvm::sys::path::is_absolute(Header.FileName)) { RelativePathName = Header.FileName; File = SourceMgr.getFileManager().getFile(RelativePathName); } else { // Search for the header file within the search directory. SmallString<128> FullPathName(Directory->getName()); unsigned FullPathLength = FullPathName.size(); if (ActiveModule->isPartOfFramework()) { appendSubframeworkPaths(ActiveModule, RelativePathName); // Check whether this file is in the public headers. llvm::sys::path::append(RelativePathName, "Headers", Header.FileName); llvm::sys::path::append(FullPathName, RelativePathName); File = SourceMgr.getFileManager().getFile(FullPathName); if (!File) { // Check whether this file is in the private headers. // FIXME: Should we retain the subframework paths here? RelativePathName.clear(); FullPathName.resize(FullPathLength); llvm::sys::path::append(RelativePathName, "PrivateHeaders", Header.FileName); llvm::sys::path::append(FullPathName, RelativePathName); File = SourceMgr.getFileManager().getFile(FullPathName); } } else { // Lookup for normal headers. llvm::sys::path::append(RelativePathName, Header.FileName); llvm::sys::path::append(FullPathName, RelativePathName); File = SourceMgr.getFileManager().getFile(FullPathName); // If this is a system module with a top-level header, this header // may have a counterpart (or replacement) in the set of headers // supplied by Clang. Find that builtin header. if (ActiveModule->IsSystem && LeadingToken != MMToken::UmbrellaKeyword && BuiltinIncludeDir && BuiltinIncludeDir != Directory && isBuiltinHeader(Header.FileName)) { SmallString<128> BuiltinPathName(BuiltinIncludeDir->getName()); llvm::sys::path::append(BuiltinPathName, Header.FileName); BuiltinFile = SourceMgr.getFileManager().getFile(BuiltinPathName); // If Clang supplies this header but the underlying system does not, // just silently swap in our builtin version. Otherwise, we'll end // up adding both (later). // // For local visibility, entirely replace the system file with our // one and textually include the system one. We need to pass macros // from our header to the system one if we #include_next it. // // FIXME: Can we do this in all cases? if (BuiltinFile && (!File || Map.LangOpts.ModulesLocalVisibility)) { File = BuiltinFile; RelativePathName = BuiltinPathName; BuiltinFile = nullptr; } } } } // FIXME: We shouldn't be eagerly stat'ing every file named in a module map. // Come up with a lazy way to do this. if (File) { if (LeadingToken == MMToken::UmbrellaKeyword) { const DirectoryEntry *UmbrellaDir = File->getDir(); if (Module *UmbrellaModule = Map.UmbrellaDirs[UmbrellaDir]) { Diags.Report(LeadingLoc, diag::err_mmap_umbrella_clash) << UmbrellaModule->getFullModuleName(); HadError = true; } else { // Record this umbrella header. Map.setUmbrellaHeader(ActiveModule, File, RelativePathName.str()); } } else if (LeadingToken == MMToken::ExcludeKeyword) { Module::Header H = {RelativePathName.str(), File}; Map.excludeHeader(ActiveModule, H); } else { // If there is a builtin counterpart to this file, add it now, before // the "real" header, so we build the built-in one first when building // the module. if (BuiltinFile) { // FIXME: Taking the name from the FileEntry is unstable and can give // different results depending on how we've previously named that file // in this build. Module::Header H = { BuiltinFile->getName(), BuiltinFile }; Map.addHeader(ActiveModule, H, Role); } // Record this header. Module::Header H = { RelativePathName.str(), File }; Map.addHeader(ActiveModule, H, Role); } } else if (LeadingToken != MMToken::ExcludeKeyword) { // Ignore excluded header files. They're optional anyway. // If we find a module that has a missing header, we mark this module as // unavailable and store the header directive for displaying diagnostics. Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword; ActiveModule->markUnavailable(); ActiveModule->MissingHeaders.push_back(Header); } } /// \brief Parse an umbrella directory declaration. /// /// umbrella-dir-declaration: /// umbrella string-literal void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) { // Parse the directory name. if (!Tok.is(MMToken::StringLiteral)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header) << "umbrella"; HadError = true; return; } std::string DirName = Tok.getString(); SourceLocation DirNameLoc = consumeToken(); // Check whether we already have an umbrella. if (ActiveModule->Umbrella) { Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash) << ActiveModule->getFullModuleName(); HadError = true; return; } // Look for this file. const DirectoryEntry *Dir = nullptr; if (llvm::sys::path::is_absolute(DirName)) Dir = SourceMgr.getFileManager().getDirectory(DirName); else { SmallString<128> PathName; PathName = Directory->getName(); llvm::sys::path::append(PathName, DirName); Dir = SourceMgr.getFileManager().getDirectory(PathName); } if (!Dir) { Diags.Report(DirNameLoc, diag::err_mmap_umbrella_dir_not_found) << DirName; HadError = true; return; } if (Module *OwningModule = Map.UmbrellaDirs[Dir]) { Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash) << OwningModule->getFullModuleName(); HadError = true; return; } // Record this umbrella directory. Map.setUmbrellaDir(ActiveModule, Dir, DirName); } /// \brief Parse a module export declaration. /// /// export-declaration: /// 'export' wildcard-module-id /// /// wildcard-module-id: /// identifier /// '*' /// identifier '.' wildcard-module-id void ModuleMapParser::parseExportDecl() { assert(Tok.is(MMToken::ExportKeyword)); SourceLocation ExportLoc = consumeToken(); // Parse the module-id with an optional wildcard at the end. ModuleId ParsedModuleId; bool Wildcard = false; do { // FIXME: Support string-literal module names here. if (Tok.is(MMToken::Identifier)) { ParsedModuleId.push_back(std::make_pair(Tok.getString(), Tok.getLocation())); consumeToken(); if (Tok.is(MMToken::Period)) { consumeToken(); continue; } break; } if(Tok.is(MMToken::Star)) { Wildcard = true; consumeToken(); break; } Diags.Report(Tok.getLocation(), diag::err_mmap_module_id); HadError = true; return; } while (true); Module::UnresolvedExportDecl Unresolved = { ExportLoc, ParsedModuleId, Wildcard }; ActiveModule->UnresolvedExports.push_back(Unresolved); } /// \brief Parse a module use declaration. /// /// use-declaration: /// 'use' wildcard-module-id void ModuleMapParser::parseUseDecl() { assert(Tok.is(MMToken::UseKeyword)); auto KWLoc = consumeToken(); // Parse the module-id. ModuleId ParsedModuleId; parseModuleId(ParsedModuleId); if (ActiveModule->Parent) Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule); else ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId); } /// \brief Parse a link declaration. /// /// module-declaration: /// 'link' 'framework'[opt] string-literal void ModuleMapParser::parseLinkDecl() { assert(Tok.is(MMToken::LinkKeyword)); SourceLocation LinkLoc = consumeToken(); // Parse the optional 'framework' keyword. bool IsFramework = false; if (Tok.is(MMToken::FrameworkKeyword)) { consumeToken(); IsFramework = true; } // Parse the library name if (!Tok.is(MMToken::StringLiteral)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name) << IsFramework << SourceRange(LinkLoc); HadError = true; return; } std::string LibraryName = Tok.getString(); consumeToken(); ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName, IsFramework)); } /// \brief Parse a configuration macro declaration. /// /// module-declaration: /// 'config_macros' attributes[opt] config-macro-list? /// /// config-macro-list: /// identifier (',' identifier)? void ModuleMapParser::parseConfigMacros() { assert(Tok.is(MMToken::ConfigMacros)); SourceLocation ConfigMacrosLoc = consumeToken(); // Only top-level modules can have configuration macros. if (ActiveModule->Parent) { Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule); } // Parse the optional attributes. Attributes Attrs; parseOptionalAttributes(Attrs); if (Attrs.IsExhaustive && !ActiveModule->Parent) { ActiveModule->ConfigMacrosExhaustive = true; } // If we don't have an identifier, we're done. // FIXME: Support macros with the same name as a keyword here. if (!Tok.is(MMToken::Identifier)) return; // Consume the first identifier. if (!ActiveModule->Parent) { ActiveModule->ConfigMacros.push_back(Tok.getString().str()); } consumeToken(); do { // If there's a comma, consume it. if (!Tok.is(MMToken::Comma)) break; consumeToken(); // We expect to see a macro name here. // FIXME: Support macros with the same name as a keyword here. if (!Tok.is(MMToken::Identifier)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro); break; } // Consume the macro name. if (!ActiveModule->Parent) { ActiveModule->ConfigMacros.push_back(Tok.getString().str()); } consumeToken(); } while (true); } /// \brief Format a module-id into a string. static std::string formatModuleId(const ModuleId &Id) { std::string result; { llvm::raw_string_ostream OS(result); for (unsigned I = 0, N = Id.size(); I != N; ++I) { if (I) OS << "."; OS << Id[I].first; } } return result; } /// \brief Parse a conflict declaration. /// /// module-declaration: /// 'conflict' module-id ',' string-literal void ModuleMapParser::parseConflict() { assert(Tok.is(MMToken::Conflict)); SourceLocation ConflictLoc = consumeToken(); Module::UnresolvedConflict Conflict; // Parse the module-id. if (parseModuleId(Conflict.Id)) return; // Parse the ','. if (!Tok.is(MMToken::Comma)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma) << SourceRange(ConflictLoc); return; } consumeToken(); // Parse the message. if (!Tok.is(MMToken::StringLiteral)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message) << formatModuleId(Conflict.Id); return; } Conflict.Message = Tok.getString().str(); consumeToken(); // Add this unresolved conflict. ActiveModule->UnresolvedConflicts.push_back(Conflict); } /// \brief Parse an inferred module declaration (wildcard modules). /// /// module-declaration: /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt] /// { inferred-module-member* } /// /// inferred-module-member: /// 'export' '*' /// 'exclude' identifier void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) { assert(Tok.is(MMToken::Star)); SourceLocation StarLoc = consumeToken(); bool Failed = false; // Inferred modules must be submodules. if (!ActiveModule && !Framework) { Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule); Failed = true; } if (ActiveModule) { // Inferred modules must have umbrella directories. if (!Failed && ActiveModule->IsAvailable && !ActiveModule->getUmbrellaDir()) { Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella); Failed = true; } // Check for redefinition of an inferred module. if (!Failed && ActiveModule->InferSubmodules) { Diags.Report(StarLoc, diag::err_mmap_inferred_redef); if (ActiveModule->InferredSubmoduleLoc.isValid()) Diags.Report(ActiveModule->InferredSubmoduleLoc, diag::note_mmap_prev_definition); Failed = true; } // Check for the 'framework' keyword, which is not permitted here. if (Framework) { Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule); Framework = false; } } else if (Explicit) { Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework); Explicit = false; } // If there were any problems with this inferred submodule, skip its body. if (Failed) { if (Tok.is(MMToken::LBrace)) { consumeToken(); skipUntil(MMToken::RBrace); if (Tok.is(MMToken::RBrace)) consumeToken(); } HadError = true; return; } // Parse optional attributes. Attributes Attrs; parseOptionalAttributes(Attrs); if (ActiveModule) { // Note that we have an inferred submodule. ActiveModule->InferSubmodules = true; ActiveModule->InferredSubmoduleLoc = StarLoc; ActiveModule->InferExplicitSubmodules = Explicit; } else { // We'll be inferring framework modules for this directory. Map.InferredDirectories[Directory].InferModules = true; Map.InferredDirectories[Directory].Attrs = Attrs; Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile; // FIXME: Handle the 'framework' keyword. } // Parse the opening brace. if (!Tok.is(MMToken::LBrace)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard); HadError = true; return; } SourceLocation LBraceLoc = consumeToken(); // Parse the body of the inferred submodule. bool Done = false; do { switch (Tok.Kind) { case MMToken::EndOfFile: case MMToken::RBrace: Done = true; break; case MMToken::ExcludeKeyword: { if (ActiveModule) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) << (ActiveModule != nullptr); consumeToken(); break; } consumeToken(); // FIXME: Support string-literal module names here. if (!Tok.is(MMToken::Identifier)) { Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name); break; } Map.InferredDirectories[Directory].ExcludedModules .push_back(Tok.getString()); consumeToken(); break; } case MMToken::ExportKeyword: if (!ActiveModule) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) << (ActiveModule != nullptr); consumeToken(); break; } consumeToken(); if (Tok.is(MMToken::Star)) ActiveModule->InferExportWildcard = true; else Diags.Report(Tok.getLocation(), diag::err_mmap_expected_export_wildcard); consumeToken(); break; case MMToken::ExplicitKeyword: case MMToken::ModuleKeyword: case MMToken::HeaderKeyword: case MMToken::PrivateKeyword: case MMToken::UmbrellaKeyword: default: Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member) << (ActiveModule != nullptr); consumeToken(); break; } } while (!Done); if (Tok.is(MMToken::RBrace)) consumeToken(); else { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace); Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match); HadError = true; } } /// \brief Parse optional attributes. /// /// attributes: /// attribute attributes /// attribute /// /// attribute: /// [ identifier ] /// /// \param Attrs Will be filled in with the parsed attributes. /// /// \returns true if an error occurred, false otherwise. bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) { bool HadError = false; while (Tok.is(MMToken::LSquare)) { // Consume the '['. SourceLocation LSquareLoc = consumeToken(); // Check whether we have an attribute name here. if (!Tok.is(MMToken::Identifier)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute); skipUntil(MMToken::RSquare); if (Tok.is(MMToken::RSquare)) consumeToken(); HadError = true; } // Decode the attribute name. AttributeKind Attribute = llvm::StringSwitch<AttributeKind>(Tok.getString()) .Case("exhaustive", AT_exhaustive) .Case("extern_c", AT_extern_c) .Case("system", AT_system) .Default(AT_unknown); switch (Attribute) { case AT_unknown: Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute) << Tok.getString(); break; case AT_system: Attrs.IsSystem = true; break; case AT_extern_c: Attrs.IsExternC = true; break; case AT_exhaustive: Attrs.IsExhaustive = true; break; } consumeToken(); // Consume the ']'. if (!Tok.is(MMToken::RSquare)) { Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare); Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match); skipUntil(MMToken::RSquare); HadError = true; } if (Tok.is(MMToken::RSquare)) consumeToken(); } return HadError; } /// \brief Parse a module map file. /// /// module-map-file: /// module-declaration* bool ModuleMapParser::parseModuleMapFile() { do { switch (Tok.Kind) { case MMToken::EndOfFile: return HadError; case MMToken::ExplicitKeyword: case MMToken::ExternKeyword: case MMToken::ModuleKeyword: case MMToken::FrameworkKeyword: parseModuleDecl(); break; case MMToken::Comma: case MMToken::ConfigMacros: case MMToken::Conflict: case MMToken::Exclaim: case MMToken::ExcludeKeyword: case MMToken::ExportKeyword: case MMToken::HeaderKeyword: case MMToken::Identifier: case MMToken::LBrace: case MMToken::LinkKeyword: case MMToken::LSquare: case MMToken::Period: case MMToken::PrivateKeyword: case MMToken::RBrace: case MMToken::RSquare: case MMToken::RequiresKeyword: case MMToken::Star: case MMToken::StringLiteral: case MMToken::TextualKeyword: case MMToken::UmbrellaKeyword: case MMToken::UseKeyword: Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module); HadError = true; consumeToken(); break; } } while (true); } bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem, const DirectoryEntry *Dir, SourceLocation ExternModuleLoc) { llvm::DenseMap<const FileEntry *, bool>::iterator Known = ParsedModuleMap.find(File); if (Known != ParsedModuleMap.end()) return Known->second; assert(Target && "Missing target information"); auto FileCharacter = IsSystem ? SrcMgr::C_System : SrcMgr::C_User; FileID ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter); const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID); if (!Buffer) { // HLSL Change Starts - the assignment and return value usage are expected, but is flagged as a problem by static analysis // return ParsedModuleMap[File] = true; ParsedModuleMap[File] = true; return true; } // HLSL Change Ends // Parse this module map file. Lexer L(ID, SourceMgr.getBuffer(ID), SourceMgr, MMapLangOpts); ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir, BuiltinIncludeDir, IsSystem); bool Result = Parser.parseModuleMapFile(); ParsedModuleMap[File] = Result; return Result; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/PPCallbacks.cpp
//===--- PPCallbacks.cpp - Callbacks for Preprocessor actions ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Lex/PPCallbacks.h" using namespace clang; void PPChainedCallbacks::anchor() { }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/PPDirectives.cpp
//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Implements # directive processing for the Preprocessor. /// //===----------------------------------------------------------------------===// #include "clang/Lex/Preprocessor.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/ModuleLoader.h" #include "clang/Lex/Pragma.h" #include "llvm/ADT/APInt.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Path.h" #include "llvm/Support/SaveAndRestore.h" #include "clang/Lex/PreprocessorOptions.h" // HLSL Change - ignore line directives. using namespace clang; //===----------------------------------------------------------------------===// // Utility Methods for Preprocessor Directive Handling. //===----------------------------------------------------------------------===// MacroInfo *Preprocessor::AllocateMacroInfo() { MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>(); MIChain->Next = MIChainHead; MIChainHead = MIChain; return &MIChain->MI; } MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) { MacroInfo *MI = AllocateMacroInfo(); new (MI) MacroInfo(L); return MI; } MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L, unsigned SubModuleID) { static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID), "alignment for MacroInfo is less than the ID"); DeserializedMacroInfoChain *MIChain = BP.Allocate<DeserializedMacroInfoChain>(); MIChain->Next = DeserialMIChainHead; DeserialMIChainHead = MIChain; MacroInfo *MI = &MIChain->MI; new (MI) MacroInfo(L); MI->FromASTFile = true; MI->setOwningModuleID(SubModuleID); return MI; } DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI, SourceLocation Loc) { return new (BP) DefMacroDirective(MI, Loc); } UndefMacroDirective * Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) { return new (BP) UndefMacroDirective(UndefLoc); } VisibilityMacroDirective * Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc, bool isPublic) { return new (BP) VisibilityMacroDirective(Loc, isPublic); } /// \brief Read and discard all tokens remaining on the current line until /// the tok::eod token is found. void Preprocessor::DiscardUntilEndOfDirective() { Token Tmp; do { LexUnexpandedToken(Tmp); assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens"); } while (Tmp.isNot(tok::eod)); } /// \brief Enumerates possible cases of #define/#undef a reserved identifier. enum MacroDiag { MD_NoWarn, //> Not a reserved identifier MD_KeywordDef, //> Macro hides keyword, enabled by default MD_ReservedMacro //> #define of #undef reserved id, disabled by default }; /// \brief Checks if the specified identifier is reserved in the specified /// language. /// This function does not check if the identifier is a keyword. static bool isReservedId(StringRef Text, const LangOptions &Lang) { // C++ [macro.names], C11 7.1.3: // All identifiers that begin with an underscore and either an uppercase // letter or another underscore are always reserved for any use. if (Text.size() >= 2 && Text[0] == '_' && (isUppercase(Text[1]) || Text[1] == '_')) return true; // C++ [global.names] // Each name that contains a double underscore ... is reserved to the // implementation for any use. if (Lang.CPlusPlus) { if (Text.find("__") != StringRef::npos) return true; } return false; } static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) { const LangOptions &Lang = PP.getLangOpts(); StringRef Text = II->getName(); if (isReservedId(Text, Lang)) return MD_ReservedMacro; if (II->isKeyword(Lang)) return MD_KeywordDef; if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final"))) return MD_KeywordDef; return MD_NoWarn; } static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) { const LangOptions &Lang = PP.getLangOpts(); StringRef Text = II->getName(); // Do not warn on keyword undef. It is generally harmless and widely used. if (isReservedId(Text, Lang)) return MD_ReservedMacro; return MD_NoWarn; } bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef, bool *ShadowFlag) { // Missing macro name? if (MacroNameTok.is(tok::eod)) return Diag(MacroNameTok, diag::err_pp_missing_macro_name); IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); if (!II) { bool Invalid = false; std::string Spelling = getSpelling(MacroNameTok, &Invalid); if (Invalid) return Diag(MacroNameTok, diag::err_pp_macro_not_identifier); II = getIdentifierInfo(Spelling); if (!II->isCPlusPlusOperatorKeyword() || getLangOpts().HLSL) // HLSL Change: guard against HLSL return Diag(MacroNameTok, diag::err_pp_macro_not_identifier); // C++ 2.5p2: Alternative tokens behave the same as its primary token // except for their spellings. Diag(MacroNameTok, getLangOpts().MicrosoftExt ? diag::ext_pp_operator_used_as_macro_name : diag::err_pp_operator_used_as_macro_name) << II << MacroNameTok.getKind(); // Allow #defining |and| and friends for Microsoft compatibility or // recovery when legacy C headers are included in C++. MacroNameTok.setIdentifierInfo(II); } if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) { // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4. return Diag(MacroNameTok, diag::err_defined_macro_name); } if (isDefineUndef == MU_Undef) { auto *MI = getMacroInfo(II); if (MI && MI->isBuiltinMacro()) { // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4 // and C++ [cpp.predefined]p4], but allow it as an extension. Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro); } } // If defining/undefining reserved identifier or a keyword, we need to issue // a warning. SourceLocation MacroNameLoc = MacroNameTok.getLocation(); if (ShadowFlag) *ShadowFlag = false; if (!SourceMgr.isInSystemHeader(MacroNameLoc) && (strcmp(SourceMgr.getBufferName(MacroNameLoc), "<built-in>") != 0)) { MacroDiag D = MD_NoWarn; if (isDefineUndef == MU_Define) { D = shouldWarnOnMacroDef(*this, II); } else if (isDefineUndef == MU_Undef) D = shouldWarnOnMacroUndef(*this, II); if (D == MD_KeywordDef) { // We do not want to warn on some patterns widely used in configuration // scripts. This requires analyzing next tokens, so do not issue warnings // now, only inform caller. if (ShadowFlag) *ShadowFlag = true; } if (D == MD_ReservedMacro) Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id); } // Okay, we got a good identifier. return false; } /// \brief Lex and validate a macro name, which occurs after a /// \#define or \#undef. /// /// This sets the token kind to eod and discards the rest of the macro line if /// the macro name is invalid. /// /// \param MacroNameTok Token that is expected to be a macro name. /// \param isDefineUndef Context in which macro is used. /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword. void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef, bool *ShadowFlag) { // Read the token, don't allow macro expansion on it. LexUnexpandedToken(MacroNameTok); if (MacroNameTok.is(tok::code_completion)) { if (CodeComplete) CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define); setCodeCompletionReached(); LexUnexpandedToken(MacroNameTok); } if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag)) return; // Invalid macro name, read and discard the rest of the line and set the // token kind to tok::eod if necessary. if (MacroNameTok.isNot(tok::eod)) { MacroNameTok.setKind(tok::eod); DiscardUntilEndOfDirective(); } } /// \brief Ensure that the next token is a tok::eod token. /// /// If not, emit a diagnostic and consume up until the eod. If EnableMacros is /// true, then we consider macros that expand to zero tokens as being ok. void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) { Token Tmp; // Lex unexpanded tokens for most directives: macros might expand to zero // tokens, causing us to miss diagnosing invalid lines. Some directives (like // #line) allow empty macros. if (EnableMacros) Lex(Tmp); else LexUnexpandedToken(Tmp); // There should be no tokens after the directive, but we allow them as an // extension. while (Tmp.is(tok::comment)) // Skip comments in -C mode. LexUnexpandedToken(Tmp); if (Tmp.isNot(tok::eod)) { // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89, // or if this is a macro-style preprocessing directive, because it is more // trouble than it is worth to insert /**/ and check that there is no /**/ // in the range also. FixItHint Hint; if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) && !CurTokenLexer) Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//"); Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint; DiscardUntilEndOfDirective(); } } /// SkipExcludedConditionalBlock - We just read a \#if or related directive and /// decided that the subsequent tokens are in the \#if'd out portion of the /// file. Lex the rest of the file, until we see an \#endif. If /// FoundNonSkipPortion is true, then we have already emitted code for part of /// this \#if directive, so \#else/\#elif blocks should never be entered. /// If ElseOk is true, then \#else directives are ok, if not, then we have /// already seen one so a \#else directive is a duplicate. When this returns, /// the caller can lex the first valid token. void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, bool FoundNonSkipPortion, bool FoundElse, SourceLocation ElseLoc) { ++NumSkipped; assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?"); CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false, FoundNonSkipPortion, FoundElse); if (CurPTHLexer) { PTHSkipExcludedConditionalBlock(); return; } // Enter raw mode to disable identifier lookup (and thus macro expansion), // disabling warnings, etc. CurPPLexer->LexingRawMode = true; Token Tok; while (1) { CurLexer->Lex(Tok); if (Tok.is(tok::code_completion)) { if (CodeComplete) CodeComplete->CodeCompleteInConditionalExclusion(); setCodeCompletionReached(); continue; } // If this is the end of the buffer, we have an error. if (Tok.is(tok::eof)) { // Emit errors for each unterminated conditional on the stack, including // the current one. while (!CurPPLexer->ConditionalStack.empty()) { if (CurLexer->getFileLoc() != CodeCompletionFileLoc) Diag(CurPPLexer->ConditionalStack.back().IfLoc, diag::err_pp_unterminated_conditional); CurPPLexer->ConditionalStack.pop_back(); } // Just return and let the caller lex after this #include. break; } // If this token is not a preprocessor directive, just skip it. if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) continue; // We just parsed a # character at the start of a line, so we're in // directive mode. Tell the lexer this so any newlines we see will be // converted into an EOD token (this terminates the macro). CurPPLexer->ParsingPreprocessorDirective = true; if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); // Read the next token, the directive flavor. LexUnexpandedToken(Tok); // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or // something bogus), skip it. if (Tok.isNot(tok::raw_identifier)) { CurPPLexer->ParsingPreprocessorDirective = false; // Restore comment saving mode. if (CurLexer) CurLexer->resetExtendedTokenMode(); continue; } // If the first letter isn't i or e, it isn't intesting to us. We know that // this is safe in the face of spelling differences, because there is no way // to spell an i/e in a strange way that is another letter. Skipping this // allows us to avoid looking up the identifier info for #define/#undef and // other common directives. StringRef RI = Tok.getRawIdentifier(); char FirstChar = RI[0]; if (FirstChar >= 'a' && FirstChar <= 'z' && FirstChar != 'i' && FirstChar != 'e') { CurPPLexer->ParsingPreprocessorDirective = false; // Restore comment saving mode. if (CurLexer) CurLexer->resetExtendedTokenMode(); continue; } // Get the identifier name without trigraphs or embedded newlines. Note // that we can't use Tok.getIdentifierInfo() because its lookup is disabled // when skipping. char DirectiveBuf[20]; StringRef Directive; if (!Tok.needsCleaning() && RI.size() < 20) { Directive = RI; } else { std::string DirectiveStr = getSpelling(Tok); unsigned IdLen = DirectiveStr.size(); if (IdLen >= 20) { CurPPLexer->ParsingPreprocessorDirective = false; // Restore comment saving mode. if (CurLexer) CurLexer->resetExtendedTokenMode(); continue; } memcpy(DirectiveBuf, &DirectiveStr[0], IdLen); Directive = StringRef(DirectiveBuf, IdLen); } if (Directive.startswith("if")) { StringRef Sub = Directive.substr(2); if (Sub.empty() || // "if" Sub == "def" || // "ifdef" Sub == "ndef") { // "ifndef" // We know the entire #if/#ifdef/#ifndef block will be skipped, don't // bother parsing the condition. DiscardUntilEndOfDirective(); CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true, /*foundnonskip*/false, /*foundelse*/false); } } else if (Directive[0] == 'e') { StringRef Sub = Directive.substr(1); if (Sub == "ndif") { // "endif" PPConditionalInfo CondInfo; CondInfo.WasSkipping = true; // Silence bogus warning. bool InCond = CurPPLexer->popConditionalLevel(CondInfo); (void)InCond; // Silence warning in no-asserts mode. assert(!InCond && "Can't be skipping if not in a conditional!"); // If we popped the outermost skipping block, we're done skipping! if (!CondInfo.WasSkipping) { // Restore the value of LexingRawMode so that trailing comments // are handled correctly, if we've reached the outermost block. CurPPLexer->LexingRawMode = false; CheckEndOfDirective("endif"); CurPPLexer->LexingRawMode = true; if (Callbacks) Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc); break; } else { DiscardUntilEndOfDirective(); } } else if (Sub == "lse") { // "else". // #else directive in a skipping conditional. If not in some other // skipping conditional, and if #else hasn't already been seen, enter it // as a non-skipping conditional. PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); // If this is a #else with a #else before it, report the error. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else); // Note that we've seen a #else in this conditional. CondInfo.FoundElse = true; // If the conditional is at the top level, and the #if block wasn't // entered, enter the #else block now. if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) { CondInfo.FoundNonSkip = true; // Restore the value of LexingRawMode so that trailing comments // are handled correctly. CurPPLexer->LexingRawMode = false; CheckEndOfDirective("else"); CurPPLexer->LexingRawMode = true; if (Callbacks) Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc); break; } else { DiscardUntilEndOfDirective(); // C99 6.10p4. } } else if (Sub == "lif") { // "elif". PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); // If this is a #elif with a #else before it, report the error. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); // If this is in a skipping block or if we're already handled this #if // block, don't bother parsing the condition. if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) { DiscardUntilEndOfDirective(); } else { const SourceLocation CondBegin = CurPPLexer->getSourceLocation(); // Restore the value of LexingRawMode so that identifiers are // looked up, etc, inside the #elif expression. assert(CurPPLexer->LexingRawMode && "We have to be skipping here!"); CurPPLexer->LexingRawMode = false; IdentifierInfo *IfNDefMacro = nullptr; const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro); CurPPLexer->LexingRawMode = true; if (Callbacks) { const SourceLocation CondEnd = CurPPLexer->getSourceLocation(); Callbacks->Elif(Tok.getLocation(), SourceRange(CondBegin, CondEnd), (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc); } // If this condition is true, enter it! if (CondValue) { CondInfo.FoundNonSkip = true; break; } } } } CurPPLexer->ParsingPreprocessorDirective = false; // Restore comment saving mode. if (CurLexer) CurLexer->resetExtendedTokenMode(); } // Finally, if we are out of the conditional (saw an #endif or ran off the end // of the file, just stop skipping and return to lexing whatever came after // the #if block. CurPPLexer->LexingRawMode = false; if (Callbacks) { SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc; Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation())); } } void Preprocessor::PTHSkipExcludedConditionalBlock() { while (1) { assert(CurPTHLexer); assert(CurPTHLexer->LexingRawMode == false); // Skip to the next '#else', '#elif', or #endif. if (CurPTHLexer->SkipBlock()) { // We have reached an #endif. Both the '#' and 'endif' tokens // have been consumed by the PTHLexer. Just pop off the condition level. PPConditionalInfo CondInfo; bool InCond = CurPTHLexer->popConditionalLevel(CondInfo); (void)InCond; // Silence warning in no-asserts mode. assert(!InCond && "Can't be skipping if not in a conditional!"); break; } // We have reached a '#else' or '#elif'. Lex the next token to get // the directive flavor. Token Tok; LexUnexpandedToken(Tok); // We can actually look up the IdentifierInfo here since we aren't in // raw mode. tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID(); if (K == tok::pp_else) { // #else: Enter the else condition. We aren't in a nested condition // since we skip those. We're always in the one matching the last // blocked we skipped. PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); // Note that we've seen a #else in this conditional. CondInfo.FoundElse = true; // If the #if block wasn't entered then enter the #else block now. if (!CondInfo.FoundNonSkip) { CondInfo.FoundNonSkip = true; // Scan until the eod token. CurPTHLexer->ParsingPreprocessorDirective = true; DiscardUntilEndOfDirective(); CurPTHLexer->ParsingPreprocessorDirective = false; break; } // Otherwise skip this block. continue; } assert(K == tok::pp_elif); PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel(); // If this is a #elif with a #else before it, report the error. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); // If this is in a skipping block or if we're already handled this #if // block, don't bother parsing the condition. We just skip this block. if (CondInfo.FoundNonSkip) continue; // Evaluate the condition of the #elif. IdentifierInfo *IfNDefMacro = nullptr; CurPTHLexer->ParsingPreprocessorDirective = true; bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro); CurPTHLexer->ParsingPreprocessorDirective = false; // If this condition is true, enter it! if (ShouldEnter) { CondInfo.FoundNonSkip = true; break; } // Otherwise, skip this block and go to the next one. continue; } } Module *Preprocessor::getModuleForLocation(SourceLocation Loc) { ModuleMap &ModMap = HeaderInfo.getModuleMap(); if (SourceMgr.isInMainFile(Loc)) { if (Module *CurMod = getCurrentModule()) return CurMod; // Compiling a module. return HeaderInfo.getModuleMap().SourceModule; // Compiling a source. } // Try to determine the module of the include directive. // FIXME: Look into directly passing the FileEntry from LookupFile instead. FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc)); if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) { // The include comes from a file. return ModMap.findModuleForHeader(EntryOfIncl).getModule(); } else { // The include does not come from a file, // so it is probably a module compilation. return getCurrentModule(); } } Module *Preprocessor::getModuleContainingLocation(SourceLocation Loc) { return HeaderInfo.getModuleMap().inferModuleFromLocation( FullSourceLoc(Loc, SourceMgr)); } const FileEntry *Preprocessor::LookupFile( SourceLocation FilenameLoc, StringRef Filename, bool isAngled, const DirectoryLookup *FromDir, const FileEntry *FromFile, const DirectoryLookup *&CurDir, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) { // If the header lookup mechanism may be relative to the current inclusion // stack, record the parent #includes. SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16> Includers; if (!FromDir && !FromFile) { FileID FID = getCurrentFileLexer()->getFileID(); const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID); // If there is no file entry associated with this file, it must be the // predefines buffer or the module includes buffer. Any other file is not // lexed with a normal lexer, so it won't be scanned for preprocessor // directives. // // If we have the predefines buffer, resolve #include references (which come // from the -include command line argument) from the current working // directory instead of relative to the main file. // // If we have the module includes buffer, resolve #include references (which // come from header declarations in the module map) relative to the module // map file. if (!FileEnt) { if (FID == SourceMgr.getMainFileID() && MainFileDir) Includers.push_back(std::make_pair(nullptr, MainFileDir)); else if ((FileEnt = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()))) Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory("."))); } else { Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir())); } // MSVC searches the current include stack from top to bottom for // headers included by quoted include directives. // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx if ((LangOpts.MSVCCompat || LangOpts.HLSL) && !isAngled) { // HLSL Change - use MSVC compat behavior for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1]; if (IsFileLexer(ISEntry)) if ((FileEnt = SourceMgr.getFileEntryForID( ISEntry.ThePPLexer->getFileID()))) Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir())); } } } CurDir = CurDirLookup; if (FromFile) { // We're supposed to start looking from after a particular file. Search // the include path until we find that file or run out of files. const DirectoryLookup *TmpCurDir = CurDir; const DirectoryLookup *TmpFromDir = nullptr; while (const FileEntry *FE = HeaderInfo.LookupFile( Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir, Includers, SearchPath, RelativePath, SuggestedModule, SkipCache)) { // Keep looking as if this file did a #include_next. TmpFromDir = TmpCurDir; ++TmpFromDir; if (FE == FromFile) { // Found it. FromDir = TmpFromDir; CurDir = TmpCurDir; break; } } } // Do a standard file entry lookup. const FileEntry *FE = HeaderInfo.LookupFile( Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath, RelativePath, SuggestedModule, SkipCache); if (FE) { if (SuggestedModule && !LangOpts.AsmPreprocessor) HeaderInfo.getModuleMap().diagnoseHeaderInclusion( getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE); return FE; } const FileEntry *CurFileEnt; // Otherwise, see if this is a subframework header. If so, this is relative // to one of the headers on the #include stack. Walk the list of the current // headers on the #include stack and pass them to HeaderInfo. if (IsFileLexer()) { if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) { if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt, SearchPath, RelativePath, SuggestedModule))) { if (SuggestedModule && !LangOpts.AsmPreprocessor) HeaderInfo.getModuleMap().diagnoseHeaderInclusion( getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE); return FE; } } } for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1]; if (IsFileLexer(ISEntry)) { if ((CurFileEnt = SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) { if ((FE = HeaderInfo.LookupSubframeworkHeader( Filename, CurFileEnt, SearchPath, RelativePath, SuggestedModule))) { if (SuggestedModule && !LangOpts.AsmPreprocessor) HeaderInfo.getModuleMap().diagnoseHeaderInclusion( getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE); return FE; } } } } // Otherwise, we really couldn't find the file. return nullptr; } //===----------------------------------------------------------------------===// // Preprocessor Directive Handling. //===----------------------------------------------------------------------===// class Preprocessor::ResetMacroExpansionHelper { public: ResetMacroExpansionHelper(Preprocessor *pp) : PP(pp), save(pp->DisableMacroExpansion) { if (pp->MacroExpansionInDirectivesOverride) pp->DisableMacroExpansion = false; } ~ResetMacroExpansionHelper() { PP->DisableMacroExpansion = save; } private: Preprocessor *PP; bool save; }; /// HandleDirective - This callback is invoked when the lexer sees a # token /// at the start of a line. This consumes the directive, modifies the /// lexer/preprocessor state, and advances the lexer(s) so that the next token /// read is the correct one. void Preprocessor::HandleDirective(Token &Result) { // FIXME: Traditional: # with whitespace before it not recognized by K&R? // We just parsed a # character at the start of a line, so we're in directive // mode. Tell the lexer this so any newlines we see will be converted into an // EOD token (which terminates the directive). CurPPLexer->ParsingPreprocessorDirective = true; if (CurLexer) CurLexer->SetKeepWhitespaceMode(false); bool ImmediatelyAfterTopLevelIfndef = CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef(); CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef(); ++NumDirectives; // We are about to read a token. For the multiple-include optimization FA to // work, we have to remember if we had read any tokens *before* this // pp-directive. bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal(); // Save the '#' token in case we need to return it later. Token SavedHash = Result; // Read the next token, the directive flavor. This isn't expanded due to // C99 6.10.3p8. LexUnexpandedToken(Result); // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.: // #define A(x) #x // A(abc // #warning blah // def) // If so, the user is relying on undefined behavior, emit a diagnostic. Do // not support this for #include-like directives, since that can result in // terrible diagnostics, and does not work in GCC. if (InMacroArgs) { if (IdentifierInfo *II = Result.getIdentifierInfo()) { switch (II->getPPKeywordID()) { case tok::pp_include: case tok::pp_import: case tok::pp_include_next: case tok::pp___include_macros: case tok::pp_pragma: Diag(Result, diag::err_embedded_directive) << II->getName(); DiscardUntilEndOfDirective(); return; default: break; } } Diag(Result, diag::ext_embedded_directive); } // Temporarily enable macro expansion if set so // and reset to previous state when returning from this function. ResetMacroExpansionHelper helper(this); switch (Result.getKind()) { case tok::eod: return; // null directive. case tok::code_completion: if (CodeComplete) CodeComplete->CodeCompleteDirective( CurPPLexer->getConditionalStackDepth() > 0); setCodeCompletionReached(); return; case tok::numeric_constant: // # 7 GNU line marker directive. if (getLangOpts().AsmPreprocessor) break; // # 4 is not a preprocessor directive in .S files. return HandleDigitDirective(Result); default: IdentifierInfo *II = Result.getIdentifierInfo(); if (!II) break; // Not an identifier. // Ask what the preprocessor keyword ID is. switch (II->getPPKeywordID()) { default: break; // C99 6.10.1 - Conditional Inclusion. case tok::pp_if: return HandleIfDirective(Result, ReadAnyTokensBeforeDirective); case tok::pp_ifdef: return HandleIfdefDirective(Result, false, true/*not valid for miopt*/); case tok::pp_ifndef: return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective); case tok::pp_elif: return HandleElifDirective(Result); case tok::pp_else: return HandleElseDirective(Result); case tok::pp_endif: return HandleEndifDirective(Result); // C99 6.10.2 - Source File Inclusion. case tok::pp_include: // Handle #include. return HandleIncludeDirective(SavedHash.getLocation(), Result); case tok::pp___include_macros: // Handle -imacros. return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result); // C99 6.10.3 - Macro Replacement. case tok::pp_define: return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef); case tok::pp_undef: return HandleUndefDirective(Result); // C99 6.10.4 - Line Control. case tok::pp_line: return HandleLineDirective(Result); // C99 6.10.5 - Error Directive. case tok::pp_error: return HandleUserDiagnosticDirective(Result, false); // C99 6.10.6 - Pragma Directive. case tok::pp_pragma: return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma); // GNU Extensions. case tok::pp_import: if (getLangOpts().HLSL) break; // HLSL Change - disable #import return HandleImportDirective(SavedHash.getLocation(), Result); case tok::pp_include_next: if (getLangOpts().HLSL) break; // HLSL Change - disable #include_next return HandleIncludeNextDirective(SavedHash.getLocation(), Result); case tok::pp_warning: Diag(Result, diag::ext_pp_warning_directive); return HandleUserDiagnosticDirective(Result, true); case tok::pp_ident: if (getLangOpts().HLSL) break; // HLSL Change - disable #ident return HandleIdentSCCSDirective(Result); case tok::pp_sccs: if (getLangOpts().HLSL) break; // HLSL Change - disable #sccs return HandleIdentSCCSDirective(Result); case tok::pp_assert: //isExtension = true; // FIXME: implement #assert break; case tok::pp_unassert: //isExtension = true; // FIXME: implement #unassert break; case tok::pp___public_macro: if (getLangOpts().Modules) return HandleMacroPublicDirective(Result); break; case tok::pp___private_macro: if (getLangOpts().Modules) return HandleMacroPrivateDirective(Result); break; } break; } // If this is a .S file, treat unknown # directives as non-preprocessor // directives. This is important because # may be a comment or introduce // various pseudo-ops. Just return the # token and push back the following // token to be lexed next time. if (getLangOpts().AsmPreprocessor) { Token *Toks = new Token[2]; // Return the # and the token after it. Toks[0] = SavedHash; Toks[1] = Result; // If the second token is a hashhash token, then we need to translate it to // unknown so the token lexer doesn't try to perform token pasting. if (Result.is(tok::hashhash)) Toks[1].setKind(tok::unknown); // Enter this token stream so that we re-lex the tokens. Make sure to // enable macro expansion, in case the token after the # is an identifier // that is expanded. EnterTokenStream(Toks, 2, false, true); return; } // If we reached here, the preprocessing token is not valid! Diag(Result, diag::err_pp_invalid_directive); // Read the rest of the PP line. DiscardUntilEndOfDirective(); // Okay, we're done parsing the directive. } /// GetLineValue - Convert a numeric token into an unsigned value, emitting /// Diagnostic DiagID if it is invalid, and returning the value in Val. static bool GetLineValue(Token &DigitTok, unsigned &Val, unsigned DiagID, Preprocessor &PP, bool IsGNULineDirective=false) { if (DigitTok.isNot(tok::numeric_constant)) { PP.Diag(DigitTok, DiagID); if (DigitTok.isNot(tok::eod)) PP.DiscardUntilEndOfDirective(); return true; } SmallString<64> IntegerBuffer; IntegerBuffer.resize(DigitTok.getLength()); const char *DigitTokBegin = &IntegerBuffer[0]; bool Invalid = false; unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid); if (Invalid) return true; // Verify that we have a simple digit-sequence, and compute the value. This // is always a simple digit string computed in decimal, so we do this manually // here. Val = 0; for (unsigned i = 0; i != ActualLength; ++i) { // C++1y [lex.fcon]p1: // Optional separating single quotes in a digit-sequence are ignored if (DigitTokBegin[i] == '\'') continue; if (!isDigit(DigitTokBegin[i])) { PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i), diag::err_pp_line_digit_sequence) << IsGNULineDirective; PP.DiscardUntilEndOfDirective(); return true; } unsigned NextVal = Val*10+(DigitTokBegin[i]-'0'); if (NextVal < Val) { // overflow. PP.Diag(DigitTok, DiagID); PP.DiscardUntilEndOfDirective(); return true; } Val = NextVal; } if (DigitTokBegin[0] == '0' && Val) PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal) << IsGNULineDirective; return false; } /// \brief Handle a \#line directive: C99 6.10.4. /// /// The two acceptable forms are: /// \verbatim /// # line digit-sequence /// # line digit-sequence "s-char-sequence" /// \endverbatim void Preprocessor::HandleLineDirective(Token &Tok) { // Read the line # and string argument. Per C99 6.10.4p5, these tokens are // expanded. Token DigitTok; Lex(DigitTok); // Validate the number and convert it to an unsigned. unsigned LineNo; if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this)) return; if (LineNo == 0) Diag(DigitTok, diag::ext_pp_line_zero); // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a // number greater than 2147483647". C90 requires that the line # be <= 32767. unsigned LineLimit = 32768U; if (LangOpts.C99 || LangOpts.CPlusPlus11) LineLimit = 2147483648U; if (LineNo >= LineLimit) Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit; else if (LangOpts.CPlusPlus11 && LineNo >= 32768U) Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big); int FilenameID = -1; Token StrTok; Lex(StrTok); // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a // string followed by eod. if (StrTok.is(tok::eod)) ; // ok else if (StrTok.isNot(tok::string_literal)) { Diag(StrTok, diag::err_pp_line_invalid_filename); return DiscardUntilEndOfDirective(); } else if (StrTok.hasUDSuffix()) { Diag(StrTok, diag::err_invalid_string_udl); return DiscardUntilEndOfDirective(); } else { // Parse and validate the string, converting it into a unique ID. StringLiteralParser Literal(StrTok, *this); assert(Literal.isAscii() && "Didn't allow wide strings in"); if (Literal.hadError) return DiscardUntilEndOfDirective(); if (Literal.Pascal) { Diag(StrTok, diag::err_pp_linemarker_invalid_filename); return DiscardUntilEndOfDirective(); } FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString()); // Verify that there is nothing after the string, other than EOD. Because // of C99 6.10.4p5, macros that expand to empty tokens are ok. CheckEndOfDirective("line", true); } // HLSL Change Begin - ignore line directives. if (PPOpts->IgnoreLineDirectives) return; // HLSL Change End SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID); if (Callbacks) Callbacks->FileChanged(CurPPLexer->getSourceLocation(), PPCallbacks::RenameFile, SrcMgr::C_User); } /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line /// marker directive. static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit, bool &IsSystemHeader, bool &IsExternCHeader, Preprocessor &PP) { unsigned FlagVal; Token FlagTok; PP.Lex(FlagTok); if (FlagTok.is(tok::eod)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) return true; if (FlagVal == 1) { IsFileEntry = true; PP.Lex(FlagTok); if (FlagTok.is(tok::eod)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) return true; } else if (FlagVal == 2) { IsFileExit = true; SourceManager &SM = PP.getSourceManager(); // If we are leaving the current presumed file, check to make sure the // presumed include stack isn't empty! FileID CurFileID = SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first; PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation()); if (PLoc.isInvalid()) return true; // If there is no include loc (main file) or if the include loc is in a // different physical file, then we aren't in a "1" line marker flag region. SourceLocation IncLoc = PLoc.getIncludeLoc(); if (IncLoc.isInvalid() || SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) { PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop); PP.DiscardUntilEndOfDirective(); return true; } PP.Lex(FlagTok); if (FlagTok.is(tok::eod)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP)) return true; } // We must have 3 if there are still flags. if (FlagVal != 3) { PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); PP.DiscardUntilEndOfDirective(); return true; } IsSystemHeader = true; PP.Lex(FlagTok); if (FlagTok.is(tok::eod)) return false; if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP)) return true; // We must have 4 if there is yet another flag. if (FlagVal != 4) { PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); PP.DiscardUntilEndOfDirective(); return true; } IsExternCHeader = true; PP.Lex(FlagTok); if (FlagTok.is(tok::eod)) return false; // There are no more valid flags here. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag); PP.DiscardUntilEndOfDirective(); return true; } /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is /// one of the following forms: /// /// # 42 /// # 42 "file" ('1' | '2')? /// # 42 "file" ('1' | '2')? '3' '4'? /// void Preprocessor::HandleDigitDirective(Token &DigitTok) { // Validate the number and convert it to an unsigned. GNU does not have a // line # limit other than it fit in 32-bits. unsigned LineNo; if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer, *this, true)) return; Token StrTok; Lex(StrTok); bool IsFileEntry = false, IsFileExit = false; bool IsSystemHeader = false, IsExternCHeader = false; int FilenameID = -1; // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a // string followed by eod. if (StrTok.is(tok::eod)) ; // ok else if (StrTok.isNot(tok::string_literal)) { Diag(StrTok, diag::err_pp_linemarker_invalid_filename); return DiscardUntilEndOfDirective(); } else if (StrTok.hasUDSuffix()) { Diag(StrTok, diag::err_invalid_string_udl); return DiscardUntilEndOfDirective(); } else { // Parse and validate the string, converting it into a unique ID. StringLiteralParser Literal(StrTok, *this); assert(Literal.isAscii() && "Didn't allow wide strings in"); if (Literal.hadError) return DiscardUntilEndOfDirective(); if (Literal.Pascal) { Diag(StrTok, diag::err_pp_linemarker_invalid_filename); return DiscardUntilEndOfDirective(); } FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString()); // If a filename was present, read any flags that are present. if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, IsSystemHeader, IsExternCHeader, *this)) return; } // Create a line note with this information. SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry, IsFileExit, IsSystemHeader, IsExternCHeader); // If the preprocessor has callbacks installed, notify them of the #line // change. This is used so that the line marker comes out in -E mode for // example. if (Callbacks) { PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile; if (IsFileEntry) Reason = PPCallbacks::EnterFile; else if (IsFileExit) Reason = PPCallbacks::ExitFile; SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User; if (IsExternCHeader) FileKind = SrcMgr::C_ExternCSystem; else if (IsSystemHeader) FileKind = SrcMgr::C_System; Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind); } } /// HandleUserDiagnosticDirective - Handle a #warning or #error directive. /// void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, bool isWarning) { // PTH doesn't emit #warning or #error directives. if (CurPTHLexer) return CurPTHLexer->DiscardToEndOfLine(); // Read the rest of the line raw. We do this because we don't want macros // to be expanded and we don't require that the tokens be valid preprocessing // tokens. For example, this is allowed: "#warning ` 'foo". GCC does // collapse multiple consequtive white space between tokens, but this isn't // specified by the standard. SmallString<128> Message; CurLexer->ReadToEndOfLine(&Message); // Find the first non-whitespace character, so that we can make the // diagnostic more succinct. StringRef Msg = StringRef(Message).ltrim(" "); if (isWarning) Diag(Tok, diag::pp_hash_warning) << Msg; else Diag(Tok, diag::err_pp_hash_error) << Msg; } /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive. /// void Preprocessor::HandleIdentSCCSDirective(Token &Tok) { // Yes, this directive is an extension. Diag(Tok, diag::ext_pp_ident_directive); // Read the string argument. Token StrTok; Lex(StrTok); // If the token kind isn't a string, it's a malformed directive. if (StrTok.isNot(tok::string_literal) && StrTok.isNot(tok::wide_string_literal)) { Diag(StrTok, diag::err_pp_malformed_ident); if (StrTok.isNot(tok::eod)) DiscardUntilEndOfDirective(); return; } if (StrTok.hasUDSuffix()) { Diag(StrTok, diag::err_invalid_string_udl); return DiscardUntilEndOfDirective(); } // Verify that there is nothing after the string, other than EOD. CheckEndOfDirective("ident"); if (Callbacks) { bool Invalid = false; std::string Str = getSpelling(StrTok, &Invalid); if (!Invalid) Callbacks->Ident(Tok.getLocation(), Str); } } /// \brief Handle a #public directive. void Preprocessor::HandleMacroPublicDirective(Token &Tok) { Token MacroNameTok; ReadMacroName(MacroNameTok, MU_Undef); // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eod)) return; // Check to see if this is the last token on the #__public_macro line. CheckEndOfDirective("__public_macro"); IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); // Okay, we finally have a valid identifier to undef. MacroDirective *MD = getLocalMacroDirective(II); // If the macro is not defined, this is an error. if (!MD) { Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II; return; } // Note that this macro has now been exported. appendMacroDirective(II, AllocateVisibilityMacroDirective( MacroNameTok.getLocation(), /*IsPublic=*/true)); } /// \brief Handle a #private directive. void Preprocessor::HandleMacroPrivateDirective(Token &Tok) { Token MacroNameTok; ReadMacroName(MacroNameTok, MU_Undef); // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eod)) return; // Check to see if this is the last token on the #__private_macro line. CheckEndOfDirective("__private_macro"); IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); // Okay, we finally have a valid identifier to undef. MacroDirective *MD = getLocalMacroDirective(II); // If the macro is not defined, this is an error. if (!MD) { Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II; return; } // Note that this macro has now been marked private. appendMacroDirective(II, AllocateVisibilityMacroDirective( MacroNameTok.getLocation(), /*IsPublic=*/false)); } //===----------------------------------------------------------------------===// // Preprocessor Include Directive Handling. //===----------------------------------------------------------------------===// /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully /// checked and spelled filename, e.g. as an operand of \#include. This returns /// true if the input filename was in <>'s or false if it were in ""'s. The /// caller is expected to provide a buffer that is large enough to hold the /// spelling of the filename, but is also expected to handle the case when /// this method decides to use a different buffer. bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Buffer) { // Get the text form of the filename. assert(!Buffer.empty() && "Can't have tokens with empty spellings!"); // Make sure the filename is <x> or "x". bool isAngled; if (Buffer[0] == '<') { if (Buffer.back() != '>') { Diag(Loc, diag::err_pp_expects_filename); Buffer = StringRef(); return true; } isAngled = true; } else if (Buffer[0] == '"') { if (Buffer.back() != '"') { Diag(Loc, diag::err_pp_expects_filename); Buffer = StringRef(); return true; } isAngled = false; } else { Diag(Loc, diag::err_pp_expects_filename); Buffer = StringRef(); return true; } // Diagnose #include "" as invalid. if (Buffer.size() <= 2) { Diag(Loc, diag::err_pp_empty_filename); Buffer = StringRef(); return true; } // Skip the brackets. Buffer = Buffer.substr(1, Buffer.size()-2); return isAngled; } // \brief Handle cases where the \#include name is expanded from a macro // as multiple tokens, which need to be glued together. // // This occurs for code like: // \code // \#define FOO <a/b.h> // \#include FOO // \endcode // because in this case, "<a/b.h>" is returned as 7 tokens, not one. // // This code concatenates and consumes tokens up to the '>' token. It returns // false if the > was found, otherwise it returns true if it finds and consumes // the EOD marker. bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer, SourceLocation &End) { Token CurTok; Lex(CurTok); while (CurTok.isNot(tok::eod)) { End = CurTok.getLocation(); // FIXME: Provide code completion for #includes. if (CurTok.is(tok::code_completion)) { setCodeCompletionReached(); Lex(CurTok); continue; } // Append the spelling of this token to the buffer. If there was a space // before it, add it now. if (CurTok.hasLeadingSpace()) FilenameBuffer.push_back(' '); // Get the spelling of the token, directly into FilenameBuffer if possible. unsigned PreAppendSize = FilenameBuffer.size(); FilenameBuffer.resize(PreAppendSize+CurTok.getLength()); const char *BufPtr = &FilenameBuffer[PreAppendSize]; unsigned ActualLen = getSpelling(CurTok, BufPtr); // If the token was spelled somewhere else, copy it into FilenameBuffer. if (BufPtr != &FilenameBuffer[PreAppendSize]) memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen); // Resize FilenameBuffer to the correct size. if (CurTok.getLength() != ActualLen) FilenameBuffer.resize(PreAppendSize+ActualLen); // If we found the '>' marker, return success. if (CurTok.is(tok::greater)) return false; Lex(CurTok); } // If we hit the eod marker, emit an error and return true so that the caller // knows the EOD has been read. Diag(CurTok.getLocation(), diag::err_pp_expects_filename); return true; } /// \brief Push a token onto the token stream containing an annotation. static void EnterAnnotationToken(Preprocessor &PP, SourceLocation Begin, SourceLocation End, tok::TokenKind Kind, void *AnnotationVal) { // FIXME: Produce this as the current token directly, rather than // allocating a new token for it. Token *Tok = new Token[1]; Tok[0].startToken(); Tok[0].setKind(Kind); Tok[0].setLocation(Begin); Tok[0].setAnnotationEndLoc(End); Tok[0].setAnnotationValue(AnnotationVal); PP.EnterTokenStream(Tok, 1, true, true); } /// \brief Produce a diagnostic informing the user that a #include or similar /// was implicitly treated as a module import. static void diagnoseAutoModuleImport( Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok, ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path, SourceLocation PathEnd) { assert(PP.getLangOpts().ObjC2 && "no import syntax available"); SmallString<128> PathString; for (unsigned I = 0, N = Path.size(); I != N; ++I) { if (I) PathString += '.'; PathString += Path[I].first->getName(); } int IncludeKind = 0; switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) { case tok::pp_include: IncludeKind = 0; break; case tok::pp_import: IncludeKind = 1; break; case tok::pp_include_next: IncludeKind = 2; break; case tok::pp___include_macros: IncludeKind = 3; break; default: llvm_unreachable("unknown include directive kind"); } CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd), /*IsTokenRange=*/false); PP.Diag(HashLoc, diag::warn_auto_module_import) << IncludeKind << PathString << FixItHint::CreateReplacement(ReplaceRange, ("@import " + PathString + ";").str()); } /// HandleIncludeDirective - The "\#include" tokens have just been read, read /// the file to be included from the lexer, then include it! This is a common /// routine with functionality shared between \#include, \#include_next and /// \#import. LookupFrom is set when this is a \#include_next directive, it /// specifies the file to start searching from. void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc, Token &IncludeTok, const DirectoryLookup *LookupFrom, const FileEntry *LookupFromFile, bool isImport) { Token FilenameTok; CurPPLexer->LexIncludeFilename(FilenameTok); // Reserve a buffer to get the spelling. SmallString<128> FilenameBuffer; StringRef Filename; SourceLocation End; SourceLocation CharEnd; // the end of this directive, in characters switch (FilenameTok.getKind()) { case tok::eod: // If the token kind is EOD, the error has already been diagnosed. return; case tok::angle_string_literal: case tok::string_literal: Filename = getSpelling(FilenameTok, FilenameBuffer); End = FilenameTok.getLocation(); CharEnd = End.getLocWithOffset(FilenameTok.getLength()); break; case tok::less: // This could be a <foo/bar.h> file coming from a macro expansion. In this // case, glue the tokens together into FilenameBuffer and interpret those. FilenameBuffer.push_back('<'); if (ConcatenateIncludeName(FilenameBuffer, End)) return; // Found <eod> but no ">"? Diagnostic already emitted. Filename = FilenameBuffer; CharEnd = End.getLocWithOffset(1); break; default: Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); DiscardUntilEndOfDirective(); return; } CharSourceRange FilenameRange = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd); StringRef OriginalFilename = Filename; bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename); // If GetIncludeFilenameSpelling set the start ptr to null, there was an // error. if (Filename.empty()) { DiscardUntilEndOfDirective(); return; } // Verify that there is nothing after the filename, other than EOD. Note that // we allow macros that expand to nothing after the filename, because this // falls into the category of "#include pp-tokens new-line" specified in // C99 6.10.2p4. CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true); // Check that we don't have infinite #include recursion. if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) { Diag(FilenameTok, diag::err_pp_include_too_deep); return; } // Complain about attempts to #include files in an audit pragma. if (PragmaARCCFCodeAuditedLoc.isValid()) { Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited); Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here); // Immediately leave the pragma. PragmaARCCFCodeAuditedLoc = SourceLocation(); } // Complain about attempts to #include files in an assume-nonnull pragma. if (PragmaAssumeNonNullLoc.isValid()) { Diag(HashLoc, diag::err_pp_include_in_assume_nonnull); Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here); // Immediately leave the pragma. PragmaAssumeNonNullLoc = SourceLocation(); } if (HeaderInfo.HasIncludeAliasMap()) { // Map the filename with the brackets still attached. If the name doesn't // map to anything, fall back on the filename we've already gotten the // spelling for. StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename); if (!NewName.empty()) Filename = NewName; } // Search include directories. const DirectoryLookup *CurDir; SmallString<1024> SearchPath; SmallString<1024> RelativePath; // We get the raw path only if we have 'Callbacks' to which we later pass // the path. ModuleMap::KnownHeader SuggestedModule; SourceLocation FilenameLoc = FilenameTok.getLocation(); SmallString<128> NormalizedPath; if (LangOpts.MSVCCompat || LangOpts.HLSL) { // HLSL Change: use MSVC compat behavior NormalizedPath = Filename.str(); #ifndef LLVM_ON_WIN32 llvm::sys::path::native(NormalizedPath); #endif } const FileEntry *File = LookupFile( FilenameLoc, (LangOpts.MSVCCompat || LangOpts.HLSL) ? NormalizedPath.c_str() : Filename, // HLSL Change: use MSVC compat behavior isAngled, LookupFrom, LookupFromFile, CurDir, Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr, &SuggestedModule); if (!File) { if (Callbacks) { // Give the clients a chance to recover. SmallString<128> RecoveryPath; if (Callbacks->FileNotFound(Filename, RecoveryPath)) { if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) { // Add the recovery path to the list of search paths. DirectoryLookup DL(DE, SrcMgr::C_User, false); HeaderInfo.AddSearchPath(DL, isAngled); // Try the lookup again, skipping the cache. File = LookupFile( FilenameLoc, (LangOpts.MSVCCompat || LangOpts.HLSL) ? NormalizedPath.c_str() : Filename, isAngled, // HLSL Change: use MSVC compat behavior LookupFrom, LookupFromFile, CurDir, nullptr, nullptr, &SuggestedModule, /*SkipCache*/ true); } } } if (!SuppressIncludeNotFoundError) { // If the file could not be located and it was included via angle // brackets, we can attempt a lookup as though it were a quoted path to // provide the user with a possible fixit. if (isAngled) { File = LookupFile( FilenameLoc, (LangOpts.MSVCCompat || LangOpts.HLSL) ? NormalizedPath.c_str() : Filename, false, // HLSL Change: use MSVC compat behavior LookupFrom, LookupFromFile, CurDir, Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr, &SuggestedModule); if (File) { SourceRange Range(FilenameTok.getLocation(), CharEnd); Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) << Filename << FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\""); } } // If the file is still not found, just go with the vanilla diagnostic if (!File) Diag(FilenameTok, diag::err_pp_file_not_found) << Filename; } } // Should we enter the source file? Set to false if either the source file is // known to have no effect beyond its effect on module visibility -- that is, // if it's got an include guard that is already defined or is a modular header // we've imported or already built. bool ShouldEnter = true; // Determine whether we should try to import the module for this #include, if // there is one. Don't do so if precompiled module support is disabled or we // are processing this module textually (because we're building the module). if (File && SuggestedModule && getLangOpts().Modules && SuggestedModule.getModule()->getTopLevelModuleName() != getLangOpts().CurrentModule && SuggestedModule.getModule()->getTopLevelModuleName() != getLangOpts().ImplementationOfModule) { // Compute the module access path corresponding to this module. // FIXME: Should we have a second loadModule() overload to avoid this // extra lookup step? SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent) Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name), FilenameTok.getLocation())); std::reverse(Path.begin(), Path.end()); // Warn that we're replacing the include/import with a module import. // We only do this in Objective-C, where we have a module-import syntax. if (getLangOpts().ObjC2) diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd); // Load the module to import its macros. We'll make the declarations // visible when the parser gets here. // FIXME: Pass SuggestedModule in here rather than converting it to a path // and making the module loader convert it back again. ModuleLoadResult Imported = TheModuleLoader.loadModule( IncludeTok.getLocation(), Path, Module::Hidden, /*IsIncludeDirective=*/true); assert((Imported == nullptr || Imported == SuggestedModule.getModule()) && "the imported module is different than the suggested one"); if (Imported) ShouldEnter = false; else if (Imported.isMissingExpected()) { // We failed to find a submodule that we assumed would exist (because it // was in the directory of an umbrella header, for instance), but no // actual module exists for it (because the umbrella header is // incomplete). Treat this as a textual inclusion. SuggestedModule = ModuleMap::KnownHeader(); } else { // We hit an error processing the import. Bail out. if (hadModuleLoaderFatalFailure()) { // With a fatal failure in the module loader, we abort parsing. Token &Result = IncludeTok; if (CurLexer) { Result.startToken(); CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); CurLexer->cutOffLexing(); } else { assert(CurPTHLexer && "#include but no current lexer set!"); CurPTHLexer->getEOF(Result); } } return; } } if (Callbacks) { // Notify the callback object that we've seen an inclusion directive. Callbacks->InclusionDirective( HashLoc, IncludeTok, (LangOpts.MSVCCompat || LangOpts.HLSL) ? NormalizedPath.c_str() : Filename, isAngled, // HLSL Change: use MSVC compat behavior FilenameRange, File, SearchPath, RelativePath, ShouldEnter ? nullptr : SuggestedModule.getModule()); } if (!File) return; // The #included file will be considered to be a system header if either it is // in a system include directory, or if the #includer is a system include // header. SrcMgr::CharacteristicKind FileCharacter = std::max(HeaderInfo.getFileDirFlavor(File), SourceMgr.getFileCharacteristic(FilenameTok.getLocation())); // FIXME: If we have a suggested module, and we've already visited this file, // don't bother entering it again. We know it has no further effect. // Ask HeaderInfo if we should enter this #include file. If not, #including // this file will have no effect. if (ShouldEnter && !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport, SuggestedModule.getModule())) { ShouldEnter = false; if (Callbacks) Callbacks->FileSkipped(*File, FilenameTok, FileCharacter); } // If we don't need to enter the file, stop now. if (!ShouldEnter) { // If this is a module import, make it visible if needed. if (auto *M = SuggestedModule.getModule()) { makeModuleVisible(M, HashLoc); if (IncludeTok.getIdentifierInfo()->getPPKeywordID() != tok::pp___include_macros) EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include, M); } return; } // Look up the file, create a File ID for it. SourceLocation IncludePos = End; // If the filename string was the result of macro expansions, set the include // position on the file where it will be included and after the expansions. if (IncludePos.isMacroID()) IncludePos = SourceMgr.getExpansionRange(IncludePos).second; FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter); assert(!FID.isInvalid() && "Expected valid file ID"); // If all is good, enter the new file! if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation())) return; // Determine if we're switching to building a new submodule, and which one. if (auto *M = SuggestedModule.getModule()) { assert(!CurSubmodule && "should not have marked this as a module yet"); CurSubmodule = M; // Let the macro handling code know that any future macros are within // the new submodule. EnterSubmodule(M, HashLoc); // Let the parser know that any future declarations are within the new // submodule. // FIXME: There's no point doing this if we're handling a #__include_macros // directive. EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin, M); } } /// HandleIncludeNextDirective - Implements \#include_next. /// void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc, Token &IncludeNextTok) { Diag(IncludeNextTok, diag::ext_pp_include_next_directive); // #include_next is like #include, except that we start searching after // the current found directory. If we can't do this, issue a // diagnostic. const DirectoryLookup *Lookup = CurDirLookup; const FileEntry *LookupFromFile = nullptr; if (isInPrimaryFile()) { Lookup = nullptr; Diag(IncludeNextTok, diag::pp_include_next_in_primary); } else if (CurSubmodule) { // Start looking up in the directory *after* the one in which the current // file would be found, if any. assert(CurPPLexer && "#include_next directive in macro?"); LookupFromFile = CurPPLexer->getFileEntry(); Lookup = nullptr; } else if (!Lookup) { Diag(IncludeNextTok, diag::pp_include_next_absolute_path); } else { // Start looking up in the next directory. ++Lookup; } return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup, LookupFromFile); } /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) { // The Microsoft #import directive takes a type library and generates header // files from it, and includes those. This is beyond the scope of what clang // does, so we ignore it and error out. However, #import can optionally have // trailing attributes that span multiple lines. We're going to eat those // so we can continue processing from there. Diag(Tok, diag::err_pp_import_directive_ms ); // Read tokens until we get to the end of the directive. Note that the // directive can be split over multiple lines using the backslash character. DiscardUntilEndOfDirective(); } /// HandleImportDirective - Implements \#import. /// void Preprocessor::HandleImportDirective(SourceLocation HashLoc, Token &ImportTok) { if (!LangOpts.ObjC1) { // #import is standard for ObjC. if (LangOpts.MSVCCompat) return HandleMicrosoftImportDirective(ImportTok); Diag(ImportTok, diag::ext_pp_import_directive); } return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true); } /// HandleIncludeMacrosDirective - The -imacros command line option turns into a /// pseudo directive in the predefines buffer. This handles it by sucking all /// tokens through the preprocessor and discarding them (only keeping the side /// effects on the preprocessor). void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc, Token &IncludeMacrosTok) { // This directive should only occur in the predefines buffer. If not, emit an // error and reject it. SourceLocation Loc = IncludeMacrosTok.getLocation(); if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) { Diag(IncludeMacrosTok.getLocation(), diag::pp_include_macros_out_of_predefines); DiscardUntilEndOfDirective(); return; } // Treat this as a normal #include for checking purposes. If this is // successful, it will push a new lexer onto the include stack. HandleIncludeDirective(HashLoc, IncludeMacrosTok); Token TmpTok; do { Lex(TmpTok); assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!"); } while (TmpTok.isNot(tok::hashhash)); } //===----------------------------------------------------------------------===// // Preprocessor Macro Directive Handling. //===----------------------------------------------------------------------===// /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro /// definition has just been read. Lex the rest of the arguments and the /// closing ), updating MI with what we learn. Return true if an error occurs /// parsing the arg list. bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) { SmallVector<IdentifierInfo*, 32> Arguments; while (1) { LexUnexpandedToken(Tok); switch (Tok.getKind()) { case tok::r_paren: // Found the end of the argument list. if (Arguments.empty()) // #define FOO() return false; // Otherwise we have #define FOO(A,) Diag(Tok, diag::err_pp_expected_ident_in_arg_list); return true; case tok::ellipsis: // #define X(... -> C99 varargs if (!LangOpts.C99) Diag(Tok, LangOpts.CPlusPlus11 ? diag::warn_cxx98_compat_variadic_macro : diag::ext_variadic_macro); // OpenCL v1.2 s6.9.e: variadic macros are not supported. if (LangOpts.OpenCL) { Diag(Tok, diag::err_pp_opencl_variadic_macros); return true; } // Lex the token after the identifier. LexUnexpandedToken(Tok); if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); return true; } // Add the __VA_ARGS__ identifier as an argument. Arguments.push_back(Ident__VA_ARGS__); MI->setIsC99Varargs(); MI->setArgumentList(&Arguments[0], Arguments.size(), BP); return false; case tok::eod: // #define X( Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); return true; default: // Handle keywords and identifiers here to accept things like // #define Foo(for) for. IdentifierInfo *II = Tok.getIdentifierInfo(); if (!II) { // #define X(1 Diag(Tok, diag::err_pp_invalid_tok_in_arg_list); return true; } // If this is already used as an argument, it is used multiple times (e.g. // #define X(A,A. if (std::find(Arguments.begin(), Arguments.end(), II) != Arguments.end()) { // C99 6.10.3p6 Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II; return true; } // Add the argument to the macro info. Arguments.push_back(II); // Lex the token after the identifier. LexUnexpandedToken(Tok); switch (Tok.getKind()) { default: // #define X(A B Diag(Tok, diag::err_pp_expected_comma_in_arg_list); return true; case tok::r_paren: // #define X(A) MI->setArgumentList(&Arguments[0], Arguments.size(), BP); return false; case tok::comma: // #define X(A, break; case tok::ellipsis: // #define X(A... -> GCC extension // Diagnose extension. Diag(Tok, diag::ext_named_variadic_macro); // Lex the token after the identifier. LexUnexpandedToken(Tok); if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); return true; } MI->setIsGNUVarargs(); MI->setArgumentList(&Arguments[0], Arguments.size(), BP); return false; } } } } static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI, const LangOptions &LOptions) { if (MI->getNumTokens() == 1) { const Token &Value = MI->getReplacementToken(0); // Macro that is identity, like '#define inline inline' is a valid pattern. if (MacroName.getKind() == Value.getKind()) return true; // Macro that maps a keyword to the same keyword decorated with leading/ // trailing underscores is a valid pattern: // #define inline __inline // #define inline __inline__ // #define inline _inline (in MS compatibility mode) StringRef MacroText = MacroName.getIdentifierInfo()->getName(); if (IdentifierInfo *II = Value.getIdentifierInfo()) { if (!II->isKeyword(LOptions)) return false; StringRef ValueText = II->getName(); StringRef TrimmedValue = ValueText; if (!ValueText.startswith("__")) { if (ValueText.startswith("_")) TrimmedValue = TrimmedValue.drop_front(1); else return false; } else { TrimmedValue = TrimmedValue.drop_front(2); if (TrimmedValue.endswith("__")) TrimmedValue = TrimmedValue.drop_back(2); } return TrimmedValue.equals(MacroText); } else { return false; } } // #define inline if (MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static, tok::kw_const) && MI->getNumTokens() == 0) { return true; } return false; } /// HandleDefineDirective - Implements \#define. This consumes the entire macro /// line then lets the caller lex the next real token. void Preprocessor::HandleDefineDirective(Token &DefineTok, bool ImmediatelyAfterHeaderGuard) { ++NumDefined; Token MacroNameTok; bool MacroShadowsKeyword; ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword); // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eod)) return; Token LastTok = MacroNameTok; // If we are supposed to keep comments in #defines, reenable comment saving // mode. if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments); // Create the new macro. MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation()); Token Tok; LexUnexpandedToken(Tok); // If this is a function-like macro definition, parse the argument list, // marking each of the identifiers as being used as macro arguments. Also, // check other constraints on the first token of the macro body. if (Tok.is(tok::eod)) { if (ImmediatelyAfterHeaderGuard) { // Save this macro information since it may part of a header guard. CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(), MacroNameTok.getLocation()); } // If there is no body to this macro, we have no special handling here. } else if (Tok.hasLeadingSpace()) { // This is a normal token with leading space. Clear the leading space // marker on the first token to get proper expansion. Tok.clearFlag(Token::LeadingSpace); } else if (Tok.is(tok::l_paren)) { // This is a function-like macro definition. Read the argument list. MI->setIsFunctionLike(); if (ReadMacroDefinitionArgList(MI, LastTok)) { // Throw away the rest of the line. if (CurPPLexer->ParsingPreprocessorDirective) DiscardUntilEndOfDirective(); return; } // If this is a definition of a variadic C99 function-like macro, not using // the GNU named varargs extension, enabled __VA_ARGS__. // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. // This gets unpoisoned where it is allowed. assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!"); if (MI->isC99Varargs()) Ident__VA_ARGS__->setIsPoisoned(false); // Read the first token after the arg list for down below. LexUnexpandedToken(Tok); } else if (LangOpts.C99 || LangOpts.CPlusPlus11) { // C99 requires whitespace between the macro definition and the body. Emit // a diagnostic for something like "#define X+". Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name); } else { // C90 6.8 TC1 says: "In the definition of an object-like macro, if the // first character of a replacement list is not a character required by // subclause 5.2.1, then there shall be white-space separation between the // identifier and the replacement list.". 5.2.1 lists this set: // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which // is irrelevant here. bool isInvalid = false; if (Tok.is(tok::at)) // @ is not in the list above. isInvalid = true; else if (Tok.is(tok::unknown)) { // If we have an unknown token, it is something strange like "`". Since // all of valid characters would have lexed into a single character // token of some sort, we know this is not a valid case. isInvalid = true; } if (isInvalid) Diag(Tok, diag::ext_missing_whitespace_after_macro_name); else Diag(Tok, diag::warn_missing_whitespace_after_macro_name); } if (!Tok.is(tok::eod)) LastTok = Tok; // Read the rest of the macro body. if (MI->isObjectLike()) { // Object-like macros are very simple, just read their body. while (Tok.isNot(tok::eod)) { LastTok = Tok; MI->AddTokenToBody(Tok); // Get the next token of the macro. LexUnexpandedToken(Tok); } } else { // Otherwise, read the body of a function-like macro. While we are at it, // check C99 6.10.3.2p1: ensure that # operators are followed by macro // parameters in function-like macro expansions. while (Tok.isNot(tok::eod)) { LastTok = Tok; if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) { MI->AddTokenToBody(Tok); // Get the next token of the macro. LexUnexpandedToken(Tok); continue; } // If we're in -traditional mode, then we should ignore stringification // and token pasting. Mark the tokens as unknown so as not to confuse // things. if (getLangOpts().TraditionalCPP) { Tok.setKind(tok::unknown); MI->AddTokenToBody(Tok); // Get the next token of the macro. LexUnexpandedToken(Tok); continue; } if (Tok.is(tok::hashhash)) { // If we see token pasting, check if it looks like the gcc comma // pasting extension. We'll use this information to suppress // diagnostics later on. // Get the next token of the macro. LexUnexpandedToken(Tok); if (Tok.is(tok::eod)) { MI->AddTokenToBody(LastTok); break; } unsigned NumTokens = MI->getNumTokens(); if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ && MI->getReplacementToken(NumTokens-1).is(tok::comma)) MI->setHasCommaPasting(); // Things look ok, add the '##' token to the macro. MI->AddTokenToBody(LastTok); continue; } // Get the next token of the macro. LexUnexpandedToken(Tok); // Check for a valid macro arg identifier. if (Tok.getIdentifierInfo() == nullptr || MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) { // If this is assembler-with-cpp mode, we accept random gibberish after // the '#' because '#' is often a comment character. However, change // the kind of the token to tok::unknown so that the preprocessor isn't // confused. if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) { LastTok.setKind(tok::unknown); MI->AddTokenToBody(LastTok); continue; } else { Diag(Tok, diag::err_pp_stringize_not_parameter); // Disable __VA_ARGS__ again. Ident__VA_ARGS__->setIsPoisoned(true); return; } } // Things look ok, add the '#' and param name tokens to the macro. MI->AddTokenToBody(LastTok); MI->AddTokenToBody(Tok); LastTok = Tok; // Get the next token of the macro. LexUnexpandedToken(Tok); } } if (MacroShadowsKeyword && !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) { Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword); } // Disable __VA_ARGS__ again. Ident__VA_ARGS__->setIsPoisoned(true); // Check that there is no paste (##) operator at the beginning or end of the // replacement list. unsigned NumTokens = MI->getNumTokens(); if (NumTokens != 0) { if (MI->getReplacementToken(0).is(tok::hashhash)) { Diag(MI->getReplacementToken(0), diag::err_paste_at_start); return; } if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) { Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end); return; } } MI->setDefinitionEndLoc(LastTok.getLocation()); // Finally, if this identifier already had a macro defined for it, verify that // the macro bodies are identical, and issue diagnostics if they are not. if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) { // It is very common for system headers to have tons of macro redefinitions // and for warnings to be disabled in system headers. If this is the case, // then don't bother calling MacroInfo::isIdenticalTo. if (!getDiagnostics().getSuppressSystemWarnings() || !SourceMgr.isInSystemHeader(DefineTok.getLocation())) { if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused()) Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used); // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and // C++ [cpp.predefined]p4, but allow it as an extension. if (OtherMI->isBuiltinMacro()) Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro); // Macros must be identical. This means all tokens and whitespace // separation must be the same. C99 6.10.3p2. else if (!OtherMI->isAllowRedefinitionsWithoutWarning() && !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) { Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef) << MacroNameTok.getIdentifierInfo(); Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition); } } if (OtherMI->isWarnIfUnused()) WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc()); } DefMacroDirective *MD = appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI); assert(!MI->isUsed()); // If we need warning for not using the macro, add its location in the // warn-because-unused-macro set. If it gets used it will be removed from set. if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) && !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) { MI->setIsWarnIfUnused(true); WarnUnusedMacroLocs.insert(MI->getDefinitionLoc()); } // If the callbacks want to know, tell them about the macro definition. if (Callbacks) Callbacks->MacroDefined(MacroNameTok, MD); } /// HandleUndefDirective - Implements \#undef. /// void Preprocessor::HandleUndefDirective(Token &UndefTok) { ++NumUndefined; Token MacroNameTok; ReadMacroName(MacroNameTok, MU_Undef); // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eod)) return; // Check to see if this is the last token on the #undef line. CheckEndOfDirective("undef"); // Okay, we have a valid identifier to undef. auto *II = MacroNameTok.getIdentifierInfo(); auto MD = getMacroDefinition(II); // If the callbacks want to know, tell them about the macro #undef. // Note: no matter if the macro was defined or not. if (Callbacks) Callbacks->MacroUndefined(MacroNameTok, MD); // If the macro is not defined, this is a noop undef, just return. const MacroInfo *MI = MD.getMacroInfo(); if (!MI) return; if (!MI->isUsed() && MI->isWarnIfUnused()) Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used); if (MI->isWarnIfUnused()) WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); appendMacroDirective(MacroNameTok.getIdentifierInfo(), AllocateUndefMacroDirective(MacroNameTok.getLocation())); } //===----------------------------------------------------------------------===// // Preprocessor Conditional Directive Handling. //===----------------------------------------------------------------------===// /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef /// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is /// true if any tokens have been returned or pp-directives activated before this /// \#ifndef has been lexed. /// void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, bool ReadAnyTokensBeforeDirective) { ++NumIf; Token DirectiveTok = Result; Token MacroNameTok; ReadMacroName(MacroNameTok); // Error reading macro name? If so, diagnostic already issued. if (MacroNameTok.is(tok::eod)) { // Skip code until we get to #endif. This helps with recovery by not // emitting an error when the #endif is reached. SkipExcludedConditionalBlock(DirectiveTok.getLocation(), /*Foundnonskip*/false, /*FoundElse*/false); return; } // Check to see if this is the last token on the #if[n]def line. CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef"); IdentifierInfo *MII = MacroNameTok.getIdentifierInfo(); auto MD = getMacroDefinition(MII); MacroInfo *MI = MD.getMacroInfo(); if (CurPPLexer->getConditionalStackDepth() == 0) { // If the start of a top-level #ifdef and if the macro is not defined, // inform MIOpt that this might be the start of a proper include guard. // Otherwise it is some other form of unknown conditional which we can't // handle. if (!ReadAnyTokensBeforeDirective && !MI) { assert(isIfndef && "#ifdef shouldn't reach here"); CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation()); } else CurPPLexer->MIOpt.EnterTopLevelConditional(); } // If there is a macro, process it. if (MI) // Mark it used. markMacroAsUsed(MI); if (Callbacks) { if (isIfndef) Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD); else Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD); } // Should we include the stuff contained by this directive? if (!MI == isIfndef) { // Yes, remember that we are inside a conditional, then lex the next token. CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false, /*foundnonskip*/true, /*foundelse*/false); } else { // No, skip the contents of this block. SkipExcludedConditionalBlock(DirectiveTok.getLocation(), /*Foundnonskip*/false, /*FoundElse*/false); } } /// HandleIfDirective - Implements the \#if directive. /// void Preprocessor::HandleIfDirective(Token &IfToken, bool ReadAnyTokensBeforeDirective) { ++NumIf; // Parse and evaluate the conditional expression. IdentifierInfo *IfNDefMacro = nullptr; const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation(); const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro); const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation(); // If this condition is equivalent to #ifndef X, and if this is the first // directive seen, handle it for the multiple-include optimization. if (CurPPLexer->getConditionalStackDepth() == 0) { if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue) // FIXME: Pass in the location of the macro name, not the 'if' token. CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation()); else CurPPLexer->MIOpt.EnterTopLevelConditional(); } if (Callbacks) Callbacks->If(IfToken.getLocation(), SourceRange(ConditionalBegin, ConditionalEnd), (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False)); // Should we include the stuff contained by this directive? if (ConditionalTrue) { // Yes, remember that we are inside a conditional, then lex the next token. CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false, /*foundnonskip*/true, /*foundelse*/false); } else { // No, skip the contents of this block. SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false, /*FoundElse*/false); } } /// HandleEndifDirective - Implements the \#endif directive. /// void Preprocessor::HandleEndifDirective(Token &EndifToken) { ++NumEndif; // Check that this is the whole directive. CheckEndOfDirective("endif"); PPConditionalInfo CondInfo; if (CurPPLexer->popConditionalLevel(CondInfo)) { // No conditionals on the stack: this is an #endif without an #if. Diag(EndifToken, diag::err_pp_endif_without_if); return; } // If this the end of a top-level #endif, inform MIOpt. if (CurPPLexer->getConditionalStackDepth() == 0) CurPPLexer->MIOpt.ExitTopLevelConditional(); assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode && "This code should only be reachable in the non-skipping case!"); if (Callbacks) Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc); } /// HandleElseDirective - Implements the \#else directive. /// void Preprocessor::HandleElseDirective(Token &Result) { ++NumElse; // #else directive in a non-skipping conditional... start skipping. CheckEndOfDirective("else"); PPConditionalInfo CI; if (CurPPLexer->popConditionalLevel(CI)) { Diag(Result, diag::pp_err_else_without_if); return; } // If this is a top-level #else, inform the MIOpt. if (CurPPLexer->getConditionalStackDepth() == 0) CurPPLexer->MIOpt.EnterTopLevelConditional(); // If this is a #else with a #else before it, report the error. if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else); if (Callbacks) Callbacks->Else(Result.getLocation(), CI.IfLoc); // Finally, skip the rest of the contents of this block. SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, /*FoundElse*/true, Result.getLocation()); } /// HandleElifDirective - Implements the \#elif directive. /// void Preprocessor::HandleElifDirective(Token &ElifToken) { ++NumElse; // #elif directive in a non-skipping conditional... start skipping. // We don't care what the condition is, because we will always skip it (since // the block immediately before it was included). const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation(); DiscardUntilEndOfDirective(); const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation(); PPConditionalInfo CI; if (CurPPLexer->popConditionalLevel(CI)) { Diag(ElifToken, diag::pp_err_elif_without_if); return; } // If this is a top-level #elif, inform the MIOpt. if (CurPPLexer->getConditionalStackDepth() == 0) CurPPLexer->MIOpt.EnterTopLevelConditional(); // If this is a #elif with a #else before it, report the error. if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else); if (Callbacks) Callbacks->Elif(ElifToken.getLocation(), SourceRange(ConditionalBegin, ConditionalEnd), PPCallbacks::CVK_NotEvaluated, CI.IfLoc); // Finally, skip the rest of the contents of this block. SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, /*FoundElse*/CI.FoundElse, ElifToken.getLocation()); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/PPMacroExpansion.cpp
//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the top level handling of macro expansion for the // preprocessor. // //===----------------------------------------------------------------------===// #include "clang/Lex/Preprocessor.h" #include "clang/Basic/Attributes.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/ExternalPreprocessorSource.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/MacroArgs.h" #include "clang/Lex/MacroInfo.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Config/llvm-config.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" #include <cstdio> #include <ctime> using namespace clang; MacroDirective * Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const { if (!II->hadMacroDefinition()) return nullptr; auto Pos = CurSubmoduleState->Macros.find(II); return Pos == CurSubmoduleState->Macros.end() ? nullptr : Pos->second.getLatest(); } void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){ assert(MD && "MacroDirective should be non-zero!"); assert(!MD->getPrevious() && "Already attached to a MacroDirective history."); MacroState &StoredMD = CurSubmoduleState->Macros[II]; auto *OldMD = StoredMD.getLatest(); MD->setPrevious(OldMD); StoredMD.setLatest(MD); StoredMD.overrideActiveModuleMacros(*this, II); // Set up the identifier as having associated macro history. II->setHasMacroDefinition(true); if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end()) II->setHasMacroDefinition(false); if (II->isFromAST()) II->setChangedSinceDeserialization(); } void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *MD) { assert(II && MD); MacroState &StoredMD = CurSubmoduleState->Macros[II]; assert(!StoredMD.getLatest() && "the macro history was modified before initializing it from a pch"); StoredMD = MD; // Setup the identifier as having associated macro history. II->setHasMacroDefinition(true); if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end()) II->setHasMacroDefinition(false); } ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef<ModuleMacro *> Overrides, bool &New) { llvm::FoldingSetNodeID ID; ModuleMacro::Profile(ID, Mod, II); void *InsertPos; if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) { New = false; return MM; } auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides); ModuleMacros.InsertNode(MM, InsertPos); // Each overridden macro is now overridden by one more macro. bool HidAny = false; for (auto *O : Overrides) { HidAny |= (O->NumOverriddenBy == 0); ++O->NumOverriddenBy; } // If we were the first overrider for any macro, it's no longer a leaf. auto &LeafMacros = LeafModuleMacros[II]; if (HidAny) { LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(), [](ModuleMacro *MM) { return MM->NumOverriddenBy != 0; }), LeafMacros.end()); } // The new macro is always a leaf macro. LeafMacros.push_back(MM); // The identifier now has defined macros (that may or may not be visible). II->setHasMacroDefinition(true); New = true; return MM; } ModuleMacro *Preprocessor::getModuleMacro(Module *Mod, IdentifierInfo *II) { llvm::FoldingSetNodeID ID; ModuleMacro::Profile(ID, Mod, II); void *InsertPos; return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos); } void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info) { assert(Info.ActiveModuleMacrosGeneration != CurSubmoduleState->VisibleModules.getGeneration() && "don't need to update this macro name info"); Info.ActiveModuleMacrosGeneration = CurSubmoduleState->VisibleModules.getGeneration(); auto Leaf = LeafModuleMacros.find(II); if (Leaf == LeafModuleMacros.end()) { // No imported macros at all: nothing to do. return; } Info.ActiveModuleMacros.clear(); // Every macro that's locally overridden is overridden by a visible macro. llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides; for (auto *O : Info.OverriddenMacros) NumHiddenOverrides[O] = -1; // Collect all macros that are not overridden by a visible macro. llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf->second.begin(), Leaf->second.end()); while (!Worklist.empty()) { auto *MM = Worklist.pop_back_val(); if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) { // We only care about collecting definitions; undefinitions only act // to override other definitions. if (MM->getMacroInfo()) Info.ActiveModuleMacros.push_back(MM); } else { for (auto *O : MM->overrides()) if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros()) Worklist.push_back(O); } } // Our reverse postorder walk found the macros in reverse order. std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end()); // Determine whether the macro name is ambiguous. MacroInfo *MI = nullptr; bool IsSystemMacro = true; bool IsAmbiguous = false; if (auto *MD = Info.MD) { while (MD && isa<VisibilityMacroDirective>(MD)) MD = MD->getPrevious(); if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) { MI = DMD->getInfo(); IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation()); } } for (auto *Active : Info.ActiveModuleMacros) { auto *NewMI = Active->getMacroInfo(); // Before marking the macro as ambiguous, check if this is a case where // both macros are in system headers. If so, we trust that the system // did not get it wrong. This also handles cases where Clang's own // headers have a different spelling of certain system macros: // #define LONG_MAX __LONG_MAX__ (clang's limits.h) // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h) // // FIXME: Remove the defined-in-system-headers check. clang's limits.h // overrides the system limits.h's macros, so there's no conflict here. if (MI && NewMI != MI && !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true)) IsAmbiguous = true; IsSystemMacro &= Active->getOwningModule()->IsSystem || SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc()); MI = NewMI; } Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro; } void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) { ArrayRef<ModuleMacro*> Leaf; auto LeafIt = LeafModuleMacros.find(II); if (LeafIt != LeafModuleMacros.end()) Leaf = LeafIt->second; const MacroState *State = nullptr; auto Pos = CurSubmoduleState->Macros.find(II); if (Pos != CurSubmoduleState->Macros.end()) State = &Pos->second; llvm::errs() << "MacroState " << State << " " << II->getNameStart(); if (State && State->isAmbiguous(*this, II)) llvm::errs() << " ambiguous"; if (State && !State->getOverriddenMacros().empty()) { llvm::errs() << " overrides"; for (auto *O : State->getOverriddenMacros()) llvm::errs() << " " << O->getOwningModule()->getFullModuleName(); } llvm::errs() << "\n"; // Dump local macro directives. for (auto *MD = State ? State->getLatest() : nullptr; MD; MD = MD->getPrevious()) { llvm::errs() << " "; MD->dump(); } // Dump module macros. llvm::DenseSet<ModuleMacro*> Active; for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None) Active.insert(MM); llvm::DenseSet<ModuleMacro*> Visited; llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end()); while (!Worklist.empty()) { auto *MM = Worklist.pop_back_val(); llvm::errs() << " ModuleMacro " << MM << " " << MM->getOwningModule()->getFullModuleName(); if (!MM->getMacroInfo()) llvm::errs() << " undef"; if (Active.count(MM)) llvm::errs() << " active"; else if (!CurSubmoduleState->VisibleModules.isVisible( MM->getOwningModule())) llvm::errs() << " hidden"; else if (MM->getMacroInfo()) llvm::errs() << " overridden"; if (!MM->overrides().empty()) { llvm::errs() << " overrides"; for (auto *O : MM->overrides()) { llvm::errs() << " " << O->getOwningModule()->getFullModuleName(); if (Visited.insert(O).second) Worklist.push_back(O); } } llvm::errs() << "\n"; if (auto *MI = MM->getMacroInfo()) { llvm::errs() << " "; MI->dump(); llvm::errs() << "\n"; } } } /// RegisterBuiltinMacro - Register the specified identifier in the identifier /// table and mark it as a builtin macro to be expanded. static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){ // Get the identifier. IdentifierInfo *Id = PP.getIdentifierInfo(Name); // Mark it as being a macro that is builtin. MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation()); MI->setIsBuiltinMacro(); PP.appendDefMacroDirective(Id, MI); return Id; } /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the /// identifier table. void Preprocessor::RegisterBuiltinMacros() { Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__"); Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__"); Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__"); Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__"); Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__"); Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma"); // C++ Standing Document Extensions. if (LangOpts.CPlusPlus) Ident__has_cpp_attribute = RegisterBuiltinMacro(*this, "__has_cpp_attribute"); else Ident__has_cpp_attribute = nullptr; // GCC Extensions. Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__"); Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__"); Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__"); // Microsoft Extensions. if (LangOpts.MicrosoftExt) { Ident__identifier = RegisterBuiltinMacro(*this, "__identifier"); Ident__pragma = RegisterBuiltinMacro(*this, "__pragma"); } else { Ident__identifier = nullptr; Ident__pragma = nullptr; } // Clang Extensions. Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature"); Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension"); Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin"); Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute"); Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute"); Ident__has_include = RegisterBuiltinMacro(*this, "__has_include"); Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next"); Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning"); Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier"); // Modules. if (LangOpts.Modules) { Ident__building_module = RegisterBuiltinMacro(*this, "__building_module"); // __MODULE__ if (!LangOpts.CurrentModule.empty()) Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__"); else Ident__MODULE__ = nullptr; } else { Ident__building_module = nullptr; Ident__MODULE__ = nullptr; } } /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token /// in its expansion, currently expands to that token literally. static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, const IdentifierInfo *MacroIdent, Preprocessor &PP) { IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo(); // If the token isn't an identifier, it's always literally expanded. if (!II) return true; // If the information about this identifier is out of date, update it from // the external source. if (II->isOutOfDate()) PP.getExternalSource()->updateOutOfDateIdentifier(*II); // If the identifier is a macro, and if that macro is enabled, it may be // expanded so it's not a trivial expansion. if (auto *ExpansionMI = PP.getMacroInfo(II)) if (ExpansionMI->isEnabled() && // Fast expanding "#define X X" is ok, because X would be disabled. II != MacroIdent) return false; // If this is an object-like macro invocation, it is safe to trivially expand // it. if (MI->isObjectLike()) return true; // If this is a function-like macro invocation, it's safe to trivially expand // as long as the identifier is not a macro argument. return std::find(MI->arg_begin(), MI->arg_end(), II) == MI->arg_end(); } /// isNextPPTokenLParen - Determine whether the next preprocessor token to be /// lexed is a '('. If so, consume the token and return true, if not, this /// method should have no observable side-effect on the lexed tokens. bool Preprocessor::isNextPPTokenLParen() { // Do some quick tests for rejection cases. unsigned Val; if (CurLexer) Val = CurLexer->isNextPPTokenLParen(); else if (CurPTHLexer) Val = CurPTHLexer->isNextPPTokenLParen(); else Val = CurTokenLexer->isNextTokenLParen(); if (Val == 2) { // We have run off the end. If it's a source file we don't // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the // macro stack. if (CurPPLexer) return false; for (unsigned i = IncludeMacroStack.size(); i != 0; --i) { IncludeStackInfo &Entry = IncludeMacroStack[i-1]; if (Entry.TheLexer) Val = Entry.TheLexer->isNextPPTokenLParen(); else if (Entry.ThePTHLexer) Val = Entry.ThePTHLexer->isNextPPTokenLParen(); else Val = Entry.TheTokenLexer->isNextTokenLParen(); if (Val != 2) break; // Ran off the end of a source file? if (Entry.ThePPLexer) return false; } } // Okay, if we know that the token is a '(', lex it and return. Otherwise we // have found something that isn't a '(' or we found the end of the // translation unit. In either case, return false. return Val == 1; } /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be /// expanded as a macro, handle it and return the next token as 'Identifier'. bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, const MacroDefinition &M) { MacroInfo *MI = M.getMacroInfo(); // If this is a macro expansion in the "#if !defined(x)" line for the file, // then the macro could expand to different things in other contexts, we need // to disable the optimization in this case. if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro(); // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially. if (MI->isBuiltinMacro()) { if (Callbacks) Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(), /*Args=*/nullptr); ExpandBuiltinMacro(Identifier); return true; } /// Args - If this is a function-like macro expansion, this contains, /// for each macro argument, the list of tokens that were provided to the /// invocation. MacroArgs *Args = nullptr; // Remember where the end of the expansion occurred. For an object-like // macro, this is the identifier. For a function-like macro, this is the ')'. SourceLocation ExpansionEnd = Identifier.getLocation(); // If this is a function-like macro, read the arguments. if (MI->isFunctionLike()) { // Remember that we are now parsing the arguments to a macro invocation. // Preprocessor directives used inside macro arguments are not portable, and // this enables the warning. InMacroArgs = true; Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd); // Finished parsing args. InMacroArgs = false; // If there was an error parsing the arguments, bail out. if (!Args) return true; ++NumFnMacroExpanded; } else { ++NumMacroExpanded; } // Notice that this macro has been used. markMacroAsUsed(MI); // Remember where the token is expanded. SourceLocation ExpandLoc = Identifier.getLocation(); SourceRange ExpansionRange(ExpandLoc, ExpansionEnd); if (Callbacks) { if (InMacroArgs) { // We can have macro expansion inside a conditional directive while // reading the function macro arguments. To ensure, in that case, that // MacroExpands callbacks still happen in source order, queue this // callback to have it happen after the function macro callback. DelayedMacroExpandsCallbacks.push_back( MacroExpandsInfo(Identifier, M, ExpansionRange)); } else { Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args); if (!DelayedMacroExpandsCallbacks.empty()) { for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) { MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i]; // FIXME: We lose macro args info with delayed callback. Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range, /*Args=*/nullptr); } DelayedMacroExpandsCallbacks.clear(); } } } // If the macro definition is ambiguous, complain. if (M.isAmbiguous()) { Diag(Identifier, diag::warn_pp_ambiguous_macro) << Identifier.getIdentifierInfo(); Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen) << Identifier.getIdentifierInfo(); M.forAllDefinitions([&](const MacroInfo *OtherMI) { if (OtherMI != MI) Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other) << Identifier.getIdentifierInfo(); }); } // If we started lexing a macro, enter the macro expansion body. // If this macro expands to no tokens, don't bother to push it onto the // expansion stack, only to take it right back off. if (MI->getNumTokens() == 0) { // No need for arg info. if (Args) Args->destroy(*this); // Propagate whitespace info as if we had pushed, then popped, // a macro context. Identifier.setFlag(Token::LeadingEmptyMacro); PropagateLineStartLeadingSpaceInfo(Identifier); ++NumFastMacroExpanded; return false; } else if (MI->getNumTokens() == 1 && isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(), *this)) { // Otherwise, if this macro expands into a single trivially-expanded // token: expand it now. This handles common cases like // "#define VAL 42". // No need for arg info. if (Args) Args->destroy(*this); // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro // identifier to the expanded token. bool isAtStartOfLine = Identifier.isAtStartOfLine(); bool hasLeadingSpace = Identifier.hasLeadingSpace(); // Replace the result token. Identifier = MI->getReplacementToken(0); // Restore the StartOfLine/LeadingSpace markers. Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine); Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace); // Update the tokens location to include both its expansion and physical // locations. SourceLocation Loc = SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc, ExpansionEnd,Identifier.getLength()); Identifier.setLocation(Loc); // If this is a disabled macro or #define X X, we must mark the result as // unexpandable. if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) { if (MacroInfo *NewMI = getMacroInfo(NewII)) if (!NewMI->isEnabled() || NewMI == MI) { Identifier.setFlag(Token::DisableExpand); // Don't warn for "#define X X" like "#define bool bool" from // stdbool.h. if (NewMI != MI || MI->isFunctionLike()) Diag(Identifier, diag::pp_disabled_macro_expansion); } } // Since this is not an identifier token, it can't be macro expanded, so // we're done. ++NumFastMacroExpanded; return true; } // Start expanding the macro. EnterMacro(Identifier, ExpansionEnd, MI, Args); return false; } enum Bracket { Brace, Paren }; /// CheckMatchedBrackets - Returns true if the braces and parentheses in the /// token vector are properly nested. static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) { SmallVector<Bracket, 8> Brackets; for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(), E = Tokens.end(); I != E; ++I) { if (I->is(tok::l_paren)) { Brackets.push_back(Paren); } else if (I->is(tok::r_paren)) { if (Brackets.empty() || Brackets.back() == Brace) return false; Brackets.pop_back(); } else if (I->is(tok::l_brace)) { Brackets.push_back(Brace); } else if (I->is(tok::r_brace)) { if (Brackets.empty() || Brackets.back() == Paren) return false; Brackets.pop_back(); } } if (!Brackets.empty()) return false; return true; } /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new /// vector of tokens in NewTokens. The new number of arguments will be placed /// in NumArgs and the ranges which need to surrounded in parentheses will be /// in ParenHints. /// Returns false if the token stream cannot be changed. If this is because /// of an initializer list starting a macro argument, the range of those /// initializer lists will be place in InitLists. static bool GenerateNewArgTokens(Preprocessor &PP, SmallVectorImpl<Token> &OldTokens, SmallVectorImpl<Token> &NewTokens, unsigned &NumArgs, SmallVectorImpl<SourceRange> &ParenHints, SmallVectorImpl<SourceRange> &InitLists) { if (!CheckMatchedBrackets(OldTokens)) return false; // Once it is known that the brackets are matched, only a simple count of the // braces is needed. unsigned Braces = 0; // First token of a new macro argument. SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin(); // First closing brace in a new macro argument. Used to generate // SourceRanges for InitLists. SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end(); NumArgs = 0; Token TempToken; // Set to true when a macro separator token is found inside a braced list. // If true, the fixed argument spans multiple old arguments and ParenHints // will be updated. bool FoundSeparatorToken = false; for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(), E = OldTokens.end(); I != E; ++I) { if (I->is(tok::l_brace)) { ++Braces; } else if (I->is(tok::r_brace)) { --Braces; if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken) ClosingBrace = I; } else if (I->is(tok::eof)) { // EOF token is used to separate macro arguments if (Braces != 0) { // Assume comma separator is actually braced list separator and change // it back to a comma. FoundSeparatorToken = true; I->setKind(tok::comma); I->setLength(1); } else { // Braces == 0 // Separator token still separates arguments. ++NumArgs; // If the argument starts with a brace, it can't be fixed with // parentheses. A different diagnostic will be given. if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) { InitLists.push_back( SourceRange(ArgStartIterator->getLocation(), PP.getLocForEndOfToken(ClosingBrace->getLocation()))); ClosingBrace = E; } // Add left paren if (FoundSeparatorToken) { TempToken.startToken(); TempToken.setKind(tok::l_paren); TempToken.setLocation(ArgStartIterator->getLocation()); TempToken.setLength(0); NewTokens.push_back(TempToken); } // Copy over argument tokens NewTokens.insert(NewTokens.end(), ArgStartIterator, I); // Add right paren and store the paren locations in ParenHints if (FoundSeparatorToken) { SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation()); TempToken.startToken(); TempToken.setKind(tok::r_paren); TempToken.setLocation(Loc); TempToken.setLength(0); NewTokens.push_back(TempToken); ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(), Loc)); } // Copy separator token NewTokens.push_back(*I); // Reset values ArgStartIterator = I + 1; FoundSeparatorToken = false; } } } return !ParenHints.empty() && InitLists.empty(); } /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next /// token is the '(' of the macro, this method is invoked to read all of the /// actual arguments specified for the macro invocation. This returns null on /// error. MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, MacroInfo *MI, SourceLocation &MacroEnd) { // The number of fixed arguments to parse. unsigned NumFixedArgsLeft = MI->getNumArgs(); bool isVariadic = MI->isVariadic(); // Outer loop, while there are more arguments, keep reading them. Token Tok; // Read arguments as unexpanded tokens. This avoids issues, e.g., where // an argument value in a macro could expand to ',' or '(' or ')'. LexUnexpandedToken(Tok); assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?"); // ArgTokens - Build up a list of tokens that make up each argument. Each // argument is separated by an EOF token. Use a SmallVector so we can avoid // heap allocations in the common case. SmallVector<Token, 64> ArgTokens; bool ContainsCodeCompletionTok = false; SourceLocation TooManyArgsLoc; unsigned NumActuals = 0; while (Tok.isNot(tok::r_paren)) { if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod)) break; assert(Tok.isOneOf(tok::l_paren, tok::comma) && "only expect argument separators here"); unsigned ArgTokenStart = ArgTokens.size(); SourceLocation ArgStartLoc = Tok.getLocation(); // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note // that we already consumed the first one. unsigned NumParens = 0; while (1) { // Read arguments as unexpanded tokens. This avoids issues, e.g., where // an argument value in a macro could expand to ',' or '(' or ')'. LexUnexpandedToken(Tok); if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n" if (!ContainsCodeCompletionTok) { Diag(MacroName, diag::err_unterm_macro_invoc); Diag(MI->getDefinitionLoc(), diag::note_macro_here) << MacroName.getIdentifierInfo(); // Do not lose the EOF/EOD. Return it to the client. MacroName = Tok; return nullptr; } else { // Do not lose the EOF/EOD. Token *Toks = new Token[1]; Toks[0] = Tok; EnterTokenStream(Toks, 1, true, true); break; } } else if (Tok.is(tok::r_paren)) { // If we found the ) token, the macro arg list is done. if (NumParens-- == 0) { MacroEnd = Tok.getLocation(); break; } } else if (Tok.is(tok::l_paren)) { ++NumParens; } else if (Tok.is(tok::comma) && NumParens == 0 && !(Tok.getFlags() & Token::IgnoredComma)) { // In Microsoft-compatibility mode, single commas from nested macro // expansions should not be considered as argument separators. We test // for this with the IgnoredComma token flag above. // Comma ends this argument if there are more fixed arguments expected. // However, if this is a variadic macro, and this is part of the // variadic part, then the comma is just an argument token. if (!isVariadic) break; if (NumFixedArgsLeft > 1) break; } else if (Tok.is(tok::comment) && !KeepMacroComments) { // If this is a comment token in the argument list and we're just in // -C mode (not -CC mode), discard the comment. continue; } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) { // Reading macro arguments can cause macros that we are currently // expanding from to be popped off the expansion stack. Doing so causes // them to be reenabled for expansion. Here we record whether any // identifiers we lex as macro arguments correspond to disabled macros. // If so, we mark the token as noexpand. This is a subtle aspect of // C99 6.10.3.4p2. if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo())) if (!MI->isEnabled()) Tok.setFlag(Token::DisableExpand); } else if (Tok.is(tok::code_completion)) { ContainsCodeCompletionTok = true; if (CodeComplete) CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(), MI, NumActuals); // Don't mark that we reached the code-completion point because the // parser is going to handle the token and there will be another // code-completion callback. } ArgTokens.push_back(Tok); } // If this was an empty argument list foo(), don't add this as an empty // argument. if (ArgTokens.empty() && Tok.getKind() == tok::r_paren) break; // If this is not a variadic macro, and too many args were specified, emit // an error. if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) { if (ArgTokens.size() != ArgTokenStart) TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation(); else TooManyArgsLoc = ArgStartLoc; } // Empty arguments are standard in C99 and C++0x, and are supported as an // extension in other modes. if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99) Diag(Tok, LangOpts.CPlusPlus11 ? diag::warn_cxx98_compat_empty_fnmacro_arg : diag::ext_empty_fnmacro_arg); // Add a marker EOF token to the end of the token list for this argument. Token EOFTok; EOFTok.startToken(); EOFTok.setKind(tok::eof); EOFTok.setLocation(Tok.getLocation()); EOFTok.setLength(0); ArgTokens.push_back(EOFTok); ++NumActuals; if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0) --NumFixedArgsLeft; } // Okay, we either found the r_paren. Check to see if we parsed too few // arguments. unsigned MinArgsExpected = MI->getNumArgs(); // If this is not a variadic macro, and too many args were specified, emit // an error. if (!isVariadic && NumActuals > MinArgsExpected && !ContainsCodeCompletionTok) { // Emit the diagnostic at the macro name in case there is a missing ). // Emitting it at the , could be far away from the macro name. Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc); Diag(MI->getDefinitionLoc(), diag::note_macro_here) << MacroName.getIdentifierInfo(); // Commas from braced initializer lists will be treated as argument // separators inside macros. Attempt to correct for this with parentheses. // TODO: See if this can be generalized to angle brackets for templates // inside macro arguments. SmallVector<Token, 4> FixedArgTokens; unsigned FixedNumArgs = 0; SmallVector<SourceRange, 4> ParenHints, InitLists; if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs, ParenHints, InitLists)) { if (!InitLists.empty()) { DiagnosticBuilder DB = Diag(MacroName, diag::note_init_list_at_beginning_of_macro_argument); for (const SourceRange &Range : InitLists) DB << Range; } return nullptr; } if (FixedNumArgs != MinArgsExpected) return nullptr; DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro); for (const SourceRange &ParenLocation : ParenHints) { DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "("); DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")"); } ArgTokens.swap(FixedArgTokens); NumActuals = FixedNumArgs; } // See MacroArgs instance var for description of this. bool isVarargsElided = false; if (ContainsCodeCompletionTok) { // Recover from not-fully-formed macro invocation during code-completion. Token EOFTok; EOFTok.startToken(); EOFTok.setKind(tok::eof); EOFTok.setLocation(Tok.getLocation()); EOFTok.setLength(0); for (; NumActuals < MinArgsExpected; ++NumActuals) ArgTokens.push_back(EOFTok); } if (NumActuals < MinArgsExpected) { // There are several cases where too few arguments is ok, handle them now. if (NumActuals == 0 && MinArgsExpected == 1) { // #define A(X) or #define A(...) ---> A() // If there is exactly one argument, and that argument is missing, // then we have an empty "()" argument empty list. This is fine, even if // the macro expects one argument (the argument is just empty). isVarargsElided = MI->isVariadic(); } else if (MI->isVariadic() && (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X) (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A() // Varargs where the named vararg parameter is missing: OK as extension. // #define A(x, ...) // A("blah") // // If the macro contains the comma pasting extension, the diagnostic // is suppressed; we know we'll get another diagnostic later. if (!MI->hasCommaPasting()) { Diag(Tok, diag::ext_missing_varargs_arg); Diag(MI->getDefinitionLoc(), diag::note_macro_here) << MacroName.getIdentifierInfo(); } // Remember this occurred, allowing us to elide the comma when used for // cases like: // #define A(x, foo...) blah(a, ## foo) // #define B(x, ...) blah(a, ## __VA_ARGS__) // #define C(...) blah(a, ## __VA_ARGS__) // A(x) B(x) C() isVarargsElided = true; } else if (!ContainsCodeCompletionTok) { // Otherwise, emit the error. Diag(Tok, diag::err_too_few_args_in_macro_invoc); Diag(MI->getDefinitionLoc(), diag::note_macro_here) << MacroName.getIdentifierInfo(); return nullptr; } // Add a marker EOF token to the end of the token list for this argument. SourceLocation EndLoc = Tok.getLocation(); Tok.startToken(); Tok.setKind(tok::eof); Tok.setLocation(EndLoc); Tok.setLength(0); ArgTokens.push_back(Tok); // If we expect two arguments, add both as empty. if (NumActuals == 0 && MinArgsExpected == 2) ArgTokens.push_back(Tok); } else if (NumActuals > MinArgsExpected && !MI->isVariadic() && !ContainsCodeCompletionTok) { // Emit the diagnostic at the macro name in case there is a missing ). // Emitting it at the , could be far away from the macro name. Diag(MacroName, diag::err_too_many_args_in_macro_invoc); Diag(MI->getDefinitionLoc(), diag::note_macro_here) << MacroName.getIdentifierInfo(); return nullptr; } return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this); } /// \brief Keeps macro expanded tokens for TokenLexers. // /// Works like a stack; a TokenLexer adds the macro expanded tokens that is /// going to lex in the cache and when it finishes the tokens are removed /// from the end of the cache. Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer, ArrayRef<Token> tokens) { assert(tokLexer); if (tokens.empty()) return nullptr; size_t newIndex = MacroExpandedTokens.size(); bool cacheNeedsToGrow = tokens.size() > MacroExpandedTokens.capacity()-MacroExpandedTokens.size(); MacroExpandedTokens.append(tokens.begin(), tokens.end()); if (cacheNeedsToGrow) { // Go through all the TokenLexers whose 'Tokens' pointer points in the // buffer and update the pointers to the (potential) new buffer array. for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) { TokenLexer *prevLexer; size_t tokIndex; std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i]; prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex; } } MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex)); return MacroExpandedTokens.data() + newIndex; } void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() { assert(!MacroExpandingLexersStack.empty()); size_t tokIndex = MacroExpandingLexersStack.back().second; assert(tokIndex < MacroExpandedTokens.size()); // Pop the cached macro expanded tokens from the end. MacroExpandedTokens.resize(tokIndex); MacroExpandingLexersStack.pop_back(); } /// ComputeDATE_TIME - Compute the current time, enter it into the specified /// scratch buffer, then return DATELoc/TIMELoc locations with the position of /// the identifier tokens inserted. static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, Preprocessor &PP) { time_t TT = time(nullptr); struct tm *TM = localtime(&TT); static const char * const Months[] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; { SmallString<32> TmpBuffer; llvm::raw_svector_ostream TmpStream(TmpBuffer); TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday, TM->tm_year + 1900); Token TmpTok; TmpTok.startToken(); PP.CreateString(TmpStream.str(), TmpTok); DATELoc = TmpTok.getLocation(); } { SmallString<32> TmpBuffer; llvm::raw_svector_ostream TmpStream(TmpBuffer); TmpStream << llvm::format("\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec); Token TmpTok; TmpTok.startToken(); PP.CreateString(TmpStream.str(), TmpTok); TIMELoc = TmpTok.getLocation(); } } /// HasFeature - Return true if we recognize and implement the feature /// specified by the identifier as a standard language feature. static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) { const LangOptions &LangOpts = PP.getLangOpts(); StringRef Feature = II->getName(); // Normalize the feature name, __foo__ becomes foo. if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4) Feature = Feature.substr(2, Feature.size() - 4); return llvm::StringSwitch<bool>(Feature) .Case("address_sanitizer", LangOpts.Sanitize.hasOneOf(SanitizerKind::Address | SanitizerKind::KernelAddress)) .Case("assume_nonnull", true) .Case("attribute_analyzer_noreturn", true) .Case("attribute_availability", true) .Case("attribute_availability_with_message", true) .Case("attribute_availability_app_extension", true) .Case("attribute_cf_returns_not_retained", true) .Case("attribute_cf_returns_retained", true) .Case("attribute_cf_returns_on_parameters", true) .Case("attribute_deprecated_with_message", true) .Case("attribute_ext_vector_type", true) .Case("attribute_ns_returns_not_retained", true) .Case("attribute_ns_returns_retained", true) .Case("attribute_ns_consumes_self", true) .Case("attribute_ns_consumed", true) .Case("attribute_cf_consumed", true) .Case("attribute_objc_ivar_unused", true) .Case("attribute_objc_method_family", true) .Case("attribute_overloadable", true) .Case("attribute_unavailable_with_message", true) .Case("attribute_unused_on_fields", true) .Case("blocks", LangOpts.Blocks) .Case("c_thread_safety_attributes", true) .Case("cxx_exceptions", LangOpts.CXXExceptions) .Case("cxx_rtti", LangOpts.RTTI) .Case("enumerator_attributes", true) .Case("nullability", true) .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory)) .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread)) .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow)) // Objective-C features .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE? .Case("objc_arc", LangOpts.ObjCAutoRefCount) .Case("objc_arc_weak", LangOpts.ObjCARCWeak) .Case("objc_default_synthesize_properties", LangOpts.ObjC2) .Case("objc_fixed_enum", LangOpts.ObjC2) .Case("objc_instancetype", LangOpts.ObjC2) .Case("objc_kindof", LangOpts.ObjC2) .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules) .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile()) .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword? .Case("objc_protocol_qualifier_mangling", true) .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport()) .Case("ownership_holds", true) .Case("ownership_returns", true) .Case("ownership_takes", true) .Case("objc_bool", true) .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile()) .Case("objc_array_literals", LangOpts.ObjC2) .Case("objc_dictionary_literals", LangOpts.ObjC2) .Case("objc_boxed_expressions", LangOpts.ObjC2) .Case("objc_boxed_nsvalue_expressions", LangOpts.ObjC2) .Case("arc_cf_code_audited", true) .Case("objc_bridge_id", true) .Case("objc_bridge_id_on_typedefs", true) .Case("objc_generics", LangOpts.ObjC2) .Case("objc_generics_variance", LangOpts.ObjC2) // C11 features .Case("c_alignas", LangOpts.C11) .Case("c_alignof", LangOpts.C11) .Case("c_atomic", LangOpts.C11) .Case("c_generic_selections", LangOpts.C11) .Case("c_static_assert", LangOpts.C11) .Case("c_thread_local", LangOpts.C11 && PP.getTargetInfo().isTLSSupported()) // C++11 features .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11) .Case("cxx_alias_templates", LangOpts.CPlusPlus11) .Case("cxx_alignas", LangOpts.CPlusPlus11) .Case("cxx_alignof", LangOpts.CPlusPlus11) .Case("cxx_atomic", LangOpts.CPlusPlus11) .Case("cxx_attributes", LangOpts.CPlusPlus11) .Case("cxx_auto_type", LangOpts.CPlusPlus11) .Case("cxx_constexpr", LangOpts.CPlusPlus11) .Case("cxx_decltype", LangOpts.CPlusPlus11) .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11) .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11) .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11) .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11) .Case("cxx_deleted_functions", LangOpts.CPlusPlus11) .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11) .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11) .Case("cxx_implicit_moves", LangOpts.CPlusPlus11) .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11) .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11) .Case("cxx_lambdas", LangOpts.CPlusPlus11) .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11) .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11) .Case("cxx_noexcept", LangOpts.CPlusPlus11) .Case("cxx_nullptr", LangOpts.CPlusPlus11) .Case("cxx_override_control", LangOpts.CPlusPlus11) .Case("cxx_range_for", LangOpts.CPlusPlus11) .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11) .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11) .Case("cxx_rvalue_references", LangOpts.CPlusPlus11) .Case("cxx_strong_enums", LangOpts.CPlusPlus11) .Case("cxx_static_assert", LangOpts.CPlusPlus11) .Case("cxx_thread_local", LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported()) .Case("cxx_trailing_return", LangOpts.CPlusPlus11) .Case("cxx_unicode_literals", LangOpts.CPlusPlus11) .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11) .Case("cxx_user_literals", LangOpts.CPlusPlus11) .Case("cxx_variadic_templates", LangOpts.CPlusPlus11) // C++1y features .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14) .Case("cxx_binary_literals", LangOpts.CPlusPlus14) .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14) .Case("cxx_decltype_auto", LangOpts.CPlusPlus14) .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14) .Case("cxx_init_captures", LangOpts.CPlusPlus14) .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14) .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14) .Case("cxx_variable_templates", LangOpts.CPlusPlus14) // C++ TSes //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays) //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts) // FIXME: Should this be __has_feature or __has_extension? //.Case("raw_invocation_type", LangOpts.CPlusPlus) // Type traits .Case("has_nothrow_assign", LangOpts.CPlusPlus) .Case("has_nothrow_copy", LangOpts.CPlusPlus) .Case("has_nothrow_constructor", LangOpts.CPlusPlus) .Case("has_trivial_assign", LangOpts.CPlusPlus) .Case("has_trivial_copy", LangOpts.CPlusPlus) .Case("has_trivial_constructor", LangOpts.CPlusPlus) .Case("has_trivial_destructor", LangOpts.CPlusPlus) .Case("has_virtual_destructor", LangOpts.CPlusPlus) .Case("is_abstract", LangOpts.CPlusPlus) .Case("is_base_of", LangOpts.CPlusPlus) .Case("is_class", LangOpts.CPlusPlus) .Case("is_constructible", LangOpts.CPlusPlus) .Case("is_convertible_to", LangOpts.CPlusPlus) .Case("is_empty", LangOpts.CPlusPlus) .Case("is_enum", LangOpts.CPlusPlus) .Case("is_final", LangOpts.CPlusPlus) .Case("is_literal", LangOpts.CPlusPlus) .Case("is_standard_layout", LangOpts.CPlusPlus) .Case("is_pod", LangOpts.CPlusPlus) .Case("is_polymorphic", LangOpts.CPlusPlus) .Case("is_sealed", LangOpts.MicrosoftExt) .Case("is_trivial", LangOpts.CPlusPlus) .Case("is_trivially_assignable", LangOpts.CPlusPlus) .Case("is_trivially_constructible", LangOpts.CPlusPlus) .Case("is_trivially_copyable", LangOpts.CPlusPlus) .Case("is_union", LangOpts.CPlusPlus) .Case("modules", LangOpts.Modules) .Case("safe_stack", LangOpts.Sanitize.has(SanitizerKind::SafeStack)) .Case("tls", PP.getTargetInfo().isTLSSupported()) .Case("underlying_type", LangOpts.CPlusPlus) .Default(false); } /// HasExtension - Return true if we recognize and implement the feature /// specified by the identifier, either as an extension or a standard language /// feature. static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) { if (HasFeature(PP, II)) return true; // If the use of an extension results in an error diagnostic, extensions are // effectively unavailable, so just return false here. if (PP.getDiagnostics().getExtensionHandlingBehavior() >= diag::Severity::Error) return false; const LangOptions &LangOpts = PP.getLangOpts(); StringRef Extension = II->getName(); // Normalize the extension name, __foo__ becomes foo. if (Extension.startswith("__") && Extension.endswith("__") && Extension.size() >= 4) Extension = Extension.substr(2, Extension.size() - 4); // Because we inherit the feature list from HasFeature, this string switch // must be less restrictive than HasFeature's. return llvm::StringSwitch<bool>(Extension) // C11 features supported by other languages as extensions. .Case("c_alignas", true) .Case("c_alignof", true) .Case("c_atomic", true) .Case("c_generic_selections", true) .Case("c_static_assert", true) .Case("c_thread_local", PP.getTargetInfo().isTLSSupported()) // C++11 features supported by other languages as extensions. .Case("cxx_atomic", LangOpts.CPlusPlus) .Case("cxx_deleted_functions", LangOpts.CPlusPlus) .Case("cxx_explicit_conversions", LangOpts.CPlusPlus) .Case("cxx_inline_namespaces", LangOpts.CPlusPlus) .Case("cxx_local_type_template_args", LangOpts.CPlusPlus) .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus) .Case("cxx_override_control", LangOpts.CPlusPlus) .Case("cxx_range_for", LangOpts.CPlusPlus) .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus) .Case("cxx_rvalue_references", LangOpts.CPlusPlus) .Case("cxx_variadic_templates", LangOpts.CPlusPlus) // C++1y features supported by other languages as extensions. .Case("cxx_binary_literals", true) .Case("cxx_init_captures", LangOpts.CPlusPlus11) .Case("cxx_variable_templates", LangOpts.CPlusPlus) .Default(false); } /// EvaluateHasIncludeCommon - Process a '__has_include("path")' /// or '__has_include_next("path")' expression. /// Returns true if successful. static bool EvaluateHasIncludeCommon(Token &Tok, IdentifierInfo *II, Preprocessor &PP, const DirectoryLookup *LookupFrom, const FileEntry *LookupFromFile) { // Save the location of the current token. If a '(' is later found, use // that location. If not, use the end of this location instead. SourceLocation LParenLoc = Tok.getLocation(); // These expressions are only allowed within a preprocessor directive. if (!PP.isParsingIfOrElifDirective()) { PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName(); // Return a valid identifier token. assert(Tok.is(tok::identifier)); Tok.setIdentifierInfo(II); return false; } // Get '('. PP.LexNonComment(Tok); // Ensure we have a '('. if (Tok.isNot(tok::l_paren)) { // No '(', use end of last token. LParenLoc = PP.getLocForEndOfToken(LParenLoc); PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren; // If the next token looks like a filename or the start of one, // assume it is and process it as such. if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) && !Tok.is(tok::less)) return false; } else { // Save '(' location for possible missing ')' message. LParenLoc = Tok.getLocation(); if (PP.getCurrentLexer()) { // Get the file name. PP.getCurrentLexer()->LexIncludeFilename(Tok); } else { // We're in a macro, so we can't use LexIncludeFilename; just // grab the next token. PP.Lex(Tok); } } // Reserve a buffer to get the spelling. SmallString<128> FilenameBuffer; StringRef Filename; SourceLocation EndLoc; switch (Tok.getKind()) { case tok::eod: // If the token kind is EOD, the error has already been diagnosed. return false; case tok::angle_string_literal: case tok::string_literal: { bool Invalid = false; Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid); if (Invalid) return false; break; } case tok::less: // This could be a <foo/bar.h> file coming from a macro expansion. In this // case, glue the tokens together into FilenameBuffer and interpret those. FilenameBuffer.push_back('<'); if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) { // Let the caller know a <eod> was found by changing the Token kind. Tok.setKind(tok::eod); return false; // Found <eod> but no ">"? Diagnostic already emitted. } Filename = FilenameBuffer; break; default: PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename); return false; } SourceLocation FilenameLoc = Tok.getLocation(); // Get ')'. PP.LexNonComment(Tok); // Ensure we have a trailing ). if (Tok.isNot(tok::r_paren)) { PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after) << II << tok::r_paren; PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; return false; } bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename); // If GetIncludeFilenameSpelling set the start ptr to null, there was an // error. if (Filename.empty()) return false; // Search include directories. const DirectoryLookup *CurDir; const FileEntry *File = PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile, CurDir, nullptr, nullptr, nullptr); // Get the result value. A result of true means the file exists. return File != nullptr; } /// EvaluateHasInclude - Process a '__has_include("path")' expression. /// Returns true if successful. static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II, Preprocessor &PP) { return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr); } /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression. /// Returns true if successful. static bool EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II, Preprocessor &PP) { // __has_include_next is like __has_include, except that we start // searching after the current found directory. If we can't do this, // issue a diagnostic. // FIXME: Factor out duplication with // Preprocessor::HandleIncludeNextDirective. const DirectoryLookup *Lookup = PP.GetCurDirLookup(); const FileEntry *LookupFromFile = nullptr; if (PP.isInPrimaryFile()) { Lookup = nullptr; PP.Diag(Tok, diag::pp_include_next_in_primary); } else if (PP.getCurrentSubmodule()) { // Start looking up in the directory *after* the one in which the current // file would be found, if any. assert(PP.getCurrentLexer() && "#include_next directive in macro?"); LookupFromFile = PP.getCurrentLexer()->getFileEntry(); Lookup = nullptr; } else if (!Lookup) { PP.Diag(Tok, diag::pp_include_next_absolute_path); } else { // Start looking up in the next directory. ++Lookup; } return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile); } /// \brief Process __building_module(identifier) expression. /// \returns true if we are building the named module, false otherwise. static bool EvaluateBuildingModule(Token &Tok, IdentifierInfo *II, Preprocessor &PP) { // Get '('. PP.LexNonComment(Tok); // Ensure we have a '('. if (Tok.isNot(tok::l_paren)) { PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II << tok::l_paren; return false; } // Save '(' location for possible missing ')' message. SourceLocation LParenLoc = Tok.getLocation(); // Get the module name. PP.LexNonComment(Tok); // Ensure that we have an identifier. if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module); return false; } bool Result = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule; // Get ')'. PP.LexNonComment(Tok); // Ensure we have a trailing ). if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II << tok::r_paren; PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; return false; } return Result; } /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded /// as a builtin macro, handle it and return the next token as 'Tok'. void Preprocessor::ExpandBuiltinMacro(Token &Tok) { // Figure out which token this is. IdentifierInfo *II = Tok.getIdentifierInfo(); assert(II && "Can't be a macro without id info!"); // If this is an _Pragma or Microsoft __pragma directive, expand it, // invoke the pragma handler, then lex the token after it. if (II == Ident_Pragma) return Handle_Pragma(Tok); else if (II == Ident__pragma) // in non-MS mode this is null return HandleMicrosoft__pragma(Tok); ++NumBuiltinMacroExpanded; SmallString<128> TmpBuffer; llvm::raw_svector_ostream OS(TmpBuffer); // Set up the return result. Tok.setIdentifierInfo(nullptr); Tok.clearFlag(Token::NeedsCleaning); if (II == Ident__LINE__) { // C99 6.10.8: "__LINE__: The presumed line number (within the current // source file) of the current source line (an integer constant)". This can // be affected by #line. SourceLocation Loc = Tok.getLocation(); // Advance to the location of the first _, this might not be the first byte // of the token if it starts with an escaped newline. Loc = AdvanceToTokenCharacter(Loc, 0); // One wrinkle here is that GCC expands __LINE__ to location of the *end* of // a macro expansion. This doesn't matter for object-like macros, but // can matter for a function-like macro that expands to contain __LINE__. // Skip down through expansion points until we find a file loc for the // end of the expansion history. Loc = SourceMgr.getExpansionRange(Loc).second; PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); // __LINE__ expands to a simple numeric value. OS << (PLoc.isValid()? PLoc.getLine() : 1); Tok.setKind(tok::numeric_constant); } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) { // C99 6.10.8: "__FILE__: The presumed name of the current source file (a // character string literal)". This can be affected by #line. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); // __BASE_FILE__ is a GNU extension that returns the top of the presumed // #include stack instead of the current file. if (II == Ident__BASE_FILE__ && PLoc.isValid()) { SourceLocation NextLoc = PLoc.getIncludeLoc(); while (NextLoc.isValid()) { PLoc = SourceMgr.getPresumedLoc(NextLoc); if (PLoc.isInvalid()) break; NextLoc = PLoc.getIncludeLoc(); } } // Escape this filename. Turn '\' -> '\\' '"' -> '\"' SmallString<128> FN; if (PLoc.isValid()) { FN += PLoc.getFilename(); Lexer::Stringify(FN); OS << '"' << FN << '"'; } Tok.setKind(tok::string_literal); } else if (II == Ident__DATE__) { Diag(Tok.getLocation(), diag::warn_pp_date_time); if (!DATELoc.isValid()) ComputeDATE_TIME(DATELoc, TIMELoc, *this); Tok.setKind(tok::string_literal); Tok.setLength(strlen("\"Mmm dd yyyy\"")); Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(), Tok.getLocation(), Tok.getLength())); return; } else if (II == Ident__TIME__) { Diag(Tok.getLocation(), diag::warn_pp_date_time); if (!TIMELoc.isValid()) ComputeDATE_TIME(DATELoc, TIMELoc, *this); Tok.setKind(tok::string_literal); Tok.setLength(strlen("\"hh:mm:ss\"")); Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(), Tok.getLocation(), Tok.getLength())); return; } else if (II == Ident__INCLUDE_LEVEL__) { // Compute the presumed include depth of this token. This can be affected // by GNU line markers. unsigned Depth = 0; PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); if (PLoc.isValid()) { PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); for (; PLoc.isValid(); ++Depth) PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); } // __INCLUDE_LEVEL__ expands to a simple numeric value. OS << Depth; Tok.setKind(tok::numeric_constant); } else if (II == Ident__TIMESTAMP__) { Diag(Tok.getLocation(), diag::warn_pp_date_time); // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime. // Get the file that we are lexing out of. If we're currently lexing from // a macro, dig into the include stack. const FileEntry *CurFile = nullptr; PreprocessorLexer *TheLexer = getCurrentFileLexer(); if (TheLexer) CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID()); const char *Result; if (CurFile) { time_t TT = CurFile->getModificationTime(); struct tm *TM = localtime(&TT); Result = asctime(TM); } else { Result = "??? ??? ?? ??:??:?? ????\n"; } // Surround the string with " and strip the trailing newline. OS << '"' << StringRef(Result).drop_back() << '"'; Tok.setKind(tok::string_literal); } else if (II == Ident__COUNTER__) { // __COUNTER__ expands to a simple numeric value. OS << CounterValue++; Tok.setKind(tok::numeric_constant); } else if (II == Ident__has_feature || II == Ident__has_extension || II == Ident__has_builtin || II == Ident__is_identifier || II == Ident__has_attribute || II == Ident__has_declspec || II == Ident__has_cpp_attribute) { // The argument to these builtins should be a parenthesized identifier. SourceLocation StartLoc = Tok.getLocation(); bool IsValid = false; IdentifierInfo *FeatureII = nullptr; IdentifierInfo *ScopeII = nullptr; // Read the '('. LexUnexpandedToken(Tok); if (Tok.is(tok::l_paren)) { // Read the identifier LexUnexpandedToken(Tok); if ((FeatureII = Tok.getIdentifierInfo())) { // If we're checking __has_cpp_attribute, it is possible to receive a // scope token. Read the "::", if it's available. LexUnexpandedToken(Tok); bool IsScopeValid = true; if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) { LexUnexpandedToken(Tok); // The first thing we read was not the feature, it was the scope. ScopeII = FeatureII; if ((FeatureII = Tok.getIdentifierInfo())) LexUnexpandedToken(Tok); else IsScopeValid = false; } // Read the closing paren. if (IsScopeValid && Tok.is(tok::r_paren)) IsValid = true; } // Eat tokens until ')'. while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) LexUnexpandedToken(Tok); } int Value = 0; if (!IsValid) Diag(StartLoc, diag::err_feature_check_malformed); else if (II == Ident__is_identifier) Value = FeatureII->getTokenID() == tok::identifier; else if (II == Ident__has_builtin) { // Check for a builtin is trivial. Value = FeatureII->getBuiltinID() != 0; } else if (II == Ident__has_attribute) Value = hasAttribute(AttrSyntax::GNU, nullptr, FeatureII, getTargetInfo().getTriple(), getLangOpts()); else if (II == Ident__has_cpp_attribute) Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII, getTargetInfo().getTriple(), getLangOpts()); else if (II == Ident__has_declspec) Value = hasAttribute(AttrSyntax::Declspec, nullptr, FeatureII, getTargetInfo().getTriple(), getLangOpts()); else if (II == Ident__has_extension) Value = HasExtension(*this, FeatureII); else { assert(II == Ident__has_feature && "Must be feature check"); Value = HasFeature(*this, FeatureII); } if (!IsValid) return; OS << Value; Tok.setKind(tok::numeric_constant); } else if (II == Ident__has_include || II == Ident__has_include_next) { // The argument to these two builtins should be a parenthesized // file name string literal using angle brackets (<>) or // double-quotes (""). bool Value; if (II == Ident__has_include) Value = EvaluateHasInclude(Tok, II, *this); else Value = EvaluateHasIncludeNext(Tok, II, *this); if (Tok.isNot(tok::r_paren)) return; OS << (int)Value; Tok.setKind(tok::numeric_constant); } else if (II == Ident__has_warning) { // The argument should be a parenthesized string literal. // The argument to these builtins should be a parenthesized identifier. SourceLocation StartLoc = Tok.getLocation(); bool IsValid = false; bool Value = false; // Read the '('. LexUnexpandedToken(Tok); do { if (Tok.isNot(tok::l_paren)) { Diag(StartLoc, diag::err_warning_check_malformed); break; } LexUnexpandedToken(Tok); std::string WarningName; SourceLocation StrStartLoc = Tok.getLocation(); if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'", /*MacroExpansion=*/false)) { // Eat tokens until ')'. while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) LexUnexpandedToken(Tok); break; } // Is the end a ')'? if (!(IsValid = Tok.is(tok::r_paren))) { Diag(StartLoc, diag::err_warning_check_malformed); break; } // FIXME: Should we accept "-R..." flags here, or should that be handled // by a separate __has_remark? if (WarningName.size() < 3 || WarningName[0] != '-' || WarningName[1] != 'W') { Diag(StrStartLoc, diag::warn_has_warning_invalid_option); break; } // Finally, check if the warning flags maps to a diagnostic group. // We construct a SmallVector here to talk to getDiagnosticIDs(). // Although we don't use the result, this isn't a hot path, and not // worth special casing. SmallVector<diag::kind, 10> Diags; Value = !getDiagnostics().getDiagnosticIDs()-> getDiagnosticsInGroup(diag::Flavor::WarningOrError, WarningName.substr(2), Diags); } while (false); if (!IsValid) return; OS << (int)Value; Tok.setKind(tok::numeric_constant); } else if (II == Ident__building_module) { // The argument to this builtin should be an identifier. The // builtin evaluates to 1 when that identifier names the module we are // currently building. OS << (int)EvaluateBuildingModule(Tok, II, *this); Tok.setKind(tok::numeric_constant); } else if (II == Ident__MODULE__) { // The current module as an identifier. OS << getLangOpts().CurrentModule; IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule); Tok.setIdentifierInfo(ModuleII); Tok.setKind(ModuleII->getTokenID()); } else if (II == Ident__identifier) { SourceLocation Loc = Tok.getLocation(); // We're expecting '__identifier' '(' identifier ')'. Try to recover // if the parens are missing. LexNonComment(Tok); if (Tok.isNot(tok::l_paren)) { // No '(', use end of last token. Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after) << II << tok::l_paren; // If the next token isn't valid as our argument, we can't recover. if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) Tok.setKind(tok::identifier); return; } SourceLocation LParenLoc = Tok.getLocation(); LexNonComment(Tok); if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) Tok.setKind(tok::identifier); else { Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier) << Tok.getKind(); // Don't walk past anything that's not a real token. if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation()) return; } // Discard the ')', preserving 'Tok' as our result. Token RParen; LexNonComment(RParen); if (RParen.isNot(tok::r_paren)) { Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after) << Tok.getKind() << tok::r_paren; Diag(LParenLoc, diag::note_matching) << tok::l_paren; } return; } else { llvm_unreachable("Unknown identifier!"); } CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation()); } void Preprocessor::markMacroAsUsed(MacroInfo *MI) { // If the 'used' status changed, and the macro requires 'unused' warning, // remove its SourceLocation from the warn-for-unused-macro locations. if (MI->isWarnIfUnused() && !MI->isUsed()) WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); MI->setIsUsed(true); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/PreprocessingRecord.cpp
//===--- PreprocessingRecord.cpp - Record of Preprocessing ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PreprocessingRecord class, which maintains a record // of what occurred during preprocessing, and its helpers. // //===----------------------------------------------------------------------===// #include "clang/Lex/PreprocessingRecord.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Token.h" #include "llvm/Support/Capacity.h" #include "llvm/Support/ErrorHandling.h" // // /////////////////////////////////////////////////////////////////////////////// using namespace clang; ExternalPreprocessingRecordSource::~ExternalPreprocessingRecordSource() { } InclusionDirective::InclusionDirective(PreprocessingRecord &PPRec, InclusionKind Kind, StringRef FileName, bool InQuotes, bool ImportedModule, const FileEntry *File, SourceRange Range) : PreprocessingDirective(InclusionDirectiveKind, Range), InQuotes(InQuotes), Kind(Kind), ImportedModule(ImportedModule), File(File) { char *Memory = (char*)PPRec.Allocate(FileName.size() + 1, llvm::alignOf<char>()); memcpy(Memory, FileName.data(), FileName.size()); Memory[FileName.size()] = 0; this->FileName = StringRef(Memory, FileName.size()); } PreprocessingRecord::PreprocessingRecord(SourceManager &SM) : SourceMgr(SM), ExternalSource(nullptr) { } /// \brief Returns a pair of [Begin, End) iterators of preprocessed entities /// that source range \p Range encompasses. llvm::iterator_range<PreprocessingRecord::iterator> PreprocessingRecord::getPreprocessedEntitiesInRange(SourceRange Range) { if (Range.isInvalid()) return llvm::make_range(iterator(), iterator()); if (CachedRangeQuery.Range == Range) { return llvm::make_range(iterator(this, CachedRangeQuery.Result.first), iterator(this, CachedRangeQuery.Result.second)); } std::pair<int, int> Res = getPreprocessedEntitiesInRangeSlow(Range); CachedRangeQuery.Range = Range; CachedRangeQuery.Result = Res; return llvm::make_range(iterator(this, Res.first), iterator(this, Res.second)); } static bool isPreprocessedEntityIfInFileID(PreprocessedEntity *PPE, FileID FID, SourceManager &SM) { assert(!FID.isInvalid()); if (!PPE) return false; SourceLocation Loc = PPE->getSourceRange().getBegin(); if (Loc.isInvalid()) return false; return SM.isInFileID(SM.getFileLoc(Loc), FID); } /// \brief Returns true if the preprocessed entity that \arg PPEI iterator /// points to is coming from the file \arg FID. /// /// Can be used to avoid implicit deserializations of preallocated /// preprocessed entities if we only care about entities of a specific file /// and not from files \#included in the range given at /// \see getPreprocessedEntitiesInRange. bool PreprocessingRecord::isEntityInFileID(iterator PPEI, FileID FID) { if (FID.isInvalid()) return false; int Pos = std::distance(iterator(this, 0), PPEI); if (Pos < 0) { if (unsigned(-Pos-1) >= LoadedPreprocessedEntities.size()) { assert(0 && "Out-of bounds loaded preprocessed entity"); return false; } assert(ExternalSource && "No external source to load from"); unsigned LoadedIndex = LoadedPreprocessedEntities.size()+Pos; if (PreprocessedEntity *PPE = LoadedPreprocessedEntities[LoadedIndex]) return isPreprocessedEntityIfInFileID(PPE, FID, SourceMgr); // See if the external source can see if the entity is in the file without // deserializing it. Optional<bool> IsInFile = ExternalSource->isPreprocessedEntityInFileID(LoadedIndex, FID); if (IsInFile.hasValue()) return IsInFile.getValue(); // The external source did not provide a definite answer, go and deserialize // the entity to check it. return isPreprocessedEntityIfInFileID( getLoadedPreprocessedEntity(LoadedIndex), FID, SourceMgr); } if (unsigned(Pos) >= PreprocessedEntities.size()) { assert(0 && "Out-of bounds local preprocessed entity"); return false; } return isPreprocessedEntityIfInFileID(PreprocessedEntities[Pos], FID, SourceMgr); } /// \brief Returns a pair of [Begin, End) iterators of preprocessed entities /// that source range \arg R encompasses. std::pair<int, int> PreprocessingRecord::getPreprocessedEntitiesInRangeSlow(SourceRange Range) { assert(Range.isValid()); assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); std::pair<unsigned, unsigned> Local = findLocalPreprocessedEntitiesInRange(Range); // Check if range spans local entities. if (!ExternalSource || SourceMgr.isLocalSourceLocation(Range.getBegin())) return std::make_pair(Local.first, Local.second); std::pair<unsigned, unsigned> Loaded = ExternalSource->findPreprocessedEntitiesInRange(Range); // Check if range spans local entities. if (Loaded.first == Loaded.second) return std::make_pair(Local.first, Local.second); unsigned TotalLoaded = LoadedPreprocessedEntities.size(); // Check if range spans loaded entities. if (Local.first == Local.second) return std::make_pair(int(Loaded.first)-TotalLoaded, int(Loaded.second)-TotalLoaded); // Range spands loaded and local entities. return std::make_pair(int(Loaded.first)-TotalLoaded, Local.second); } std::pair<unsigned, unsigned> PreprocessingRecord::findLocalPreprocessedEntitiesInRange( SourceRange Range) const { if (Range.isInvalid()) return std::make_pair(0,0); assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin())); unsigned Begin = findBeginLocalPreprocessedEntity(Range.getBegin()); unsigned End = findEndLocalPreprocessedEntity(Range.getEnd()); return std::make_pair(Begin, End); } namespace { template <SourceLocation (SourceRange::*getRangeLoc)() const> struct PPEntityComp { const SourceManager &SM; explicit PPEntityComp(const SourceManager &SM) : SM(SM) { } bool operator()(PreprocessedEntity *L, PreprocessedEntity *R) const { SourceLocation LHS = getLoc(L); SourceLocation RHS = getLoc(R); return SM.isBeforeInTranslationUnit(LHS, RHS); } bool operator()(PreprocessedEntity *L, SourceLocation RHS) const { SourceLocation LHS = getLoc(L); return SM.isBeforeInTranslationUnit(LHS, RHS); } bool operator()(SourceLocation LHS, PreprocessedEntity *R) const { SourceLocation RHS = getLoc(R); return SM.isBeforeInTranslationUnit(LHS, RHS); } SourceLocation getLoc(PreprocessedEntity *PPE) const { SourceRange Range = PPE->getSourceRange(); return (Range.*getRangeLoc)(); } }; } unsigned PreprocessingRecord::findBeginLocalPreprocessedEntity( SourceLocation Loc) const { if (SourceMgr.isLoadedSourceLocation(Loc)) return 0; size_t Count = PreprocessedEntities.size(); size_t Half; std::vector<PreprocessedEntity *>::const_iterator First = PreprocessedEntities.begin(); std::vector<PreprocessedEntity *>::const_iterator I; // Do a binary search manually instead of using std::lower_bound because // The end locations of entities may be unordered (when a macro expansion // is inside another macro argument), but for this case it is not important // whether we get the first macro expansion or its containing macro. while (Count > 0) { Half = Count/2; I = First; std::advance(I, Half); if (SourceMgr.isBeforeInTranslationUnit((*I)->getSourceRange().getEnd(), Loc)){ First = I; ++First; Count = Count - Half - 1; } else Count = Half; } return First - PreprocessedEntities.begin(); } unsigned PreprocessingRecord::findEndLocalPreprocessedEntity( SourceLocation Loc) const { if (SourceMgr.isLoadedSourceLocation(Loc)) return 0; std::vector<PreprocessedEntity *>::const_iterator I = std::upper_bound(PreprocessedEntities.begin(), PreprocessedEntities.end(), Loc, PPEntityComp<&SourceRange::getBegin>(SourceMgr)); return I - PreprocessedEntities.begin(); } PreprocessingRecord::PPEntityID PreprocessingRecord::addPreprocessedEntity(PreprocessedEntity *Entity) { assert(Entity); SourceLocation BeginLoc = Entity->getSourceRange().getBegin(); if (isa<MacroDefinitionRecord>(Entity)) { assert((PreprocessedEntities.empty() || !SourceMgr.isBeforeInTranslationUnit( BeginLoc, PreprocessedEntities.back()->getSourceRange().getBegin())) && "a macro definition was encountered out-of-order"); PreprocessedEntities.push_back(Entity); return getPPEntityID(PreprocessedEntities.size()-1, /*isLoaded=*/false); } // Check normal case, this entity begin location is after the previous one. if (PreprocessedEntities.empty() || !SourceMgr.isBeforeInTranslationUnit(BeginLoc, PreprocessedEntities.back()->getSourceRange().getBegin())) { PreprocessedEntities.push_back(Entity); return getPPEntityID(PreprocessedEntities.size()-1, /*isLoaded=*/false); } // The entity's location is not after the previous one; this can happen with // include directives that form the filename using macros, e.g: // "#include MACRO(STUFF)" // or with macro expansions inside macro arguments where the arguments are // not expanded in the same order as listed, e.g: // \code // #define M1 1 // #define M2 2 // #define FM(x,y) y x // FM(M1, M2) // \endcode typedef std::vector<PreprocessedEntity *>::iterator pp_iter; // Usually there are few macro expansions when defining the filename, do a // linear search for a few entities. unsigned count = 0; for (pp_iter RI = PreprocessedEntities.end(), Begin = PreprocessedEntities.begin(); RI != Begin && count < 4; --RI, ++count) { pp_iter I = RI; --I; if (!SourceMgr.isBeforeInTranslationUnit(BeginLoc, (*I)->getSourceRange().getBegin())) { pp_iter insertI = PreprocessedEntities.insert(RI, Entity); return getPPEntityID(insertI - PreprocessedEntities.begin(), /*isLoaded=*/false); } } // Linear search unsuccessful. Do a binary search. pp_iter I = std::upper_bound(PreprocessedEntities.begin(), PreprocessedEntities.end(), BeginLoc, PPEntityComp<&SourceRange::getBegin>(SourceMgr)); pp_iter insertI = PreprocessedEntities.insert(I, Entity); return getPPEntityID(insertI - PreprocessedEntities.begin(), /*isLoaded=*/false); } void PreprocessingRecord::SetExternalSource( ExternalPreprocessingRecordSource &Source) { assert(!ExternalSource && "Preprocessing record already has an external source"); ExternalSource = &Source; } unsigned PreprocessingRecord::allocateLoadedEntities(unsigned NumEntities) { unsigned Result = LoadedPreprocessedEntities.size(); LoadedPreprocessedEntities.resize(LoadedPreprocessedEntities.size() + NumEntities); return Result; } void PreprocessingRecord::RegisterMacroDefinition(MacroInfo *Macro, MacroDefinitionRecord *Def) { MacroDefinitions[Macro] = Def; } /// \brief Retrieve the preprocessed entity at the given ID. PreprocessedEntity *PreprocessingRecord::getPreprocessedEntity(PPEntityID PPID){ if (PPID.ID < 0) { unsigned Index = -PPID.ID - 1; assert(Index < LoadedPreprocessedEntities.size() && "Out-of bounds loaded preprocessed entity"); return getLoadedPreprocessedEntity(Index); } if (PPID.ID == 0) return nullptr; unsigned Index = PPID.ID - 1; assert(Index < PreprocessedEntities.size() && "Out-of bounds local preprocessed entity"); return PreprocessedEntities[Index]; } /// \brief Retrieve the loaded preprocessed entity at the given index. PreprocessedEntity * PreprocessingRecord::getLoadedPreprocessedEntity(unsigned Index) { assert(Index < LoadedPreprocessedEntities.size() && "Out-of bounds loaded preprocessed entity"); assert(ExternalSource && "No external source to load from"); PreprocessedEntity *&Entity = LoadedPreprocessedEntities[Index]; if (!Entity) { Entity = ExternalSource->ReadPreprocessedEntity(Index); if (!Entity) // Failed to load. Entity = new (*this) PreprocessedEntity(PreprocessedEntity::InvalidKind, SourceRange()); } return Entity; } MacroDefinitionRecord * PreprocessingRecord::findMacroDefinition(const MacroInfo *MI) { llvm::DenseMap<const MacroInfo *, MacroDefinitionRecord *>::iterator Pos = MacroDefinitions.find(MI); if (Pos == MacroDefinitions.end()) return nullptr; return Pos->second; } void PreprocessingRecord::addMacroExpansion(const Token &Id, const MacroInfo *MI, SourceRange Range) { // We don't record nested macro expansions. if (Id.getLocation().isMacroID()) return; if (MI->isBuiltinMacro()) addPreprocessedEntity(new (*this) MacroExpansion(Id.getIdentifierInfo(), Range)); else if (MacroDefinitionRecord *Def = findMacroDefinition(MI)) addPreprocessedEntity(new (*this) MacroExpansion(Def, Range)); } void PreprocessingRecord::Ifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) { // This is not actually a macro expansion but record it as a macro reference. if (MD) addMacroExpansion(MacroNameTok, MD.getMacroInfo(), MacroNameTok.getLocation()); } void PreprocessingRecord::Ifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) { // This is not actually a macro expansion but record it as a macro reference. if (MD) addMacroExpansion(MacroNameTok, MD.getMacroInfo(), MacroNameTok.getLocation()); } void PreprocessingRecord::Defined(const Token &MacroNameTok, const MacroDefinition &MD, SourceRange Range) { // This is not actually a macro expansion but record it as a macro reference. if (MD) addMacroExpansion(MacroNameTok, MD.getMacroInfo(), MacroNameTok.getLocation()); } void PreprocessingRecord::SourceRangeSkipped(SourceRange Range) { SkippedRanges.push_back(Range); } void PreprocessingRecord::MacroExpands(const Token &Id, const MacroDefinition &MD, SourceRange Range, const MacroArgs *Args) { addMacroExpansion(Id, MD.getMacroInfo(), Range); } void PreprocessingRecord::MacroDefined(const Token &Id, const MacroDirective *MD) { const MacroInfo *MI = MD->getMacroInfo(); SourceRange R(MI->getDefinitionLoc(), MI->getDefinitionEndLoc()); MacroDefinitionRecord *Def = new (*this) MacroDefinitionRecord(Id.getIdentifierInfo(), R); addPreprocessedEntity(Def); MacroDefinitions[MI] = Def; } void PreprocessingRecord::MacroUndefined(const Token &Id, const MacroDefinition &MD) { MD.forAllDefinitions([&](MacroInfo *MI) { MacroDefinitions.erase(MI); }); } void PreprocessingRecord::InclusionDirective( SourceLocation HashLoc, const clang::Token &IncludeTok, StringRef FileName, bool IsAngled, CharSourceRange FilenameRange, const FileEntry *File, StringRef SearchPath, StringRef RelativePath, const Module *Imported) { InclusionDirective::InclusionKind Kind = InclusionDirective::Include; switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) { case tok::pp_include: Kind = InclusionDirective::Include; break; case tok::pp_import: Kind = InclusionDirective::Import; break; case tok::pp_include_next: Kind = InclusionDirective::IncludeNext; break; case tok::pp___include_macros: Kind = InclusionDirective::IncludeMacros; break; default: llvm_unreachable("Unknown include directive kind"); } SourceLocation EndLoc; if (!IsAngled) { EndLoc = FilenameRange.getBegin(); } else { EndLoc = FilenameRange.getEnd(); if (FilenameRange.isCharRange()) EndLoc = EndLoc.getLocWithOffset(-1); // the InclusionDirective expects // a token range. } clang::InclusionDirective *ID = new (*this) clang::InclusionDirective(*this, Kind, FileName, !IsAngled, (bool)Imported, File, SourceRange(HashLoc, EndLoc)); addPreprocessedEntity(ID); } size_t PreprocessingRecord::getTotalMemory() const { return BumpAlloc.getTotalMemory() + llvm::capacity_in_bytes(MacroDefinitions) + llvm::capacity_in_bytes(PreprocessedEntities) + llvm::capacity_in_bytes(LoadedPreprocessedEntities); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/TokenConcatenation.cpp
//===--- TokenConcatenation.cpp - Token Concatenation Avoidance -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TokenConcatenation class. // //===----------------------------------------------------------------------===// #include "clang/Lex/TokenConcatenation.h" #include "clang/Basic/CharInfo.h" #include "clang/Lex/Preprocessor.h" #include "llvm/Support/ErrorHandling.h" using namespace clang; /// IsStringPrefix - Return true if Str is a string prefix. /// 'L', 'u', 'U', or 'u8'. Including raw versions. static bool IsStringPrefix(StringRef Str, bool CPlusPlus11) { if (Str[0] == 'L' || (CPlusPlus11 && (Str[0] == 'u' || Str[0] == 'U' || Str[0] == 'R'))) { if (Str.size() == 1) return true; // "L", "u", "U", and "R" // Check for raw flavors. Need to make sure the first character wasn't // already R. Need CPlusPlus11 check for "LR". if (Str[1] == 'R' && Str[0] != 'R' && Str.size() == 2 && CPlusPlus11) return true; // "LR", "uR", "UR" // Check for "u8" and "u8R" if (Str[0] == 'u' && Str[1] == '8') { if (Str.size() == 2) return true; // "u8" if (Str.size() == 3 && Str[2] == 'R') return true; // "u8R" } } return false; } /// IsIdentifierStringPrefix - Return true if the spelling of the token /// is literally 'L', 'u', 'U', or 'u8'. Including raw versions. bool TokenConcatenation::IsIdentifierStringPrefix(const Token &Tok) const { const LangOptions &LangOpts = PP.getLangOpts(); if (!Tok.needsCleaning()) { if (Tok.getLength() < 1 || Tok.getLength() > 3) return false; SourceManager &SM = PP.getSourceManager(); const char *Ptr = SM.getCharacterData(SM.getSpellingLoc(Tok.getLocation())); return IsStringPrefix(StringRef(Ptr, Tok.getLength()), LangOpts.CPlusPlus11); } if (Tok.getLength() < 256) { char Buffer[256]; const char *TokPtr = Buffer; unsigned length = PP.getSpelling(Tok, TokPtr); return IsStringPrefix(StringRef(TokPtr, length), LangOpts.CPlusPlus11); } return IsStringPrefix(StringRef(PP.getSpelling(Tok)), LangOpts.CPlusPlus11); } TokenConcatenation::TokenConcatenation(Preprocessor &pp) : PP(pp) { memset(TokenInfo, 0, sizeof(TokenInfo)); // These tokens have custom code in AvoidConcat. TokenInfo[tok::identifier ] |= aci_custom; TokenInfo[tok::numeric_constant] |= aci_custom_firstchar; TokenInfo[tok::period ] |= aci_custom_firstchar; TokenInfo[tok::amp ] |= aci_custom_firstchar; TokenInfo[tok::plus ] |= aci_custom_firstchar; TokenInfo[tok::minus ] |= aci_custom_firstchar; TokenInfo[tok::slash ] |= aci_custom_firstchar; TokenInfo[tok::less ] |= aci_custom_firstchar; TokenInfo[tok::greater ] |= aci_custom_firstchar; TokenInfo[tok::pipe ] |= aci_custom_firstchar; TokenInfo[tok::percent ] |= aci_custom_firstchar; TokenInfo[tok::colon ] |= aci_custom_firstchar; TokenInfo[tok::hash ] |= aci_custom_firstchar; TokenInfo[tok::arrow ] |= aci_custom_firstchar; // These tokens have custom code in C++11 mode. if (PP.getLangOpts().CPlusPlus11) { TokenInfo[tok::string_literal ] |= aci_custom; TokenInfo[tok::wide_string_literal ] |= aci_custom; TokenInfo[tok::utf8_string_literal ] |= aci_custom; TokenInfo[tok::utf16_string_literal] |= aci_custom; TokenInfo[tok::utf32_string_literal] |= aci_custom; TokenInfo[tok::char_constant ] |= aci_custom; TokenInfo[tok::wide_char_constant ] |= aci_custom; TokenInfo[tok::utf16_char_constant ] |= aci_custom; TokenInfo[tok::utf32_char_constant ] |= aci_custom; } // These tokens have custom code in C++1z mode. if (PP.getLangOpts().CPlusPlus1z) TokenInfo[tok::utf8_char_constant] |= aci_custom; // These tokens change behavior if followed by an '='. TokenInfo[tok::amp ] |= aci_avoid_equal; // &= TokenInfo[tok::plus ] |= aci_avoid_equal; // += TokenInfo[tok::minus ] |= aci_avoid_equal; // -= TokenInfo[tok::slash ] |= aci_avoid_equal; // /= TokenInfo[tok::less ] |= aci_avoid_equal; // <= TokenInfo[tok::greater ] |= aci_avoid_equal; // >= TokenInfo[tok::pipe ] |= aci_avoid_equal; // |= TokenInfo[tok::percent ] |= aci_avoid_equal; // %= TokenInfo[tok::star ] |= aci_avoid_equal; // *= TokenInfo[tok::exclaim ] |= aci_avoid_equal; // != TokenInfo[tok::lessless ] |= aci_avoid_equal; // <<= TokenInfo[tok::greatergreater] |= aci_avoid_equal; // >>= TokenInfo[tok::caret ] |= aci_avoid_equal; // ^= TokenInfo[tok::equal ] |= aci_avoid_equal; // == } /// GetFirstChar - Get the first character of the token \arg Tok, /// avoiding calls to getSpelling where possible. static char GetFirstChar(Preprocessor &PP, const Token &Tok) { if (IdentifierInfo *II = Tok.getIdentifierInfo()) { // Avoid spelling identifiers, the most common form of token. return II->getNameStart()[0]; } else if (!Tok.needsCleaning()) { if (Tok.isLiteral() && Tok.getLiteralData()) { return *Tok.getLiteralData(); } else { SourceManager &SM = PP.getSourceManager(); return *SM.getCharacterData(SM.getSpellingLoc(Tok.getLocation())); } } else if (Tok.getLength() < 256) { char Buffer[256]; const char *TokPtr = Buffer; PP.getSpelling(Tok, TokPtr); return TokPtr[0]; } else { return PP.getSpelling(Tok)[0]; } } /// AvoidConcat - If printing PrevTok immediately followed by Tok would cause /// the two individual tokens to be lexed as a single token, return true /// (which causes a space to be printed between them). This allows the output /// of -E mode to be lexed to the same token stream as lexing the input /// directly would. /// /// This code must conservatively return true if it doesn't want to be 100% /// accurate. This will cause the output to include extra space characters, /// but the resulting output won't have incorrect concatenations going on. /// Examples include "..", which we print with a space between, because we /// don't want to track enough to tell "x.." from "...". bool TokenConcatenation::AvoidConcat(const Token &PrevPrevTok, const Token &PrevTok, const Token &Tok) const { // First, check to see if the tokens were directly adjacent in the original // source. If they were, it must be okay to stick them together: if there // were an issue, the tokens would have been lexed differently. SourceManager &SM = PP.getSourceManager(); SourceLocation PrevSpellLoc = SM.getSpellingLoc(PrevTok.getLocation()); SourceLocation SpellLoc = SM.getSpellingLoc(Tok.getLocation()); if (PrevSpellLoc.getLocWithOffset(PrevTok.getLength()) == SpellLoc) return false; tok::TokenKind PrevKind = PrevTok.getKind(); if (!PrevTok.isAnnotation() && PrevTok.getIdentifierInfo()) PrevKind = tok::identifier; // Language keyword or named operator. // Look up information on when we should avoid concatenation with prevtok. unsigned ConcatInfo = TokenInfo[PrevKind]; // If prevtok never causes a problem for anything after it, return quickly. if (ConcatInfo == 0) return false; if (ConcatInfo & aci_avoid_equal) { // If the next token is '=' or '==', avoid concatenation. if (Tok.isOneOf(tok::equal, tok::equalequal)) return true; ConcatInfo &= ~aci_avoid_equal; } if (Tok.isAnnotation()) { // Modules annotation can show up when generated automatically for includes. assert(Tok.isOneOf(tok::annot_module_include, tok::annot_module_begin, tok::annot_module_end) && "unexpected annotation in AvoidConcat"); ConcatInfo = 0; } if (ConcatInfo == 0) return false; // Basic algorithm: we look at the first character of the second token, and // determine whether it, if appended to the first token, would form (or // would contribute) to a larger token if concatenated. char FirstChar = 0; if (ConcatInfo & aci_custom) { // If the token does not need to know the first character, don't get it. } else { FirstChar = GetFirstChar(PP, Tok); } switch (PrevKind) { default: llvm_unreachable("InitAvoidConcatTokenInfo built wrong"); case tok::raw_identifier: llvm_unreachable("tok::raw_identifier in non-raw lexing mode!"); case tok::string_literal: case tok::wide_string_literal: case tok::utf8_string_literal: case tok::utf16_string_literal: case tok::utf32_string_literal: case tok::char_constant: case tok::wide_char_constant: case tok::utf8_char_constant: case tok::utf16_char_constant: case tok::utf32_char_constant: if (!PP.getLangOpts().CPlusPlus11) return false; // In C++11, a string or character literal followed by an identifier is a // single token. if (Tok.getIdentifierInfo()) return true; // A ud-suffix is an identifier. If the previous token ends with one, treat // it as an identifier. if (!PrevTok.hasUDSuffix()) return false; // FALL THROUGH. case tok::identifier: // id+id or id+number or id+L"foo". // id+'.'... will not append. if (Tok.is(tok::numeric_constant)) return GetFirstChar(PP, Tok) != '.'; if (Tok.getIdentifierInfo() || Tok.isOneOf(tok::wide_string_literal, tok::utf8_string_literal, tok::utf16_string_literal, tok::utf32_string_literal, tok::wide_char_constant, tok::utf8_char_constant, tok::utf16_char_constant, tok::utf32_char_constant)) return true; // If this isn't identifier + string, we're done. if (Tok.isNot(tok::char_constant) && Tok.isNot(tok::string_literal)) return false; // Otherwise, this is a narrow character or string. If the *identifier* // is a literal 'L', 'u8', 'u' or 'U', avoid pasting L "foo" -> L"foo". return IsIdentifierStringPrefix(PrevTok); case tok::numeric_constant: return isPreprocessingNumberBody(FirstChar) || FirstChar == '+' || FirstChar == '-'; case tok::period: // ..., .*, .1234 return (FirstChar == '.' && PrevPrevTok.is(tok::period)) || isDigit(FirstChar) || (PP.getLangOpts().CPlusPlus && FirstChar == '*'); case tok::amp: // && return FirstChar == '&'; case tok::plus: // ++ return FirstChar == '+'; case tok::minus: // --, ->, ->* return FirstChar == '-' || FirstChar == '>'; case tok::slash: //, /*, // return FirstChar == '*' || FirstChar == '/'; case tok::less: // <<, <<=, <:, <% return FirstChar == '<' || FirstChar == ':' || FirstChar == '%'; case tok::greater: // >>, >>= return FirstChar == '>'; case tok::pipe: // || return FirstChar == '|'; case tok::percent: // %>, %: return FirstChar == '>' || FirstChar == ':'; case tok::colon: // ::, :> return FirstChar == '>' || (PP.getLangOpts().CPlusPlus && FirstChar == ':'); case tok::hash: // ##, #@, %:%: return FirstChar == '#' || FirstChar == '@' || FirstChar == '%'; case tok::arrow: // ->* return PP.getLangOpts().CPlusPlus && FirstChar == '*'; } }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/PPConditionalDirectiveRecord.cpp
//===--- PPConditionalDirectiveRecord.h - Preprocessing Directives-*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PPConditionalDirectiveRecord class, which maintains // a record of conditional directive regions. // //===----------------------------------------------------------------------===// #include "clang/Lex/PPConditionalDirectiveRecord.h" #include "llvm/Support/Capacity.h" // // /////////////////////////////////////////////////////////////////////////////// using namespace clang; PPConditionalDirectiveRecord::PPConditionalDirectiveRecord(SourceManager &SM) : SourceMgr(SM) { CondDirectiveStack.push_back(SourceLocation()); } bool PPConditionalDirectiveRecord::rangeIntersectsConditionalDirective( SourceRange Range) const { if (Range.isInvalid()) return false; CondDirectiveLocsTy::const_iterator low = std::lower_bound(CondDirectiveLocs.begin(), CondDirectiveLocs.end(), Range.getBegin(), CondDirectiveLoc::Comp(SourceMgr)); if (low == CondDirectiveLocs.end()) return false; if (SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), low->getLoc())) return false; CondDirectiveLocsTy::const_iterator upp = std::upper_bound(low, CondDirectiveLocs.end(), Range.getEnd(), CondDirectiveLoc::Comp(SourceMgr)); SourceLocation uppRegion; if (upp != CondDirectiveLocs.end()) uppRegion = upp->getRegionLoc(); return low->getRegionLoc() != uppRegion; } SourceLocation PPConditionalDirectiveRecord::findConditionalDirectiveRegionLoc( SourceLocation Loc) const { if (Loc.isInvalid()) return SourceLocation(); if (CondDirectiveLocs.empty()) return SourceLocation(); if (SourceMgr.isBeforeInTranslationUnit(CondDirectiveLocs.back().getLoc(), Loc)) return CondDirectiveStack.back(); CondDirectiveLocsTy::const_iterator low = std::lower_bound(CondDirectiveLocs.begin(), CondDirectiveLocs.end(), Loc, CondDirectiveLoc::Comp(SourceMgr)); assert(low != CondDirectiveLocs.end()); return low->getRegionLoc(); } void PPConditionalDirectiveRecord::addCondDirectiveLoc( CondDirectiveLoc DirLoc) { // Ignore directives in system headers. if (SourceMgr.isInSystemHeader(DirLoc.getLoc())) return; assert(CondDirectiveLocs.empty() || SourceMgr.isBeforeInTranslationUnit(CondDirectiveLocs.back().getLoc(), DirLoc.getLoc())); CondDirectiveLocs.push_back(DirLoc); } void PPConditionalDirectiveRecord::If(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue) { addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back())); CondDirectiveStack.push_back(Loc); } void PPConditionalDirectiveRecord::Ifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) { addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back())); CondDirectiveStack.push_back(Loc); } void PPConditionalDirectiveRecord::Ifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD) { addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back())); CondDirectiveStack.push_back(Loc); } void PPConditionalDirectiveRecord::Elif(SourceLocation Loc, SourceRange ConditionRange, ConditionValueKind ConditionValue, SourceLocation IfLoc) { addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back())); CondDirectiveStack.back() = Loc; } void PPConditionalDirectiveRecord::Else(SourceLocation Loc, SourceLocation IfLoc) { addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back())); CondDirectiveStack.back() = Loc; } void PPConditionalDirectiveRecord::Endif(SourceLocation Loc, SourceLocation IfLoc) { addCondDirectiveLoc(CondDirectiveLoc(Loc, CondDirectiveStack.back())); assert(!CondDirectiveStack.empty()); CondDirectiveStack.pop_back(); } size_t PPConditionalDirectiveRecord::getTotalMemory() const { return llvm::capacity_in_bytes(CondDirectiveLocs); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/HeaderMap.cpp
//===--- HeaderMap.cpp - A file that acts like dir of symlinks ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the HeaderMap interface. // //===----------------------------------------------------------------------===// #include "clang/Lex/HeaderMap.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/FileManager.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/DataTypes.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" #include <cstdio> #include <memory> using namespace clang; //===----------------------------------------------------------------------===// // Data Structures and Manifest Constants //===----------------------------------------------------------------------===// enum { HMAP_HeaderMagicNumber = ('h' << 24) | ('m' << 16) | ('a' << 8) | 'p', HMAP_HeaderVersion = 1, HMAP_EmptyBucketKey = 0 }; namespace clang { struct HMapBucket { uint32_t Key; // Offset (into strings) of key. uint32_t Prefix; // Offset (into strings) of value prefix. uint32_t Suffix; // Offset (into strings) of value suffix. }; struct HMapHeader { uint32_t Magic; // Magic word, also indicates byte order. uint16_t Version; // Version number -- currently 1. uint16_t Reserved; // Reserved for future use - zero for now. uint32_t StringsOffset; // Offset to start of string pool. uint32_t NumEntries; // Number of entries in the string table. uint32_t NumBuckets; // Number of buckets (always a power of 2). uint32_t MaxValueLength; // Length of longest result path (excluding nul). // An array of 'NumBuckets' HMapBucket objects follows this header. // Strings follow the buckets, at StringsOffset. }; } // end namespace clang. /// HashHMapKey - This is the 'well known' hash function required by the file /// format, used to look up keys in the hash table. The hash table uses simple /// linear probing based on this function. static inline unsigned HashHMapKey(StringRef Str) { unsigned Result = 0; const char *S = Str.begin(), *End = Str.end(); for (; S != End; S++) Result += toLowercase(*S) * 13; return Result; } //===----------------------------------------------------------------------===// // Verification and Construction //===----------------------------------------------------------------------===// /// HeaderMap::Create - This attempts to load the specified file as a header /// map. If it doesn't look like a HeaderMap, it gives up and returns null. /// If it looks like a HeaderMap but is obviously corrupted, it puts a reason /// into the string error argument and returns null. const HeaderMap *HeaderMap::Create(const FileEntry *FE, FileManager &FM) { // If the file is too small to be a header map, ignore it. unsigned FileSize = FE->getSize(); if (FileSize <= sizeof(HMapHeader)) return nullptr; auto FileBuffer = FM.getBufferForFile(FE); if (!FileBuffer) return nullptr; // Unreadable file? const char *FileStart = (*FileBuffer)->getBufferStart(); // We know the file is at least as big as the header, check it now. const HMapHeader *Header = reinterpret_cast<const HMapHeader*>(FileStart); // Sniff it to see if it's a headermap by checking the magic number and // version. bool NeedsByteSwap; if (Header->Magic == HMAP_HeaderMagicNumber && Header->Version == HMAP_HeaderVersion) NeedsByteSwap = false; else if (Header->Magic == llvm::ByteSwap_32(HMAP_HeaderMagicNumber) && Header->Version == llvm::ByteSwap_16(HMAP_HeaderVersion)) NeedsByteSwap = true; // Mixed endianness headermap. else return nullptr; // Not a header map. if (Header->Reserved != 0) return nullptr; // Okay, everything looks good, create the header map. return new HeaderMap(std::move(*FileBuffer), NeedsByteSwap); } //===----------------------------------------------------------------------===// // Utility Methods //===----------------------------------------------------------------------===// /// getFileName - Return the filename of the headermap. const char *HeaderMap::getFileName() const { return FileBuffer->getBufferIdentifier(); } unsigned HeaderMap::getEndianAdjustedWord(unsigned X) const { if (!NeedsBSwap) return X; return llvm::ByteSwap_32(X); } /// getHeader - Return a reference to the file header, in unbyte-swapped form. /// This method cannot fail. const HMapHeader &HeaderMap::getHeader() const { // We know the file is at least as big as the header. Return it. return *reinterpret_cast<const HMapHeader*>(FileBuffer->getBufferStart()); } /// getBucket - Return the specified hash table bucket from the header map, /// bswap'ing its fields as appropriate. If the bucket number is not valid, /// this return a bucket with an empty key (0). HMapBucket HeaderMap::getBucket(unsigned BucketNo) const { HMapBucket Result; Result.Key = HMAP_EmptyBucketKey; const HMapBucket *BucketArray = reinterpret_cast<const HMapBucket*>(FileBuffer->getBufferStart() + sizeof(HMapHeader)); const HMapBucket *BucketPtr = BucketArray+BucketNo; if ((const char*)(BucketPtr+1) > FileBuffer->getBufferEnd()) { Result.Prefix = 0; Result.Suffix = 0; return Result; // Invalid buffer, corrupt hmap. } // Otherwise, the bucket is valid. Load the values, bswapping as needed. Result.Key = getEndianAdjustedWord(BucketPtr->Key); Result.Prefix = getEndianAdjustedWord(BucketPtr->Prefix); Result.Suffix = getEndianAdjustedWord(BucketPtr->Suffix); return Result; } /// getString - Look up the specified string in the string table. If the string /// index is not valid, it returns an empty string. const char *HeaderMap::getString(unsigned StrTabIdx) const { // Add the start of the string table to the idx. StrTabIdx += getEndianAdjustedWord(getHeader().StringsOffset); // Check for invalid index. if (StrTabIdx >= FileBuffer->getBufferSize()) return nullptr; // Otherwise, we have a valid pointer into the file. Just return it. We know // that the "string" can not overrun the end of the file, because the buffer // is nul terminated by virtue of being a MemoryBuffer. return FileBuffer->getBufferStart()+StrTabIdx; } //===----------------------------------------------------------------------===// // The Main Drivers //===----------------------------------------------------------------------===// /// dump - Print the contents of this headermap to stderr. void HeaderMap::dump() const { const HMapHeader &Hdr = getHeader(); unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets); fprintf(stderr, "Header Map %s:\n %d buckets, %d entries\n", getFileName(), NumBuckets, getEndianAdjustedWord(Hdr.NumEntries)); for (unsigned i = 0; i != NumBuckets; ++i) { HMapBucket B = getBucket(i); if (B.Key == HMAP_EmptyBucketKey) continue; const char *Key = getString(B.Key); const char *Prefix = getString(B.Prefix); const char *Suffix = getString(B.Suffix); fprintf(stderr, " %d. %s -> '%s' '%s'\n", i, Key, Prefix, Suffix); } } /// LookupFile - Check to see if the specified relative filename is located in /// this HeaderMap. If so, open it and return its FileEntry. const FileEntry *HeaderMap::LookupFile( StringRef Filename, FileManager &FM) const { SmallString<1024> Path; StringRef Dest = lookupFilename(Filename, Path); if (Dest.empty()) return nullptr; return FM.getFile(Dest); } StringRef HeaderMap::lookupFilename(StringRef Filename, SmallVectorImpl<char> &DestPath) const { const HMapHeader &Hdr = getHeader(); unsigned NumBuckets = getEndianAdjustedWord(Hdr.NumBuckets); // If the number of buckets is not a power of two, the headermap is corrupt. // Don't probe infinitely. if (NumBuckets & (NumBuckets-1)) return StringRef(); // Linearly probe the hash table. for (unsigned Bucket = HashHMapKey(Filename);; ++Bucket) { HMapBucket B = getBucket(Bucket & (NumBuckets-1)); if (B.Key == HMAP_EmptyBucketKey) return StringRef(); // Hash miss. // See if the key matches. If not, probe on. if (!Filename.equals_lower(getString(B.Key))) continue; // If so, we have a match in the hash table. Construct the destination // path. StringRef Prefix = getString(B.Prefix); StringRef Suffix = getString(B.Suffix); DestPath.clear(); DestPath.append(Prefix.begin(), Prefix.end()); DestPath.append(Suffix.begin(), Suffix.end()); return StringRef(DestPath.begin(), DestPath.size()); } }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/LiteralSupport.cpp
//===--- LiteralSupport.cpp - Code to parse and process literals ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the NumericLiteralParser, CharLiteralParser, and // StringLiteralParser interfaces. // //===----------------------------------------------------------------------===// #include "clang/Lex/LiteralSupport.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/ErrorHandling.h" using namespace clang; static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) { switch (kind) { default: llvm_unreachable("Unknown token type!"); case tok::char_constant: case tok::string_literal: case tok::utf8_char_constant: case tok::utf8_string_literal: return Target.getCharWidth(); case tok::wide_char_constant: case tok::wide_string_literal: return Target.getWCharWidth(); case tok::utf16_char_constant: case tok::utf16_string_literal: return Target.getChar16Width(); case tok::utf32_char_constant: case tok::utf32_string_literal: return Target.getChar32Width(); } } static CharSourceRange MakeCharSourceRange(const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd) { SourceLocation Begin = Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin, TokLoc.getManager(), Features); SourceLocation End = Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin, TokLoc.getManager(), Features); return CharSourceRange::getCharRange(Begin, End); } /// \brief Produce a diagnostic highlighting some portion of a literal. /// /// Emits the diagnostic \p DiagID, highlighting the range of characters from /// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be /// a substring of a spelling buffer for the token beginning at \p TokBegin. static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID) { SourceLocation Begin = Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin, TokLoc.getManager(), Features); return Diags->Report(Begin, DiagID) << MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd); } /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in /// either a character or a string literal. static unsigned ProcessCharEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, bool &HadError, FullSourceLoc Loc, unsigned CharWidth, DiagnosticsEngine *Diags, const LangOptions &Features) { const char *EscapeBegin = ThisTokBuf; // Skip the '\' char. ++ThisTokBuf; // We know that this character can't be off the end of the buffer, because // that would have been \", which would not have been the end of string. unsigned ResultChar = *ThisTokBuf++; switch (ResultChar) { // These map to themselves. case '\\': case '\'': case '"': case '?': break; // These have fixed mappings. case 'a': // TODO: K&R: the meaning of '\\a' is different in traditional C ResultChar = 7; break; case 'b': ResultChar = 8; break; case 'e': if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::ext_nonstandard_escape) << "e"; ResultChar = 27; break; case 'E': if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::ext_nonstandard_escape) << "E"; ResultChar = 27; break; case 'f': ResultChar = 12; break; case 'n': ResultChar = 10; break; case 'r': ResultChar = 13; break; case 't': ResultChar = 9; break; case 'v': ResultChar = 11; break; case 'x': { // Hex escape. ResultChar = 0; if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) { if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::err_hex_escape_no_digits) << "x"; HadError = 1; break; } // Hex escapes are a maximal series of hex digits. bool Overflow = false; for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) { int CharVal = llvm::hexDigitValue(ThisTokBuf[0]); if (CharVal == -1) break; // About to shift out a digit? if (ResultChar & 0xF0000000) Overflow = true; ResultChar <<= 4; ResultChar |= CharVal; } // See if any bits will be truncated when evaluated as a character. if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) { Overflow = true; ResultChar &= ~0U >> (32-CharWidth); } // Check for overflow. if (Overflow && Diags) // Too many digits to fit in Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::err_hex_escape_too_large); break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { // Octal escapes. --ThisTokBuf; ResultChar = 0; // Octal escapes are a series of octal digits with maximum length 3. // "\0123" is a two digit sequence equal to "\012" "3". unsigned NumDigits = 0; do { ResultChar <<= 3; ResultChar |= *ThisTokBuf++ - '0'; ++NumDigits; } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 && ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7'); // Check for overflow. Reject '\777', but not L'\777'. if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) { if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::err_octal_escape_too_large); ResultChar &= ~0U >> (32-CharWidth); } break; } // Otherwise, these are not valid escapes. case '(': case '{': case '[': case '%': // GCC accepts these as extensions. We warn about them as such though. if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::ext_nonstandard_escape) << std::string(1, ResultChar); break; default: if (!Diags) break; if (isPrintable(ResultChar)) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::ext_unknown_escape) << std::string(1, ResultChar); else Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::ext_unknown_escape) << "x" + llvm::utohexstr(ResultChar); break; } return ResultChar; } static void appendCodePoint(unsigned Codepoint, llvm::SmallVectorImpl<char> &Str) { char ResultBuf[4]; char *ResultPtr = ResultBuf; bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr); (void)Res; assert(Res && "Unexpected conversion failure"); Str.append(ResultBuf, ResultPtr); } void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) { for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) { if (*I != '\\') { Buf.push_back(*I); continue; } ++I; assert(*I == 'u' || *I == 'U'); unsigned NumHexDigits; if (*I == 'u') NumHexDigits = 4; else NumHexDigits = 8; assert(I + NumHexDigits <= E); uint32_t CodePoint = 0; for (++I; NumHexDigits != 0; ++I, --NumHexDigits) { unsigned Value = llvm::hexDigitValue(*I); assert(Value != -1U); CodePoint <<= 4; CodePoint += Value; } appendCodePoint(CodePoint, Buf); --I; } } /// ProcessUCNEscape - Read the Universal Character Name, check constraints and /// return the UTF32. static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, uint32_t &UcnVal, unsigned short &UcnLen, FullSourceLoc Loc, DiagnosticsEngine *Diags, const LangOptions &Features, bool in_char_string_literal = false) { const char *UcnBegin = ThisTokBuf; // Skip the '\u' char's. ThisTokBuf += 2; if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) { if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1); return false; } UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8); unsigned short UcnLenSave = UcnLen; for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) { int CharVal = llvm::hexDigitValue(ThisTokBuf[0]); if (CharVal == -1) break; UcnVal <<= 4; UcnVal |= CharVal; } // If we didn't consume the proper number of digits, there is a problem. if (UcnLenSave) { if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, diag::err_ucn_escape_incomplete); return false; } // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2] if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints UcnVal > 0x10FFFF) { // maximum legal UTF32 value if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, diag::err_ucn_escape_invalid); return false; } // C++11 allows UCNs that refer to control characters and basic source // characters inside character and string literals if (UcnVal < 0xa0 && (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, ` bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal); if (Diags) { char BasicSCSChar = UcnVal; if (UcnVal >= 0x20 && UcnVal < 0x7f) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, IsError ? diag::err_ucn_escape_basic_scs : diag::warn_cxx98_compat_literal_ucn_escape_basic_scs) << StringRef(&BasicSCSChar, 1); else Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, IsError ? diag::err_ucn_control_character : diag::warn_cxx98_compat_literal_ucn_control_character); } if (IsError) return false; } if (!Features.CPlusPlus && !Features.C99 && Diags) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, diag::warn_ucn_not_valid_in_c89_literal); return true; } /// MeasureUCNEscape - Determine the number of bytes within the resulting string /// which this UCN will occupy. static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, unsigned CharByteWidth, const LangOptions &Features, bool &HadError) { // UTF-32: 4 bytes per escape. if (CharByteWidth == 4) return 4; uint32_t UcnVal = 0; unsigned short UcnLen = 0; FullSourceLoc Loc; if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen, Loc, nullptr, Features, true)) { HadError = true; return 0; } // UTF-16: 2 bytes for BMP, 4 bytes otherwise. if (CharByteWidth == 2) return UcnVal <= 0xFFFF ? 2 : 4; // UTF-8. if (UcnVal < 0x80) return 1; if (UcnVal < 0x800) return 2; if (UcnVal < 0x10000) return 3; return 4; } /// EncodeUCNEscape - Read the Universal Character Name, check constraints and /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of /// StringLiteralParser. When we decide to implement UCN's for identifiers, /// we will likely rework our support for UCN's. static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, char *&ResultBuf, bool &HadError, FullSourceLoc Loc, unsigned CharByteWidth, DiagnosticsEngine *Diags, const LangOptions &Features) { typedef uint32_t UTF32; UTF32 UcnVal = 0; unsigned short UcnLen = 0; if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen, Loc, Diags, Features, true)) { HadError = true; return; } assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) && "only character widths of 1, 2, or 4 bytes supported"); (void)UcnLen; assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported"); if (CharByteWidth == 4) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. UTF32 *ResultPtr = reinterpret_cast<UTF32*>(ResultBuf); *ResultPtr = UcnVal; ResultBuf += 4; return; } if (CharByteWidth == 2) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. UTF16 *ResultPtr = reinterpret_cast<UTF16*>(ResultBuf); if (UcnVal <= (UTF32)0xFFFF) { *ResultPtr = UcnVal; ResultBuf += 2; return; } // Convert to UTF16. UcnVal -= 0x10000; *ResultPtr = 0xD800 + (UcnVal >> 10); *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF); ResultBuf += 4; return; } assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters"); // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8. // The conversion below was inspired by: // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c // First, we determine how many bytes the result will require. typedef uint8_t UTF8; unsigned short bytesToWrite = 0; if (UcnVal < (UTF32)0x80) bytesToWrite = 1; else if (UcnVal < (UTF32)0x800) bytesToWrite = 2; else if (UcnVal < (UTF32)0x10000) bytesToWrite = 3; else bytesToWrite = 4; const unsigned byteMask = 0xBF; const unsigned byteMark = 0x80; // Once the bits are split out into bytes of UTF8, this is a mask OR-ed // into the first byte, depending on how many bytes follow. static const UTF8 firstByteMark[5] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0 }; // Finally, we write the bytes into ResultBuf. ResultBuf += bytesToWrite; switch (bytesToWrite) { // note: everything falls through. case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; LLVM_FALLTHROUGH; // HLSL Change case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; LLVM_FALLTHROUGH; // HLSL Change case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; LLVM_FALLTHROUGH; // HLSL Change case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]); } // Update the buffer. ResultBuf += bytesToWrite; } /// integer-constant: [C99 6.4.4.1] /// decimal-constant integer-suffix /// octal-constant integer-suffix /// hexadecimal-constant integer-suffix /// binary-literal integer-suffix [GNU, C++1y] /// user-defined-integer-literal: [C++11 lex.ext] /// decimal-literal ud-suffix /// octal-literal ud-suffix /// hexadecimal-literal ud-suffix /// binary-literal ud-suffix [GNU, C++1y] /// decimal-constant: /// nonzero-digit /// decimal-constant digit /// octal-constant: /// 0 /// octal-constant octal-digit /// hexadecimal-constant: /// hexadecimal-prefix hexadecimal-digit /// hexadecimal-constant hexadecimal-digit /// hexadecimal-prefix: one of /// 0x 0X /// binary-literal: /// 0b binary-digit /// 0B binary-digit /// binary-literal binary-digit /// integer-suffix: /// unsigned-suffix [long-suffix] /// unsigned-suffix [long-long-suffix] /// long-suffix [unsigned-suffix] /// long-long-suffix [unsigned-sufix] /// nonzero-digit: /// 1 2 3 4 5 6 7 8 9 /// octal-digit: /// 0 1 2 3 4 5 6 7 /// hexadecimal-digit: /// 0 1 2 3 4 5 6 7 8 9 /// a b c d e f /// A B C D E F /// binary-digit: /// 0 /// 1 /// unsigned-suffix: one of /// u U /// long-suffix: one of /// l L /// long-long-suffix: one of /// ll LL /// /// floating-constant: [C99 6.4.4.2] /// TODO: add rules... /// NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling, SourceLocation TokLoc, Preprocessor &PP) : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) { // This routine assumes that the range begin/end matches the regex for integer // and FP constants (specifically, the 'pp-number' regex), and assumes that // the byte at "*end" is both valid and not part of the regex. Because of // this, it doesn't have to check for 'overscan' in various places. assert((!isPreprocessingNumberBody(*ThisTokEnd) || *ThisTokEnd == '.' || *ThisTokEnd == '#') && "didn't maximally munch?"); // HLSL Change - '.' might be a second '.' for a '1.2.x' literal s = DigitsBegin = ThisTokBegin; saw_inf = false; saw_exponent = false; saw_period = false; saw_ud_suffix = false; isLong = false; isUnsigned = false; isLongLong = false; isFloat = false; isHalf = false; // HLSL Change isImaginary = false; MicrosoftInteger = 0; hadError = false; if (*s == '0') { // parse radix ParseNumberStartingWithZero(TokLoc); if (hadError) return; } else { // the first digit is non-zero radix = 10; s = SkipDigits(s); if (s == ThisTokEnd) { // Done. } else if (isHexDigit(*s) && !(*s == 'e' || *s == 'E')) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin), diag::err_invalid_decimal_digit) << StringRef(s, 1); hadError = true; return; } else if (*s == '.') { checkSeparator(TokLoc, s, CSK_AfterDigits); s++; saw_period = true; checkSeparator(TokLoc, s, CSK_BeforeDigits); s = SkipDigits(s); } if ((*s == 'e' || *s == 'E')) { // exponent checkSeparator(TokLoc, s, CSK_AfterDigits); const char *Exponent = s; s++; saw_exponent = true; if (*s == '+' || *s == '-') s++; // sign checkSeparator(TokLoc, s, CSK_BeforeDigits); const char *first_non_digit = SkipDigits(s); if (first_non_digit != s) { s = first_non_digit; } else { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent - ThisTokBegin), diag::err_exponent_has_no_digits); hadError = true; return; } } // HLSL Change Starts else if (*s == '#') { const char *InfBegin = s; if (s[1] == 'I' && s[2] == 'N' && s[3] == 'F') { saw_inf = true; if (!saw_period) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, InfBegin - ThisTokBegin), diag::err_invalid_suffix_integer_constant) << StringRef(InfBegin, ThisTokEnd - InfBegin); hadError = true; return; } s += 4; } } // HLSL Change Ends } SuffixBegin = s; checkSeparator(TokLoc, s, CSK_AfterDigits); // Parse the suffix. At this point we can classify whether we have an FP or // integer constant. bool isFPConstant = isFloatingLiteral(); const char *ImaginarySuffixLoc = nullptr; // Loop over all of the characters of the suffix. If we see something bad, // we break out of the loop. for (; s != ThisTokEnd; ++s) { switch (*s) { case 'f': // FP Suffix for "float" case 'F': if (!isFPConstant) break; // Error for integer constant. if (isFloat || isLong) break; // FF, LF invalid. isFloat = true; continue; // Success. // HLSL Change Starts // TODO : When we support true half type, these suffixes should be treated differently from f/F case 'h': case 'H': if (!isFPConstant) break; if (isHalf) break; isHalf = true; continue; // HLSL Change Ends case 'u': case 'U': if (isFPConstant) break; // Error for floating constant. if (isUnsigned) break; // Cannot be repeated. isUnsigned = true; continue; // Success. case 'l': case 'L': if (isLong || isLongLong) break; // Cannot be repeated. if (isFloat) break; // LF invalid. // Check for long long. The L's need to be adjacent and the same case. if (s[1] == s[0]) { assert(s + 1 < ThisTokEnd && "didn't maximally munch?"); if (isFPConstant) break; // long long invalid for floats. isLongLong = true; ++s; // Eat both of them. } else { isLong = true; } continue; // Success. case 'i': case 'I': if (PP.getLangOpts().MicrosoftExt) { if (isLong || isLongLong || MicrosoftInteger) break; if (!isFPConstant) { // Allow i8, i16, i32, i64, and i128. switch (s[1]) { case '8': s += 2; // i8 suffix MicrosoftInteger = 8; break; case '1': if (s[2] == '6') { s += 3; // i16 suffix MicrosoftInteger = 16; } else if (s[2] == '2' && s[3] == '8') { s += 4; // i128 suffix MicrosoftInteger = 128; } break; case '3': if (s[2] == '2') { s += 3; // i32 suffix MicrosoftInteger = 32; } break; case '6': if (s[2] == '4') { s += 3; // i64 suffix MicrosoftInteger = 64; } break; default: break; } } if (MicrosoftInteger) { assert(s <= ThisTokEnd && "didn't maximally munch?"); break; } } // "i", "if", and "il" are user-defined suffixes in C++1y. if (*s == 'i' && PP.getLangOpts().CPlusPlus14) break; LLVM_FALLTHROUGH; // HLSL Change case 'j': case 'J': if (isImaginary) break; // Cannot be repeated. isImaginary = true; ImaginarySuffixLoc = s; // HLSL Change Starts. if (PP.getLangOpts().HLSL) { // Don't advance; this leaves us with an invalid suffix. // Great if imaginary literals are implemented at some point, in // the meantime catches '.#INFI' as an error rather than a suffix // on an INF literal. break; } // HLSL Change Ends. continue; // Success. } // If we reached here, there was an error or a ud-suffix. break; } if (s != ThisTokEnd) { // FIXME: Don't bother expanding UCNs if !tok.hasUCN(). expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin)); if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) { // Any suffix pieces we might have parsed are actually part of the // ud-suffix. isLong = false; isUnsigned = false; isLongLong = false; isFloat = false; isImaginary = false; MicrosoftInteger = 0; saw_ud_suffix = true; return; } // Report an error if there are any. PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin), isFPConstant ? diag::err_invalid_suffix_float_constant : diag::err_invalid_suffix_integer_constant) << StringRef(SuffixBegin, ThisTokEnd-SuffixBegin); hadError = true; return; } if (isImaginary) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, ImaginarySuffixLoc - ThisTokBegin), diag::ext_imaginary_constant); } } /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved /// suffixes as ud-suffixes, because the diagnostic experience is better if we /// treat it as an invalid suffix. bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix) { if (!LangOpts.CPlusPlus11 || Suffix.empty()) return false; // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid. if (Suffix[0] == '_') return true; // In C++11, there are no library suffixes. if (!LangOpts.CPlusPlus14) return false; // In C++1y, "s", "h", "min", "ms", "us", and "ns" are used in the library. // Per tweaked N3660, "il", "i", and "if" are also used in the library. return llvm::StringSwitch<bool>(Suffix) .Cases("h", "min", "s", true) .Cases("ms", "us", "ns", true) .Cases("il", "i", "if", true) .Default(false); } void NumericLiteralParser::checkSeparator(SourceLocation TokLoc, const char *Pos, CheckSeparatorKind IsAfterDigits) { if (IsAfterDigits == CSK_AfterDigits) { if (Pos == ThisTokBegin) return; --Pos; } else if (Pos == ThisTokEnd) return; if (isDigitSeparator(*Pos)) PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin), diag::err_digit_separator_not_between_digits) << IsAfterDigits; } /// ParseNumberStartingWithZero - This method is called when the first character /// of the number is found to be a zero. This means it is either an octal /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or /// a floating point number (01239.123e4). Eat the prefix, determining the /// radix etc. void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { assert(s[0] == '0' && "Invalid method call"); s++; int c1 = s[0]; // Handle a hex number like 0x1234. if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) { s++; assert(s < ThisTokEnd && "didn't maximally munch?"); radix = 16; DigitsBegin = s; s = SkipHexDigits(s); bool noSignificand = (s == DigitsBegin); if (s == ThisTokEnd) { // Done. } else if (*s == '.') { s++; saw_period = true; const char *floatDigitsBegin = s; checkSeparator(TokLoc, s, CSK_BeforeDigits); s = SkipHexDigits(s); noSignificand &= (floatDigitsBegin == s); } if (noSignificand) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin), diag::err_hexconstant_requires_digits); hadError = true; return; } // A binary exponent can appear with or with a '.'. If dotted, the // binary exponent is required. if (*s == 'p' || *s == 'P') { checkSeparator(TokLoc, s, CSK_AfterDigits); const char *Exponent = s; s++; saw_exponent = true; if (*s == '+' || *s == '-') s++; // sign const char *first_non_digit = SkipDigits(s); if (first_non_digit == s) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), diag::err_exponent_has_no_digits); hadError = true; return; } checkSeparator(TokLoc, s, CSK_BeforeDigits); s = first_non_digit; if (!PP.getLangOpts().HexFloats) PP.Diag(TokLoc, diag::ext_hexconstant_invalid); } else if (saw_period) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), diag::err_hexconstant_requires_exponent); hadError = true; } return; } // Handle simple binary numbers 0b01010 if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) { // 0b101010 is a C++1y / GCC extension. PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus14 ? diag::warn_cxx11_compat_binary_literal : PP.getLangOpts().CPlusPlus ? diag::ext_binary_literal_cxx14 : diag::ext_binary_literal); ++s; assert(s < ThisTokEnd && "didn't maximally munch?"); radix = 2; DigitsBegin = s; s = SkipBinaryDigits(s); if (s == ThisTokEnd) { // Done. } else if (isHexDigit(*s)) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), diag::err_invalid_binary_digit) << StringRef(s, 1); hadError = true; } // Other suffixes will be diagnosed by the caller. return; } // For now, the radix is set to 8. If we discover that we have a // floating point constant, the radix will change to 10. Octal floating // point constants are not permitted (only decimal and hexadecimal). radix = 8; DigitsBegin = s; s = SkipOctalDigits(s); if (s == ThisTokEnd) return; // Done, simple octal number like 01234 // If we have some other non-octal digit that *is* a decimal digit, see if // this is part of a floating point number like 094.123 or 09e1. if (isDigit(*s)) { const char *EndDecimal = SkipDigits(s); if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') { s = EndDecimal; radix = 10; } } // If we have a hex digit other than 'e' (which denotes a FP exponent) then // the code is using an incorrect base. if (isHexDigit(*s) && *s != 'e' && *s != 'E') { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), diag::err_invalid_octal_digit) << StringRef(s, 1); hadError = true; return; } if (*s == '.') { s++; radix = 10; saw_period = true; checkSeparator(TokLoc, s, CSK_BeforeDigits); s = SkipDigits(s); // Skip suffix. } if (*s == 'e' || *s == 'E') { // exponent checkSeparator(TokLoc, s, CSK_AfterDigits); const char *Exponent = s; s++; radix = 10; saw_exponent = true; if (*s == '+' || *s == '-') s++; // sign const char *first_non_digit = SkipDigits(s); if (first_non_digit != s) { checkSeparator(TokLoc, s, CSK_BeforeDigits); s = first_non_digit; } else { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), diag::err_exponent_has_no_digits); hadError = true; return; } } } static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) { switch (Radix) { case 2: return NumDigits <= 64; case 8: return NumDigits <= 64 / 3; // Digits are groups of 3 bits. case 10: return NumDigits <= 19; // floor(log10(2^64)) case 16: return NumDigits <= 64 / 4; // Digits are groups of 4 bits. default: llvm_unreachable("impossible Radix"); } } /// GetIntegerValue - Convert this numeric literal value to an APInt that /// matches Val's input width. If there is an overflow, set Val to the low bits /// of the result and return true. Otherwise, return false. bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) { // Fast path: Compute a conservative bound on the maximum number of // bits per digit in this radix. If we can't possibly overflow a // uint64 based on that bound then do the simple conversion to // integer. This avoids the expensive overflow checking below, and // handles the common cases that matter (small decimal integers and // hex/octal values which don't overflow). const unsigned NumDigits = SuffixBegin - DigitsBegin; if (alwaysFitsInto64Bits(radix, NumDigits)) { uint64_t N = 0; for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr) if (!isDigitSeparator(*Ptr)) N = N * radix + llvm::hexDigitValue(*Ptr); // This will truncate the value to Val's input width. Simply check // for overflow by comparing. Val = N; return Val.getZExtValue() != N; } Val = 0; const char *Ptr = DigitsBegin; llvm::APInt RadixVal(Val.getBitWidth(), radix); llvm::APInt CharVal(Val.getBitWidth(), 0); llvm::APInt OldVal = Val; bool OverflowOccurred = false; while (Ptr < SuffixBegin) { if (isDigitSeparator(*Ptr)) { ++Ptr; continue; } unsigned C = llvm::hexDigitValue(*Ptr++); // If this letter is out of bound for this radix, reject it. assert(C < radix && "NumericLiteralParser ctor should have rejected this"); CharVal = C; // Add the digit to the value in the appropriate radix. If adding in digits // made the value smaller, then this overflowed. OldVal = Val; // Multiply by radix, did overflow occur on the multiply? Val *= RadixVal; OverflowOccurred |= Val.udiv(RadixVal) != OldVal; // Add value, did overflow occur on the value? // (a + b) ult b <=> overflow Val += CharVal; OverflowOccurred |= Val.ult(CharVal); } return OverflowOccurred; } llvm::APFloat::opStatus NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) { using llvm::APFloat; unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin); llvm::SmallString<16> Buffer; StringRef Str(ThisTokBegin, n); if (Str.find('\'') != StringRef::npos) { Buffer.reserve(n); std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer), &isDigitSeparator); Str = Buffer; } return Result.convertFromString(Str, APFloat::rmNearestTiesToEven); } /// \verbatim /// user-defined-character-literal: [C++11 lex.ext] /// character-literal ud-suffix /// ud-suffix: /// identifier /// character-literal: [C++11 lex.ccon] /// ' c-char-sequence ' /// u' c-char-sequence ' /// U' c-char-sequence ' /// L' c-char-sequence ' /// c-char-sequence: /// c-char /// c-char-sequence c-char /// c-char: /// any member of the source character set except the single-quote ', /// backslash \, or new-line character /// escape-sequence /// universal-character-name /// escape-sequence: /// simple-escape-sequence /// octal-escape-sequence /// hexadecimal-escape-sequence /// simple-escape-sequence: /// one of \' \" \? \\ \a \b \f \n \r \t \v /// octal-escape-sequence: /// \ octal-digit /// \ octal-digit octal-digit /// \ octal-digit octal-digit octal-digit /// hexadecimal-escape-sequence: /// \x hexadecimal-digit /// hexadecimal-escape-sequence hexadecimal-digit /// universal-character-name: [C++11 lex.charset] /// \u hex-quad /// \U hex-quad hex-quad /// hex-quad: /// hex-digit hex-digit hex-digit hex-digit /// \endverbatim /// CharLiteralParser::CharLiteralParser(const char *begin, const char *end, SourceLocation Loc, Preprocessor &PP, tok::TokenKind kind) { // At this point we know that the character matches the regex "(L|u|U)?'.*'". HadError = false; Kind = kind; const char *TokBegin = begin; // Skip over wide character determinant. if (Kind != tok::char_constant) ++begin; if (Kind == tok::utf8_char_constant) ++begin; // Skip over the entry quote. assert(begin[0] == '\'' && "Invalid token lexed"); ++begin; // Remove an optional ud-suffix. if (end[-1] != '\'') { const char *UDSuffixEnd = end; do { --end; } while (end[-1] != '\''); // FIXME: Don't bother with this if !tok.hasUCN(). expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end)); UDSuffixOffset = end - TokBegin; } // Trim the ending quote. assert(end != begin && "Invalid token lexed"); --end; // FIXME: The "Value" is an uint64_t so we can handle char literals of // up to 64-bits. // FIXME: This extensively assumes that 'char' is 8-bits. assert(PP.getTargetInfo().getCharWidth() == 8 && "Assumes char is 8 bits"); assert(PP.getTargetInfo().getIntWidth() <= 64 && (PP.getTargetInfo().getIntWidth() & 7) == 0 && "Assumes sizeof(int) on target is <= 64 and a multiple of char"); assert(PP.getTargetInfo().getWCharWidth() <= 64 && "Assumes sizeof(wchar) on target is <= 64"); SmallVector<uint32_t, 4> codepoint_buffer; codepoint_buffer.resize(end - begin); uint32_t *buffer_begin = &codepoint_buffer.front(); uint32_t *buffer_end = buffer_begin + codepoint_buffer.size(); // Unicode escapes representing characters that cannot be correctly // represented in a single code unit are disallowed in character literals // by this implementation. uint32_t largest_character_for_kind; if (tok::wide_char_constant == Kind) { largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth()); } else if (tok::utf8_char_constant == Kind) { largest_character_for_kind = 0x7F; } else if (tok::utf16_char_constant == Kind) { largest_character_for_kind = 0xFFFF; } else if (tok::utf32_char_constant == Kind) { largest_character_for_kind = 0x10FFFF; } else { largest_character_for_kind = 0x7Fu; } while (begin != end) { // Is this a span of non-escape characters? if (begin[0] != '\\') { char const *start = begin; do { ++begin; } while (begin != end && *begin != '\\'); char const *tmp_in_start = start; uint32_t *tmp_out_start = buffer_begin; ConversionResult res = ConvertUTF8toUTF32(reinterpret_cast<UTF8 const **>(&start), reinterpret_cast<UTF8 const *>(begin), &buffer_begin, buffer_end, strictConversion); if (res != conversionOK) { // If we see bad encoding for unprefixed character literals, warn and // simply copy the byte values, for compatibility with gcc and // older versions of clang. bool NoErrorOnBadEncoding = isAscii(); unsigned Msg = diag::err_bad_character_encoding; if (NoErrorOnBadEncoding) Msg = diag::warn_bad_character_encoding; PP.Diag(Loc, Msg); if (NoErrorOnBadEncoding) { start = tmp_in_start; buffer_begin = tmp_out_start; for (; start != begin; ++start, ++buffer_begin) *buffer_begin = static_cast<uint8_t>(*start); } else { HadError = true; } } else { for (; tmp_out_start < buffer_begin; ++tmp_out_start) { if (*tmp_out_start > largest_character_for_kind) { HadError = true; PP.Diag(Loc, diag::err_character_too_large); } } } continue; } // Is this a Universal Character Name escape? if (begin[1] == 'u' || begin[1] == 'U') { unsigned short UcnLen = 0; if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen, FullSourceLoc(Loc, PP.getSourceManager()), &PP.getDiagnostics(), PP.getLangOpts(), true)) { HadError = true; } else if (*buffer_begin > largest_character_for_kind) { HadError = true; PP.Diag(Loc, diag::err_character_too_large); } ++buffer_begin; continue; } unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo()); uint64_t result = ProcessCharEscape(TokBegin, begin, end, HadError, FullSourceLoc(Loc,PP.getSourceManager()), CharWidth, &PP.getDiagnostics(), PP.getLangOpts()); *buffer_begin++ = result; } unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front(); if (NumCharsSoFar > 1) { if (isWide()) PP.Diag(Loc, diag::warn_extraneous_char_constant); else if (isAscii() && NumCharsSoFar == 4) PP.Diag(Loc, diag::ext_four_char_character_literal); else if (isAscii()) PP.Diag(Loc, diag::ext_multichar_character_literal); else PP.Diag(Loc, diag::err_multichar_utf_character_literal); IsMultiChar = true; } else { IsMultiChar = false; } llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0); // Narrow character literals act as though their value is concatenated // in this implementation, but warn on overflow. bool multi_char_too_long = false; if (isAscii() && isMultiChar()) { LitVal = 0; for (size_t i = 0; i < NumCharsSoFar; ++i) { // check for enough leading zeros to shift into multi_char_too_long |= (LitVal.countLeadingZeros() < 8); LitVal <<= 8; LitVal = LitVal + (codepoint_buffer[i] & 0xFF); } } else if (NumCharsSoFar > 0) { // otherwise just take the last character LitVal = buffer_begin[-1]; } if (!HadError && multi_char_too_long) { PP.Diag(Loc, diag::warn_char_constant_too_large); } // Transfer the value from APInt to uint64_t Value = LitVal.getZExtValue(); // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1") // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple // character constants are not sign extended in the this implementation: // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC. if (isAscii() && NumCharsSoFar == 1 && (Value & 128) && PP.getLangOpts().CharIsSigned) Value = (signed char)Value; } /// \verbatim /// string-literal: [C++0x lex.string] /// encoding-prefix " [s-char-sequence] " /// encoding-prefix R raw-string /// encoding-prefix: /// u8 /// u /// U /// L /// s-char-sequence: /// s-char /// s-char-sequence s-char /// s-char: /// any member of the source character set except the double-quote ", /// backslash \, or new-line character /// escape-sequence /// universal-character-name /// raw-string: /// " d-char-sequence ( r-char-sequence ) d-char-sequence " /// r-char-sequence: /// r-char /// r-char-sequence r-char /// r-char: /// any member of the source character set, except a right parenthesis ) /// followed by the initial d-char-sequence (which may be empty) /// followed by a double quote ". /// d-char-sequence: /// d-char /// d-char-sequence d-char /// d-char: /// any member of the basic source character set except: /// space, the left parenthesis (, the right parenthesis ), /// the backslash \, and the control characters representing horizontal /// tab, vertical tab, form feed, and newline. /// escape-sequence: [C++0x lex.ccon] /// simple-escape-sequence /// octal-escape-sequence /// hexadecimal-escape-sequence /// simple-escape-sequence: /// one of \' \" \? \\ \a \b \f \n \r \t \v /// octal-escape-sequence: /// \ octal-digit /// \ octal-digit octal-digit /// \ octal-digit octal-digit octal-digit /// hexadecimal-escape-sequence: /// \x hexadecimal-digit /// hexadecimal-escape-sequence hexadecimal-digit /// universal-character-name: /// \u hex-quad /// \U hex-quad hex-quad /// hex-quad: /// hex-digit hex-digit hex-digit hex-digit /// \endverbatim /// StringLiteralParser:: StringLiteralParser(ArrayRef<Token> StringToks, Preprocessor &PP, bool Complain) : SM(PP.getSourceManager()), Features(PP.getLangOpts()), Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr), MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown), ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) { init(StringToks); } void StringLiteralParser::init(ArrayRef<Token> StringToks){ // The literal token may have come from an invalid source location (e.g. due // to a PCH error), in which case the token length will be 0. if (StringToks.empty() || StringToks[0].getLength() < 2) return DiagnoseLexingError(SourceLocation()); // Scan all of the string portions, remember the max individual token length, // computing a bound on the concatenated string length, and see whether any // piece is a wide-string. If any of the string portions is a wide-string // literal, the result is a wide-string literal [C99 6.4.5p4]. assert(!StringToks.empty() && "expected at least one token"); MaxTokenLength = StringToks[0].getLength(); assert(StringToks[0].getLength() >= 2 && "literal token is invalid!"); SizeBound = StringToks[0].getLength()-2; // -2 for "". Kind = StringToks[0].getKind(); hadError = false; // Implement Translation Phase #6: concatenation of string literals /// (C99 5.1.1.2p1). The common case is only one string fragment. for (unsigned i = 1; i != StringToks.size(); ++i) { if (StringToks[i].getLength() < 2) return DiagnoseLexingError(StringToks[i].getLocation()); // The string could be shorter than this if it needs cleaning, but this is a // reasonable bound, which is all we need. assert(StringToks[i].getLength() >= 2 && "literal token is invalid!"); SizeBound += StringToks[i].getLength()-2; // -2 for "". // Remember maximum string piece length. if (StringToks[i].getLength() > MaxTokenLength) MaxTokenLength = StringToks[i].getLength(); // Remember if we see any wide or utf-8/16/32 strings. // Also check for illegal concatenations. if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) { if (isAscii()) { Kind = StringToks[i].getKind(); } else { if (Diags) Diags->Report(StringToks[i].getLocation(), diag::err_unsupported_string_concat); hadError = true; } } } // Include space for the null terminator. ++SizeBound; // TODO: K&R warning: "traditional C rejects string constant concatenation" // Get the width in bytes of char/wchar_t/char16_t/char32_t CharByteWidth = getCharWidth(Kind, Target); assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple"); CharByteWidth /= 8; // The output buffer size needs to be large enough to hold wide characters. // This is a worst-case assumption which basically corresponds to L"" "long". SizeBound *= CharByteWidth; // Size the temporary buffer to hold the result string data. ResultBuf.resize(SizeBound); // Likewise, but for each string piece. SmallString<512> TokenBuf; TokenBuf.resize(MaxTokenLength); // Loop over all the strings, getting their spelling, and expanding them to // wide strings as appropriate. ResultPtr = &ResultBuf[0]; // Next byte to fill in. Pascal = false; SourceLocation UDSuffixTokLoc; for (unsigned i = 0, e = StringToks.size(); i != e; ++i) { const char *ThisTokBuf = &TokenBuf[0]; // Get the spelling of the token, which eliminates trigraphs, etc. We know // that ThisTokBuf points to a buffer that is big enough for the whole token // and 'spelled' tokens can only shrink. bool StringInvalid = false; unsigned ThisTokLen = Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features, &StringInvalid); if (StringInvalid) return DiagnoseLexingError(StringToks[i].getLocation()); const char *ThisTokBegin = ThisTokBuf; const char *ThisTokEnd = ThisTokBuf+ThisTokLen; // Remove an optional ud-suffix. if (ThisTokEnd[-1] != '"') { const char *UDSuffixEnd = ThisTokEnd; do { --ThisTokEnd; } while (ThisTokEnd[-1] != '"'); StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd); if (UDSuffixBuf.empty()) { if (StringToks[i].hasUCN()) expandUCNs(UDSuffixBuf, UDSuffix); else UDSuffixBuf.assign(UDSuffix); UDSuffixToken = i; UDSuffixOffset = ThisTokEnd - ThisTokBuf; UDSuffixTokLoc = StringToks[i].getLocation(); } else { SmallString<32> ExpandedUDSuffix; if (StringToks[i].hasUCN()) { expandUCNs(ExpandedUDSuffix, UDSuffix); UDSuffix = ExpandedUDSuffix; } // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the // result of a concatenation involving at least one user-defined-string- // literal, all the participating user-defined-string-literals shall // have the same ud-suffix. if (UDSuffixBuf != UDSuffix) { if (Diags) { SourceLocation TokLoc = StringToks[i].getLocation(); Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix) << UDSuffixBuf << UDSuffix << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc) << SourceRange(TokLoc, TokLoc); } hadError = true; } } } // Strip the end quote. --ThisTokEnd; // TODO: Input character set mapping support. // Skip marker for wide or unicode strings. if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') { ++ThisTokBuf; // Skip 8 of u8 marker for utf8 strings. if (ThisTokBuf[0] == '8') ++ThisTokBuf; } // Check for raw string if (ThisTokBuf[0] == 'R') { ThisTokBuf += 2; // skip R" const char *Prefix = ThisTokBuf; while (ThisTokBuf[0] != '(') ++ThisTokBuf; ++ThisTokBuf; // skip '(' // Remove same number of characters from the end ThisTokEnd -= ThisTokBuf - Prefix; assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal"); // Copy the string over if (CopyStringFragment(StringToks[i], ThisTokBegin, StringRef(ThisTokBuf, ThisTokEnd - ThisTokBuf))) hadError = true; } else { if (ThisTokBuf[0] != '"') { // The file may have come from PCH and then changed after loading the // PCH; Fail gracefully. return DiagnoseLexingError(StringToks[i].getLocation()); } ++ThisTokBuf; // skip " // Check if this is a pascal string if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd && ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') { // If the \p sequence is found in the first token, we have a pascal string // Otherwise, if we already have a pascal string, ignore the first \p if (i == 0) { ++ThisTokBuf; Pascal = true; } else if (Pascal) ThisTokBuf += 2; } while (ThisTokBuf != ThisTokEnd) { // Is this a span of non-escape characters? if (ThisTokBuf[0] != '\\') { const char *InStart = ThisTokBuf; do { ++ThisTokBuf; } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\'); // Copy the character span over. if (CopyStringFragment(StringToks[i], ThisTokBegin, StringRef(InStart, ThisTokBuf - InStart))) hadError = true; continue; } // Is this a Universal Character Name escape? if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') { EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, ResultPtr, hadError, FullSourceLoc(StringToks[i].getLocation(), SM), CharByteWidth, Diags, Features); continue; } // Otherwise, this is a non-UCN escape character. Process it. unsigned ResultChar = ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError, FullSourceLoc(StringToks[i].getLocation(), SM), CharByteWidth*8, Diags, Features); if (CharByteWidth == 4) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultPtr); *ResultWidePtr = ResultChar; ResultPtr += 4; } else if (CharByteWidth == 2) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultPtr); *ResultWidePtr = ResultChar & 0xFFFF; ResultPtr += 2; } else { assert(CharByteWidth == 1 && "Unexpected char width"); *ResultPtr++ = ResultChar & 0xFF; } } } } if (Pascal) { if (CharByteWidth == 4) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. UTF32 *ResultWidePtr = reinterpret_cast<UTF32*>(ResultBuf.data()); ResultWidePtr[0] = GetNumStringChars() - 1; } else if (CharByteWidth == 2) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. UTF16 *ResultWidePtr = reinterpret_cast<UTF16*>(ResultBuf.data()); ResultWidePtr[0] = GetNumStringChars() - 1; } else { assert(CharByteWidth == 1 && "Unexpected char width"); ResultBuf[0] = GetNumStringChars() - 1; } // Verify that pascal strings aren't too large. if (GetStringLength() > 256) { if (Diags) Diags->Report(StringToks.front().getLocation(), diag::err_pascal_string_too_long) << SourceRange(StringToks.front().getLocation(), StringToks.back().getLocation()); hadError = true; return; } } else if (Diags) { // Complain if this string literal has too many characters. unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509; if (GetNumStringChars() > MaxChars) Diags->Report(StringToks.front().getLocation(), diag::ext_string_too_long) << GetNumStringChars() << MaxChars << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0) << SourceRange(StringToks.front().getLocation(), StringToks.back().getLocation()); } } static const char *resyncUTF8(const char *Err, const char *End) { if (Err == End) return End; End = Err + std::min<unsigned>(getNumBytesForUTF8(*Err), End-Err); while (++Err != End && (*Err & 0xC0) == 0x80) ; return Err; } /// \brief This function copies from Fragment, which is a sequence of bytes /// within Tok's contents (which begin at TokBegin) into ResultPtr. /// Performs widening for multi-byte characters. bool StringLiteralParser::CopyStringFragment(const Token &Tok, const char *TokBegin, StringRef Fragment) { const UTF8 *ErrorPtrTmp; if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp)) return false; // If we see bad encoding for unprefixed string literals, warn and // simply copy the byte values, for compatibility with gcc and older // versions of clang. bool NoErrorOnBadEncoding = isAscii(); if (NoErrorOnBadEncoding) { memcpy(ResultPtr, Fragment.data(), Fragment.size()); ResultPtr += Fragment.size(); } if (Diags) { const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp); FullSourceLoc SourceLoc(Tok.getLocation(), SM); const DiagnosticBuilder &Builder = Diag(Diags, Features, SourceLoc, TokBegin, ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()), NoErrorOnBadEncoding ? diag::warn_bad_string_encoding : diag::err_bad_string_encoding); const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end()); StringRef NextFragment(NextStart, Fragment.end()-NextStart); // Decode into a dummy buffer. SmallString<512> Dummy; Dummy.reserve(Fragment.size() * CharByteWidth); char *Ptr = Dummy.data(); while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) { const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp); NextStart = resyncUTF8(ErrorPtr, Fragment.end()); Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin, ErrorPtr, NextStart); NextFragment = StringRef(NextStart, Fragment.end()-NextStart); } } return !NoErrorOnBadEncoding; } void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) { hadError = true; if (Diags) Diags->Report(Loc, diag::err_lexing_string); } /// getOffsetOfStringByte - This function returns the offset of the /// specified byte of the string data represented by Token. This handles /// advancing over escape sequences in the string. unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok, unsigned ByteNo) const { // Get the spelling of the token. SmallString<32> SpellingBuffer; SpellingBuffer.resize(Tok.getLength()); bool StringInvalid = false; const char *SpellingPtr = &SpellingBuffer[0]; unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features, &StringInvalid); if (StringInvalid) return 0; const char *SpellingStart = SpellingPtr; const char *SpellingEnd = SpellingPtr+TokLen; // Handle UTF-8 strings just like narrow strings. if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8') SpellingPtr += 2; assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' && SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet"); // For raw string literals, this is easy. if (SpellingPtr[0] == 'R') { assert(SpellingPtr[1] == '"' && "Should be a raw string literal!"); // Skip 'R"'. SpellingPtr += 2; while (*SpellingPtr != '(') { ++SpellingPtr; assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal"); } // Skip '('. ++SpellingPtr; return SpellingPtr - SpellingStart + ByteNo; } // Skip over the leading quote assert(SpellingPtr[0] == '"' && "Should be a string literal!"); ++SpellingPtr; // Skip over bytes until we find the offset we're looking for. while (ByteNo) { assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!"); // Step over non-escapes simply. if (*SpellingPtr != '\\') { ++SpellingPtr; --ByteNo; continue; } // Otherwise, this is an escape character. Advance over it. bool HadError = false; if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') { const char *EscapePtr = SpellingPtr; unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd, 1, Features, HadError); if (Len > ByteNo) { // ByteNo is somewhere within the escape sequence. SpellingPtr = EscapePtr; break; } ByteNo -= Len; } else { ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError, FullSourceLoc(Tok.getLocation(), SM), CharByteWidth*8, Diags, Features); --ByteNo; } assert(!HadError && "This method isn't valid on erroneous strings"); } return SpellingPtr-SpellingStart; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/CMakeLists.txt
# TODO: Add -maltivec when ARCH is PowerPC. set(LLVM_LINK_COMPONENTS support) add_clang_library(clangLex HeaderMap.cpp HeaderSearch.cpp HLSLMacroExpander.cpp Lexer.cpp LiteralSupport.cpp MacroArgs.cpp MacroInfo.cpp ModuleMap.cpp PPCaching.cpp PPCallbacks.cpp PPConditionalDirectiveRecord.cpp PPDirectives.cpp PPExpressions.cpp PPLexerChange.cpp PPMacroExpansion.cpp PTHLexer.cpp Pragma.cpp PreprocessingRecord.cpp Preprocessor.cpp PreprocessorLexer.cpp ScratchBuffer.cpp TokenConcatenation.cpp TokenLexer.cpp LINK_LIBS clangBasic )
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/PPCaching.cpp
//===--- PPCaching.cpp - Handle caching lexed tokens ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements pieces of the Preprocessor interface that manage the // caching of lexed tokens. // //===----------------------------------------------------------------------===// #include "clang/Lex/Preprocessor.h" using namespace clang; // EnableBacktrackAtThisPos - From the point that this method is called, and // until CommitBacktrackedTokens() or Backtrack() is called, the Preprocessor // keeps track of the lexed tokens so that a subsequent Backtrack() call will // make the Preprocessor re-lex the same tokens. // // Nested backtracks are allowed, meaning that EnableBacktrackAtThisPos can // be called multiple times and CommitBacktrackedTokens/Backtrack calls will // be combined with the EnableBacktrackAtThisPos calls in reverse order. void Preprocessor::EnableBacktrackAtThisPos() { BacktrackPositions.push_back(CachedLexPos); EnterCachingLexMode(); } // Disable the last EnableBacktrackAtThisPos call. void Preprocessor::CommitBacktrackedTokens() { assert(!BacktrackPositions.empty() && "EnableBacktrackAtThisPos was not called!"); BacktrackPositions.pop_back(); } // Make Preprocessor re-lex the tokens that were lexed since // EnableBacktrackAtThisPos() was previously called. void Preprocessor::Backtrack() { assert(!BacktrackPositions.empty() && "EnableBacktrackAtThisPos was not called!"); CachedLexPos = BacktrackPositions.back(); BacktrackPositions.pop_back(); recomputeCurLexerKind(); } void Preprocessor::CachingLex(Token &Result) { if (!InCachingLexMode()) return; if (CachedLexPos < CachedTokens.size()) { Result = CachedTokens[CachedLexPos++]; return; } ExitCachingLexMode(); Lex(Result); if (isBacktrackEnabled()) { // Cache the lexed token. EnterCachingLexMode(); CachedTokens.push_back(Result); ++CachedLexPos; return; } if (CachedLexPos < CachedTokens.size()) { EnterCachingLexMode(); } else { // All cached tokens were consumed. CachedTokens.clear(); CachedLexPos = 0; } } void Preprocessor::EnterCachingLexMode() { if (InCachingLexMode()) return; PushIncludeMacroStack(); CurLexerKind = CLK_CachingLexer; } const Token &Preprocessor::PeekAhead(unsigned N) { assert(CachedLexPos + N > CachedTokens.size() && "Confused caching."); ExitCachingLexMode(); for (unsigned C = CachedLexPos + N - CachedTokens.size(); C > 0; --C) { CachedTokens.push_back(Token()); Lex(CachedTokens.back()); } EnterCachingLexMode(); return CachedTokens.back(); } void Preprocessor::AnnotatePreviousCachedTokens(const Token &Tok) { assert(Tok.isAnnotation() && "Expected annotation token"); assert(CachedLexPos != 0 && "Expected to have some cached tokens"); assert(CachedTokens[CachedLexPos-1].getLastLoc() == Tok.getAnnotationEndLoc() && "The annotation should be until the most recent cached token"); // Start from the end of the cached tokens list and look for the token // that is the beginning of the annotation token. for (CachedTokensTy::size_type i = CachedLexPos; i != 0; --i) { CachedTokensTy::iterator AnnotBegin = CachedTokens.begin() + i-1; if (AnnotBegin->getLocation() == Tok.getLocation()) { assert((BacktrackPositions.empty() || BacktrackPositions.back() < i) && "The backtrack pos points inside the annotated tokens!"); // Replace the cached tokens with the single annotation token. if (i < CachedLexPos) CachedTokens.erase(AnnotBegin + 1, CachedTokens.begin() + CachedLexPos); *AnnotBegin = Tok; CachedLexPos = i; return; } } }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/HeaderSearch.cpp
//===--- HeaderSearch.cpp - Resolve Header File Locations ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the DirectoryLookup and HeaderSearch interfaces. // //===----------------------------------------------------------------------===// #include "clang/Lex/HeaderSearch.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Frontend/PCHContainerOperations.h" #include "clang/Lex/ExternalPreprocessorSource.h" #include "clang/Lex/HeaderMap.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/Capacity.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <cstdio> #if defined(LLVM_ON_UNIX) #include <limits.h> #endif using namespace clang; const IdentifierInfo * HeaderFileInfo::getControllingMacro(ExternalPreprocessorSource *External) { if (ControllingMacro) { if (ControllingMacro->isOutOfDate()) External->updateOutOfDateIdentifier( *const_cast<IdentifierInfo *>(ControllingMacro)); return ControllingMacro; } if (!ControllingMacroID || !External) return nullptr; ControllingMacro = External->GetIdentifier(ControllingMacroID); return ControllingMacro; } ExternalHeaderFileInfoSource::~ExternalHeaderFileInfoSource() {} HeaderSearch::HeaderSearch(IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts, SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target) : HSOpts(HSOpts), Diags(Diags), FileMgr(SourceMgr.getFileManager()), FrameworkMap(64), ModMap(SourceMgr, Diags, LangOpts, Target, *this), LangOpts(LangOpts) { AngledDirIdx = 0; SystemDirIdx = 0; NoCurDirSearch = false; ExternalLookup = nullptr; ExternalSource = nullptr; NumIncluded = 0; NumMultiIncludeFileOptzn = 0; NumFrameworkLookups = NumSubFrameworkLookups = 0; } HeaderSearch::~HeaderSearch() { // Delete headermaps. for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) delete HeaderMaps[i].second; } void HeaderSearch::PrintStats() { fprintf(stderr, "\n*** HeaderSearch Stats:\n"); fprintf(stderr, "%d files tracked.\n", (int)FileInfo.size()); unsigned NumOnceOnlyFiles = 0, MaxNumIncludes = 0, NumSingleIncludedFiles = 0; for (unsigned i = 0, e = FileInfo.size(); i != e; ++i) { NumOnceOnlyFiles += FileInfo[i].isImport; if (MaxNumIncludes < FileInfo[i].NumIncludes) MaxNumIncludes = FileInfo[i].NumIncludes; NumSingleIncludedFiles += FileInfo[i].NumIncludes == 1; } fprintf(stderr, " %d #import/#pragma once files.\n", NumOnceOnlyFiles); fprintf(stderr, " %d included exactly once.\n", NumSingleIncludedFiles); fprintf(stderr, " %d max times a file is included.\n", MaxNumIncludes); fprintf(stderr, " %d #include/#include_next/#import.\n", NumIncluded); fprintf(stderr, " %d #includes skipped due to" " the multi-include optimization.\n", NumMultiIncludeFileOptzn); fprintf(stderr, "%d framework lookups.\n", NumFrameworkLookups); fprintf(stderr, "%d subframework lookups.\n", NumSubFrameworkLookups); } /// CreateHeaderMap - This method returns a HeaderMap for the specified /// FileEntry, uniquing them through the 'HeaderMaps' datastructure. const HeaderMap *HeaderSearch::CreateHeaderMap(const FileEntry *FE) { // We expect the number of headermaps to be small, and almost always empty. // If it ever grows, use of a linear search should be re-evaluated. if (!HeaderMaps.empty()) { for (unsigned i = 0, e = HeaderMaps.size(); i != e; ++i) // Pointer equality comparison of FileEntries works because they are // already uniqued by inode. if (HeaderMaps[i].first == FE) return HeaderMaps[i].second; } if (const HeaderMap *HM = HeaderMap::Create(FE, FileMgr)) { HeaderMaps.push_back(std::make_pair(FE, HM)); return HM; } return nullptr; } std::string HeaderSearch::getModuleFileName(Module *Module) { const FileEntry *ModuleMap = getModuleMap().getModuleMapFileForUniquing(Module); return getModuleFileName(Module->Name, ModuleMap->getName()); } std::string HeaderSearch::getModuleFileName(StringRef ModuleName, StringRef ModuleMapPath) { // If we don't have a module cache path, we can't do anything. if (ModuleCachePath.empty()) return std::string(); SmallString<256> Result(ModuleCachePath); llvm::sys::fs::make_absolute(Result); if (HSOpts->DisableModuleHash) { llvm::sys::path::append(Result, ModuleName + ".pcm"); } else { // Construct the name <ModuleName>-<hash of ModuleMapPath>.pcm which should // ideally be globally unique to this particular module. Name collisions // in the hash are safe (because any translation unit can only import one // module with each name), but result in a loss of caching. // // To avoid false-negatives, we form as canonical a path as we can, and map // to lower-case in case we're on a case-insensitive file system. auto *Dir = FileMgr.getDirectory(llvm::sys::path::parent_path(ModuleMapPath)); if (!Dir) return std::string(); auto DirName = FileMgr.getCanonicalName(Dir); auto FileName = llvm::sys::path::filename(ModuleMapPath); llvm::hash_code Hash = llvm::hash_combine(DirName.lower(), FileName.lower(), HSOpts->ModuleFormat); SmallString<128> HashStr; llvm::APInt(64, size_t(Hash)).toStringUnsigned(HashStr, /*Radix*/36); llvm::sys::path::append(Result, ModuleName + "-" + HashStr + ".pcm"); } return Result.str().str(); } Module *HeaderSearch::lookupModule(StringRef ModuleName, bool AllowSearch) { // Look in the module map to determine if there is a module by this name. Module *Module = ModMap.findModule(ModuleName); if (Module || !AllowSearch || !HSOpts->ImplicitModuleMaps) return Module; // Look through the various header search paths to load any available module // maps, searching for a module map that describes this module. for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { if (SearchDirs[Idx].isFramework()) { // Search for or infer a module map for a framework. SmallString<128> FrameworkDirName; FrameworkDirName += SearchDirs[Idx].getFrameworkDir()->getName(); llvm::sys::path::append(FrameworkDirName, ModuleName + ".framework"); if (const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(FrameworkDirName)) { bool IsSystem = SearchDirs[Idx].getDirCharacteristic() != SrcMgr::C_User; Module = loadFrameworkModule(ModuleName, FrameworkDir, IsSystem); if (Module) break; } } // FIXME: Figure out how header maps and module maps will work together. // Only deal with normal search directories. if (!SearchDirs[Idx].isNormalDir()) continue; bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory(); // Search for a module map file in this directory. if (loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, /*IsFramework*/false) == LMM_NewlyLoaded) { // We just loaded a module map file; check whether the module is // available now. Module = ModMap.findModule(ModuleName); if (Module) break; } // Search for a module map in a subdirectory with the same name as the // module. SmallString<128> NestedModuleMapDirName; NestedModuleMapDirName = SearchDirs[Idx].getDir()->getName(); llvm::sys::path::append(NestedModuleMapDirName, ModuleName); if (loadModuleMapFile(NestedModuleMapDirName, IsSystem, /*IsFramework*/false) == LMM_NewlyLoaded){ // If we just loaded a module map file, look for the module again. Module = ModMap.findModule(ModuleName); if (Module) break; } // If we've already performed the exhaustive search for module maps in this // search directory, don't do it again. if (SearchDirs[Idx].haveSearchedAllModuleMaps()) continue; // Load all module maps in the immediate subdirectories of this search // directory. loadSubdirectoryModuleMaps(SearchDirs[Idx]); // Look again for the module. Module = ModMap.findModule(ModuleName); if (Module) break; } return Module; } //===----------------------------------------------------------------------===// // File lookup within a DirectoryLookup scope //===----------------------------------------------------------------------===// /// getName - Return the directory or filename corresponding to this lookup /// object. const char *DirectoryLookup::getName() const { if (isNormalDir()) return getDir()->getName(); if (isFramework()) return getFrameworkDir()->getName(); assert(isHeaderMap() && "Unknown DirectoryLookup"); return getHeaderMap()->getFileName(); } static const FileEntry * getFileAndSuggestModule(HeaderSearch &HS, StringRef FileName, const DirectoryEntry *Dir, bool IsSystemHeaderDir, ModuleMap::KnownHeader *SuggestedModule) { // If we have a module map that might map this header, load it and // check whether we'll have a suggestion for a module. HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir); if (SuggestedModule) { const FileEntry *File = HS.getFileMgr().getFile(FileName, /*OpenFile=*/false); if (File) { // If there is a module that corresponds to this header, suggest it. *SuggestedModule = HS.findModuleForHeader(File); // FIXME: This appears to be a no-op. We loaded the module map for this // directory at the start of this function. if (!SuggestedModule->getModule() && HS.hasModuleMap(FileName, Dir, IsSystemHeaderDir)) *SuggestedModule = HS.findModuleForHeader(File); } return File; } return HS.getFileMgr().getFile(FileName, /*openFile=*/true); } /// LookupFile - Lookup the specified file in this search path, returning it /// if it exists or returning null if not. const FileEntry *DirectoryLookup::LookupFile( StringRef &Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool &InUserSpecifiedSystemFramework, bool &HasBeenMapped, SmallVectorImpl<char> &MappedName) const { InUserSpecifiedSystemFramework = false; HasBeenMapped = false; SmallString<1024> TmpDir; if (isNormalDir()) { // Concatenate the requested file onto the directory. TmpDir = getDir()->getName(); llvm::sys::path::append(TmpDir, Filename); if (SearchPath) { StringRef SearchPathRef(getDir()->getName()); SearchPath->clear(); SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); } if (RelativePath) { RelativePath->clear(); RelativePath->append(Filename.begin(), Filename.end()); } return getFileAndSuggestModule(HS, TmpDir, getDir(), isSystemHeaderDirectory(), SuggestedModule); } if (isFramework()) return DoFrameworkLookup(Filename, HS, SearchPath, RelativePath, SuggestedModule, InUserSpecifiedSystemFramework); assert(isHeaderMap() && "Unknown directory lookup"); const HeaderMap *HM = getHeaderMap(); SmallString<1024> Path; StringRef Dest = HM->lookupFilename(Filename, Path); if (Dest.empty()) return nullptr; const FileEntry *Result; // Check if the headermap maps the filename to a framework include // ("Foo.h" -> "Foo/Foo.h"), in which case continue header lookup using the // framework include. if (llvm::sys::path::is_relative(Dest)) { MappedName.clear(); MappedName.append(Dest.begin(), Dest.end()); Filename = StringRef(MappedName.begin(), MappedName.size()); HasBeenMapped = true; Result = HM->LookupFile(Filename, HS.getFileMgr()); } else { Result = HS.getFileMgr().getFile(Dest); } if (Result) { if (SearchPath) { StringRef SearchPathRef(getName()); SearchPath->clear(); SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); } if (RelativePath) { RelativePath->clear(); RelativePath->append(Filename.begin(), Filename.end()); } } return Result; } /// \brief Given a framework directory, find the top-most framework directory. /// /// \param FileMgr The file manager to use for directory lookups. /// \param DirName The name of the framework directory. /// \param SubmodulePath Will be populated with the submodule path from the /// returned top-level module to the originally named framework. static const DirectoryEntry * getTopFrameworkDir(FileManager &FileMgr, StringRef DirName, SmallVectorImpl<std::string> &SubmodulePath) { assert(llvm::sys::path::extension(DirName) == ".framework" && "Not a framework directory"); // Note: as an egregious but useful hack we use the real path here, because // frameworks moving between top-level frameworks to embedded frameworks tend // to be symlinked, and we base the logical structure of modules on the // physical layout. In particular, we need to deal with crazy includes like // // #include <Foo/Frameworks/Bar.framework/Headers/Wibble.h> // // where 'Bar' used to be embedded in 'Foo', is now a top-level framework // which one should access with, e.g., // // #include <Bar/Wibble.h> // // Similar issues occur when a top-level framework has moved into an // embedded framework. const DirectoryEntry *TopFrameworkDir = FileMgr.getDirectory(DirName); DirName = FileMgr.getCanonicalName(TopFrameworkDir); do { // Get the parent directory name. DirName = llvm::sys::path::parent_path(DirName); if (DirName.empty()) break; // Determine whether this directory exists. const DirectoryEntry *Dir = FileMgr.getDirectory(DirName); if (!Dir) break; // If this is a framework directory, then we're a subframework of this // framework. if (llvm::sys::path::extension(DirName) == ".framework") { SubmodulePath.push_back(llvm::sys::path::stem(DirName)); TopFrameworkDir = Dir; } } while (true); return TopFrameworkDir; } /// DoFrameworkLookup - Do a lookup of the specified file in the current /// DirectoryLookup, which is a framework directory. const FileEntry *DirectoryLookup::DoFrameworkLookup( StringRef Filename, HeaderSearch &HS, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool &InUserSpecifiedSystemFramework) const { FileManager &FileMgr = HS.getFileMgr(); // Framework names must have a '/' in the filename. size_t SlashPos = Filename.find('/'); if (SlashPos == StringRef::npos) return nullptr; // Find out if this is the home for the specified framework, by checking // HeaderSearch. Possible answers are yes/no and unknown. HeaderSearch::FrameworkCacheEntry &CacheEntry = HS.LookupFrameworkCache(Filename.substr(0, SlashPos)); // If it is known and in some other directory, fail. if (CacheEntry.Directory && CacheEntry.Directory != getFrameworkDir()) return nullptr; // Otherwise, construct the path to this framework dir. // FrameworkName = "/System/Library/Frameworks/" SmallString<1024> FrameworkName; FrameworkName += getFrameworkDir()->getName(); if (FrameworkName.empty() || FrameworkName.back() != '/') FrameworkName.push_back('/'); // FrameworkName = "/System/Library/Frameworks/Cocoa" StringRef ModuleName(Filename.begin(), SlashPos); FrameworkName += ModuleName; // FrameworkName = "/System/Library/Frameworks/Cocoa.framework/" FrameworkName += ".framework/"; // If the cache entry was unresolved, populate it now. if (!CacheEntry.Directory) { HS.IncrementFrameworkLookupCount(); // If the framework dir doesn't exist, we fail. const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName); if (!Dir) return nullptr; // Otherwise, if it does, remember that this is the right direntry for this // framework. CacheEntry.Directory = getFrameworkDir(); // If this is a user search directory, check if the framework has been // user-specified as a system framework. if (getDirCharacteristic() == SrcMgr::C_User) { SmallString<1024> SystemFrameworkMarker(FrameworkName); SystemFrameworkMarker += ".system_framework"; if (llvm::sys::fs::exists(SystemFrameworkMarker)) { CacheEntry.IsUserSpecifiedSystemFramework = true; } } } // Set the 'user-specified system framework' flag. InUserSpecifiedSystemFramework = CacheEntry.IsUserSpecifiedSystemFramework; if (RelativePath) { RelativePath->clear(); RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); } // Check "/System/Library/Frameworks/Cocoa.framework/Headers/file.h" unsigned OrigSize = FrameworkName.size(); FrameworkName += "Headers/"; if (SearchPath) { SearchPath->clear(); // Without trailing '/'. SearchPath->append(FrameworkName.begin(), FrameworkName.end()-1); } FrameworkName.append(Filename.begin()+SlashPos+1, Filename.end()); const FileEntry *FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule); if (!FE) { // Check "/System/Library/Frameworks/Cocoa.framework/PrivateHeaders/file.h" const char *Private = "Private"; FrameworkName.insert(FrameworkName.begin()+OrigSize, Private, Private+strlen(Private)); if (SearchPath) SearchPath->insert(SearchPath->begin()+OrigSize, Private, Private+strlen(Private)); FE = FileMgr.getFile(FrameworkName, /*openFile=*/!SuggestedModule); } // If we found the header and are allowed to suggest a module, do so now. if (FE && SuggestedModule) { // Find the framework in which this header occurs. StringRef FrameworkPath = FE->getDir()->getName(); bool FoundFramework = false; do { // Determine whether this directory exists. const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkPath); if (!Dir) break; // If this is a framework directory, then we're a subframework of this // framework. if (llvm::sys::path::extension(FrameworkPath) == ".framework") { FoundFramework = true; break; } // Get the parent directory name. FrameworkPath = llvm::sys::path::parent_path(FrameworkPath); if (FrameworkPath.empty()) break; } while (true); if (FoundFramework) { // Find the top-level framework based on this framework. SmallVector<std::string, 4> SubmodulePath; const DirectoryEntry *TopFrameworkDir = ::getTopFrameworkDir(FileMgr, FrameworkPath, SubmodulePath); // Determine the name of the top-level framework. StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName()); // Load this framework module. If that succeeds, find the suggested module // for this header, if any. bool IsSystem = getDirCharacteristic() != SrcMgr::C_User; HS.loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem); // FIXME: This can find a module not part of ModuleName, which is // important so that we're consistent about whether this header // corresponds to a module. Possibly we should lock down framework modules // so that this is not possible. *SuggestedModule = HS.findModuleForHeader(FE); } else { *SuggestedModule = HS.findModuleForHeader(FE); } } return FE; } void HeaderSearch::setTarget(const TargetInfo &Target) { ModMap.setTarget(Target); } //===----------------------------------------------------------------------===// // Header File Location. //===----------------------------------------------------------------------===// /// \brief Return true with a diagnostic if the file that MSVC would have found /// fails to match the one that Clang would have found with MSVC header search /// disabled. static bool checkMSVCHeaderSearch(DiagnosticsEngine &Diags, const FileEntry *MSFE, const FileEntry *FE, SourceLocation IncludeLoc) { if (MSFE && FE != MSFE) { #if 0 // HLSL Change - turn off warnings of MSVC search rules Diags.Report(IncludeLoc, diag::ext_pp_include_search_ms) << MSFE->getName(); #endif // HLSL Change return true; } return false; } static const char *copyString(StringRef Str, llvm::BumpPtrAllocator &Alloc) { assert(!Str.empty()); char *CopyStr = Alloc.Allocate<char>(Str.size()+1); std::copy(Str.begin(), Str.end(), CopyStr); CopyStr[Str.size()] = '\0'; return CopyStr; } /// LookupFile - Given a "foo" or \<foo> reference, look up the indicated file, /// return null on failure. isAngled indicates whether the file reference is /// for system \#include's or not (i.e. using <> instead of ""). Includers, if /// non-empty, indicates where the \#including file(s) are, in case a relative /// search is needed. Microsoft mode will pass all \#including files. const FileEntry *HeaderSearch::LookupFile( StringRef Filename, SourceLocation IncludeLoc, bool isAngled, const DirectoryLookup *FromDir, const DirectoryLookup *&CurDir, ArrayRef<std::pair<const FileEntry *, const DirectoryEntry *>> Includers, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool SkipCache) { if (SuggestedModule) *SuggestedModule = ModuleMap::KnownHeader(); // If 'Filename' is absolute, check to see if it exists and no searching. if (llvm::sys::path::is_absolute(Filename)) { CurDir = nullptr; // If this was an #include_next "/absolute/file", fail. if (FromDir) return nullptr; if (SearchPath) SearchPath->clear(); if (RelativePath) { RelativePath->clear(); RelativePath->append(Filename.begin(), Filename.end()); } // Otherwise, just return the file. const FileEntry *File = FileMgr.getFile(Filename, /*openFile=*/true); if (File && SuggestedModule) { // If there is a module that corresponds to this header, suggest it. hasModuleMap(Filename, File->getDir(), /*SystemHeaderDir*/false); *SuggestedModule = findModuleForHeader(File); } return File; } // This is the header that MSVC's header search would have found. const FileEntry *MSFE = nullptr; ModuleMap::KnownHeader MSSuggestedModule; // Unless disabled, check to see if the file is in the #includer's // directory. This cannot be based on CurDir, because each includer could be // a #include of a subdirectory (#include "foo/bar.h") and a subsequent // include of "baz.h" should resolve to "whatever/foo/baz.h". // This search is not done for <> headers. if (!Includers.empty() && !isAngled && !NoCurDirSearch) { SmallString<1024> TmpDir; bool First = true; for (const auto &IncluderAndDir : Includers) { const FileEntry *Includer = IncluderAndDir.first; // Concatenate the requested file onto the directory. // FIXME: Portability. Filename concatenation should be in sys::Path. TmpDir = IncluderAndDir.second->getName(); TmpDir.push_back('/'); TmpDir.append(Filename.begin(), Filename.end()); // FIXME: We don't cache the result of getFileInfo across the call to // getFileAndSuggestModule, because it's a reference to an element of // a container that could be reallocated across this call. // // FIXME: If we have no includer, that means we're processing a #include // from a module build. We should treat this as a system header if we're // building a [system] module. bool IncluderIsSystemHeader = Includer && getFileInfo(Includer).DirInfo != SrcMgr::C_User; if (const FileEntry *FE = getFileAndSuggestModule( *this, TmpDir, IncluderAndDir.second, IncluderIsSystemHeader, SuggestedModule)) { if (!Includer) { assert(First && "only first includer can have no file"); return FE; } // Leave CurDir unset. // This file is a system header or C++ unfriendly if the old file is. // // Note that we only use one of FromHFI/ToHFI at once, due to potential // reallocation of the underlying vector potentially making the first // reference binding dangling. HeaderFileInfo &FromHFI = getFileInfo(Includer); unsigned DirInfo = FromHFI.DirInfo; bool IndexHeaderMapHeader = FromHFI.IndexHeaderMapHeader; StringRef Framework = FromHFI.Framework; HeaderFileInfo &ToHFI = getFileInfo(FE); ToHFI.DirInfo = DirInfo; ToHFI.IndexHeaderMapHeader = IndexHeaderMapHeader; ToHFI.Framework = Framework; if (SearchPath) { StringRef SearchPathRef(IncluderAndDir.second->getName()); SearchPath->clear(); SearchPath->append(SearchPathRef.begin(), SearchPathRef.end()); } if (RelativePath) { RelativePath->clear(); RelativePath->append(Filename.begin(), Filename.end()); } if (First) return FE; // Otherwise, we found the path via MSVC header search rules. If // -Wmsvc-include is enabled, we have to keep searching to see if we // would've found this header in -I or -isystem directories. if (Diags.isIgnored(diag::ext_pp_include_search_ms, IncludeLoc)) { return FE; } else { MSFE = FE; if (SuggestedModule) { MSSuggestedModule = *SuggestedModule; *SuggestedModule = ModuleMap::KnownHeader(); } break; } } First = false; } } CurDir = nullptr; // If this is a system #include, ignore the user #include locs. unsigned i = isAngled ? AngledDirIdx : 0; // If this is a #include_next request, start searching after the directory the // file was found in. if (FromDir) i = FromDir-&SearchDirs[0]; // Cache all of the lookups performed by this method. Many headers are // multiply included, and the "pragma once" optimization prevents them from // being relex/pp'd, but they would still have to search through a // (potentially huge) series of SearchDirs to find it. LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename]; // If the entry has been previously looked up, the first value will be // non-zero. If the value is equal to i (the start point of our search), then // this is a matching hit. if (!SkipCache && CacheLookup.StartIdx == i+1) { // Skip querying potentially lots of directories for this lookup. i = CacheLookup.HitIdx; if (CacheLookup.MappedName) Filename = CacheLookup.MappedName; } else { // Otherwise, this is the first query, or the previous query didn't match // our search start. We will fill in our found location below, so prime the // start point value. CacheLookup.reset(/*StartIdx=*/i+1); } SmallString<64> MappedName; // Check each directory in sequence to see if it contains this file. for (; i != SearchDirs.size(); ++i) { bool InUserSpecifiedSystemFramework = false; bool HasBeenMapped = false; const FileEntry *FE = SearchDirs[i].LookupFile(Filename, *this, SearchPath, RelativePath, SuggestedModule, InUserSpecifiedSystemFramework, HasBeenMapped, MappedName); if (HasBeenMapped) { CacheLookup.MappedName = copyString(Filename, LookupFileCache.getAllocator()); } if (!FE) continue; CurDir = &SearchDirs[i]; // This file is a system header or C++ unfriendly if the dir is. HeaderFileInfo &HFI = getFileInfo(FE); HFI.DirInfo = CurDir->getDirCharacteristic(); // If the directory characteristic is User but this framework was // user-specified to be treated as a system framework, promote the // characteristic. if (HFI.DirInfo == SrcMgr::C_User && InUserSpecifiedSystemFramework) HFI.DirInfo = SrcMgr::C_System; // If the filename matches a known system header prefix, override // whether the file is a system header. for (unsigned j = SystemHeaderPrefixes.size(); j; --j) { if (Filename.startswith(SystemHeaderPrefixes[j-1].first)) { HFI.DirInfo = SystemHeaderPrefixes[j-1].second ? SrcMgr::C_System : SrcMgr::C_User; break; } } // If this file is found in a header map and uses the framework style of // includes, then this header is part of a framework we're building. if (CurDir->isIndexHeaderMap()) { size_t SlashPos = Filename.find('/'); if (SlashPos != StringRef::npos) { HFI.IndexHeaderMapHeader = 1; HFI.Framework = getUniqueFrameworkName(StringRef(Filename.begin(), SlashPos)); } } if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) { if (SuggestedModule) *SuggestedModule = MSSuggestedModule; return MSFE; } // Remember this location for the next lookup we do. CacheLookup.HitIdx = i; return FE; } // If we are including a file with a quoted include "foo.h" from inside // a header in a framework that is currently being built, and we couldn't // resolve "foo.h" any other way, change the include to <Foo/foo.h>, where // "Foo" is the name of the framework in which the including header was found. if (!Includers.empty() && Includers.front().first && !isAngled && Filename.find('/') == StringRef::npos) { HeaderFileInfo &IncludingHFI = getFileInfo(Includers.front().first); if (IncludingHFI.IndexHeaderMapHeader) { SmallString<128> ScratchFilename; ScratchFilename += IncludingHFI.Framework; ScratchFilename += '/'; ScratchFilename += Filename; const FileEntry *FE = LookupFile( ScratchFilename, IncludeLoc, /*isAngled=*/true, FromDir, CurDir, Includers.front(), SearchPath, RelativePath, SuggestedModule); if (checkMSVCHeaderSearch(Diags, MSFE, FE, IncludeLoc)) { if (SuggestedModule) *SuggestedModule = MSSuggestedModule; return MSFE; } LookupFileCacheInfo &CacheLookup = LookupFileCache[Filename]; CacheLookup.HitIdx = LookupFileCache[ScratchFilename].HitIdx; // FIXME: SuggestedModule. return FE; } } if (checkMSVCHeaderSearch(Diags, MSFE, nullptr, IncludeLoc)) { if (SuggestedModule) *SuggestedModule = MSSuggestedModule; return MSFE; } // Otherwise, didn't find it. Remember we didn't find this. CacheLookup.HitIdx = SearchDirs.size(); return nullptr; } /// LookupSubframeworkHeader - Look up a subframework for the specified /// \#include file. For example, if \#include'ing <HIToolbox/HIToolbox.h> from /// within ".../Carbon.framework/Headers/Carbon.h", check to see if HIToolbox /// is a subframework within Carbon.framework. If so, return the FileEntry /// for the designated file, otherwise return null. const FileEntry *HeaderSearch:: LookupSubframeworkHeader(StringRef Filename, const FileEntry *ContextFileEnt, SmallVectorImpl<char> *SearchPath, SmallVectorImpl<char> *RelativePath, ModuleMap::KnownHeader *SuggestedModule) { assert(ContextFileEnt && "No context file?"); // Framework names must have a '/' in the filename. Find it. // FIXME: Should we permit '\' on Windows? size_t SlashPos = Filename.find('/'); if (SlashPos == StringRef::npos) return nullptr; // Look up the base framework name of the ContextFileEnt. const char *ContextName = ContextFileEnt->getName(); // If the context info wasn't a framework, couldn't be a subframework. const unsigned DotFrameworkLen = 10; const char *FrameworkPos = strstr(ContextName, ".framework"); if (FrameworkPos == nullptr || (FrameworkPos[DotFrameworkLen] != '/' && FrameworkPos[DotFrameworkLen] != '\\')) return nullptr; SmallString<1024> FrameworkName(ContextName, FrameworkPos+DotFrameworkLen+1); // Append Frameworks/HIToolbox.framework/ FrameworkName += "Frameworks/"; FrameworkName.append(Filename.begin(), Filename.begin()+SlashPos); FrameworkName += ".framework/"; auto &CacheLookup = *FrameworkMap.insert(std::make_pair(Filename.substr(0, SlashPos), FrameworkCacheEntry())).first; // Some other location? if (CacheLookup.second.Directory && CacheLookup.first().size() == FrameworkName.size() && memcmp(CacheLookup.first().data(), &FrameworkName[0], CacheLookup.first().size()) != 0) return nullptr; // Cache subframework. if (!CacheLookup.second.Directory) { ++NumSubFrameworkLookups; // If the framework dir doesn't exist, we fail. const DirectoryEntry *Dir = FileMgr.getDirectory(FrameworkName); if (!Dir) return nullptr; // Otherwise, if it does, remember that this is the right direntry for this // framework. CacheLookup.second.Directory = Dir; } const FileEntry *FE = nullptr; if (RelativePath) { RelativePath->clear(); RelativePath->append(Filename.begin()+SlashPos+1, Filename.end()); } // Check ".../Frameworks/HIToolbox.framework/Headers/HIToolbox.h" SmallString<1024> HeadersFilename(FrameworkName); HeadersFilename += "Headers/"; if (SearchPath) { SearchPath->clear(); // Without trailing '/'. SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); } HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) { // Check ".../Frameworks/HIToolbox.framework/PrivateHeaders/HIToolbox.h" HeadersFilename = FrameworkName; HeadersFilename += "PrivateHeaders/"; if (SearchPath) { SearchPath->clear(); // Without trailing '/'. SearchPath->append(HeadersFilename.begin(), HeadersFilename.end()-1); } HeadersFilename.append(Filename.begin()+SlashPos+1, Filename.end()); if (!(FE = FileMgr.getFile(HeadersFilename, /*openFile=*/true))) return nullptr; } // This file is a system header or C++ unfriendly if the old file is. // // Note that the temporary 'DirInfo' is required here, as either call to // getFileInfo could resize the vector and we don't want to rely on order // of evaluation. unsigned DirInfo = getFileInfo(ContextFileEnt).DirInfo; getFileInfo(FE).DirInfo = DirInfo; // If we're supposed to suggest a module, look for one now. if (SuggestedModule) { // Find the top-level framework based on this framework. FrameworkName.pop_back(); // remove the trailing '/' SmallVector<std::string, 4> SubmodulePath; const DirectoryEntry *TopFrameworkDir = ::getTopFrameworkDir(FileMgr, FrameworkName, SubmodulePath); // Determine the name of the top-level framework. StringRef ModuleName = llvm::sys::path::stem(TopFrameworkDir->getName()); // Load this framework module. If that succeeds, find the suggested module // for this header, if any. bool IsSystem = false; if (loadFrameworkModule(ModuleName, TopFrameworkDir, IsSystem)) { *SuggestedModule = findModuleForHeader(FE); } } return FE; } //===----------------------------------------------------------------------===// // File Info Management. //===----------------------------------------------------------------------===// /// \brief Merge the header file info provided by \p OtherHFI into the current /// header file info (\p HFI) static void mergeHeaderFileInfo(HeaderFileInfo &HFI, const HeaderFileInfo &OtherHFI) { HFI.isImport |= OtherHFI.isImport; HFI.isPragmaOnce |= OtherHFI.isPragmaOnce; HFI.isModuleHeader |= OtherHFI.isModuleHeader; HFI.NumIncludes += OtherHFI.NumIncludes; if (!HFI.ControllingMacro && !HFI.ControllingMacroID) { HFI.ControllingMacro = OtherHFI.ControllingMacro; HFI.ControllingMacroID = OtherHFI.ControllingMacroID; } if (OtherHFI.External) { HFI.DirInfo = OtherHFI.DirInfo; HFI.External = OtherHFI.External; HFI.IndexHeaderMapHeader = OtherHFI.IndexHeaderMapHeader; } if (HFI.Framework.empty()) HFI.Framework = OtherHFI.Framework; HFI.Resolved = true; } /// getFileInfo - Return the HeaderFileInfo structure for the specified /// FileEntry. HeaderFileInfo &HeaderSearch::getFileInfo(const FileEntry *FE) { if (FE->getUID() >= FileInfo.size()) FileInfo.resize(FE->getUID()+1); HeaderFileInfo &HFI = FileInfo[FE->getUID()]; if (ExternalSource && !HFI.Resolved) mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(FE)); HFI.IsValid = 1; return HFI; } bool HeaderSearch::tryGetFileInfo(const FileEntry *FE, HeaderFileInfo &Result) const { if (FE->getUID() >= FileInfo.size()) return false; const HeaderFileInfo &HFI = FileInfo[FE->getUID()]; if (HFI.IsValid) { Result = HFI; return true; } return false; } bool HeaderSearch::isFileMultipleIncludeGuarded(const FileEntry *File) { // Check if we've ever seen this file as a header. if (File->getUID() >= FileInfo.size()) return false; // Resolve header file info from the external source, if needed. HeaderFileInfo &HFI = FileInfo[File->getUID()]; if (ExternalSource && !HFI.Resolved) mergeHeaderFileInfo(HFI, ExternalSource->GetHeaderFileInfo(File)); return HFI.isPragmaOnce || HFI.isImport || HFI.ControllingMacro || HFI.ControllingMacroID; } void HeaderSearch::MarkFileModuleHeader(const FileEntry *FE, ModuleMap::ModuleHeaderRole Role, bool isCompilingModuleHeader) { if (FE->getUID() >= FileInfo.size()) FileInfo.resize(FE->getUID()+1); HeaderFileInfo &HFI = FileInfo[FE->getUID()]; HFI.isModuleHeader = true; HFI.isCompilingModuleHeader |= isCompilingModuleHeader; HFI.setHeaderRole(Role); } bool HeaderSearch::ShouldEnterIncludeFile(Preprocessor &PP, const FileEntry *File, bool isImport, Module *M) { ++NumIncluded; // Count # of attempted #includes. // Get information about this file. HeaderFileInfo &FileInfo = getFileInfo(File); // If this is a #import directive, check that we have not already imported // this header. if (isImport) { // If this has already been imported, don't import it again. FileInfo.isImport = true; // Has this already been #import'ed or #include'd? if (FileInfo.NumIncludes) return false; } else { // Otherwise, if this is a #include of a file that was previously #import'd // or if this is the second #include of a #pragma once file, ignore it. if (FileInfo.isImport) return false; } // Next, check to see if the file is wrapped with #ifndef guards. If so, and // if the macro that guards it is defined, we know the #include has no effect. if (const IdentifierInfo *ControllingMacro = FileInfo.getControllingMacro(ExternalLookup)) { // If the header corresponds to a module, check whether the macro is already // defined in that module rather than checking in the current set of visible // modules. if (M ? PP.isMacroDefinedInLocalModule(ControllingMacro, M) : PP.isMacroDefined(ControllingMacro)) { ++NumMultiIncludeFileOptzn; return false; } } // Increment the number of times this file has been included. ++FileInfo.NumIncludes; return true; } size_t HeaderSearch::getTotalMemory() const { return SearchDirs.capacity() + llvm::capacity_in_bytes(FileInfo) + llvm::capacity_in_bytes(HeaderMaps) + LookupFileCache.getAllocator().getTotalMemory() + FrameworkMap.getAllocator().getTotalMemory(); } StringRef HeaderSearch::getUniqueFrameworkName(StringRef Framework) { return FrameworkNames.insert(Framework).first->first(); } bool HeaderSearch::hasModuleMap(StringRef FileName, const DirectoryEntry *Root, bool IsSystem) { if (!HSOpts->ImplicitModuleMaps) return false; SmallVector<const DirectoryEntry *, 2> FixUpDirectories; StringRef DirName = FileName; do { // Get the parent directory name. DirName = llvm::sys::path::parent_path(DirName); if (DirName.empty()) return false; // Determine whether this directory exists. const DirectoryEntry *Dir = FileMgr.getDirectory(DirName); if (!Dir) return false; // Try to load the module map file in this directory. switch (loadModuleMapFile(Dir, IsSystem, llvm::sys::path::extension(Dir->getName()) == ".framework")) { case LMM_NewlyLoaded: case LMM_AlreadyLoaded: // Success. All of the directories we stepped through inherit this module // map file. for (unsigned I = 0, N = FixUpDirectories.size(); I != N; ++I) DirectoryHasModuleMap[FixUpDirectories[I]] = true; return true; case LMM_NoDirectory: case LMM_InvalidModuleMap: break; } // If we hit the top of our search, we're done. if (Dir == Root) return false; // Keep track of all of the directories we checked, so we can mark them as // having module maps if we eventually do find a module map. FixUpDirectories.push_back(Dir); } while (true); } ModuleMap::KnownHeader HeaderSearch::findModuleForHeader(const FileEntry *File) const { if (ExternalSource) { // Make sure the external source has handled header info about this file, // which includes whether the file is part of a module. (void)getFileInfo(File); } return ModMap.findModuleForHeader(File); } static const FileEntry *getPrivateModuleMap(const FileEntry *File, FileManager &FileMgr) { StringRef Filename = llvm::sys::path::filename(File->getName()); SmallString<128> PrivateFilename(File->getDir()->getName()); if (Filename == "module.map") llvm::sys::path::append(PrivateFilename, "module_private.map"); else if (Filename == "module.modulemap") llvm::sys::path::append(PrivateFilename, "module.private.modulemap"); else return nullptr; return FileMgr.getFile(PrivateFilename); } bool HeaderSearch::loadModuleMapFile(const FileEntry *File, bool IsSystem) { // Find the directory for the module. For frameworks, that may require going // up from the 'Modules' directory. const DirectoryEntry *Dir = nullptr; if (getHeaderSearchOpts().ModuleMapFileHomeIsCwd) Dir = FileMgr.getDirectory("."); else { Dir = File->getDir(); StringRef DirName(Dir->getName()); if (llvm::sys::path::filename(DirName) == "Modules") { DirName = llvm::sys::path::parent_path(DirName); if (DirName.endswith(".framework")) Dir = FileMgr.getDirectory(DirName); // FIXME: This assert can fail if there's a race between the above check // and the removal of the directory. assert(Dir && "parent must exist"); } } switch (loadModuleMapFileImpl(File, IsSystem, Dir)) { case LMM_AlreadyLoaded: case LMM_NewlyLoaded: return false; case LMM_NoDirectory: case LMM_InvalidModuleMap: return true; } llvm_unreachable("Unknown load module map result"); } HeaderSearch::LoadModuleMapResult HeaderSearch::loadModuleMapFileImpl(const FileEntry *File, bool IsSystem, const DirectoryEntry *Dir) { assert(File && "expected FileEntry"); // Check whether we've already loaded this module map, and mark it as being // loaded in case we recursively try to load it from itself. auto AddResult = LoadedModuleMaps.insert(std::make_pair(File, true)); if (!AddResult.second) return AddResult.first->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; if (ModMap.parseModuleMapFile(File, IsSystem, Dir)) { LoadedModuleMaps[File] = false; return LMM_InvalidModuleMap; } // Try to load a corresponding private module map. if (const FileEntry *PMMFile = getPrivateModuleMap(File, FileMgr)) { if (ModMap.parseModuleMapFile(PMMFile, IsSystem, Dir)) { LoadedModuleMaps[File] = false; return LMM_InvalidModuleMap; } } // This directory has a module map. return LMM_NewlyLoaded; } const FileEntry * HeaderSearch::lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework) { if (!HSOpts->ImplicitModuleMaps) return nullptr; // For frameworks, the preferred spelling is Modules/module.modulemap, but // module.map at the framework root is also accepted. SmallString<128> ModuleMapFileName(Dir->getName()); if (IsFramework) llvm::sys::path::append(ModuleMapFileName, "Modules"); llvm::sys::path::append(ModuleMapFileName, "module.modulemap"); if (const FileEntry *F = FileMgr.getFile(ModuleMapFileName)) return F; // Continue to allow module.map ModuleMapFileName = Dir->getName(); llvm::sys::path::append(ModuleMapFileName, "module.map"); return FileMgr.getFile(ModuleMapFileName); } Module *HeaderSearch::loadFrameworkModule(StringRef Name, const DirectoryEntry *Dir, bool IsSystem) { if (Module *Module = ModMap.findModule(Name)) return Module; // Try to load a module map file. switch (loadModuleMapFile(Dir, IsSystem, /*IsFramework*/true)) { case LMM_InvalidModuleMap: // Try to infer a module map from the framework directory. if (HSOpts->ImplicitModuleMaps) ModMap.inferFrameworkModule(Dir, IsSystem, /*Parent=*/nullptr); break; case LMM_AlreadyLoaded: case LMM_NoDirectory: return nullptr; case LMM_NewlyLoaded: break; } return ModMap.findModule(Name); } HeaderSearch::LoadModuleMapResult HeaderSearch::loadModuleMapFile(StringRef DirName, bool IsSystem, bool IsFramework) { if (const DirectoryEntry *Dir = FileMgr.getDirectory(DirName)) return loadModuleMapFile(Dir, IsSystem, IsFramework); return LMM_NoDirectory; } HeaderSearch::LoadModuleMapResult HeaderSearch::loadModuleMapFile(const DirectoryEntry *Dir, bool IsSystem, bool IsFramework) { auto KnownDir = DirectoryHasModuleMap.find(Dir); if (KnownDir != DirectoryHasModuleMap.end()) return KnownDir->second ? LMM_AlreadyLoaded : LMM_InvalidModuleMap; if (const FileEntry *ModuleMapFile = lookupModuleMapFile(Dir, IsFramework)) { LoadModuleMapResult Result = loadModuleMapFileImpl(ModuleMapFile, IsSystem, Dir); // Add Dir explicitly in case ModuleMapFile is in a subdirectory. // E.g. Foo.framework/Modules/module.modulemap // ^Dir ^ModuleMapFile if (Result == LMM_NewlyLoaded) DirectoryHasModuleMap[Dir] = true; else if (Result == LMM_InvalidModuleMap) DirectoryHasModuleMap[Dir] = false; return Result; } return LMM_InvalidModuleMap; } void HeaderSearch::collectAllModules(SmallVectorImpl<Module *> &Modules) { Modules.clear(); if (HSOpts->ImplicitModuleMaps) { // Load module maps for each of the header search directories. for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { bool IsSystem = SearchDirs[Idx].isSystemHeaderDirectory(); if (SearchDirs[Idx].isFramework()) { std::error_code EC; SmallString<128> DirNative; llvm::sys::path::native(SearchDirs[Idx].getFrameworkDir()->getName(), DirNative); // Search each of the ".framework" directories to load them as modules. for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { if (llvm::sys::path::extension(Dir->path()) != ".framework") continue; const DirectoryEntry *FrameworkDir = FileMgr.getDirectory(Dir->path()); if (!FrameworkDir) continue; // Load this framework module. loadFrameworkModule(llvm::sys::path::stem(Dir->path()), FrameworkDir, IsSystem); } continue; } // FIXME: Deal with header maps. if (SearchDirs[Idx].isHeaderMap()) continue; // Try to load a module map file for the search directory. loadModuleMapFile(SearchDirs[Idx].getDir(), IsSystem, /*IsFramework*/ false); // Try to load module map files for immediate subdirectories of this // search directory. loadSubdirectoryModuleMaps(SearchDirs[Idx]); } } // Populate the list of modules. for (ModuleMap::module_iterator M = ModMap.module_begin(), MEnd = ModMap.module_end(); M != MEnd; ++M) { Modules.push_back(M->getValue()); } } void HeaderSearch::loadTopLevelSystemModules() { if (!HSOpts->ImplicitModuleMaps) return; // Load module maps for each of the header search directories. for (unsigned Idx = 0, N = SearchDirs.size(); Idx != N; ++Idx) { // We only care about normal header directories. if (!SearchDirs[Idx].isNormalDir()) { continue; } // Try to load a module map file for the search directory. loadModuleMapFile(SearchDirs[Idx].getDir(), SearchDirs[Idx].isSystemHeaderDirectory(), SearchDirs[Idx].isFramework()); } } void HeaderSearch::loadSubdirectoryModuleMaps(DirectoryLookup &SearchDir) { assert(HSOpts->ImplicitModuleMaps && "Should not be loading subdirectory module maps"); if (SearchDir.haveSearchedAllModuleMaps()) return; std::error_code EC; SmallString<128> DirNative; llvm::sys::path::native(SearchDir.getDir()->getName(), DirNative); for (llvm::sys::fs::directory_iterator Dir(DirNative, EC), DirEnd; Dir != DirEnd && !EC; Dir.increment(EC)) { bool IsFramework = llvm::sys::path::extension(Dir->path()) == ".framework"; if (IsFramework == SearchDir.isFramework()) loadModuleMapFile(Dir->path(), SearchDir.isSystemHeaderDirectory(), SearchDir.isFramework()); } SearchDir.setSearchedAllModuleMaps(true); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/Preprocessor.cpp
//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Preprocessor interface. // //===----------------------------------------------------------------------===// // // Options to support: // -H - Print the name of each header file used. // -d[DNI] - Dump various things. // -fworking-directory - #line's with preprocessor's working dir. // -fpreprocessed // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD // -W* // -w // // Messages to emit: // "Multiple include guards may be useful for:\n" // //===----------------------------------------------------------------------===// #include "clang/Lex/Preprocessor.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemStatCache.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/ExternalPreprocessorSource.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Lex/MacroArgs.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/ModuleLoader.h" #include "clang/Lex/Pragma.h" #include "clang/Lex/PreprocessingRecord.h" #include "clang/Lex/PreprocessorOptions.h" #include "clang/Lex/ScratchBuffer.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Capacity.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" using namespace clang; //===----------------------------------------------------------------------===// ExternalPreprocessorSource::~ExternalPreprocessorSource() { } Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts, DiagnosticsEngine &diags, LangOptions &opts, SourceManager &SM, HeaderSearch &Headers, ModuleLoader &TheModuleLoader, IdentifierInfoLookup *IILookup, bool OwnsHeaders, TranslationUnitKind TUKind) : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(nullptr), FileMgr(Headers.getFileMgr()), SourceMgr(SM), ScratchBuf(new ScratchBuffer(SourceMgr)),HeaderInfo(Headers), TheModuleLoader(TheModuleLoader), ExternalSource(nullptr), Identifiers(opts, IILookup), PragmaHandlers(new PragmaNamespace(StringRef())), IncrementalProcessing(false), TUKind(TUKind), CodeComplete(nullptr), CodeCompletionFile(nullptr), CodeCompletionOffset(0), LastTokenWasAt(false), ModuleImportExpectsIdentifier(false), CodeCompletionReached(0), MainFileDir(nullptr), SkipMainFilePreamble(0, true), CurPPLexer(nullptr), CurDirLookup(nullptr), CurLexerKind(CLK_Lexer), CurSubmodule(nullptr), Callbacks(nullptr), CurSubmoduleState(&NullSubmoduleState), MacroArgCache(nullptr), Record(nullptr), MIChainHead(nullptr), DeserialMIChainHead(nullptr) { OwnsHeaderSearch = OwnsHeaders; CounterValue = 0; // __COUNTER__ starts at 0. // Clear stats. NumDirectives = NumDefined = NumUndefined = NumPragma = 0; NumIf = NumElse = NumEndif = 0; NumEnteredSourceFiles = 0; NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0; NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0; MaxIncludeStackDepth = 0; NumSkipped = 0; // Default to discarding comments. KeepComments = false; KeepMacroComments = false; SuppressIncludeNotFoundError = false; // Macro expansion is enabled. DisableMacroExpansion = false; MacroExpansionInDirectivesOverride = false; InMacroArgs = false; InMacroArgPreExpansion = false; NumCachedTokenLexers = 0; PragmasEnabled = true; ParsingIfOrElifDirective = false; PreprocessedOutput = false; CachedLexPos = 0; // We haven't read anything from the external source. ReadMacrosFromExternalSource = false; // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. // This gets unpoisoned where it is allowed. (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned(); SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use); // Initialize the pragma handlers. RegisterBuiltinPragmas(); // Initialize builtin macros like __LINE__ and friends. RegisterBuiltinMacros(); if(LangOpts.Borland) { Ident__exception_info = getIdentifierInfo("_exception_info"); Ident___exception_info = getIdentifierInfo("__exception_info"); Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation"); Ident__exception_code = getIdentifierInfo("_exception_code"); Ident___exception_code = getIdentifierInfo("__exception_code"); Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode"); Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination"); Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination"); Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination"); } else { Ident__exception_info = Ident__exception_code = nullptr; Ident__abnormal_termination = Ident___exception_info = nullptr; Ident___exception_code = Ident___abnormal_termination = nullptr; Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr; Ident_AbnormalTermination = nullptr; } } Preprocessor::~Preprocessor() { assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!"); IncludeMacroStack.clear(); // Destroy any macro definitions. while (MacroInfoChain *I = MIChainHead) { MIChainHead = I->Next; I->~MacroInfoChain(); } // Free any cached macro expanders. // This populates MacroArgCache, so all TokenLexers need to be destroyed // before the code below that frees up the MacroArgCache list. std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr); CurTokenLexer.reset(); while (DeserializedMacroInfoChain *I = DeserialMIChainHead) { DeserialMIChainHead = I->Next; I->~DeserializedMacroInfoChain(); } // Free any cached MacroArgs. for (MacroArgs *ArgList = MacroArgCache; ArgList;) ArgList = ArgList->deallocate(); // Delete the header search info, if we own it. if (OwnsHeaderSearch) delete &HeaderInfo; } void Preprocessor::Initialize(const TargetInfo &Target) { assert((!this->Target || this->Target == &Target) && "Invalid override of target information"); this->Target = &Target; // Initialize information about built-ins. BuiltinInfo.InitializeTarget(Target); HeaderInfo.setTarget(Target); } void Preprocessor::InitializeForModelFile() { NumEnteredSourceFiles = 0; // Reset pragmas PragmaHandlersBackup = std::move(PragmaHandlers); PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef()); RegisterBuiltinPragmas(); // Reset PredefinesFileID PredefinesFileID = FileID(); } void Preprocessor::FinalizeForModelFile() { NumEnteredSourceFiles = 1; PragmaHandlers = std::move(PragmaHandlersBackup); } void Preprocessor::setPTHManager(PTHManager* pm) { PTH.reset(pm); FileMgr.addStatCache(PTH->createStatCache()); } void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { llvm::errs() << tok::getTokenName(Tok.getKind()) << " '" << getSpelling(Tok) << "'"; if (!DumpFlags) return; llvm::errs() << "\t"; if (Tok.isAtStartOfLine()) llvm::errs() << " [StartOfLine]"; if (Tok.hasLeadingSpace()) llvm::errs() << " [LeadingSpace]"; if (Tok.isExpandDisabled()) llvm::errs() << " [ExpandDisabled]"; if (Tok.needsCleaning()) { const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) << "']"; } llvm::errs() << "\tLoc=<"; DumpLocation(Tok.getLocation()); llvm::errs() << ">"; } void Preprocessor::DumpLocation(SourceLocation Loc) const { Loc.dump(SourceMgr); } void Preprocessor::DumpMacro(const MacroInfo &MI) const { llvm::errs() << "MACRO: "; for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { DumpToken(MI.getReplacementToken(i)); llvm::errs() << " "; } llvm::errs() << "\n"; } void Preprocessor::PrintStats() { llvm::errs() << "\n*** Preprocessor Stats:\n"; llvm::errs() << NumDirectives << " directives found:\n"; llvm::errs() << " " << NumDefined << " #define.\n"; llvm::errs() << " " << NumUndefined << " #undef.\n"; llvm::errs() << " #include/#include_next/#import:\n"; llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n"; llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n"; llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n"; llvm::errs() << " " << NumElse << " #else/#elif.\n"; llvm::errs() << " " << NumEndif << " #endif.\n"; llvm::errs() << " " << NumPragma << " #pragma.\n"; llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " << NumFastMacroExpanded << " on the fast path.\n"; llvm::errs() << (NumFastTokenPaste+NumTokenPaste) << " token paste (##) operations performed, " << NumFastTokenPaste << " on the fast path.\n"; llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total"; llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory(); llvm::errs() << "\n Macro Expanded Tokens: " << llvm::capacity_in_bytes(MacroExpandedTokens); llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity(); // FIXME: List information for all submodules. llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(CurSubmoduleState->Macros); llvm::errs() << "\n #pragma push_macro Info: " << llvm::capacity_in_bytes(PragmaPushMacroInfo); llvm::errs() << "\n Poison Reasons: " << llvm::capacity_in_bytes(PoisonReasons); llvm::errs() << "\n Comment Handlers: " << llvm::capacity_in_bytes(CommentHandlers) << "\n"; } Preprocessor::macro_iterator Preprocessor::macro_begin(bool IncludeExternalMacros) const { if (IncludeExternalMacros && ExternalSource && !ReadMacrosFromExternalSource) { ReadMacrosFromExternalSource = true; ExternalSource->ReadDefinedMacros(); } // Make sure we cover all macros in visible modules. for (const ModuleMacro &Macro : ModuleMacros) CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState())); return CurSubmoduleState->Macros.begin(); } size_t Preprocessor::getTotalMemory() const { return BP.getTotalMemory() + llvm::capacity_in_bytes(MacroExpandedTokens) + Predefines.capacity() /* Predefines buffer. */ // FIXME: Include sizes from all submodules, and include MacroInfo sizes, // and ModuleMacros. + llvm::capacity_in_bytes(CurSubmoduleState->Macros) + llvm::capacity_in_bytes(PragmaPushMacroInfo) + llvm::capacity_in_bytes(PoisonReasons) + llvm::capacity_in_bytes(CommentHandlers); } Preprocessor::macro_iterator Preprocessor::macro_end(bool IncludeExternalMacros) const { if (IncludeExternalMacros && ExternalSource && !ReadMacrosFromExternalSource) { ReadMacrosFromExternalSource = true; ExternalSource->ReadDefinedMacros(); } return CurSubmoduleState->Macros.end(); } /// \brief Compares macro tokens with a specified token value sequence. static bool MacroDefinitionEquals(const MacroInfo *MI, ArrayRef<TokenValue> Tokens) { return Tokens.size() == MI->getNumTokens() && std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin()); } StringRef Preprocessor::getLastMacroWithSpelling( SourceLocation Loc, ArrayRef<TokenValue> Tokens) const { SourceLocation BestLocation; StringRef BestSpelling; for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end(); I != E; ++I) { const MacroDirective::DefInfo Def = I->second.findDirectiveAtLoc(Loc, SourceMgr); if (!Def || !Def.getMacroInfo()) continue; if (!Def.getMacroInfo()->isObjectLike()) continue; if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens)) continue; SourceLocation Location = Def.getLocation(); // Choose the macro defined latest. if (BestLocation.isInvalid() || (Location.isValid() && SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) { BestLocation = Location; BestSpelling = I->first->getName(); } } return BestSpelling; } void Preprocessor::recomputeCurLexerKind() { if (CurLexer) CurLexerKind = CLK_Lexer; else if (CurPTHLexer) CurLexerKind = CLK_PTHLexer; else if (CurTokenLexer) CurLexerKind = CLK_TokenLexer; else CurLexerKind = CLK_CachingLexer; } bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File, unsigned CompleteLine, unsigned CompleteColumn) { assert(File); assert(CompleteLine && CompleteColumn && "Starts from 1:1"); assert(!CodeCompletionFile && "Already set"); using llvm::MemoryBuffer; // Load the actual file's contents. bool Invalid = false; const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid); if (Invalid) return true; // Find the byte position of the truncation point. const char *Position = Buffer->getBufferStart(); for (unsigned Line = 1; Line < CompleteLine; ++Line) { for (; *Position; ++Position) { if (*Position != '\r' && *Position != '\n') continue; // Eat \r\n or \n\r as a single line. if ((Position[1] == '\r' || Position[1] == '\n') && Position[0] != Position[1]) ++Position; ++Position; break; } } Position += CompleteColumn - 1; // If pointing inside the preamble, adjust the position at the beginning of // the file after the preamble. if (SkipMainFilePreamble.first && SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) { if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first) Position = Buffer->getBufferStart() + SkipMainFilePreamble.first; } if (Position > Buffer->getBufferEnd()) Position = Buffer->getBufferEnd(); CodeCompletionFile = File; CodeCompletionOffset = Position - Buffer->getBufferStart(); std::unique_ptr<MemoryBuffer> NewBuffer = MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier()); char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart()); char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf); *NewPos = '\0'; std::copy(Position, Buffer->getBufferEnd(), NewPos+1); SourceMgr.overrideFileContents(File, std::move(NewBuffer)); return false; } void Preprocessor::CodeCompleteNaturalLanguage() { if (CodeComplete) CodeComplete->CodeCompleteNaturalLanguage(); setCodeCompletionReached(); } /// getSpelling - This method is used to get the spelling of a token into a /// SmallVector. Note that the returned StringRef may not point to the /// supplied buffer if a copy can be avoided. StringRef Preprocessor::getSpelling(const Token &Tok, SmallVectorImpl<char> &Buffer, bool *Invalid) const { // NOTE: this has to be checked *before* testing for an IdentifierInfo. if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) { // Try the fast path. if (const IdentifierInfo *II = Tok.getIdentifierInfo()) return II->getName(); } // Resize the buffer if we need to copy into it. if (Tok.needsCleaning()) Buffer.resize(Tok.getLength()); const char *Ptr = Buffer.data(); unsigned Len = getSpelling(Tok, Ptr, Invalid); return StringRef(Ptr, Len); } /// CreateString - Plop the specified string into a scratch buffer and return a /// location for it. If specified, the source location provides a source /// location for the token. void Preprocessor::CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd) { Tok.setLength(Str.size()); const char *DestPtr; SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr); if (ExpansionLocStart.isValid()) Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart, ExpansionLocEnd, Str.size()); Tok.setLocation(Loc); // If this is a raw identifier or a literal token, set the pointer data. if (Tok.is(tok::raw_identifier)) Tok.setRawIdentifierData(DestPtr); else if (Tok.isLiteral()) Tok.setLiteralData(DestPtr); } Module *Preprocessor::getCurrentModule() { if (getLangOpts().CurrentModule.empty()) return nullptr; return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule); } //===----------------------------------------------------------------------===// // Preprocessor Initialization Methods //===----------------------------------------------------------------------===// /// EnterMainSourceFile - Enter the specified FileID as the main source file, /// which implicitly adds the builtin defines etc. void Preprocessor::EnterMainSourceFile() { // We do not allow the preprocessor to reenter the main file. Doing so will // cause FileID's to accumulate information from both runs (e.g. #line // information) and predefined macros aren't guaranteed to be set properly. assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!"); FileID MainFileID = SourceMgr.getMainFileID(); // If MainFileID is loaded it means we loaded an AST file, no need to enter // a main file. if (!SourceMgr.isLoadedFileID(MainFileID)) { // Enter the main file source buffer. EnterSourceFile(MainFileID, nullptr, SourceLocation()); // If we've been asked to skip bytes in the main file (e.g., as part of a // precompiled preamble), do so now. if (SkipMainFilePreamble.first > 0) CurLexer->SkipBytes(SkipMainFilePreamble.first, SkipMainFilePreamble.second); // Tell the header info that the main file was entered. If the file is later // #imported, it won't be re-entered. if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) HeaderInfo.IncrementIncludeCount(FE); } // Preprocess Predefines to populate the initial preprocessor state. std::unique_ptr<llvm::MemoryBuffer> SB = llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>"); if (SB.get() == nullptr) throw std::bad_alloc(); // HLSL Change assert(SB && "Cannot create predefined source buffer"); FileID FID = SourceMgr.createFileID(std::move(SB)); assert(!FID.isInvalid() && "Could not create FileID for predefines?"); setPredefinesFileID(FID); // Start parsing the predefines. EnterSourceFile(FID, nullptr, SourceLocation()); } void Preprocessor::EndSourceFile() { // Notify the client that we reached the end of the source file. if (Callbacks) Callbacks->EndOfMainFile(); } //===----------------------------------------------------------------------===// // Lexer Event Handling. //===----------------------------------------------------------------------===// /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the /// identifier information for the token and install it into the token, /// updating the token kind accordingly. IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const { assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!"); // Look up this token, see if it is a macro, or if it is a language keyword. IdentifierInfo *II; if (!Identifier.needsCleaning() && !Identifier.hasUCN()) { // No cleaning needed, just use the characters from the lexed buffer. II = getIdentifierInfo(Identifier.getRawIdentifier()); } else { // Cleaning needed, alloca a buffer, clean into it, then use the buffer. SmallString<64> IdentifierBuffer; StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer); if (Identifier.hasUCN()) { SmallString<64> UCNIdentifierBuffer; expandUCNs(UCNIdentifierBuffer, CleanedStr); II = getIdentifierInfo(UCNIdentifierBuffer); } else { II = getIdentifierInfo(CleanedStr); } } // Update the token info (identifier info and appropriate token kind). Identifier.setIdentifierInfo(II); Identifier.setKind(II->getTokenID()); return II; } void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) { PoisonReasons[II] = DiagID; } void Preprocessor::PoisonSEHIdentifiers(bool Poison) { assert(Ident__exception_code && Ident__exception_info); assert(Ident___exception_code && Ident___exception_info); Ident__exception_code->setIsPoisoned(Poison); Ident___exception_code->setIsPoisoned(Poison); Ident_GetExceptionCode->setIsPoisoned(Poison); Ident__exception_info->setIsPoisoned(Poison); Ident___exception_info->setIsPoisoned(Poison); Ident_GetExceptionInfo->setIsPoisoned(Poison); Ident__abnormal_termination->setIsPoisoned(Poison); Ident___abnormal_termination->setIsPoisoned(Poison); Ident_AbnormalTermination->setIsPoisoned(Poison); } void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) { assert(Identifier.getIdentifierInfo() && "Can't handle identifiers without identifier info!"); llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it = PoisonReasons.find(Identifier.getIdentifierInfo()); if(it == PoisonReasons.end()) Diag(Identifier, diag::err_pp_used_poisoned_id); else Diag(Identifier,it->second) << Identifier.getIdentifierInfo(); } /// \brief Returns a diagnostic message kind for reporting a future keyword as /// appropriate for the identifier and specified language. static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II, const LangOptions &LangOpts) { assert(II.isFutureCompatKeyword() && "diagnostic should not be needed"); if (LangOpts.CPlusPlus) return llvm::StringSwitch<diag::kind>(II.getName()) #define CXX11_KEYWORD(NAME, FLAGS) \ .Case(#NAME, diag::warn_cxx11_keyword) #include "clang/Basic/TokenKinds.def" ; llvm_unreachable( "Keyword not known to come from a newer Standard or proposed Standard"); } /// HandleIdentifier - This callback is invoked when the lexer reads an /// identifier. This callback looks up the identifier in the map and/or /// potentially macro expands it or turns it into a named token (like 'for'). /// /// Note that callers of this method are guarded by checking the /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the /// IdentifierInfo methods that compute these properties will need to change to /// match. bool Preprocessor::HandleIdentifier(Token &Identifier) { assert(Identifier.getIdentifierInfo() && "Can't handle identifiers without identifier info!"); IdentifierInfo &II = *Identifier.getIdentifierInfo(); // If the information about this identifier is out of date, update it from // the external source. // We have to treat __VA_ARGS__ in a special way, since it gets // serialized with isPoisoned = true, but our preprocessor may have // unpoisoned it if we're defining a C99 macro. if (II.isOutOfDate()) { bool CurrentIsPoisoned = false; if (&II == Ident__VA_ARGS__) CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned(); ExternalSource->updateOutOfDateIdentifier(II); Identifier.setKind(II.getTokenID()); if (&II == Ident__VA_ARGS__) II.setIsPoisoned(CurrentIsPoisoned); } // If this identifier was poisoned, and if it was not produced from a macro // expansion, emit an error. if (II.isPoisoned() && CurPPLexer) { HandlePoisonedIdentifier(Identifier); } // If this is a macro to be expanded, do it. if (MacroDefinition MD = getMacroDefinition(&II)) { auto *MI = MD.getMacroInfo(); assert(MI && "macro definition with no macro info?"); if (!DisableMacroExpansion) { if (!Identifier.isExpandDisabled() && MI->isEnabled()) { // C99 6.10.3p10: If the preprocessing token immediately after the // macro name isn't a '(', this macro should not be expanded. if (!MI->isFunctionLike() || isNextPPTokenLParen()) return HandleMacroExpandedIdentifier(Identifier, MD); } else { // C99 6.10.3.4p2 says that a disabled macro may never again be // expanded, even if it's in a context where it could be expanded in the // future. Identifier.setFlag(Token::DisableExpand); if (MI->isObjectLike() || isNextPPTokenLParen()) Diag(Identifier, diag::pp_disabled_macro_expansion); } } } // If this identifier is a keyword in a newer Standard or proposed Standard, // produce a warning. Don't warn if we're not considering macro expansion, // since this identifier might be the name of a macro. // FIXME: This warning is disabled in cases where it shouldn't be, like // "#define constexpr constexpr", "int constexpr;" if (II.isFutureCompatKeyword() && !DisableMacroExpansion) { Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts())) << II.getName(); // Don't diagnose this keyword again in this translation unit. II.setIsFutureCompatKeyword(false); } // C++ 2.11p2: If this is an alternative representation of a C++ operator, // then we act as if it is the actual operator and not the textual // representation of it. if (II.isCPlusPlusOperatorKeyword()) Identifier.setIdentifierInfo(nullptr); // If this is an extension token, diagnose its use. // We avoid diagnosing tokens that originate from macro definitions. // FIXME: This warning is disabled in cases where it shouldn't be, // like "#define TY typeof", "TY(1) x". if (II.isExtensionToken() && !DisableMacroExpansion) Diag(Identifier, diag::ext_token_used); // If this is the 'import' contextual keyword following an '@', note // that the next token indicates a module name. // // Note that we do not treat 'import' as a contextual // keyword when we're in a caching lexer, because caching lexers only get // used in contexts where import declarations are disallowed. if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs && !DisableMacroExpansion && (getLangOpts().Modules || getLangOpts().DebuggerSupport) && CurLexerKind != CLK_CachingLexer) { ModuleImportLoc = Identifier.getLocation(); ModuleImportPath.clear(); ModuleImportExpectsIdentifier = true; CurLexerKind = CLK_LexAfterModuleImport; } return true; } void Preprocessor::Lex(Token &Result) { // We loop here until a lex function retuns a token; this avoids recursion. bool ReturnedToken; do { switch (CurLexerKind) { case CLK_Lexer: ReturnedToken = CurLexer->Lex(Result); break; case CLK_PTHLexer: ReturnedToken = CurPTHLexer->Lex(Result); break; case CLK_TokenLexer: ReturnedToken = CurTokenLexer->Lex(Result); break; case CLK_CachingLexer: CachingLex(Result); ReturnedToken = true; break; // case CLK_LexAfterModuleImport: // HLSL Change - there is no other value default: assert(CurLexerKind == CLK_LexAfterModuleImport); LexAfterModuleImport(Result); ReturnedToken = true; break; } } while (!ReturnedToken); LastTokenWasAt = Result.is(tok::at); } /// \brief Lex a token following the 'import' contextual keyword. /// void Preprocessor::LexAfterModuleImport(Token &Result) { // Figure out what kind of lexer we actually have. recomputeCurLexerKind(); // Lex the next token. Lex(Result); // The token sequence // // import identifier (. identifier)* // // indicates a module import directive. We already saw the 'import' // contextual keyword, so now we're looking for the identifiers. if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) { // We expected to see an identifier here, and we did; continue handling // identifiers. ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(), Result.getLocation())); ModuleImportExpectsIdentifier = false; CurLexerKind = CLK_LexAfterModuleImport; return; } // If we're expecting a '.' or a ';', and we got a '.', then wait until we // see the next identifier. if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) { ModuleImportExpectsIdentifier = true; CurLexerKind = CLK_LexAfterModuleImport; return; } // If we have a non-empty module path, load the named module. if (!ModuleImportPath.empty()) { Module *Imported = nullptr; if (getLangOpts().Modules) { Imported = TheModuleLoader.loadModule(ModuleImportLoc, ModuleImportPath, Module::Hidden, /*IsIncludeDirective=*/false); if (Imported) makeModuleVisible(Imported, ModuleImportLoc); } if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport)) Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported); } } void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) { CurSubmoduleState->VisibleModules.setVisible( M, Loc, [](Module *) {}, [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) { // FIXME: Include the path in the diagnostic. // FIXME: Include the import location for the conflicting module. Diag(ModuleImportLoc, diag::warn_module_conflict) << Path[0]->getFullModuleName() << Conflict->getFullModuleName() << Message; }); // Add this module to the imports list of the currently-built submodule. if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M) BuildingSubmoduleStack.back().M->Imports.insert(M); } bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion) { // We need at least one string literal. if (Result.isNot(tok::string_literal)) { Diag(Result, diag::err_expected_string_literal) << /*Source='in...'*/0 << DiagnosticTag; return false; } // Lex string literal tokens, optionally with macro expansion. SmallVector<Token, 4> StrToks; do { StrToks.push_back(Result); if (Result.hasUDSuffix()) Diag(Result, diag::err_invalid_string_udl); if (AllowMacroExpansion) Lex(Result); else LexUnexpandedToken(Result); } while (Result.is(tok::string_literal)); // Concatenate and parse the strings. StringLiteralParser Literal(StrToks, *this); assert(Literal.isAscii() && "Didn't allow wide strings in"); if (Literal.hadError) return false; if (Literal.Pascal) { Diag(StrToks[0].getLocation(), diag::err_expected_string_literal) << /*Source='in...'*/0 << DiagnosticTag; return false; } String = Literal.GetString(); return true; } bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) { assert(Tok.is(tok::numeric_constant)); SmallString<8> IntegerBuffer; bool NumberInvalid = false; StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid); if (NumberInvalid) return false; NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this); if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix()) return false; llvm::APInt APVal(64, 0); if (Literal.GetIntegerValue(APVal)) return false; Lex(Tok); Value = APVal.getLimitedValue(); return true; } void Preprocessor::addCommentHandler(CommentHandler *Handler) { assert(Handler && "NULL comment handler"); assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) == CommentHandlers.end() && "Comment handler already registered"); CommentHandlers.push_back(Handler); } void Preprocessor::removeCommentHandler(CommentHandler *Handler) { std::vector<CommentHandler *>::iterator Pos = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler); assert(Pos != CommentHandlers.end() && "Comment handler not registered"); CommentHandlers.erase(Pos); } bool Preprocessor::HandleComment(Token &result, SourceRange Comment) { bool AnyPendingTokens = false; for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(), HEnd = CommentHandlers.end(); H != HEnd; ++H) { if ((*H)->HandleComment(*this, Comment)) AnyPendingTokens = true; } if (!AnyPendingTokens || getCommentRetentionState()) return false; Lex(result); return true; } ModuleLoader::~ModuleLoader() { } CommentHandler::~CommentHandler() { } CodeCompletionHandler::~CodeCompletionHandler() { } void Preprocessor::createPreprocessingRecord() { if (Record) return; Record = new PreprocessingRecord(getSourceManager()); addPPCallbacks(std::unique_ptr<PPCallbacks>(Record)); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/TokenLexer.cpp
//===--- TokenLexer.cpp - Lex from a token stream -------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TokenLexer interface. // //===----------------------------------------------------------------------===// #include "clang/Lex/TokenLexer.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/MacroArgs.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" // HLSL Change #include "llvm/ADT/SmallString.h" using namespace clang; /// Create a TokenLexer for the specified macro with the specified actual /// arguments. Note that this ctor takes ownership of the ActualArgs pointer. void TokenLexer::Init(Token &Tok, SourceLocation ELEnd, MacroInfo *MI, MacroArgs *Actuals) { // If the client is reusing a TokenLexer, make sure to free any memory // associated with it. destroy(); Macro = MI; ActualArgs = Actuals; CurToken = 0; ExpandLocStart = Tok.getLocation(); ExpandLocEnd = ELEnd; AtStartOfLine = Tok.isAtStartOfLine(); HasLeadingSpace = Tok.hasLeadingSpace(); NextTokGetsSpace = false; Tokens = &*Macro->tokens_begin(); OwnsTokens = false; DisableMacroExpansion = false; NumTokens = Macro->tokens_end()-Macro->tokens_begin(); MacroExpansionStart = SourceLocation(); SourceManager &SM = PP.getSourceManager(); MacroStartSLocOffset = SM.getNextLocalOffset(); if (NumTokens > 0) { assert(Tokens[0].getLocation().isValid()); assert((Tokens[0].getLocation().isFileID() || Tokens[0].is(tok::comment)) && "Macro defined in macro?"); assert(ExpandLocStart.isValid()); // Reserve a source location entry chunk for the length of the macro // definition. Tokens that get lexed directly from the definition will // have their locations pointing inside this chunk. This is to avoid // creating separate source location entries for each token. MacroDefStart = SM.getExpansionLoc(Tokens[0].getLocation()); MacroDefLength = Macro->getDefinitionLength(SM); MacroExpansionStart = SM.createExpansionLoc(MacroDefStart, ExpandLocStart, ExpandLocEnd, MacroDefLength); } // If this is a function-like macro, expand the arguments and change // Tokens to point to the expanded tokens. if (Macro->isFunctionLike() && Macro->getNumArgs()) ExpandFunctionArguments(); // Mark the macro as currently disabled, so that it is not recursively // expanded. The macro must be disabled only after argument pre-expansion of // function-like macro arguments occurs. Macro->DisableMacro(); } /// Create a TokenLexer for the specified token stream. This does not /// take ownership of the specified token vector. void TokenLexer::Init(const Token *TokArray, unsigned NumToks, bool disableMacroExpansion, bool ownsTokens) { // If the client is reusing a TokenLexer, make sure to free any memory // associated with it. destroy(); Macro = nullptr; ActualArgs = nullptr; Tokens = TokArray; OwnsTokens = ownsTokens; DisableMacroExpansion = disableMacroExpansion; NumTokens = NumToks; CurToken = 0; ExpandLocStart = ExpandLocEnd = SourceLocation(); AtStartOfLine = false; HasLeadingSpace = false; NextTokGetsSpace = false; MacroExpansionStart = SourceLocation(); // Set HasLeadingSpace/AtStartOfLine so that the first token will be // returned unmodified. if (NumToks != 0) { AtStartOfLine = TokArray[0].isAtStartOfLine(); HasLeadingSpace = TokArray[0].hasLeadingSpace(); } } void TokenLexer::destroy() { // If this was a function-like macro that actually uses its arguments, delete // the expanded tokens. if (OwnsTokens) { delete [] Tokens; Tokens = nullptr; OwnsTokens = false; } // TokenLexer owns its formal arguments. if (ActualArgs) ActualArgs->destroy(PP); } bool TokenLexer::MaybeRemoveCommaBeforeVaArgs( SmallVectorImpl<Token> &ResultToks, bool HasPasteOperator, MacroInfo *Macro, unsigned MacroArgNo, Preprocessor &PP) { // Is the macro argument __VA_ARGS__? if (!Macro->isVariadic() || MacroArgNo != Macro->getNumArgs()-1) return false; // In Microsoft-compatibility mode, a comma is removed in the expansion // of " ... , __VA_ARGS__ " if __VA_ARGS__ is empty. This extension is // not supported by gcc. if (!HasPasteOperator && !PP.getLangOpts().MSVCCompat) return false; // GCC removes the comma in the expansion of " ... , ## __VA_ARGS__ " if // __VA_ARGS__ is empty, but not in strict C99 mode where there are no // named arguments, where it remains. In all other modes, including C99 // with GNU extensions, it is removed regardless of named arguments. // Microsoft also appears to support this extension, unofficially. if (PP.getLangOpts().C99 && !PP.getLangOpts().GNUMode && Macro->getNumArgs() < 2) return false; // Is a comma available to be removed? if (ResultToks.empty() || !ResultToks.back().is(tok::comma)) return false; // Issue an extension diagnostic for the paste operator. if (HasPasteOperator) PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma); // Remove the comma. ResultToks.pop_back(); // If the comma was right after another paste (e.g. "X##,##__VA_ARGS__"), // then removal of the comma should produce a placemarker token (in C99 // terms) which we model by popping off the previous ##, giving us a plain // "X" when __VA_ARGS__ is empty. if (!ResultToks.empty() && ResultToks.back().is(tok::hashhash)) ResultToks.pop_back(); // Never add a space, even if the comma, ##, or arg had a space. NextTokGetsSpace = false; return true; } /// Expand the arguments of a function-like macro so that we can quickly /// return preexpanded tokens from Tokens. void TokenLexer::ExpandFunctionArguments() { SmallVector<Token, 128> ResultToks; // Loop through 'Tokens', expanding them into ResultToks. Keep // track of whether we change anything. If not, no need to keep them. If so, // we install the newly expanded sequence as the new 'Tokens' list. bool MadeChange = false; for (unsigned i = 0, e = NumTokens; i != e; ++i) { // If we found the stringify operator, get the argument stringified. The // preprocessor already verified that the following token is a macro name // when the #define was parsed. const Token &CurTok = Tokens[i]; if (i != 0 && !Tokens[i-1].is(tok::hashhash) && CurTok.hasLeadingSpace()) NextTokGetsSpace = true; if (CurTok.isOneOf(tok::hash, tok::hashat)) { int ArgNo = Macro->getArgumentNum(Tokens[i+1].getIdentifierInfo()); assert(ArgNo != -1 && "Token following # is not an argument?"); SourceLocation ExpansionLocStart = getExpansionLocForMacroDefLoc(CurTok.getLocation()); SourceLocation ExpansionLocEnd = getExpansionLocForMacroDefLoc(Tokens[i+1].getLocation()); Token Res; if (CurTok.is(tok::hash)) // Stringify Res = ActualArgs->getStringifiedArgument(ArgNo, PP, ExpansionLocStart, ExpansionLocEnd); else { // 'charify': don't bother caching these. Res = MacroArgs::StringifyArgument(ActualArgs->getUnexpArgument(ArgNo), PP, true, ExpansionLocStart, ExpansionLocEnd); } Res.setFlag(Token::StringifiedInMacro); // The stringified/charified string leading space flag gets set to match // the #/#@ operator. if (NextTokGetsSpace) Res.setFlag(Token::LeadingSpace); ResultToks.push_back(Res); MadeChange = true; ++i; // Skip arg name. NextTokGetsSpace = false; continue; } // Find out if there is a paste (##) operator before or after the token. bool NonEmptyPasteBefore = !ResultToks.empty() && ResultToks.back().is(tok::hashhash); bool PasteBefore = i != 0 && Tokens[i-1].is(tok::hashhash); bool PasteAfter = i+1 != e && Tokens[i+1].is(tok::hashhash); assert(!NonEmptyPasteBefore || PasteBefore); // Otherwise, if this is not an argument token, just add the token to the // output buffer. IdentifierInfo *II = CurTok.getIdentifierInfo(); int ArgNo = II ? Macro->getArgumentNum(II) : -1; if (ArgNo == -1) { // This isn't an argument, just add it. ResultToks.push_back(CurTok); if (NextTokGetsSpace) { ResultToks.back().setFlag(Token::LeadingSpace); NextTokGetsSpace = false; } else if (PasteBefore && !NonEmptyPasteBefore) ResultToks.back().clearFlag(Token::LeadingSpace); continue; } // An argument is expanded somehow, the result is different than the // input. MadeChange = true; // Otherwise, this is a use of the argument. // In Microsoft mode, remove the comma before __VA_ARGS__ to ensure there // are no trailing commas if __VA_ARGS__ is empty. if (!PasteBefore && ActualArgs->isVarargsElidedUse() && MaybeRemoveCommaBeforeVaArgs(ResultToks, /*HasPasteOperator=*/false, Macro, ArgNo, PP)) continue; // If it is not the LHS/RHS of a ## operator, we must pre-expand the // argument and substitute the expanded tokens into the result. This is // C99 6.10.3.1p1. if (PP.PPOpts.get()->ExpandTokPastingArg || (!PasteBefore && !PasteAfter)) { // HLSL Change const Token *ResultArgToks; // Only preexpand the argument if it could possibly need it. This // avoids some work in common cases. const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo); if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP)) ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, Macro, PP)[0]; else ResultArgToks = ArgTok; // Use non-preexpanded tokens. // If the arg token expanded into anything, append it. if (ResultArgToks->isNot(tok::eof)) { unsigned FirstResult = ResultToks.size(); unsigned NumToks = MacroArgs::getArgLength(ResultArgToks); ResultToks.append(ResultArgToks, ResultArgToks+NumToks); // In Microsoft-compatibility mode, we follow MSVC's preprocessing // behavior by not considering single commas from nested macro // expansions as argument separators. Set a flag on the token so we can // test for this later when the macro expansion is processed. if (PP.getLangOpts().MSVCCompat && NumToks == 1 && ResultToks.back().is(tok::comma)) ResultToks.back().setFlag(Token::IgnoredComma); // If the '##' came from expanding an argument, turn it into 'unknown' // to avoid pasting. for (unsigned i = FirstResult, e = ResultToks.size(); i != e; ++i) { Token &Tok = ResultToks[i]; if (Tok.is(tok::hashhash)) Tok.setKind(tok::unknown); } if(ExpandLocStart.isValid()) { updateLocForMacroArgTokens(CurTok.getLocation(), ResultToks.begin()+FirstResult, ResultToks.end()); } // If any tokens were substituted from the argument, the whitespace // before the first token should match the whitespace of the arg // identifier. ResultToks[FirstResult].setFlagValue(Token::LeadingSpace, NextTokGetsSpace); NextTokGetsSpace = false; } continue; } // Okay, we have a token that is either the LHS or RHS of a paste (##) // argument. It gets substituted as its non-pre-expanded tokens. const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo); unsigned NumToks = MacroArgs::getArgLength(ArgToks); if (NumToks) { // Not an empty argument? // If this is the GNU ", ## __VA_ARGS__" extension, and we just learned // that __VA_ARGS__ expands to multiple tokens, avoid a pasting error when // the expander trys to paste ',' with the first token of the __VA_ARGS__ // expansion. if (NonEmptyPasteBefore && ResultToks.size() >= 2 && ResultToks[ResultToks.size()-2].is(tok::comma) && (unsigned)ArgNo == Macro->getNumArgs()-1 && Macro->isVariadic()) { // Remove the paste operator, report use of the extension. PP.Diag(ResultToks.pop_back_val().getLocation(), diag::ext_paste_comma); } ResultToks.append(ArgToks, ArgToks+NumToks); // If the '##' came from expanding an argument, turn it into 'unknown' // to avoid pasting. for (unsigned i = ResultToks.size() - NumToks, e = ResultToks.size(); i != e; ++i) { Token &Tok = ResultToks[i]; if (Tok.is(tok::hashhash)) Tok.setKind(tok::unknown); } if (ExpandLocStart.isValid()) { updateLocForMacroArgTokens(CurTok.getLocation(), ResultToks.end()-NumToks, ResultToks.end()); } // If this token (the macro argument) was supposed to get leading // whitespace, transfer this information onto the first token of the // expansion. // // Do not do this if the paste operator occurs before the macro argument, // as in "A ## MACROARG". In valid code, the first token will get // smooshed onto the preceding one anyway (forming AMACROARG). In // assembler-with-cpp mode, invalid pastes are allowed through: in this // case, we do not want the extra whitespace to be added. For example, // we want ". ## foo" -> ".foo" not ". foo". if (NextTokGetsSpace) ResultToks[ResultToks.size()-NumToks].setFlag(Token::LeadingSpace); NextTokGetsSpace = false; continue; } // If an empty argument is on the LHS or RHS of a paste, the standard (C99 // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We // implement this by eating ## operators when a LHS or RHS expands to // empty. if (PasteAfter) { // Discard the argument token and skip (don't copy to the expansion // buffer) the paste operator after it. ++i; continue; } // If this is on the RHS of a paste operator, we've already copied the // paste operator to the ResultToks list, unless the LHS was empty too. // Remove it. assert(PasteBefore); if (NonEmptyPasteBefore) { assert(ResultToks.back().is(tok::hashhash)); ResultToks.pop_back(); } // If this is the __VA_ARGS__ token, and if the argument wasn't provided, // and if the macro had at least one real argument, and if the token before // the ## was a comma, remove the comma. This is a GCC extension which is // disabled when using -std=c99. if (ActualArgs->isVarargsElidedUse()) MaybeRemoveCommaBeforeVaArgs(ResultToks, /*HasPasteOperator=*/true, Macro, ArgNo, PP); continue; } // If anything changed, install this as the new Tokens list. if (MadeChange) { assert(!OwnsTokens && "This would leak if we already own the token list"); // This is deleted in the dtor. NumTokens = ResultToks.size(); // The tokens will be added to Preprocessor's cache and will be removed // when this TokenLexer finishes lexing them. Tokens = PP.cacheMacroExpandedTokens(this, ResultToks); // The preprocessor cache of macro expanded tokens owns these tokens,not us. OwnsTokens = false; } } /// \brief Checks if two tokens form wide string literal. static bool isWideStringLiteralFromMacro(const Token &FirstTok, const Token &SecondTok) { return FirstTok.is(tok::identifier) && FirstTok.getIdentifierInfo()->isStr("L") && SecondTok.isLiteral() && SecondTok.stringifiedInMacro(); } /// Lex - Lex and return a token from this macro stream. /// bool TokenLexer::Lex(Token &Tok) { // Lexing off the end of the macro, pop this macro off the expansion stack. if (isAtEnd()) { // If this is a macro (not a token stream), mark the macro enabled now // that it is no longer being expanded. if (Macro) Macro->EnableMacro(); Tok.startToken(); Tok.setFlagValue(Token::StartOfLine , AtStartOfLine); Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace || NextTokGetsSpace); if (CurToken == 0) Tok.setFlag(Token::LeadingEmptyMacro); return PP.HandleEndOfTokenLexer(Tok); } SourceManager &SM = PP.getSourceManager(); // If this is the first token of the expanded result, we inherit spacing // properties later. bool isFirstToken = CurToken == 0; // Get the next token to return. Tok = Tokens[CurToken++]; bool TokenIsFromPaste = false; // If this token is followed by a token paste (##) operator, paste the tokens! // Note that ## is a normal token when not expanding a macro. if (!isAtEnd() && Macro && (Tokens[CurToken].is(tok::hashhash) || // Special processing of L#x macros in -fms-compatibility mode. // Microsoft compiler is able to form a wide string literal from // 'L#macro_arg' construct in a function-like macro. (PP.getLangOpts().MSVCCompat && isWideStringLiteralFromMacro(Tok, Tokens[CurToken])))) { // When handling the microsoft /##/ extension, the final token is // returned by PasteTokens, not the pasted token. if (PasteTokens(Tok)) return true; TokenIsFromPaste = true; } // The token's current location indicate where the token was lexed from. We // need this information to compute the spelling of the token, but any // diagnostics for the expanded token should appear as if they came from // ExpansionLoc. Pull this information together into a new SourceLocation // that captures all of this. if (ExpandLocStart.isValid() && // Don't do this for token streams. // Check that the token's location was not already set properly. SM.isBeforeInSLocAddrSpace(Tok.getLocation(), MacroStartSLocOffset)) { SourceLocation instLoc; if (Tok.is(tok::comment)) { instLoc = SM.createExpansionLoc(Tok.getLocation(), ExpandLocStart, ExpandLocEnd, Tok.getLength()); } else { instLoc = getExpansionLocForMacroDefLoc(Tok.getLocation()); } Tok.setLocation(instLoc); } // If this is the first token, set the lexical properties of the token to // match the lexical properties of the macro identifier. if (isFirstToken) { Tok.setFlagValue(Token::StartOfLine , AtStartOfLine); Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace); } else { // If this is not the first token, we may still need to pass through // leading whitespace if we've expanded a macro. if (AtStartOfLine) Tok.setFlag(Token::StartOfLine); if (HasLeadingSpace) Tok.setFlag(Token::LeadingSpace); } AtStartOfLine = false; HasLeadingSpace = false; // Handle recursive expansion! if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) { // Change the kind of this identifier to the appropriate token kind, e.g. // turning "for" into a keyword. IdentifierInfo *II = Tok.getIdentifierInfo(); Tok.setKind(II->getTokenID()); // If this identifier was poisoned and from a paste, emit an error. This // won't be handled by Preprocessor::HandleIdentifier because this is coming // from a macro expansion. if (II->isPoisoned() && TokenIsFromPaste) { PP.HandlePoisonedIdentifier(Tok); } if (!DisableMacroExpansion && II->isHandleIdentifierCase()) return PP.HandleIdentifier(Tok); } // Otherwise, return a normal token. return true; } /// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ## /// operator. Read the ## and RHS, and paste the LHS/RHS together. If there /// are more ## after it, chomp them iteratively. Return the result as Tok. /// If this returns true, the caller should immediately return the token. bool TokenLexer::PasteTokens(Token &Tok) { // MSVC: If previous token was pasted, this must be a recovery from an invalid // paste operation. Ignore spaces before this token to mimic MSVC output. // Required for generating valid UUID strings in some MS headers. if (PP.getLangOpts().MicrosoftExt && (CurToken >= 2) && Tokens[CurToken - 2].is(tok::hashhash)) Tok.clearFlag(Token::LeadingSpace); SmallString<128> Buffer; const char *ResultTokStrPtr = nullptr; SourceLocation StartLoc = Tok.getLocation(); SourceLocation PasteOpLoc; do { // Consume the ## operator if any. PasteOpLoc = Tokens[CurToken].getLocation(); if (Tokens[CurToken].is(tok::hashhash)) ++CurToken; assert(!isAtEnd() && "No token on the RHS of a paste operator!"); // Get the RHS token. const Token &RHS = Tokens[CurToken]; // Allocate space for the result token. This is guaranteed to be enough for // the two tokens. Buffer.resize(Tok.getLength() + RHS.getLength()); // Get the spelling of the LHS token in Buffer. const char *BufPtr = &Buffer[0]; bool Invalid = false; unsigned LHSLen = PP.getSpelling(Tok, BufPtr, &Invalid); if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer! memcpy(&Buffer[0], BufPtr, LHSLen); if (Invalid) return true; BufPtr = Buffer.data() + LHSLen; unsigned RHSLen = PP.getSpelling(RHS, BufPtr, &Invalid); if (Invalid) return true; if (RHSLen && BufPtr != &Buffer[LHSLen]) // Really, we want the chars in Buffer! memcpy(&Buffer[LHSLen], BufPtr, RHSLen); // Trim excess space. Buffer.resize(LHSLen+RHSLen); // Plop the pasted result (including the trailing newline and null) into a // scratch buffer where we can lex it. Token ResultTokTmp; ResultTokTmp.startToken(); // Claim that the tmp token is a string_literal so that we can get the // character pointer back from CreateString in getLiteralData(). ResultTokTmp.setKind(tok::string_literal); PP.CreateString(Buffer, ResultTokTmp); SourceLocation ResultTokLoc = ResultTokTmp.getLocation(); ResultTokStrPtr = ResultTokTmp.getLiteralData(); // Lex the resultant pasted token into Result. Token Result; if (Tok.isAnyIdentifier() && RHS.isAnyIdentifier()) { // Common paste case: identifier+identifier = identifier. Avoid creating // a lexer and other overhead. PP.IncrementPasteCounter(true); Result.startToken(); Result.setKind(tok::raw_identifier); Result.setRawIdentifierData(ResultTokStrPtr); Result.setLocation(ResultTokLoc); Result.setLength(LHSLen+RHSLen); } else { PP.IncrementPasteCounter(false); assert(ResultTokLoc.isFileID() && "Should be a raw location into scratch buffer"); SourceManager &SourceMgr = PP.getSourceManager(); FileID LocFileID = SourceMgr.getFileID(ResultTokLoc); bool Invalid = false; const char *ScratchBufStart = SourceMgr.getBufferData(LocFileID, &Invalid).data(); if (Invalid) return false; // Make a lexer to lex this string from. Lex just this one token. // Make a lexer object so that we lex and expand the paste result. Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID), PP.getLangOpts(), ScratchBufStart, ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen); // Lex a token in raw mode. This way it won't look up identifiers // automatically, lexing off the end will return an eof token, and // warnings are disabled. This returns true if the result token is the // entire buffer. bool isInvalid = !TL.LexFromRawLexer(Result); // If we got an EOF token, we didn't form even ONE token. For example, we // did "/ ## /" to get "//". isInvalid |= Result.is(tok::eof); // If pasting the two tokens didn't form a full new token, this is an // error. This occurs with "x ## +" and other stuff. Return with Tok // unmodified and with RHS as the next token to lex. if (isInvalid) { // Test for the Microsoft extension of /##/ turning into // here on the // error path. if (PP.getLangOpts().MicrosoftExt && Tok.is(tok::slash) && RHS.is(tok::slash)) { HandleMicrosoftCommentPaste(Tok); return true; } // Do not emit the error when preprocessing assembler code. if (!PP.getLangOpts().AsmPreprocessor) { // Explicitly convert the token location to have proper expansion // information so that the user knows where it came from. SourceManager &SM = PP.getSourceManager(); SourceLocation Loc = SM.createExpansionLoc(PasteOpLoc, ExpandLocStart, ExpandLocEnd, 2); // If we're in microsoft extensions mode, downgrade this from a hard // error to an extension that defaults to an error. This allows // disabling it. PP.Diag(Loc, PP.getLangOpts().MicrosoftExt ? diag::ext_pp_bad_paste_ms : diag::err_pp_bad_paste) << Buffer; } // An error has occurred so exit loop. break; } // Turn ## into 'unknown' to avoid # ## # from looking like a paste // operator. if (Result.is(tok::hashhash)) Result.setKind(tok::unknown); } // Transfer properties of the LHS over the Result. Result.setFlagValue(Token::StartOfLine , Tok.isAtStartOfLine()); Result.setFlagValue(Token::LeadingSpace, Tok.hasLeadingSpace()); // Finally, replace LHS with the result, consume the RHS, and iterate. ++CurToken; Tok = Result; } while (!isAtEnd() && Tokens[CurToken].is(tok::hashhash)); SourceLocation EndLoc = Tokens[CurToken - 1].getLocation(); // The token's current location indicate where the token was lexed from. We // need this information to compute the spelling of the token, but any // diagnostics for the expanded token should appear as if the token was // expanded from the full ## expression. Pull this information together into // a new SourceLocation that captures all of this. SourceManager &SM = PP.getSourceManager(); if (StartLoc.isFileID()) StartLoc = getExpansionLocForMacroDefLoc(StartLoc); if (EndLoc.isFileID()) EndLoc = getExpansionLocForMacroDefLoc(EndLoc); FileID MacroFID = SM.getFileID(MacroExpansionStart); while (SM.getFileID(StartLoc) != MacroFID) StartLoc = SM.getImmediateExpansionRange(StartLoc).first; while (SM.getFileID(EndLoc) != MacroFID) EndLoc = SM.getImmediateExpansionRange(EndLoc).second; Tok.setLocation(SM.createExpansionLoc(Tok.getLocation(), StartLoc, EndLoc, Tok.getLength())); // Now that we got the result token, it will be subject to expansion. Since // token pasting re-lexes the result token in raw mode, identifier information // isn't looked up. As such, if the result is an identifier, look up id info. if (Tok.is(tok::raw_identifier)) { // Look up the identifier info for the token. We disabled identifier lookup // by saying we're skipping contents, so we need to do this manually. PP.LookUpIdentifierInfo(Tok); } return false; } /// isNextTokenLParen - If the next token lexed will pop this macro off the /// expansion stack, return 2. If the next unexpanded token is a '(', return /// 1, otherwise return 0. unsigned TokenLexer::isNextTokenLParen() const { // Out of tokens? if (isAtEnd()) return 2; return Tokens[CurToken].is(tok::l_paren); } /// isParsingPreprocessorDirective - Return true if we are in the middle of a /// preprocessor directive. bool TokenLexer::isParsingPreprocessorDirective() const { return Tokens[NumTokens-1].is(tok::eod) && !isAtEnd(); } /// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes /// together to form a comment that comments out everything in the current /// macro, other active macros, and anything left on the current physical /// source line of the expanded buffer. Handle this by returning the /// first token on the next line. void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok) { // We 'comment out' the rest of this macro by just ignoring the rest of the // tokens that have not been lexed yet, if any. // Since this must be a macro, mark the macro enabled now that it is no longer // being expanded. assert(Macro && "Token streams can't paste comments"); Macro->EnableMacro(); PP.HandleMicrosoftCommentPaste(Tok); } /// \brief If \arg loc is a file ID and points inside the current macro /// definition, returns the appropriate source location pointing at the /// macro expansion source location entry, otherwise it returns an invalid /// SourceLocation. SourceLocation TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const { assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() && "Not appropriate for token streams"); assert(loc.isValid() && loc.isFileID()); SourceManager &SM = PP.getSourceManager(); assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) && "Expected loc to come from the macro definition"); unsigned relativeOffset = 0; SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength, &relativeOffset); return MacroExpansionStart.getLocWithOffset(relativeOffset); } /// \brief Finds the tokens that are consecutive (from the same FileID) /// creates a single SLocEntry, and assigns SourceLocations to each token that /// point to that SLocEntry. e.g for /// assert(foo == bar); /// There will be a single SLocEntry for the "foo == bar" chunk and locations /// for the 'foo', '==', 'bar' tokens will point inside that chunk. /// /// \arg begin_tokens will be updated to a position past all the found /// consecutive tokens. static void updateConsecutiveMacroArgTokens(SourceManager &SM, SourceLocation InstLoc, Token *&begin_tokens, Token * end_tokens) { assert(begin_tokens < end_tokens); SourceLocation FirstLoc = begin_tokens->getLocation(); SourceLocation CurLoc = FirstLoc; // Compare the source location offset of tokens and group together tokens that // are close, even if their locations point to different FileIDs. e.g. // // |bar | foo | cake | (3 tokens from 3 consecutive FileIDs) // ^ ^ // |bar foo cake| (one SLocEntry chunk for all tokens) // // we can perform this "merge" since the token's spelling location depends // on the relative offset. Token *NextTok = begin_tokens + 1; for (; NextTok < end_tokens; ++NextTok) { SourceLocation NextLoc = NextTok->getLocation(); if (CurLoc.isFileID() != NextLoc.isFileID()) break; // Token from different kind of FileID. int RelOffs; if (!SM.isInSameSLocAddrSpace(CurLoc, NextLoc, &RelOffs)) break; // Token from different local/loaded location. // Check that token is not before the previous token or more than 50 // "characters" away. if (RelOffs < 0 || RelOffs > 50) break; CurLoc = NextLoc; } // For the consecutive tokens, find the length of the SLocEntry to contain // all of them. Token &LastConsecutiveTok = *(NextTok-1); int LastRelOffs = 0; SM.isInSameSLocAddrSpace(FirstLoc, LastConsecutiveTok.getLocation(), &LastRelOffs); unsigned FullLength = LastRelOffs + LastConsecutiveTok.getLength(); // Create a macro expansion SLocEntry that will "contain" all of the tokens. SourceLocation Expansion = SM.createMacroArgExpansionLoc(FirstLoc, InstLoc,FullLength); // Change the location of the tokens from the spelling location to the new // expanded location. for (; begin_tokens < NextTok; ++begin_tokens) { Token &Tok = *begin_tokens; int RelOffs = 0; SM.isInSameSLocAddrSpace(FirstLoc, Tok.getLocation(), &RelOffs); Tok.setLocation(Expansion.getLocWithOffset(RelOffs)); } } /// \brief Creates SLocEntries and updates the locations of macro argument /// tokens to their new expanded locations. /// /// \param ArgIdDefLoc the location of the macro argument id inside the macro /// definition. /// \param Tokens the macro argument tokens to update. void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc, Token *begin_tokens, Token *end_tokens) { SourceManager &SM = PP.getSourceManager(); SourceLocation InstLoc = getExpansionLocForMacroDefLoc(ArgIdSpellLoc); while (begin_tokens < end_tokens) { // If there's only one token just create a SLocEntry for it. if (end_tokens - begin_tokens == 1) { Token &Tok = *begin_tokens; Tok.setLocation(SM.createMacroArgExpansionLoc(Tok.getLocation(), InstLoc, Tok.getLength())); return; } updateConsecutiveMacroArgTokens(SM, InstLoc, begin_tokens, end_tokens); } } void TokenLexer::PropagateLineStartLeadingSpaceInfo(Token &Result) { AtStartOfLine = Result.isAtStartOfLine(); HasLeadingSpace = Result.hasLeadingSpace(); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/Lexer.cpp
//===--- Lexer.cpp - C Language Family Lexer ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Lexer and Token interfaces. // //===----------------------------------------------------------------------===// #include "clang/Lex/Lexer.h" #include "UnicodeCharSets.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/MemoryBuffer.h" #include <cstring> using namespace clang; //===----------------------------------------------------------------------===// // Token Class Implementation //===----------------------------------------------------------------------===// /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier. bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const { if (IdentifierInfo *II = getIdentifierInfo()) return II->getObjCKeywordID() == objcKey; return false; } /// getObjCKeywordID - Return the ObjC keyword kind. tok::ObjCKeywordKind Token::getObjCKeywordID() const { IdentifierInfo *specId = getIdentifierInfo(); return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword; } //===----------------------------------------------------------------------===// // Lexer Class Implementation //===----------------------------------------------------------------------===// void Lexer::anchor() { } void Lexer::InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd) { BufferStart = BufStart; BufferPtr = BufPtr; BufferEnd = BufEnd; assert(BufEnd[0] == 0 && "We assume that the input buffer has a null character at the end" " to simplify lexing!"); // Check whether we have a BOM in the beginning of the buffer. If yes - act // accordingly. Right now we support only UTF-8 with and without BOM, so, just // skip the UTF-8 BOM if it's present. if (BufferStart == BufferPtr) { // Determine the size of the BOM. StringRef Buf(BufferStart, BufferEnd - BufferStart); size_t BOMLength = llvm::StringSwitch<size_t>(Buf) .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM .Default(0); // Skip the BOM. BufferPtr += BOMLength; } Is_PragmaLexer = false; CurrentConflictMarkerState = CMK_None; // Start of the file is a start of line. IsAtStartOfLine = true; IsAtPhysicalStartOfLine = true; HasLeadingSpace = false; HasLeadingEmptyMacro = false; // We are not after parsing a #. ParsingPreprocessorDirective = false; // We are not after parsing #include. ParsingFilename = false; // We are not in raw mode. Raw mode disables diagnostics and interpretation // of tokens (e.g. identifiers, thus disabling macro expansion). It is used // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block // or otherwise skipping over tokens. LexingRawMode = false; // Default to not keeping comments. ExtendedTokenMode = 0; } /// Lexer constructor - Create a new lexer object for the specified buffer /// with the specified preprocessor managing the lexing process. This lexer /// assumes that the associated file buffer and Preprocessor objects will /// outlive it, so it doesn't take ownership of either of them. Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP) : PreprocessorLexer(&PP, FID), FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)), LangOpts(PP.getLangOpts()) { InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(), InputFile->getBufferEnd()); resetExtendedTokenMode(); } void Lexer::resetExtendedTokenMode() { assert(PP && "Cannot reset token mode without a preprocessor"); if (LangOpts.TraditionalCPP) SetKeepWhitespaceMode(true); else SetCommentRetentionState(PP->getCommentRetentionState()); } /// Lexer constructor - Create a new raw lexer object. This object is only /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text /// range will outlive it, so it doesn't take ownership of it. Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts, const char *BufStart, const char *BufPtr, const char *BufEnd) : FileLoc(fileloc), LangOpts(langOpts) { InitLexer(BufStart, BufPtr, BufEnd); // We *are* in raw mode. LexingRawMode = true; } /// Lexer constructor - Create a new raw lexer object. This object is only /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text /// range will outlive it, so it doesn't take ownership of it. Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile, const SourceManager &SM, const LangOptions &langOpts) : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(), FromFile->getBufferStart(), FromFile->getBufferEnd()) {} /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for /// _Pragma expansion. This has a variety of magic semantics that this method /// sets up. It returns a new'd Lexer that must be delete'd when done. /// /// On entrance to this routine, TokStartLoc is a macro location which has a /// spelling loc that indicates the bytes to be lexed for the token and an /// expansion location that indicates where all lexed tokens should be /// "expanded from". /// /// TODO: It would really be nice to make _Pragma just be a wrapper around a /// normal lexer that remaps tokens as they fly by. This would require making /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer /// interface that could handle this stuff. This would pull GetMappedTokenLoc /// out of the critical path of the lexer! /// Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned TokLen, Preprocessor &PP) { SourceManager &SM = PP.getSourceManager(); // Create the lexer as if we were going to lex the file normally. FileID SpellingFID = SM.getFileID(SpellingLoc); const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID); Lexer *L = new Lexer(SpellingFID, InputFile, PP); // Now that the lexer is created, change the start/end locations so that we // just lex the subsection of the file that we want. This is lexing from a // scratch buffer. const char *StrData = SM.getCharacterData(SpellingLoc); L->BufferPtr = StrData; L->BufferEnd = StrData+TokLen; assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!"); // Set the SourceLocation with the remapping information. This ensures that // GetMappedTokenLoc will remap the tokens as they are lexed. L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID), ExpansionLocStart, ExpansionLocEnd, TokLen); // Ensure that the lexer thinks it is inside a directive, so that end \n will // return an EOD token. L->ParsingPreprocessorDirective = true; // This lexer really is for _Pragma. L->Is_PragmaLexer = true; return L; } /// Stringify - Convert the specified string into a C string, with surrounding /// ""'s, and with escaped \ and " characters. std::string Lexer::Stringify(StringRef Str, bool Charify) { std::string Result = Str; char Quote = Charify ? '\'' : '"'; for (unsigned i = 0, e = Result.size(); i != e; ++i) { if (Result[i] == '\\' || Result[i] == Quote) { Result.insert(Result.begin()+i, '\\'); ++i; ++e; } } return Result; } /// Stringify - Convert the specified string into a C string by escaping '\' /// and " characters. This does not add surrounding ""'s to the string. void Lexer::Stringify(SmallVectorImpl<char> &Str) { for (unsigned i = 0, e = Str.size(); i != e; ++i) { if (Str[i] == '\\' || Str[i] == '"') { Str.insert(Str.begin()+i, '\\'); ++i; ++e; } } } //===----------------------------------------------------------------------===// // Token Spelling //===----------------------------------------------------------------------===// /// \brief Slow case of getSpelling. Extract the characters comprising the /// spelling of this token from the provided input buffer. static size_t getSpellingSlow(const Token &Tok, const char *BufPtr, const LangOptions &LangOpts, char *Spelling) { assert(Tok.needsCleaning() && "getSpellingSlow called on simple token"); size_t Length = 0; const char *BufEnd = BufPtr + Tok.getLength(); if (Tok.is(tok::string_literal)) { // Munch the encoding-prefix and opening double-quote. while (BufPtr < BufEnd) { unsigned Size; Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts); BufPtr += Size; if (Spelling[Length - 1] == '"') break; } // Raw string literals need special handling; trigraph expansion and line // splicing do not occur within their d-char-sequence nor within their // r-char-sequence. if (Length >= 2 && Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') { // Search backwards from the end of the token to find the matching closing // quote. const char *RawEnd = BufEnd; do --RawEnd; while (*RawEnd != '"'); size_t RawLength = RawEnd - BufPtr + 1; // Everything between the quotes is included verbatim in the spelling. memcpy(Spelling + Length, BufPtr, RawLength); Length += RawLength; BufPtr += RawLength; // The rest of the token is lexed normally. } } while (BufPtr < BufEnd) { unsigned Size; Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts); BufPtr += Size; } assert(Length < Tok.getLength() && "NeedsCleaning flag set on token that didn't need cleaning!"); return Length; } /// getSpelling() - Return the 'spelling' of this token. The spelling of a /// token are the characters used to represent the token in the source file /// after trigraph expansion and escaped-newline folding. In particular, this /// wants to get the true, uncanonicalized, spelling of things like digraphs /// UCNs, etc. StringRef Lexer::getSpelling(SourceLocation loc, SmallVectorImpl<char> &buffer, const SourceManager &SM, const LangOptions &options, bool *invalid) { // Break down the source location. std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc); // Try to the load the file buffer. bool invalidTemp = false; StringRef file = SM.getBufferData(locInfo.first, &invalidTemp); if (invalidTemp) { if (invalid) *invalid = true; return StringRef(); } const char *tokenBegin = file.data() + locInfo.second; // Lex from the start of the given location. Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options, file.begin(), tokenBegin, file.end()); Token token; lexer.LexFromRawLexer(token); unsigned length = token.getLength(); // Common case: no need for cleaning. if (!token.needsCleaning()) return StringRef(tokenBegin, length); // Hard case, we need to relex the characters into the string. buffer.resize(length); buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data())); return StringRef(buffer.data(), buffer.size()); } /// getSpelling() - Return the 'spelling' of this token. The spelling of a /// token are the characters used to represent the token in the source file /// after trigraph expansion and escaped-newline folding. In particular, this /// wants to get the true, uncanonicalized, spelling of things like digraphs /// UCNs, etc. std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid) { assert((int)Tok.getLength() >= 0 && "Token character range is bogus!"); bool CharDataInvalid = false; const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid); if (Invalid) *Invalid = CharDataInvalid; if (CharDataInvalid) return std::string(); // If this token contains nothing interesting, return it directly. if (!Tok.needsCleaning()) return std::string(TokStart, TokStart + Tok.getLength()); std::string Result; Result.resize(Tok.getLength()); Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin())); return Result; } /// getSpelling - This method is used to get the spelling of a token into a /// preallocated buffer, instead of as an std::string. The caller is required /// to allocate enough space for the token, which is guaranteed to be at least /// Tok.getLength() bytes long. The actual length of the token is returned. /// /// Note that this method may do two possible things: it may either fill in /// the buffer specified with characters, or it may *change the input pointer* /// to point to a constant buffer with the data already in it (avoiding a /// copy). The caller is not allowed to modify the returned buffer pointer /// if an internal buffer is returned. unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid) { assert((int)Tok.getLength() >= 0 && "Token character range is bogus!"); const char *TokStart = nullptr; // NOTE: this has to be checked *before* testing for an IdentifierInfo. if (Tok.is(tok::raw_identifier)) TokStart = Tok.getRawIdentifier().data(); else if (!Tok.hasUCN()) { if (const IdentifierInfo *II = Tok.getIdentifierInfo()) { // Just return the string from the identifier table, which is very quick. Buffer = II->getNameStart(); return II->getLength(); } } // NOTE: this can be checked even after testing for an IdentifierInfo. if (Tok.isLiteral()) TokStart = Tok.getLiteralData(); if (!TokStart) { // Compute the start of the token in the input lexer buffer. bool CharDataInvalid = false; TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid); if (Invalid) *Invalid = CharDataInvalid; if (CharDataInvalid) { Buffer = ""; return 0; } } // If this token contains nothing interesting, return it directly. if (!Tok.needsCleaning()) { Buffer = TokStart; return Tok.getLength(); } // Otherwise, hard case, relex the characters into the string. return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer)); } /// MeasureTokenLength - Relex the token at the specified location and return /// its length in bytes in the input file. If the token needs cleaning (e.g. /// includes a trigraph or an escaped newline) then this count includes bytes /// that are part of that. unsigned Lexer::MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) { Token TheTok; if (getRawToken(Loc, TheTok, SM, LangOpts)) return 0; return TheTok.getLength(); } /// \brief Relex the token at the specified location. /// \returns true if there was a failure, false on success. bool Lexer::getRawToken(SourceLocation Loc, Token &Result, const SourceManager &SM, const LangOptions &LangOpts, bool IgnoreWhiteSpace) { // TODO: this could be special cased for common tokens like identifiers, ')', // etc to make this faster, if it mattered. Just look at StrData[0] to handle // all obviously single-char tokens. This could use // Lexer::isObviouslySimpleCharacter for example to handle identifiers or // something. // If this comes from a macro expansion, we really do want the macro name, not // the token this macro expanded to. Loc = SM.getExpansionLoc(Loc); std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); bool Invalid = false; StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); if (Invalid) return true; const char *StrData = Buffer.data()+LocInfo.second; if (!IgnoreWhiteSpace && isWhitespace(StrData[0])) return true; // Create a lexer starting at the beginning of this token. Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, Buffer.begin(), StrData, Buffer.end()); TheLexer.SetCommentRetentionState(true); TheLexer.LexFromRawLexer(Result); return false; } static SourceLocation getBeginningOfFileToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) { assert(Loc.isFileID()); std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); if (LocInfo.first.isInvalid()) return Loc; bool Invalid = false; StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); if (Invalid) return Loc; // Back up from the current location until we hit the beginning of a line // (or the buffer). We'll relex from that point. const char *BufStart = Buffer.data(); if (LocInfo.second >= Buffer.size()) return Loc; const char *StrData = BufStart+LocInfo.second; if (StrData[0] == '\n' || StrData[0] == '\r') return Loc; const char *LexStart = StrData; while (LexStart != BufStart) { if (LexStart[0] == '\n' || LexStart[0] == '\r') { ++LexStart; break; } --LexStart; } // Create a lexer starting at the beginning of this token. SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second); Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end()); TheLexer.SetCommentRetentionState(true); // Lex tokens until we find the token that contains the source location. Token TheTok; do { TheLexer.LexFromRawLexer(TheTok); if (TheLexer.getBufferLocation() > StrData) { // Lexing this token has taken the lexer past the source location we're // looking for. If the current token encompasses our source location, // return the beginning of that token. if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData) return TheTok.getLocation(); // We ended up skipping over the source location entirely, which means // that it points into whitespace. We're done here. break; } } while (TheTok.getKind() != tok::eof); // We've passed our source location; just return the original source location. return Loc; } SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) { if (Loc.isFileID()) return getBeginningOfFileToken(Loc, SM, LangOpts); if (!SM.isMacroArgExpansion(Loc)) return Loc; SourceLocation FileLoc = SM.getSpellingLoc(Loc); SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts); std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc); std::pair<FileID, unsigned> BeginFileLocInfo = SM.getDecomposedLoc(BeginFileLoc); assert(FileLocInfo.first == BeginFileLocInfo.first && FileLocInfo.second >= BeginFileLocInfo.second); return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second); } namespace { enum PreambleDirectiveKind { PDK_Skipped, PDK_StartIf, PDK_EndIf, PDK_Unknown }; } std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines) { // Create a lexer starting at the beginning of the file. Note that we use a // "fake" file source location at offset 1 so that the lexer will track our // position within the file. const unsigned StartOffset = 1; SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset); Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(), Buffer.end()); TheLexer.SetCommentRetentionState(true); // StartLoc will differ from FileLoc if there is a BOM that was skipped. SourceLocation StartLoc = TheLexer.getSourceLocation(); bool InPreprocessorDirective = false; Token TheTok; Token IfStartTok; unsigned IfCount = 0; SourceLocation ActiveCommentLoc; unsigned MaxLineOffset = 0; if (MaxLines) { const char *CurPtr = Buffer.begin(); unsigned CurLine = 0; while (CurPtr != Buffer.end()) { char ch = *CurPtr++; if (ch == '\n') { ++CurLine; if (CurLine == MaxLines) break; } } if (CurPtr != Buffer.end()) MaxLineOffset = CurPtr - Buffer.begin(); } do { TheLexer.LexFromRawLexer(TheTok); if (InPreprocessorDirective) { // If we've hit the end of the file, we're done. if (TheTok.getKind() == tok::eof) { break; } // If we haven't hit the end of the preprocessor directive, skip this // token. if (!TheTok.isAtStartOfLine()) continue; // We've passed the end of the preprocessor directive, and will look // at this token again below. InPreprocessorDirective = false; } // Keep track of the # of lines in the preamble. if (TheTok.isAtStartOfLine()) { unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset; // If we were asked to limit the number of lines in the preamble, // and we're about to exceed that limit, we're done. if (MaxLineOffset && TokOffset >= MaxLineOffset) break; } // Comments are okay; skip over them. if (TheTok.getKind() == tok::comment) { if (ActiveCommentLoc.isInvalid()) ActiveCommentLoc = TheTok.getLocation(); continue; } if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) { // This is the start of a preprocessor directive. Token HashTok = TheTok; InPreprocessorDirective = true; ActiveCommentLoc = SourceLocation(); // Figure out which directive this is. Since we're lexing raw tokens, // we don't have an identifier table available. Instead, just look at // the raw identifier to recognize and categorize preprocessor directives. TheLexer.LexFromRawLexer(TheTok); if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) { StringRef Keyword = TheTok.getRawIdentifier(); PreambleDirectiveKind PDK = llvm::StringSwitch<PreambleDirectiveKind>(Keyword) .Case("include", PDK_Skipped) .Case("__include_macros", PDK_Skipped) .Case("define", PDK_Skipped) .Case("undef", PDK_Skipped) .Case("line", PDK_Skipped) .Case("error", PDK_Skipped) .Case("pragma", PDK_Skipped) .Case("import", PDK_Skipped) .Case("include_next", PDK_Skipped) .Case("warning", PDK_Skipped) .Case("ident", PDK_Skipped) .Case("sccs", PDK_Skipped) .Case("assert", PDK_Skipped) .Case("unassert", PDK_Skipped) .Case("if", PDK_StartIf) .Case("ifdef", PDK_StartIf) .Case("ifndef", PDK_StartIf) .Case("elif", PDK_Skipped) .Case("else", PDK_Skipped) .Case("endif", PDK_EndIf) .Default(PDK_Unknown); switch (PDK) { case PDK_Skipped: continue; case PDK_StartIf: if (IfCount == 0) IfStartTok = HashTok; ++IfCount; continue; case PDK_EndIf: // Mismatched #endif. The preamble ends here. if (IfCount == 0) break; --IfCount; continue; case PDK_Unknown: // We don't know what this directive is; stop at the '#'. break; } } // We only end up here if we didn't recognize the preprocessor // directive or it was one that can't occur in the preamble at this // point. Roll back the current token to the location of the '#'. InPreprocessorDirective = false; TheTok = HashTok; } // We hit a token that we don't recognize as being in the // "preprocessing only" part of the file, so we're no longer in // the preamble. break; } while (true); SourceLocation End; if (IfCount) End = IfStartTok.getLocation(); else if (ActiveCommentLoc.isValid()) End = ActiveCommentLoc; // don't truncate a decl comment. else End = TheTok.getLocation(); return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(), IfCount? IfStartTok.isAtStartOfLine() : TheTok.isAtStartOfLine()); } /// AdvanceToTokenCharacter - Given a location that specifies the start of a /// token, return a new location that specifies a character within the token. SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart, unsigned CharNo, const SourceManager &SM, const LangOptions &LangOpts) { // Figure out how many physical characters away the specified expansion // character is. This needs to take into consideration newlines and // trigraphs. bool Invalid = false; const char *TokPtr = SM.getCharacterData(TokStart, &Invalid); // If they request the first char of the token, we're trivially done. if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr))) return TokStart; unsigned PhysOffset = 0; // The usual case is that tokens don't contain anything interesting. Skip // over the uninteresting characters. If a token only consists of simple // chars, this method is extremely fast. while (Lexer::isObviouslySimpleCharacter(*TokPtr)) { if (CharNo == 0) return TokStart.getLocWithOffset(PhysOffset); ++TokPtr, --CharNo, ++PhysOffset; } // If we have a character that may be a trigraph or escaped newline, use a // lexer to parse it correctly. for (; CharNo; --CharNo) { unsigned Size; Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts); TokPtr += Size; PhysOffset += Size; } // Final detail: if we end up on an escaped newline, we want to return the // location of the actual byte of the token. For example foo\<newline>bar // advanced by 3 should return the location of b, not of \\. One compounding // detail of this is that the escape may be made by a trigraph. if (!Lexer::isObviouslySimpleCharacter(*TokPtr)) PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr; return TokStart.getLocWithOffset(PhysOffset); } /// \brief Computes the source location just past the end of the /// token at this source location. /// /// This routine can be used to produce a source location that /// points just past the end of the token referenced by \p Loc, and /// is generally used when a diagnostic needs to point just after a /// token where it expected something different that it received. If /// the returned source location would not be meaningful (e.g., if /// it points into a macro), this routine returns an invalid /// source location. /// /// \param Offset an offset from the end of the token, where the source /// location should refer to. The default offset (0) produces a source /// location pointing just past the end of the token; an offset of 1 produces /// a source location pointing to the last character in the token, etc. SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts) { if (Loc.isInvalid()) return SourceLocation(); if (Loc.isMacroID()) { if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc)) return SourceLocation(); // Points inside the macro expansion. } unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts); if (Len > Offset) Len = Len - Offset; else return Loc; return Loc.getLocWithOffset(Len); } /// \brief Returns true if the given MacroID location points at the first /// token of the macro expansion. bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroBegin) { assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc"); SourceLocation expansionLoc; if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc)) return false; if (expansionLoc.isFileID()) { // No other macro expansions, this is the first. if (MacroBegin) *MacroBegin = expansionLoc; return true; } return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin); } /// \brief Returns true if the given MacroID location points at the last /// token of the macro expansion. bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroEnd) { assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc"); SourceLocation spellLoc = SM.getSpellingLoc(loc); unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts); if (tokLen == 0) return false; SourceLocation afterLoc = loc.getLocWithOffset(tokLen); SourceLocation expansionLoc; if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc)) return false; if (expansionLoc.isFileID()) { // No other macro expansions. if (MacroEnd) *MacroEnd = expansionLoc; return true; } return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd); } static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts) { SourceLocation Begin = Range.getBegin(); SourceLocation End = Range.getEnd(); assert(Begin.isFileID() && End.isFileID()); if (Range.isTokenRange()) { End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts); if (End.isInvalid()) return CharSourceRange(); } // Break down the source locations. FileID FID; unsigned BeginOffs; std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin); if (FID.isInvalid()) return CharSourceRange(); unsigned EndOffs; if (!SM.isInFileID(End, FID, &EndOffs) || BeginOffs > EndOffs) return CharSourceRange(); return CharSourceRange::getCharRange(Begin, End); } CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts) { SourceLocation Begin = Range.getBegin(); SourceLocation End = Range.getEnd(); if (Begin.isInvalid() || End.isInvalid()) return CharSourceRange(); if (Begin.isFileID() && End.isFileID()) return makeRangeFromFileLocs(Range, SM, LangOpts); if (Begin.isMacroID() && End.isFileID()) { if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin)) return CharSourceRange(); Range.setBegin(Begin); return makeRangeFromFileLocs(Range, SM, LangOpts); } if (Begin.isFileID() && End.isMacroID()) { if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts, &End)) || (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts, &End))) return CharSourceRange(); Range.setEnd(End); return makeRangeFromFileLocs(Range, SM, LangOpts); } assert(Begin.isMacroID() && End.isMacroID()); SourceLocation MacroBegin, MacroEnd; if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) && ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts, &MacroEnd)) || (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts, &MacroEnd)))) { Range.setBegin(MacroBegin); Range.setEnd(MacroEnd); return makeRangeFromFileLocs(Range, SM, LangOpts); } bool Invalid = false; const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin), &Invalid); if (Invalid) return CharSourceRange(); if (BeginEntry.getExpansion().isMacroArgExpansion()) { const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End), &Invalid); if (Invalid) return CharSourceRange(); if (EndEntry.getExpansion().isMacroArgExpansion() && BeginEntry.getExpansion().getExpansionLocStart() == EndEntry.getExpansion().getExpansionLocStart()) { Range.setBegin(SM.getImmediateSpellingLoc(Begin)); Range.setEnd(SM.getImmediateSpellingLoc(End)); return makeFileCharRange(Range, SM, LangOpts); } } return CharSourceRange(); } StringRef Lexer::getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid) { Range = makeFileCharRange(Range, SM, LangOpts); if (Range.isInvalid()) { if (Invalid) *Invalid = true; return StringRef(); } // Break down the source location. std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin()); if (beginInfo.first.isInvalid()) { if (Invalid) *Invalid = true; return StringRef(); } unsigned EndOffs; if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) || beginInfo.second > EndOffs) { if (Invalid) *Invalid = true; return StringRef(); } // Try to the load the file buffer. bool invalidTemp = false; StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp); if (invalidTemp) { if (Invalid) *Invalid = true; return StringRef(); } if (Invalid) *Invalid = false; return file.substr(beginInfo.second, EndOffs - beginInfo.second); } StringRef Lexer::getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) { assert(Loc.isMacroID() && "Only reasonble to call this on macros"); // Find the location of the immediate macro expansion. while (1) { FileID FID = SM.getFileID(Loc); const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID); const SrcMgr::ExpansionInfo &Expansion = E->getExpansion(); Loc = Expansion.getExpansionLocStart(); if (!Expansion.isMacroArgExpansion()) break; // For macro arguments we need to check that the argument did not come // from an inner macro, e.g: "MAC1( MAC2(foo) )" // Loc points to the argument id of the macro definition, move to the // macro expansion. Loc = SM.getImmediateExpansionRange(Loc).first; SourceLocation SpellLoc = Expansion.getSpellingLoc(); if (SpellLoc.isFileID()) break; // No inner macro. // If spelling location resides in the same FileID as macro expansion // location, it means there is no inner macro. FileID MacroFID = SM.getFileID(Loc); if (SM.isInFileID(SpellLoc, MacroFID)) break; // Argument came from inner macro. Loc = SpellLoc; } // Find the spelling location of the start of the non-argument expansion // range. This is where the macro name was spelled in order to begin // expanding this macro. Loc = SM.getSpellingLoc(Loc); // Dig out the buffer where the macro name was spelled and the extents of the // name so that we can render it into the expansion note. std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc); unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts); StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first); return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength); } bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) { return isIdentifierBody(c, LangOpts.DollarIdents); } //===----------------------------------------------------------------------===// // Diagnostics forwarding code. //===----------------------------------------------------------------------===// /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the /// lexer buffer was all expanded at a single point, perform the mapping. /// This is currently only used for _Pragma implementation, so it is the slow /// path of the hot getSourceLocation method. Do not allow it to be inlined. static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc( Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen); static SourceLocation GetMappedTokenLoc(Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen) { assert(FileLoc.isMacroID() && "Must be a macro expansion"); // Otherwise, we're lexing "mapped tokens". This is used for things like // _Pragma handling. Combine the expansion location of FileLoc with the // spelling location. SourceManager &SM = PP.getSourceManager(); // Create a new SLoc which is expanded from Expansion(FileLoc) but whose // characters come from spelling(FileLoc)+Offset. SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc); SpellingLoc = SpellingLoc.getLocWithOffset(CharNo); // Figure out the expansion loc range, which is the range covered by the // original _Pragma(...) sequence. std::pair<SourceLocation,SourceLocation> II = SM.getImmediateExpansionRange(FileLoc); return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen); } /// getSourceLocation - Return a source location identifier for the specified /// offset in the current file. SourceLocation Lexer::getSourceLocation(const char *Loc, unsigned TokLen) const { assert(Loc >= BufferStart && Loc <= BufferEnd && "Location out of range for this buffer!"); // In the normal case, we're just lexing from a simple file buffer, return // the file id from FileLoc with the offset specified. unsigned CharNo = Loc-BufferStart; if (FileLoc.isFileID()) return FileLoc.getLocWithOffset(CharNo); // Otherwise, this is the _Pragma lexer case, which pretends that all of the // tokens are lexed from where the _Pragma was defined. assert(PP && "This doesn't work on raw lexers"); return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen); } /// Diag - Forwarding function for diagnostics. This translate a source /// position in the current buffer into a SourceLocation object for rendering. DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const { return PP->Diag(getSourceLocation(Loc), DiagID); } //===----------------------------------------------------------------------===// // Trigraph and Escaped Newline Handling Code. //===----------------------------------------------------------------------===// /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair, /// return the decoded trigraph letter it corresponds to, or '\0' if nothing. static char GetTrigraphCharForLetter(char Letter) { switch (Letter) { default: return 0; case '=': return '#'; case ')': return ']'; case '(': return '['; case '!': return '|'; case '\'': return '^'; case '>': return '}'; case '/': return '\\'; case '<': return '{'; case '-': return '~'; } } /// DecodeTrigraphChar - If the specified character is a legal trigraph when /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled, /// return the result character. Finally, emit a warning about trigraph use /// whether trigraphs are enabled or not. static char DecodeTrigraphChar(const char *CP, Lexer *L) { char Res = GetTrigraphCharForLetter(*CP); if (!Res || !L) return Res; if (!L->getLangOpts().Trigraphs) { if (!L->isLexingRawMode()) L->Diag(CP-2, diag::trigraph_ignored); return 0; } if (!L->isLexingRawMode()) L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1); return Res; } /// getEscapedNewLineSize - Return the size of the specified escaped newline, /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a /// trigraph equivalent on entry to this function. unsigned Lexer::getEscapedNewLineSize(const char *Ptr) { unsigned Size = 0; while (isWhitespace(Ptr[Size])) { ++Size; if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r') continue; // If this is a \r\n or \n\r, skip the other half. if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') && Ptr[Size-1] != Ptr[Size]) ++Size; return Size; } // Not an escaped newline, must be a \t or something else. return 0; } /// SkipEscapedNewLines - If P points to an escaped newline (or a series of /// them), skip over them and return the first non-escaped-newline found, /// otherwise return P. const char *Lexer::SkipEscapedNewLines(const char *P) { while (1) { const char *AfterEscape; if (*P == '\\') { AfterEscape = P+1; } else if (*P == '?') { // If not a trigraph for escape, bail out. if (P[1] != '?' || P[2] != '/') return P; AfterEscape = P+3; } else { return P; } unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape); if (NewLineSize == 0) return P; P = AfterEscape+NewLineSize; } } /// \brief Checks that the given token is the first token that occurs after the /// given location (this excludes comments and whitespace). Returns the location /// immediately after the specified token. If the token is not found or the /// location is inside a macro, the returned source location will be invalid. SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) { if (Loc.isMacroID()) { if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc)) return SourceLocation(); } Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts); // Break down the source location. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); // Try to load the file buffer. bool InvalidTemp = false; StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp); if (InvalidTemp) return SourceLocation(); const char *TokenBegin = File.data() + LocInfo.second; // Lex from the start of the given location. Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(), TokenBegin, File.end()); // Find the token. Token Tok; lexer.LexFromRawLexer(Tok); if (Tok.isNot(TKind)) return SourceLocation(); SourceLocation TokenLoc = Tok.getLocation(); // Calculate how much whitespace needs to be skipped if any. unsigned NumWhitespaceChars = 0; if (SkipTrailingWhitespaceAndNewLine) { const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok.getLength(); unsigned char C = *TokenEnd; while (isHorizontalWhitespace(C)) { C = *(++TokenEnd); NumWhitespaceChars++; } // Skip \r, \n, \r\n, or \n\r if (C == '\n' || C == '\r') { char PrevC = C; C = *(++TokenEnd); NumWhitespaceChars++; if ((C == '\n' || C == '\r') && C != PrevC) NumWhitespaceChars++; } } return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars); } /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer, /// get its size, and return it. This is tricky in several cases: /// 1. If currently at the start of a trigraph, we warn about the trigraph, /// then either return the trigraph (skipping 3 chars) or the '?', /// depending on whether trigraphs are enabled or not. /// 2. If this is an escaped newline (potentially with whitespace between /// the backslash and newline), implicitly skip the newline and return /// the char after it. /// /// This handles the slow/uncommon case of the getCharAndSize method. Here we /// know that we can accumulate into Size, and that we have already incremented /// Ptr by Size bytes. /// /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should /// be updated to match. /// char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size, Token *Tok) { // If we have a slash, look for an escaped newline. if (Ptr[0] == '\\') { ++Size; ++Ptr; Slash: // Common case, backslash-char where the char is not whitespace. if (!isWhitespace(Ptr[0])) return '\\'; // See if we have optional whitespace characters between the slash and // newline. if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { // Remember that this token needs to be cleaned. if (Tok) Tok->setFlag(Token::NeedsCleaning); // Warn if there was whitespace between the backslash and newline. if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode()) Diag(Ptr, diag::backslash_newline_space); // Found backslash<whitespace><newline>. Parse the char after it. Size += EscapedNewLineSize; Ptr += EscapedNewLineSize; // If the char that we finally got was a \n, then we must have had // something like \<newline><newline>. We don't want to consume the // second newline. if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0') return ' '; // Use slow version to accumulate a correct size field. return getCharAndSizeSlow(Ptr, Size, Tok); } // Otherwise, this is not an escaped newline, just return the slash. return '\\'; } // If this is a trigraph, process it. if (Ptr[0] == '?' && Ptr[1] == '?') { // If this is actually a legal trigraph (not something like "??x"), emit // a trigraph warning. If so, and if trigraphs are enabled, return it. if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) { // Remember that this token needs to be cleaned. if (Tok) Tok->setFlag(Token::NeedsCleaning); Ptr += 3; Size += 3; if (C == '\\') goto Slash; return C; } } // If this is neither, return a single character. ++Size; return *Ptr; } /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size, /// and that we have already incremented Ptr by Size bytes. /// /// NOTE: When this method is updated, getCharAndSizeSlow (above) should /// be updated to match. char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, const LangOptions &LangOpts) { // If we have a slash, look for an escaped newline. if (Ptr[0] == '\\') { ++Size; ++Ptr; Slash: // Common case, backslash-char where the char is not whitespace. if (!isWhitespace(Ptr[0])) return '\\'; // See if we have optional whitespace characters followed by a newline. if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { // Found backslash<whitespace><newline>. Parse the char after it. Size += EscapedNewLineSize; Ptr += EscapedNewLineSize; // If the char that we finally got was a \n, then we must have had // something like \<newline><newline>. We don't want to consume the // second newline. if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0') return ' '; // Use slow version to accumulate a correct size field. return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts); } // Otherwise, this is not an escaped newline, just return the slash. return '\\'; } // If this is a trigraph, process it. if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') { // If this is actually a legal trigraph (not something like "??x"), return // it. if (char C = GetTrigraphCharForLetter(Ptr[2])) { Ptr += 3; Size += 3; if (C == '\\') goto Slash; return C; } } // If this is neither, return a single character. ++Size; return *Ptr; } //===----------------------------------------------------------------------===// // Helper methods for lexing. //===----------------------------------------------------------------------===// /// \brief Routine that indiscriminately skips bytes in the source file. void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) { BufferPtr += Bytes; if (BufferPtr > BufferEnd) BufferPtr = BufferEnd; // FIXME: What exactly does the StartOfLine bit mean? There are two // possible meanings for the "start" of the line: the first token on the // unexpanded line, or the first token on the expanded line. IsAtStartOfLine = StartOfLine; IsAtPhysicalStartOfLine = StartOfLine; } static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) { if (LangOpts.CPlusPlus11 || LangOpts.C11) { static const llvm::sys::UnicodeCharSet C11AllowedIDChars( C11AllowedIDCharRanges); return C11AllowedIDChars.contains(C); } else if (LangOpts.CPlusPlus) { static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars( CXX03AllowedIDCharRanges); return CXX03AllowedIDChars.contains(C); } else { static const llvm::sys::UnicodeCharSet C99AllowedIDChars( C99AllowedIDCharRanges); return C99AllowedIDChars.contains(C); } } static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) { assert(isAllowedIDChar(C, LangOpts)); if (LangOpts.CPlusPlus11 || LangOpts.C11) { static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars( C11DisallowedInitialIDCharRanges); return !C11DisallowedInitialIDChars.contains(C); } else if (LangOpts.CPlusPlus) { return true; } else { static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars( C99DisallowedInitialIDCharRanges); return !C99DisallowedInitialIDChars.contains(C); } } static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin, const char *End) { return CharSourceRange::getCharRange(L.getSourceLocation(Begin), L.getSourceLocation(End)); } static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C, CharSourceRange Range, bool IsFirst) { // Check C99 compatibility. if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) { enum { CannotAppearInIdentifier = 0, CannotStartIdentifier }; static const llvm::sys::UnicodeCharSet C99AllowedIDChars( C99AllowedIDCharRanges); static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars( C99DisallowedInitialIDCharRanges); if (!C99AllowedIDChars.contains(C)) { Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id) << Range << CannotAppearInIdentifier; } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) { Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id) << Range << CannotStartIdentifier; } } // Check C++98 compatibility. if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) { static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars( CXX03AllowedIDCharRanges); if (!CXX03AllowedIDChars.contains(C)) { Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id) << Range; } } } bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size, Token &Result) { const char *UCNPtr = CurPtr + Size; uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr); if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts)) return false; if (!isLexingRawMode()) maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint, makeCharRange(*this, CurPtr, UCNPtr), /*IsFirst=*/false); Result.setFlag(Token::HasUCN); if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') || (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U')) CurPtr = UCNPtr; else while (CurPtr != UCNPtr) (void)getAndAdvanceChar(CurPtr, Result); return true; } bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) { const char *UnicodePtr = CurPtr; UTF32 CodePoint; ConversionResult Result = llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr, (const UTF8 *)BufferEnd, &CodePoint, strictConversion); if (Result != conversionOK || !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts)) return false; if (!isLexingRawMode()) maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint, makeCharRange(*this, CurPtr, UnicodePtr), /*IsFirst=*/false); CurPtr = UnicodePtr; return true; } bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) { // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$] unsigned Size; unsigned char C = *CurPtr++; while (isIdentifierBody(C)) C = *CurPtr++; --CurPtr; // Back up over the skipped character. // Fast path, no $,\,? in identifier found. '\' might be an escaped newline // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN. // // TODO: Could merge these checks into an InfoTable flag to make the // comparison cheaper if (isASCII(C) && C != '\\' && C != '?' && (C != '$' || !LangOpts.DollarIdents)) { FinishIdentifier: const char *IdStart = BufferPtr; FormTokenWithChars(Result, CurPtr, tok::raw_identifier); Result.setRawIdentifierData(IdStart); // If we are in raw mode, return this identifier raw. There is no need to // look up identifier information or attempt to macro expand it. if (LexingRawMode) return true; // Fill in Result.IdentifierInfo and update the token kind, // looking up the identifier in the identifier table. IdentifierInfo *II = PP->LookUpIdentifierInfo(Result); // Finally, now that we know we have an identifier, pass this off to the // preprocessor, which may macro expand it or something. if (II->isHandleIdentifierCase()) return PP->HandleIdentifier(Result); return true; } // Otherwise, $,\,? in identifier found. Enter slower path. C = getCharAndSize(CurPtr, Size); while (1) { if (C == '$') { // If we hit a $ and they are not supported in identifiers, we are done. if (!LangOpts.DollarIdents) goto FinishIdentifier; // Otherwise, emit a diagnostic and continue. if (!isLexingRawMode()) Diag(CurPtr, diag::ext_dollar_in_identifier); CurPtr = ConsumeChar(CurPtr, Size, Result); C = getCharAndSize(CurPtr, Size); continue; } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) { C = getCharAndSize(CurPtr, Size); continue; } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) { C = getCharAndSize(CurPtr, Size); continue; } else if (!isIdentifierBody(C)) { goto FinishIdentifier; } // Otherwise, this character is good, consume it. CurPtr = ConsumeChar(CurPtr, Size, Result); C = getCharAndSize(CurPtr, Size); while (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); C = getCharAndSize(CurPtr, Size); } } } /// isHexaLiteral - Return true if Start points to a hex constant. /// in microsoft mode (where this is supposed to be several different tokens). bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) { unsigned Size; char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts); if (C1 != '0') return false; char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts); return (C2 == 'x' || C2 == 'X'); } /// LexNumericConstant - Lex the remainder of a integer or floating point /// constant. From[-1] is the first character lexed. Return the end of the /// constant. bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) { return LexNumericConstant(Result, CurPtr, 0); } bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr, unsigned Periods) { unsigned Size; char C = getCharAndSize(CurPtr, Size); char PrevCh = 0; while ((C == '#' || isPreprocessingNumberBody(C)) && !(C == '.' && Periods)) { // HLSL Change - support '1.0.xxx' floating point swizzle, and '#' for '#INF' CurPtr = ConsumeChar(CurPtr, Size, Result); PrevCh = C; // HLSL Change Begin. // Support '1.0.xxx' floating point swizzle if (C == '.') { Periods++; if (*CurPtr == 'x' || *CurPtr == 'r') { CurPtr--; break; } } // HLSL Change End. C = getCharAndSize(CurPtr, Size); } // If we fell out, check for a sign, due to 1e+12. If we have one, continue. if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) { // If we are in Microsoft mode, don't continue if the constant is hex. // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts)) return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result), Periods); } // If we have a hex FP constant, continue. if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) { // Outside C99, we accept hexadecimal floating point numbers as a // not-quite-conforming extension. Only do so if this looks like it's // actually meant to be a hexfloat, and not if it has a ud-suffix. bool IsHexFloat = true; if (!LangOpts.C99) { if (!isHexaLiteral(BufferPtr, LangOpts)) IsHexFloat = false; else if (std::find(BufferPtr, CurPtr, '_') != CurPtr) IsHexFloat = false; } if (IsHexFloat) return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result), Periods); } // If we have a digit separator, continue. if (C == '\'' && getLangOpts().CPlusPlus14) { unsigned NextSize; char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts()); if (isIdentifierBody(Next)) { if (!isLexingRawMode()) Diag(CurPtr, diag::warn_cxx11_compat_digit_separator); CurPtr = ConsumeChar(CurPtr, Size, Result); CurPtr = ConsumeChar(CurPtr, NextSize, Result); return LexNumericConstant(Result, CurPtr, Periods); } } // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue. if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) return LexNumericConstant(Result, CurPtr, Periods); if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) return LexNumericConstant(Result, CurPtr, Periods); // Update the location of token as well as BufferPtr. const char *TokStart = BufferPtr; FormTokenWithChars(Result, CurPtr, tok::numeric_constant); Result.setLiteralData(TokStart); return true; } /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes /// in C++11, or warn on a ud-suffix in C++98. const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr, bool IsStringLiteral) { assert(getLangOpts().CPlusPlus); // Maximally munch an identifier. unsigned Size; char C = getCharAndSize(CurPtr, Size); bool Consumed = false; if (!isIdentifierHead(C)) { if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) Consumed = true; else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) Consumed = true; else return CurPtr; } if (!getLangOpts().CPlusPlus11) { if (!isLexingRawMode()) Diag(CurPtr, C == '_' ? diag::warn_cxx11_compat_user_defined_literal : diag::warn_cxx11_compat_reserved_user_defined_literal) << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " "); return CurPtr; } // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix // that does not start with an underscore is ill-formed. As a conforming // extension, we treat all such suffixes as if they had whitespace before // them. We assume a suffix beginning with a UCN or UTF-8 character is more // likely to be a ud-suffix than a macro, however, and accept that. if (!Consumed) { bool IsUDSuffix = false; if (C == '_') IsUDSuffix = true; else if (IsStringLiteral && getLangOpts().CPlusPlus14) { // In C++1y, we need to look ahead a few characters to see if this is a // valid suffix for a string literal or a numeric literal (this could be // the 'operator""if' defining a numeric literal operator). const unsigned MaxStandardSuffixLength = 3; char Buffer[MaxStandardSuffixLength] = { C }; unsigned Consumed = Size; unsigned Chars = 1; while (true) { unsigned NextSize; char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize, getLangOpts()); if (!isIdentifierBody(Next)) { // End of suffix. Check whether this is on the whitelist. IsUDSuffix = (Chars == 1 && Buffer[0] == 's') || NumericLiteralParser::isValidUDSuffix( getLangOpts(), StringRef(Buffer, Chars)); break; } if (Chars == MaxStandardSuffixLength) // Too long: can't be a standard suffix. break; Buffer[Chars++] = Next; Consumed += NextSize; } } if (!IsUDSuffix) { if (!isLexingRawMode()) Diag(CurPtr, getLangOpts().MSVCCompat ? diag::ext_ms_reserved_user_defined_literal : diag::ext_reserved_user_defined_literal) << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " "); return CurPtr; } CurPtr = ConsumeChar(CurPtr, Size, Result); } Result.setFlag(Token::HasUDSuffix); while (true) { C = getCharAndSize(CurPtr, Size); if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {} else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {} else break; } return CurPtr; } /// LexStringLiteral - Lex the remainder of a string literal, after having lexed /// either " or L" or u8" or u" or U". bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr, tok::TokenKind Kind) { // Does this string contain the \0 character? const char *NulCharacter = nullptr; if (!isLexingRawMode() && (Kind == tok::utf8_string_literal || Kind == tok::utf16_string_literal || Kind == tok::utf32_string_literal)) Diag(BufferPtr, getLangOpts().CPlusPlus ? diag::warn_cxx98_compat_unicode_literal : diag::warn_c99_compat_unicode_literal); char C = getAndAdvanceChar(CurPtr, Result); while (C != '"') { // Skip escaped characters. Escaped newlines will already be processed by // getAndAdvanceChar. if (C == '\\') C = getAndAdvanceChar(CurPtr, Result); if (C == '\n' || C == '\r' || // Newline. (C == 0 && CurPtr-1 == BufferEnd)) { // End of file. if (!isLexingRawMode() && !LangOpts.AsmPreprocessor) Diag(BufferPtr, diag::ext_unterminated_string); FormTokenWithChars(Result, CurPtr-1, tok::unknown); return true; } if (C == 0) { if (isCodeCompletionPoint(CurPtr-1)) { PP->CodeCompleteNaturalLanguage(); FormTokenWithChars(Result, CurPtr-1, tok::unknown); cutOffLexing(); return true; } NulCharacter = CurPtr-1; } C = getAndAdvanceChar(CurPtr, Result); } // If we are in C++11, lex the optional ud-suffix. if (getLangOpts().CPlusPlus) CurPtr = LexUDSuffix(Result, CurPtr, true); // If a nul character existed in the string, warn about it. if (NulCharacter && !isLexingRawMode()) Diag(NulCharacter, diag::null_in_string); // Update the location of the token as well as the BufferPtr instance var. const char *TokStart = BufferPtr; FormTokenWithChars(Result, CurPtr, Kind); Result.setLiteralData(TokStart); return true; } /// LexRawStringLiteral - Lex the remainder of a raw string literal, after /// having lexed R", LR", u8R", uR", or UR". bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr, tok::TokenKind Kind) { // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3: // Between the initial and final double quote characters of the raw string, // any transformations performed in phases 1 and 2 (trigraphs, // universal-character-names, and line splicing) are reverted. if (!isLexingRawMode()) Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal); unsigned PrefixLen = 0; while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen])) ++PrefixLen; // If the last character was not a '(', then we didn't lex a valid delimiter. if (CurPtr[PrefixLen] != '(') { if (!isLexingRawMode()) { const char *PrefixEnd = &CurPtr[PrefixLen]; if (PrefixLen == 16) { Diag(PrefixEnd, diag::err_raw_delim_too_long); } else { Diag(PrefixEnd, diag::err_invalid_char_raw_delim) << StringRef(PrefixEnd, 1); } } // Search for the next '"' in hopes of salvaging the lexer. Unfortunately, // it's possible the '"' was intended to be part of the raw string, but // there's not much we can do about that. while (1) { char C = *CurPtr++; if (C == '"') break; if (C == 0 && CurPtr-1 == BufferEnd) { --CurPtr; break; } } FormTokenWithChars(Result, CurPtr, tok::unknown); return true; } // Save prefix and move CurPtr past it const char *Prefix = CurPtr; CurPtr += PrefixLen + 1; // skip over prefix and '(' while (1) { char C = *CurPtr++; if (C == ')') { // Check for prefix match and closing quote. if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') { CurPtr += PrefixLen + 1; // skip over prefix and '"' break; } } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file. if (!isLexingRawMode()) Diag(BufferPtr, diag::err_unterminated_raw_string) << StringRef(Prefix, PrefixLen); FormTokenWithChars(Result, CurPtr-1, tok::unknown); return true; } } // If we are in C++11, lex the optional ud-suffix. if (getLangOpts().CPlusPlus) CurPtr = LexUDSuffix(Result, CurPtr, true); // Update the location of token as well as BufferPtr. const char *TokStart = BufferPtr; FormTokenWithChars(Result, CurPtr, Kind); Result.setLiteralData(TokStart); return true; } /// LexAngledStringLiteral - Lex the remainder of an angled string literal, /// after having lexed the '<' character. This is used for #include filenames. bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) { // Does this string contain the \0 character? const char *NulCharacter = nullptr; const char *AfterLessPos = CurPtr; char C = getAndAdvanceChar(CurPtr, Result); while (C != '>') { // Skip escaped characters. if (C == '\\' && CurPtr < BufferEnd) { // Skip the escaped character. getAndAdvanceChar(CurPtr, Result); } else if (C == '\n' || C == '\r' || // Newline. (C == 0 && (CurPtr-1 == BufferEnd || // End of file. isCodeCompletionPoint(CurPtr-1)))) { // If the filename is unterminated, then it must just be a lone < // character. Return this as such. FormTokenWithChars(Result, AfterLessPos, tok::less); return true; } else if (C == 0) { NulCharacter = CurPtr-1; } C = getAndAdvanceChar(CurPtr, Result); } // If a nul character existed in the string, warn about it. if (NulCharacter && !isLexingRawMode()) Diag(NulCharacter, diag::null_in_string); // Update the location of token as well as BufferPtr. const char *TokStart = BufferPtr; FormTokenWithChars(Result, CurPtr, tok::angle_string_literal); Result.setLiteralData(TokStart); return true; } /// LexCharConstant - Lex the remainder of a character constant, after having /// lexed either ' or L' or u8' or u' or U'. bool Lexer::LexCharConstant(Token &Result, const char *CurPtr, tok::TokenKind Kind) { // Does this character contain the \0 character? const char *NulCharacter = nullptr; if (!isLexingRawMode()) { if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant) Diag(BufferPtr, getLangOpts().CPlusPlus ? diag::warn_cxx98_compat_unicode_literal : diag::warn_c99_compat_unicode_literal); else if (Kind == tok::utf8_char_constant) Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal); } char C = getAndAdvanceChar(CurPtr, Result); if (C == '\'') { if (!isLexingRawMode() && !LangOpts.AsmPreprocessor) Diag(BufferPtr, diag::ext_empty_character); FormTokenWithChars(Result, CurPtr, tok::unknown); return true; } while (C != '\'') { // Skip escaped characters. if (C == '\\') C = getAndAdvanceChar(CurPtr, Result); if (C == '\n' || C == '\r' || // Newline. (C == 0 && CurPtr-1 == BufferEnd)) { // End of file. if (!isLexingRawMode() && !LangOpts.AsmPreprocessor) Diag(BufferPtr, diag::ext_unterminated_char); FormTokenWithChars(Result, CurPtr-1, tok::unknown); return true; } if (C == 0) { if (isCodeCompletionPoint(CurPtr-1)) { PP->CodeCompleteNaturalLanguage(); FormTokenWithChars(Result, CurPtr-1, tok::unknown); cutOffLexing(); return true; } NulCharacter = CurPtr-1; } C = getAndAdvanceChar(CurPtr, Result); } // If we are in C++11, lex the optional ud-suffix. if (getLangOpts().CPlusPlus) CurPtr = LexUDSuffix(Result, CurPtr, false); // If a nul character existed in the character, warn about it. if (NulCharacter && !isLexingRawMode()) Diag(NulCharacter, diag::null_in_char); // Update the location of token as well as BufferPtr. const char *TokStart = BufferPtr; FormTokenWithChars(Result, CurPtr, Kind); Result.setLiteralData(TokStart); return true; } /// SkipWhitespace - Efficiently skip over a series of whitespace characters. /// Update BufferPtr to point to the next non-whitespace character and return. /// /// This method forms a token and returns true if KeepWhitespaceMode is enabled. /// bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr, bool &TokAtPhysicalStartOfLine) { // Whitespace - Skip it, then return the token after the whitespace. bool SawNewline = isVerticalWhitespace(CurPtr[-1]); unsigned char Char = *CurPtr; // Skip consecutive spaces efficiently. while (1) { // Skip horizontal whitespace very aggressively. while (isHorizontalWhitespace(Char)) Char = *++CurPtr; // Otherwise if we have something other than whitespace, we're done. if (!isVerticalWhitespace(Char)) break; if (ParsingPreprocessorDirective) { // End of preprocessor directive line, let LexTokenInternal handle this. BufferPtr = CurPtr; return false; } // OK, but handle newline. SawNewline = true; Char = *++CurPtr; } // If the client wants us to return whitespace, return it now. if (isKeepWhitespaceMode()) { FormTokenWithChars(Result, CurPtr, tok::unknown); if (SawNewline) { IsAtStartOfLine = true; IsAtPhysicalStartOfLine = true; } // FIXME: The next token will not have LeadingSpace set. return true; } // If this isn't immediately after a newline, there is leading space. char PrevChar = CurPtr[-1]; bool HasLeadingSpace = !isVerticalWhitespace(PrevChar); Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace); if (SawNewline) { Result.setFlag(Token::StartOfLine); TokAtPhysicalStartOfLine = true; } BufferPtr = CurPtr; return false; } /// We have just read the // characters from input. Skip until we find the /// newline character thats terminate the comment. Then update BufferPtr and /// return. /// /// If we're in KeepCommentMode or any CommentHandler has inserted /// some tokens, this will store the first token and return true. bool Lexer::SkipLineComment(Token &Result, const char *CurPtr, bool &TokAtPhysicalStartOfLine) { // If Line comments aren't explicitly enabled for this language, emit an // extension warning. #ifdef MS_SUPPORT_VARIABLE_LANGOPTS if (!LangOpts.LineComment && !isLexingRawMode()) { Diag(BufferPtr, diag::ext_line_comment); // Mark them enabled so we only emit one warning for this translation // unit. LangOpts.LineComment = true; } #else assert(LangOpts.LineComment); #endif // Scan over the body of the comment. The common case, when scanning, is that // the comment contains normal ascii characters with nothing interesting in // them. As such, optimize for this case with the inner loop. char C; do { C = *CurPtr; // Skip over characters in the fast loop. while (C != 0 && // Potentially EOF. C != '\n' && C != '\r') // Newline or DOS-style newline. C = *++CurPtr; const char *NextLine = CurPtr; if (C != 0) { // We found a newline, see if it's escaped. const char *EscapePtr = CurPtr-1; bool HasSpace = false; while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace. --EscapePtr; HasSpace = true; } if (*EscapePtr == '\\') // Escaped newline. CurPtr = EscapePtr; else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' && EscapePtr[-2] == '?') // Trigraph-escaped newline. CurPtr = EscapePtr-2; else break; // This is a newline, we're done. // If there was space between the backslash and newline, warn about it. if (HasSpace && !isLexingRawMode()) Diag(EscapePtr, diag::backslash_newline_space); } // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to // properly decode the character. Read it in raw mode to avoid emitting // diagnostics about things like trigraphs. If we see an escaped newline, // we'll handle it below. const char *OldPtr = CurPtr; bool OldRawMode = isLexingRawMode(); LexingRawMode = true; C = getAndAdvanceChar(CurPtr, Result); LexingRawMode = OldRawMode; // If we only read only one character, then no special handling is needed. // We're done and can skip forward to the newline. if (C != 0 && CurPtr == OldPtr+1) { CurPtr = NextLine; break; } // If we read multiple characters, and one of those characters was a \r or // \n, then we had an escaped newline within the comment. Emit diagnostic // unless the next line is also a // comment. if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') { for (; OldPtr != CurPtr; ++OldPtr) if (OldPtr[0] == '\n' || OldPtr[0] == '\r') { // Okay, we found a // comment that ends in a newline, if the next // line is also a // comment, but has spaces, don't emit a diagnostic. if (isWhitespace(C)) { const char *ForwardPtr = CurPtr; while (isWhitespace(*ForwardPtr)) // Skip whitespace. ++ForwardPtr; if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/') break; } if (!isLexingRawMode()) Diag(OldPtr-1, diag::ext_multi_line_line_comment); break; } } if (CurPtr == BufferEnd+1) { --CurPtr; break; } if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) { PP->CodeCompleteNaturalLanguage(); cutOffLexing(); return false; } } while (C != '\n' && C != '\r'); // Found but did not consume the newline. Notify comment handlers about the // comment unless we're in a #if 0 block. if (PP && !isLexingRawMode() && PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr), getSourceLocation(CurPtr)))) { BufferPtr = CurPtr; return true; // A token has to be returned. } // If we are returning comments as tokens, return this comment as a token. if (inKeepCommentMode()) return SaveLineComment(Result, CurPtr); // If we are inside a preprocessor directive and we see the end of line, // return immediately, so that the lexer can return this as an EOD token. if (ParsingPreprocessorDirective || CurPtr == BufferEnd) { BufferPtr = CurPtr; return false; } // Otherwise, eat the \n character. We don't care if this is a \n\r or // \r\n sequence. This is an efficiency hack (because we know the \n can't // contribute to another token), it isn't needed for correctness. Note that // this is ok even in KeepWhitespaceMode, because we would have returned the /// comment above in that mode. ++CurPtr; // The next returned token is at the start of the line. Result.setFlag(Token::StartOfLine); TokAtPhysicalStartOfLine = true; // No leading whitespace seen so far. Result.clearFlag(Token::LeadingSpace); BufferPtr = CurPtr; return false; } /// If in save-comment mode, package up this Line comment in an appropriate /// way and return it. bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) { // If we're not in a preprocessor directive, just return the // comment // directly. FormTokenWithChars(Result, CurPtr, tok::comment); if (!ParsingPreprocessorDirective || LexingRawMode) return true; // If this Line-style comment is in a macro definition, transmogrify it into // a C-style block comment. bool Invalid = false; std::string Spelling = PP->getSpelling(Result, &Invalid); if (Invalid) return true; assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?"); Spelling[1] = '*'; // Change prefix to "/*". Spelling += "*/"; // add suffix. Result.setKind(tok::comment); PP->CreateString(Spelling, Result, Result.getLocation(), Result.getLocation()); return true; } /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline /// character (either \\n or \\r) is part of an escaped newline sequence. Issue /// a diagnostic if so. We know that the newline is inside of a block comment. static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L) { assert(CurPtr[0] == '\n' || CurPtr[0] == '\r'); // Back up off the newline. --CurPtr; // If this is a two-character newline sequence, skip the other character. if (CurPtr[0] == '\n' || CurPtr[0] == '\r') { // \n\n or \r\r -> not escaped newline. if (CurPtr[0] == CurPtr[1]) return false; // \n\r or \r\n -> skip the newline. --CurPtr; } // If we have horizontal whitespace, skip over it. We allow whitespace // between the slash and newline. bool HasSpace = false; while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) { --CurPtr; HasSpace = true; } // If we have a slash, we know this is an escaped newline. if (*CurPtr == '\\') { if (CurPtr[-1] != '*') return false; } else { // It isn't a slash, is it the ?? / trigraph? if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' || CurPtr[-3] != '*') return false; // This is the trigraph ending the comment. Emit a stern warning! CurPtr -= 2; // If no trigraphs are enabled, warn that we ignored this trigraph and // ignore this * character. if (!L->getLangOpts().Trigraphs) { if (!L->isLexingRawMode()) L->Diag(CurPtr, diag::trigraph_ignored_block_comment); return false; } if (!L->isLexingRawMode()) L->Diag(CurPtr, diag::trigraph_ends_block_comment); } // Warn about having an escaped newline between the */ characters. if (!L->isLexingRawMode()) L->Diag(CurPtr, diag::escaped_newline_block_comment_end); // If there was space between the backslash and newline, warn about it. if (HasSpace && !L->isLexingRawMode()) L->Diag(CurPtr, diag::backslash_newline_space); return true; } #ifdef __SSE2__ #include <emmintrin.h> #elif __ALTIVEC__ #include <altivec.h> #undef bool #endif /// We have just read from input the / and * characters that started a comment. /// Read until we find the * and / characters that terminate the comment. /// Note that we don't bother decoding trigraphs or escaped newlines in block /// comments, because they cannot cause the comment to end. The only thing /// that can happen is the comment could end with an escaped newline between /// the terminating * and /. /// /// If we're in KeepCommentMode or any CommentHandler has inserted /// some tokens, this will store the first token and return true. bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr, bool &TokAtPhysicalStartOfLine) { // Scan one character past where we should, looking for a '/' character. Once // we find it, check to see if it was preceded by a *. This common // optimization helps people who like to put a lot of * characters in their // comments. // The first character we get with newlines and trigraphs skipped to handle // the degenerate /*/ case below correctly if the * has an escaped newline // after it. unsigned CharSize; unsigned char C = getCharAndSize(CurPtr, CharSize); CurPtr += CharSize; if (C == 0 && CurPtr == BufferEnd+1) { if (!isLexingRawMode()) Diag(BufferPtr, diag::err_unterminated_block_comment); --CurPtr; // KeepWhitespaceMode should return this broken comment as a token. Since // it isn't a well formed comment, just return it as an 'unknown' token. if (isKeepWhitespaceMode()) { FormTokenWithChars(Result, CurPtr, tok::unknown); return true; } BufferPtr = CurPtr; return false; } // Check to see if the first character after the '/*' is another /. If so, // then this slash does not end the block comment, it is part of it. if (C == '/') C = *CurPtr++; while (1) { // Skip over all non-interesting characters until we find end of buffer or a // (probably ending) '/' character. if (CurPtr + 24 < BufferEnd && // If there is a code-completion point avoid the fast scan because it // doesn't check for '\0'. !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) { // While not aligned to a 16-byte boundary. while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0) C = *CurPtr++; if (C == '/') goto FoundSlash; #ifdef __SSE2__ __m128i Slashes = _mm_set1_epi8('/'); while (CurPtr+16 <= BufferEnd) { int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr, Slashes)); if (cmp != 0) { // Adjust the pointer to point directly after the first slash. It's // not necessary to set C here, it will be overwritten at the end of // the outer loop. CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1; goto FoundSlash; } CurPtr += 16; } #elif __ALTIVEC__ __vector unsigned char Slashes = { '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/', '/' }; while (CurPtr+16 <= BufferEnd && !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes)) CurPtr += 16; #else // Scan for '/' quickly. Many block comments are very large. while (CurPtr[0] != '/' && CurPtr[1] != '/' && CurPtr[2] != '/' && CurPtr[3] != '/' && CurPtr+4 < BufferEnd) { CurPtr += 4; } #endif // It has to be one of the bytes scanned, increment to it and read one. C = *CurPtr++; } // Loop to scan the remainder. while (C != '/' && C != '\0') C = *CurPtr++; if (C == '/') { FoundSlash: if (CurPtr[-2] == '*') // We found the final */. We're done! break; if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) { if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) { // We found the final */, though it had an escaped newline between the // * and /. We're done! break; } } if (CurPtr[0] == '*' && CurPtr[1] != '/') { // If this is a /* inside of the comment, emit a warning. Don't do this // if this is a /*/, which will end the comment. This misses cases with // embedded escaped newlines, but oh well. if (!isLexingRawMode()) Diag(CurPtr-1, diag::warn_nested_block_comment); } } else if (C == 0 && CurPtr == BufferEnd+1) { if (!isLexingRawMode()) Diag(BufferPtr, diag::err_unterminated_block_comment); // Note: the user probably forgot a */. We could continue immediately // after the /*, but this would involve lexing a lot of what really is the // comment, which surely would confuse the parser. --CurPtr; // KeepWhitespaceMode should return this broken comment as a token. Since // it isn't a well formed comment, just return it as an 'unknown' token. if (isKeepWhitespaceMode()) { FormTokenWithChars(Result, CurPtr, tok::unknown); return true; } BufferPtr = CurPtr; return false; } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) { PP->CodeCompleteNaturalLanguage(); cutOffLexing(); return false; } C = *CurPtr++; } // Notify comment handlers about the comment unless we're in a #if 0 block. if (PP && !isLexingRawMode() && PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr), getSourceLocation(CurPtr)))) { BufferPtr = CurPtr; return true; // A token has to be returned. } // If we are returning comments as tokens, return this comment as a token. if (inKeepCommentMode()) { FormTokenWithChars(Result, CurPtr, tok::comment); return true; } // It is common for the tokens immediately after a /**/ comment to be // whitespace. Instead of going through the big switch, handle it // efficiently now. This is safe even in KeepWhitespaceMode because we would // have already returned above with the comment as a token. if (isHorizontalWhitespace(*CurPtr)) { SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine); return false; } // Otherwise, just return so that the next character will be lexed as a token. BufferPtr = CurPtr; Result.setFlag(Token::LeadingSpace); return false; } //===----------------------------------------------------------------------===// // Primary Lexing Entry Points //===----------------------------------------------------------------------===// /// ReadToEndOfLine - Read the rest of the current preprocessor line as an /// uninterpreted string. This switches the lexer out of directive mode. void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) { assert(ParsingPreprocessorDirective && ParsingFilename == false && "Must be in a preprocessing directive!"); Token Tmp; // CurPtr - Cache BufferPtr in an automatic variable. const char *CurPtr = BufferPtr; while (1) { char Char = getAndAdvanceChar(CurPtr, Tmp); switch (Char) { default: if (Result) Result->push_back(Char); break; case 0: // Null. // Found end of file? if (CurPtr-1 != BufferEnd) { if (isCodeCompletionPoint(CurPtr-1)) { PP->CodeCompleteNaturalLanguage(); cutOffLexing(); return; } // Nope, normal character, continue. if (Result) Result->push_back(Char); break; } LLVM_FALLTHROUGH; // HLSL Change case '\r': case '\n': // Okay, we found the end of the line. First, back up past the \0, \r, \n. assert(CurPtr[-1] == Char && "Trigraphs for newline?"); BufferPtr = CurPtr-1; // Next, lex the character, which should handle the EOD transition. Lex(Tmp); if (Tmp.is(tok::code_completion)) { if (PP) PP->CodeCompleteNaturalLanguage(); Lex(Tmp); } assert(Tmp.is(tok::eod) && "Unexpected token!"); // Finally, we're done; return; } } } /// LexEndOfFile - CurPtr points to the end of this file. Handle this /// condition, reporting diagnostics and handling other edge cases as required. /// This returns true if Result contains a token, false if PP.Lex should be /// called again. bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { // If we hit the end of the file while parsing a preprocessor directive, // end the preprocessor directive first. The next token returned will // then be the end of file. if (ParsingPreprocessorDirective) { // Done parsing the "line". ParsingPreprocessorDirective = false; // Update the location of token as well as BufferPtr. FormTokenWithChars(Result, CurPtr, tok::eod); // Restore comment saving mode, in case it was disabled for directive. if (PP) resetExtendedTokenMode(); return true; // Have a token. } // If we are in raw mode, return this event as an EOF token. Let the caller // that put us in raw mode handle the event. if (isLexingRawMode()) { Result.startToken(); BufferPtr = BufferEnd; FormTokenWithChars(Result, BufferEnd, tok::eof); return true; } // Issue diagnostics for unterminated #if and missing newline. // If we are in a #if directive, emit an error. while (!ConditionalStack.empty()) { if (PP->getCodeCompletionFileLoc() != FileLoc) PP->Diag(ConditionalStack.back().IfLoc, diag::err_pp_unterminated_conditional); ConditionalStack.pop_back(); } // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue // a pedwarn. if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) { DiagnosticsEngine &Diags = PP->getDiagnostics(); SourceLocation EndLoc = getSourceLocation(BufferEnd); unsigned DiagID; if (LangOpts.CPlusPlus11) { // C++11 [lex.phases] 2.2 p2 // Prefer the C++98 pedantic compatibility warning over the generic, // non-extension, user-requested "missing newline at EOF" warning. if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) { DiagID = diag::warn_cxx98_compat_no_newline_eof; } else { DiagID = diag::warn_no_newline_eof; } } else { DiagID = diag::ext_no_newline_eof; } Diag(BufferEnd, DiagID) << FixItHint::CreateInsertion(EndLoc, "\n"); } BufferPtr = CurPtr; // Finally, let the preprocessor handle this. return PP->HandleEndOfFile(Result, isPragmaLexer()); } /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from /// the specified lexer will return a tok::l_paren token, 0 if it is something /// else and 2 if there are no more tokens in the buffer controlled by the /// lexer. unsigned Lexer::isNextPPTokenLParen() { assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?"); // Switch to 'skipping' mode. This will ensure that we can lex a token // without emitting diagnostics, disables macro expansion, and will cause EOF // to return an EOF token instead of popping the include stack. LexingRawMode = true; // Save state that can be changed while lexing so that we can restore it. const char *TmpBufferPtr = BufferPtr; bool inPPDirectiveMode = ParsingPreprocessorDirective; bool atStartOfLine = IsAtStartOfLine; bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine; bool leadingSpace = HasLeadingSpace; Token Tok; Lex(Tok); // Restore state that may have changed. BufferPtr = TmpBufferPtr; ParsingPreprocessorDirective = inPPDirectiveMode; HasLeadingSpace = leadingSpace; IsAtStartOfLine = atStartOfLine; IsAtPhysicalStartOfLine = atPhysicalStartOfLine; // Restore the lexer back to non-skipping mode. LexingRawMode = false; if (Tok.is(tok::eof)) return 2; return Tok.is(tok::l_paren); } /// \brief Find the end of a version control conflict marker. static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd, ConflictMarkerKind CMK) { const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>"; size_t TermLen = CMK == CMK_Perforce ? 5 : 7; StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen); size_t Pos = RestOfBuffer.find(Terminator); while (Pos != StringRef::npos) { // Must occur at start of line. if (Pos == 0 || (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) { RestOfBuffer = RestOfBuffer.substr(Pos+TermLen); Pos = RestOfBuffer.find(Terminator); continue; } return RestOfBuffer.data()+Pos; } return nullptr; } /// IsStartOfConflictMarker - If the specified pointer is the start of a version /// control conflict marker like '<<<<<<<', recognize it as such, emit an error /// and recover nicely. This returns true if it is a conflict marker and false /// if not. bool Lexer::IsStartOfConflictMarker(const char *CurPtr) { // Only a conflict marker if it starts at the beginning of a line. if (CurPtr != BufferStart && CurPtr[-1] != '\n' && CurPtr[-1] != '\r') return false; // Check to see if we have <<<<<<< or >>>>. if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") && (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> ")) return false; // If we have a situation where we don't care about conflict markers, ignore // it. if (CurrentConflictMarkerState || isLexingRawMode()) return false; ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce; // Check to see if there is an ending marker somewhere in the buffer at the // start of a line to terminate this conflict marker. if (FindConflictEnd(CurPtr, BufferEnd, Kind)) { // We found a match. We are really in a conflict marker. // Diagnose this, and ignore to the end of line. Diag(CurPtr, diag::err_conflict_marker); CurrentConflictMarkerState = Kind; // Skip ahead to the end of line. We know this exists because the // end-of-conflict marker starts with \r or \n. while (*CurPtr != '\r' && *CurPtr != '\n') { assert(CurPtr != BufferEnd && "Didn't find end of line"); ++CurPtr; } BufferPtr = CurPtr; return true; } // No end of conflict marker found. return false; } /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it /// is the end of a conflict marker. Handle it by ignoring up until the end of /// the line. This returns true if it is a conflict marker and false if not. bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) { // Only a conflict marker if it starts at the beginning of a line. if (CurPtr != BufferStart && CurPtr[-1] != '\n' && CurPtr[-1] != '\r') return false; // If we have a situation where we don't care about conflict markers, ignore // it. if (!CurrentConflictMarkerState || isLexingRawMode()) return false; // Check to see if we have the marker (4 characters in a row). for (unsigned i = 1; i != 4; ++i) if (CurPtr[i] != CurPtr[0]) return false; // If we do have it, search for the end of the conflict marker. This could // fail if it got skipped with a '#if 0' or something. Note that CurPtr might // be the end of conflict marker. if (const char *End = FindConflictEnd(CurPtr, BufferEnd, CurrentConflictMarkerState)) { CurPtr = End; // Skip ahead to the end of line. while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n') ++CurPtr; BufferPtr = CurPtr; // No longer in the conflict marker. CurrentConflictMarkerState = CMK_None; return true; } return false; } bool Lexer::isCodeCompletionPoint(const char *CurPtr) const { if (PP && PP->isCodeCompletionEnabled()) { SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart); return Loc == PP->getCodeCompletionLoc(); } return false; } uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc, Token *Result) { unsigned CharSize; char Kind = getCharAndSize(StartPtr, CharSize); unsigned NumHexDigits; if (Kind == 'u') NumHexDigits = 4; else if (Kind == 'U') NumHexDigits = 8; else return 0; if (!LangOpts.CPlusPlus && !LangOpts.C99) { if (Result && !isLexingRawMode()) Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89); return 0; } const char *CurPtr = StartPtr + CharSize; const char *KindLoc = &CurPtr[-1]; uint32_t CodePoint = 0; for (unsigned i = 0; i < NumHexDigits; ++i) { char C = getCharAndSize(CurPtr, CharSize); unsigned Value = llvm::hexDigitValue(C); if (Value == -1U) { if (Result && !isLexingRawMode()) { if (i == 0) { Diag(BufferPtr, diag::warn_ucn_escape_no_digits) << StringRef(KindLoc, 1); } else { Diag(BufferPtr, diag::warn_ucn_escape_incomplete); // If the user wrote \U1234, suggest a fixit to \u. if (i == 4 && NumHexDigits == 8) { CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1); Diag(KindLoc, diag::note_ucn_four_not_eight) << FixItHint::CreateReplacement(URange, "u"); } } } return 0; } CodePoint <<= 4; CodePoint += Value; CurPtr += CharSize; } if (Result) { Result->setFlag(Token::HasUCN); if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2) StartPtr = CurPtr; else while (StartPtr != CurPtr) (void)getAndAdvanceChar(StartPtr, *Result); } else { StartPtr = CurPtr; } // Don't apply C family restrictions to UCNs in assembly mode if (LangOpts.AsmPreprocessor) return CodePoint; // C99 6.4.3p2: A universal character name shall not specify a character whose // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or // 0060 (`), nor one in the range D800 through DFFF inclusive.) // C++11 [lex.charset]p2: If the hexadecimal value for a // universal-character-name corresponds to a surrogate code point (in the // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally, // if the hexadecimal value for a universal-character-name outside the // c-char-sequence, s-char-sequence, or r-char-sequence of a character or // string literal corresponds to a control character (in either of the // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the // basic source character set, the program is ill-formed. if (CodePoint < 0xA0) { if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60) return CodePoint; // We don't use isLexingRawMode() here because we need to warn about bad // UCNs even when skipping preprocessing tokens in a #if block. if (Result && PP) { if (CodePoint < 0x20 || CodePoint >= 0x7F) Diag(BufferPtr, diag::err_ucn_control_character); else { char C = static_cast<char>(CodePoint); Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1); } } return 0; } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) { // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't. // We don't use isLexingRawMode() here because we need to diagnose bad // UCNs even when skipping preprocessing tokens in a #if block. if (Result && PP) { if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11) Diag(BufferPtr, diag::warn_ucn_escape_surrogate); else Diag(BufferPtr, diag::err_ucn_escape_invalid); } return 0; } return CodePoint; } bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C, const char *CurPtr) { static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars( UnicodeWhitespaceCharRanges); if (!isLexingRawMode() && !PP->isPreprocessedOutput() && UnicodeWhitespaceChars.contains(C)) { Diag(BufferPtr, diag::ext_unicode_whitespace) << makeCharRange(*this, BufferPtr, CurPtr); Result.setFlag(Token::LeadingSpace); return true; } return false; } bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) { if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) { if (!isLexingRawMode() && !ParsingPreprocessorDirective && !PP->isPreprocessedOutput()) { maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C, makeCharRange(*this, BufferPtr, CurPtr), /*IsFirst=*/true); } MIOpt.ReadToken(); return LexIdentifier(Result, CurPtr); } if (!isLexingRawMode() && !ParsingPreprocessorDirective && !PP->isPreprocessedOutput() && !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) { // Non-ASCII characters tend to creep into source code unintentionally. // Instead of letting the parser complain about the unknown token, // just drop the character. // Note that we can /only/ do this when the non-ASCII character is actually // spelled as Unicode, not written as a UCN. The standard requires that // we not throw away any possible preprocessor tokens, but there's a // loophole in the mapping of Unicode characters to basic character set // characters that allows us to map these particular characters to, say, // whitespace. Diag(BufferPtr, diag::err_non_ascii) << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr)); BufferPtr = CurPtr; return false; } // Otherwise, we have an explicit UCN or a character that's unlikely to show // up by accident. MIOpt.ReadToken(); FormTokenWithChars(Result, CurPtr, tok::unknown); return true; } void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) { IsAtStartOfLine = Result.isAtStartOfLine(); HasLeadingSpace = Result.hasLeadingSpace(); HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro(); // Note that this doesn't affect IsAtPhysicalStartOfLine. } bool Lexer::Lex(Token &Result) { // Start a new token. Result.startToken(); // Set up misc whitespace flags for LexTokenInternal. if (IsAtStartOfLine) { Result.setFlag(Token::StartOfLine); IsAtStartOfLine = false; } if (HasLeadingSpace) { Result.setFlag(Token::LeadingSpace); HasLeadingSpace = false; } if (HasLeadingEmptyMacro) { Result.setFlag(Token::LeadingEmptyMacro); HasLeadingEmptyMacro = false; } bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine; IsAtPhysicalStartOfLine = false; bool isRawLex = isLexingRawMode(); (void) isRawLex; bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine); // (After the LexTokenInternal call, the lexer might be destroyed.) assert((returnedToken || !isRawLex) && "Raw lex must succeed"); return returnedToken; } /// LexTokenInternal - This implements a simple C family lexer. It is an /// extremely performance critical piece of code. This assumes that the buffer /// has a null character at the end of the file. This returns a preprocessing /// token, not a normal token, as such, it is an internal interface. It assumes /// that the Flags of result have been cleared before calling this. bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) { LexNextToken: // New token, can't need cleaning yet. Result.clearFlag(Token::NeedsCleaning); Result.setIdentifierInfo(nullptr); // CurPtr - Cache BufferPtr in an automatic variable. const char *CurPtr = BufferPtr; // Small amounts of horizontal whitespace is very common between tokens. if ((*CurPtr == ' ') || (*CurPtr == '\t')) { ++CurPtr; while ((*CurPtr == ' ') || (*CurPtr == '\t')) ++CurPtr; // If we are keeping whitespace and other tokens, just return what we just // skipped. The next lexer invocation will return the token after the // whitespace. if (isKeepWhitespaceMode()) { FormTokenWithChars(Result, CurPtr, tok::unknown); // FIXME: The next token will not have LeadingSpace set. return true; } BufferPtr = CurPtr; Result.setFlag(Token::LeadingSpace); } unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below. // Read a character, advancing over it. char Char = getAndAdvanceChar(CurPtr, Result); tok::TokenKind Kind; switch (Char) { case 0: // Null. // Found end of file? if (CurPtr-1 == BufferEnd) return LexEndOfFile(Result, CurPtr-1); // Check if we are performing code completion. if (isCodeCompletionPoint(CurPtr-1)) { // Return the code-completion token. Result.startToken(); FormTokenWithChars(Result, CurPtr, tok::code_completion); return true; } if (!isLexingRawMode()) Diag(CurPtr-1, diag::null_in_file); Result.setFlag(Token::LeadingSpace); if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) return true; // KeepWhitespaceMode // We know the lexer hasn't changed, so just try again with this lexer. // (We manually eliminate the tail call to avoid recursion.) goto LexNextToken; case 26: // DOS & CP/M EOF: "^Z". // If we're in Microsoft extensions mode, treat this as end of file. if (LangOpts.MicrosoftExt) return LexEndOfFile(Result, CurPtr-1); // If Microsoft extensions are disabled, this is just random garbage. Kind = tok::unknown; break; case '\n': case '\r': // If we are inside a preprocessor directive and we see the end of line, // we know we are done with the directive, so return an EOD token. if (ParsingPreprocessorDirective) { // Done parsing the "line". ParsingPreprocessorDirective = false; // Restore comment saving mode, in case it was disabled for directive. if (PP) resetExtendedTokenMode(); // Since we consumed a newline, we are back at the start of a line. IsAtStartOfLine = true; IsAtPhysicalStartOfLine = true; Kind = tok::eod; break; } // No leading whitespace seen so far. Result.clearFlag(Token::LeadingSpace); if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) return true; // KeepWhitespaceMode // We only saw whitespace, so just try again with this lexer. // (We manually eliminate the tail call to avoid recursion.) goto LexNextToken; case ' ': case '\t': case '\f': case '\v': SkipHorizontalWhitespace: Result.setFlag(Token::LeadingSpace); if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) return true; // KeepWhitespaceMode SkipIgnoredUnits: CurPtr = BufferPtr; // If the next token is obviously a // or /* */ comment, skip it efficiently // too (without going through the big switch stmt). if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() && LangOpts.LineComment && (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) { if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine)) return true; // There is a token to return. goto SkipIgnoredUnits; } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) { if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine)) return true; // There is a token to return. goto SkipIgnoredUnits; } else if (isHorizontalWhitespace(*CurPtr)) { goto SkipHorizontalWhitespace; } // We only saw whitespace, so just try again with this lexer. // (We manually eliminate the tail call to avoid recursion.) goto LexNextToken; // C99 6.4.4.1: Integer Constants. // C99 6.4.4.2: Floating Constants. case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); return LexNumericConstant(Result, CurPtr); case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); if (LangOpts.CPlusPlus11 || LangOpts.C11) { Char = getCharAndSize(CurPtr, SizeTmp); // UTF-16 string literal if (Char == '"') return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), tok::utf16_string_literal); // UTF-16 character constant if (Char == '\'') return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result), tok::utf16_char_constant); // UTF-16 raw string literal if (Char == 'R' && LangOpts.CPlusPlus11 && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"') return LexRawStringLiteral(Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result), tok::utf16_string_literal); if (Char == '8') { char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2); // UTF-8 string literal if (Char2 == '"') return LexStringLiteral(Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result), tok::utf8_string_literal); if (Char2 == '\'' && LangOpts.CPlusPlus1z) return LexCharConstant( Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result), tok::utf8_char_constant); if (Char2 == 'R' && LangOpts.CPlusPlus11) { unsigned SizeTmp3; char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3); // UTF-8 raw string literal if (Char3 == '"') { return LexRawStringLiteral(Result, ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result), SizeTmp3, Result), tok::utf8_string_literal); } } } } // treat u like the start of an identifier. return LexIdentifier(Result, CurPtr); case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); if (LangOpts.CPlusPlus11 || LangOpts.C11) { Char = getCharAndSize(CurPtr, SizeTmp); // UTF-32 string literal if (Char == '"') return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), tok::utf32_string_literal); // UTF-32 character constant if (Char == '\'') return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result), tok::utf32_char_constant); // UTF-32 raw string literal if (Char == 'R' && LangOpts.CPlusPlus11 && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"') return LexRawStringLiteral(Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result), tok::utf32_string_literal); } // treat U like the start of an identifier. return LexIdentifier(Result, CurPtr); case 'R': // Identifier or C++0x raw string literal // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); if (LangOpts.CPlusPlus11) { Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '"') return LexRawStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), tok::string_literal); } // treat R like the start of an identifier. return LexIdentifier(Result, CurPtr); case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz"). // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); Char = getCharAndSize(CurPtr, SizeTmp); // Wide string literal. if (Char == '"') return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), tok::wide_string_literal); // Wide raw string literal. if (LangOpts.CPlusPlus11 && Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"') return LexRawStringLiteral(Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result), tok::wide_string_literal); // Wide character constant. if (Char == '\'') return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result), tok::wide_char_constant); // FALL THROUGH, treating L like the start of an identifier. LLVM_FALLTHROUGH; // HLSL Change // C99 6.4.2: Identifiers. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N': case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/ case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/ case 'v': case 'w': case 'x': case 'y': case 'z': case '_': // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); return LexIdentifier(Result, CurPtr); case '$': // $ in identifiers. if (LangOpts.DollarIdents) { if (!isLexingRawMode()) Diag(CurPtr-1, diag::ext_dollar_in_identifier); // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); return LexIdentifier(Result, CurPtr); } Kind = tok::unknown; break; // C99 6.4.4: Character Constants. case '\'': // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); return LexCharConstant(Result, CurPtr, tok::char_constant); // C99 6.4.5: String Literals. case '"': // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); return LexStringLiteral(Result, CurPtr, tok::string_literal); // C99 6.4.6: Punctuators. case '?': Kind = tok::question; break; case '[': Kind = tok::l_square; break; case ']': Kind = tok::r_square; break; case '(': Kind = tok::l_paren; break; case ')': Kind = tok::r_paren; break; case '{': Kind = tok::l_brace; break; case '}': Kind = tok::r_brace; break; case '.': Char = getCharAndSize(CurPtr, SizeTmp); if (Char >= '0' && Char <= '9') { // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result)); } else if (LangOpts.CPlusPlus && Char == '*') { Kind = tok::periodstar; CurPtr += SizeTmp; } else if (Char == '.' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') { Kind = tok::ellipsis; CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result); } else { Kind = tok::period; } break; case '&': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '&') { Kind = tok::ampamp; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else if (Char == '=') { Kind = tok::ampequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::amp; } break; case '*': if (getCharAndSize(CurPtr, SizeTmp) == '=') { Kind = tok::starequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::star; } break; case '+': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '+') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::plusplus; } else if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::plusequal; } else { Kind = tok::plus; } break; case '-': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '-') { // -- CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::minusminus; } else if (Char == '>' && LangOpts.CPlusPlus && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->* CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result); Kind = tok::arrowstar; } else if (Char == '>') { // -> CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::arrow; } else if (Char == '=') { // -= CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::minusequal; } else { Kind = tok::minus; } break; case '~': Kind = tok::tilde; break; case '!': if (getCharAndSize(CurPtr, SizeTmp) == '=') { Kind = tok::exclaimequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::exclaim; } break; case '/': // 6.4.9: Comments Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '/') { // Line comment. // Even if Line comments are disabled (e.g. in C89 mode), we generally // want to lex this as a comment. There is one problem with this though, // that in one particular corner case, this can change the behavior of the // resultant program. For example, In "foo //**/ bar", C89 would lex // this as "foo / bar" and langauges with Line comments would lex it as // "foo". Check to see if the character after the second slash is a '*'. // If so, we will lex that as a "/" instead of the start of a comment. // However, we never do this if we are just preprocessing. bool TreatAsComment = LangOpts.LineComment && (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP); if (!TreatAsComment) if (!(PP && PP->isPreprocessedOutput())) TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*'; if (TreatAsComment) { if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result), TokAtPhysicalStartOfLine)) return true; // There is a token to return. // It is common for the tokens immediately after a // comment to be // whitespace (indentation for the next line). Instead of going through // the big switch, handle it efficiently now. goto SkipIgnoredUnits; } } if (Char == '*') { // /**/ comment. if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result), TokAtPhysicalStartOfLine)) return true; // There is a token to return. // We only saw whitespace, so just try again with this lexer. // (We manually eliminate the tail call to avoid recursion.) goto LexNextToken; } if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::slashequal; } else { Kind = tok::slash; } break; case '%': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '=') { Kind = tok::percentequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else if (LangOpts.Digraphs && Char == '>') { Kind = tok::r_brace; // '%>' -> '}' CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else if (LangOpts.Digraphs && Char == ':') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') { Kind = tok::hashhash; // '%:%:' -> '##' CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result); } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); if (!isLexingRawMode()) Diag(BufferPtr, diag::ext_charize_microsoft); Kind = tok::hashat; } else { // '%:' -> '#' // We parsed a # character. If this occurs at the start of the line, // it's actually the start of a preprocessing directive. Callback to // the preprocessor to handle it. // TODO: -fpreprocessed mode?? if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer) goto HandleDirective; Kind = tok::hash; } } else { Kind = tok::percent; } break; case '<': Char = getCharAndSize(CurPtr, SizeTmp); if (ParsingFilename) { return LexAngledStringLiteral(Result, CurPtr); } else if (Char == '<') { char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2); if (After == '=') { Kind = tok::lesslessequal; CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result); } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) { // If this is actually a '<<<<<<<' version control conflict marker, // recognize it as such and recover nicely. goto LexNextToken; } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) { // If this is '<<<<' and we're in a Perforce-style conflict marker, // ignore it. goto LexNextToken; } else if (LangOpts.CUDA && After == '<') { Kind = tok::lesslessless; CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result); } else { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::lessless; } } else if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::lessequal; } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '[' if (LangOpts.CPlusPlus11 && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') { // C++0x [lex.pptoken]p3: // Otherwise, if the next three characters are <:: and the subsequent // character is neither : nor >, the < is treated as a preprocessor // token by itself and not as the first character of the alternative // token <:. unsigned SizeTmp3; char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3); if (After != ':' && After != '>') { Kind = tok::less; if (!isLexingRawMode()) Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon); break; } } CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::l_square; } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{' CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::l_brace; } else { Kind = tok::less; } break; case '>': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::greaterequal; } else if (Char == '>') { char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2); if (After == '=') { CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result); Kind = tok::greatergreaterequal; } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) { // If this is actually a '>>>>' conflict marker, recognize it as such // and recover nicely. goto LexNextToken; } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) { // If this is '>>>>>>>' and we're in a conflict marker, ignore it. goto LexNextToken; } else if (LangOpts.CUDA && After == '>') { Kind = tok::greatergreatergreater; CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), SizeTmp2, Result); } else { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::greatergreater; } } else { Kind = tok::greater; } break; case '^': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '=') { CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); Kind = tok::caretequal; } else { Kind = tok::caret; } break; case '|': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '=') { Kind = tok::pipeequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else if (Char == '|') { // If this is '|||||||' and we're in a conflict marker, ignore it. if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1)) goto LexNextToken; Kind = tok::pipepipe; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::pipe; } break; case ':': Char = getCharAndSize(CurPtr, SizeTmp); if (LangOpts.Digraphs && Char == '>') { Kind = tok::r_square; // ':>' -> ']' CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else if (LangOpts.CPlusPlus && Char == ':') { Kind = tok::coloncolon; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::colon; } break; case ';': Kind = tok::semi; break; case '=': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '=') { // If this is '====' and we're in a conflict marker, ignore it. if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1)) goto LexNextToken; Kind = tok::equalequal; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { Kind = tok::equal; } break; case ',': Kind = tok::comma; break; case '#': Char = getCharAndSize(CurPtr, SizeTmp); if (Char == '#') { Kind = tok::hashhash; CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize Kind = tok::hashat; if (!isLexingRawMode()) Diag(BufferPtr, diag::ext_charize_microsoft); CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); } else { // We parsed a # character. If this occurs at the start of the line, // it's actually the start of a preprocessing directive. Callback to // the preprocessor to handle it. // TODO: -fpreprocessed mode?? if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer) goto HandleDirective; Kind = tok::hash; } break; case '@': // Objective C support. if (CurPtr[-1] == '@' && LangOpts.ObjC1) Kind = tok::at; else Kind = tok::unknown; break; // UCNs (C99 6.4.3, C++11 [lex.charset]p2) case '\\': if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) { if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) { if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) return true; // KeepWhitespaceMode // We only saw whitespace, so just try again with this lexer. // (We manually eliminate the tail call to avoid recursion.) goto LexNextToken; } return LexUnicode(Result, CodePoint, CurPtr); } Kind = tok::unknown; break; default: { if (isASCII(Char)) { Kind = tok::unknown; break; } UTF32 CodePoint; // We can't just reset CurPtr to BufferPtr because BufferPtr may point to // an escaped newline. --CurPtr; ConversionResult Status = llvm::convertUTF8Sequence((const UTF8 **)&CurPtr, (const UTF8 *)BufferEnd, &CodePoint, strictConversion); if (Status == conversionOK) { if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) { if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) return true; // KeepWhitespaceMode // We only saw whitespace, so just try again with this lexer. // (We manually eliminate the tail call to avoid recursion.) goto LexNextToken; } return LexUnicode(Result, CodePoint, CurPtr); } if (isLexingRawMode() || ParsingPreprocessorDirective || PP->isPreprocessedOutput()) { ++CurPtr; Kind = tok::unknown; break; } // Non-ASCII characters tend to creep into source code unintentionally. // Instead of letting the parser complain about the unknown token, // just diagnose the invalid UTF-8, then drop the character. Diag(CurPtr, diag::err_invalid_utf8); BufferPtr = CurPtr+1; // We're pretending the character didn't exist, so just try again with // this lexer. // (We manually eliminate the tail call to avoid recursion.) goto LexNextToken; } } // Notify MIOpt that we read a non-whitespace/non-comment token. MIOpt.ReadToken(); // Update the location of token as well as BufferPtr. FormTokenWithChars(Result, CurPtr, Kind); return true; HandleDirective: // We parsed a # character and it's the start of a preprocessing directive. FormTokenWithChars(Result, CurPtr, tok::hash); PP->HandleDirective(Result); if (PP->hadModuleLoaderFatalFailure()) { // With a fatal failure in the module loader, we abort parsing. assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof"); return true; } // We parsed the directive; lex a token with the new state. return false; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/PPLexerChange.cpp
//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements pieces of the Preprocessor interface that manage the // current lexer stack. // //===----------------------------------------------------------------------===// #include "clang/Lex/Preprocessor.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/MacroInfo.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" using namespace clang; PPCallbacks::~PPCallbacks() {} //===----------------------------------------------------------------------===// // Miscellaneous Methods. //===----------------------------------------------------------------------===// /// isInPrimaryFile - Return true if we're in the top-level file, not in a /// \#include. This looks through macro expansions and active _Pragma lexers. bool Preprocessor::isInPrimaryFile() const { if (IsFileLexer()) return IncludeMacroStack.empty(); // If there are any stacked lexers, we're in a #include. assert(IsFileLexer(IncludeMacroStack[0]) && "Top level include stack isn't our primary lexer?"); for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i) if (IsFileLexer(IncludeMacroStack[i])) return false; return true; } /// getCurrentLexer - Return the current file lexer being lexed from. Note /// that this ignores any potentially active macro expansions and _Pragma /// expansions going on at the time. PreprocessorLexer *Preprocessor::getCurrentFileLexer() const { if (IsFileLexer()) return CurPPLexer; // Look for a stacked lexer. for (unsigned i = IncludeMacroStack.size(); i != 0; --i) { const IncludeStackInfo& ISI = IncludeMacroStack[i-1]; if (IsFileLexer(ISI)) return ISI.ThePPLexer; } return nullptr; } //===----------------------------------------------------------------------===// // Methods for Entering and Callbacks for leaving various contexts //===----------------------------------------------------------------------===// /// EnterSourceFile - Add a source file to the top of the include stack and /// start lexing tokens from it instead of the current buffer. bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir, SourceLocation Loc) { assert(!CurTokenLexer && "Cannot #include a file inside a macro!"); ++NumEnteredSourceFiles; if (MaxIncludeStackDepth < IncludeMacroStack.size()) MaxIncludeStackDepth = IncludeMacroStack.size(); if (PTH) { if (PTHLexer *PL = PTH->CreateLexer(FID)) { EnterSourceFileWithPTH(PL, CurDir); return false; } } // Get the MemoryBuffer for this FID, if it fails, we fail. bool Invalid = false; const llvm::MemoryBuffer *InputFile = getSourceManager().getBuffer(FID, Loc, &Invalid); if (Invalid) { SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID); Diag(Loc, diag::err_pp_error_opening_file) << std::string(SourceMgr.getBufferName(FileStart)) << ""; return true; } if (isCodeCompletionEnabled() && SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) { CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID); CodeCompletionLoc = CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset); } EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir); return false; } /// EnterSourceFileWithLexer - Add a source file to the top of the include stack /// and start lexing tokens from it instead of the current buffer. void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer, const DirectoryLookup *CurDir) { std::unique_ptr<Lexer> LexerGuard(TheLexer); // HLSL Change - guard // Add the current lexer to the include stack. if (CurPPLexer || CurTokenLexer) PushIncludeMacroStack(); LexerGuard.release(); // HLSL Change CurLexer.reset(TheLexer); CurPPLexer = TheLexer; CurDirLookup = CurDir; CurSubmodule = nullptr; if (CurLexerKind != CLK_LexAfterModuleImport) CurLexerKind = CLK_Lexer; // Notify the client, if desired, that we are in a new source file. if (Callbacks && !CurLexer->Is_PragmaLexer) { SrcMgr::CharacteristicKind FileType = SourceMgr.getFileCharacteristic(CurLexer->getFileLoc()); Callbacks->FileChanged(CurLexer->getFileLoc(), PPCallbacks::EnterFile, FileType); } } /// EnterSourceFileWithPTH - Add a source file to the top of the include stack /// and start getting tokens from it using the PTH cache. void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL, const DirectoryLookup *CurDir) { if (CurPPLexer || CurTokenLexer) PushIncludeMacroStack(); CurDirLookup = CurDir; CurPTHLexer.reset(PL); CurPPLexer = CurPTHLexer.get(); CurSubmodule = nullptr; if (CurLexerKind != CLK_LexAfterModuleImport) CurLexerKind = CLK_PTHLexer; // Notify the client, if desired, that we are in a new source file. if (Callbacks) { FileID FID = CurPPLexer->getFileID(); SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID); SrcMgr::CharacteristicKind FileType = SourceMgr.getFileCharacteristic(EnterLoc); Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType); } } /// EnterMacro - Add a Macro to the top of the include stack and start lexing /// tokens from it instead of the current buffer. void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro, MacroArgs *Args) { std::unique_ptr<TokenLexer> TokLexer; if (NumCachedTokenLexers == 0) { TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this); } else { TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]); TokLexer->Init(Tok, ILEnd, Macro, Args); } PushIncludeMacroStack(); CurDirLookup = nullptr; CurTokenLexer = std::move(TokLexer); if (CurLexerKind != CLK_LexAfterModuleImport) CurLexerKind = CLK_TokenLexer; } /// EnterTokenStream - Add a "macro" context to the top of the include stack, /// which will cause the lexer to start returning the specified tokens. /// /// If DisableMacroExpansion is true, tokens lexed from the token stream will /// not be subject to further macro expansion. Otherwise, these tokens will /// be re-macro-expanded when/if expansion is enabled. /// /// If OwnsTokens is false, this method assumes that the specified stream of /// tokens has a permanent owner somewhere, so they do not need to be copied. /// If it is true, it assumes the array of tokens is allocated with new[] and /// must be freed. /// void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks, bool DisableMacroExpansion, bool OwnsTokens) { if (CurLexerKind == CLK_CachingLexer) { if (CachedLexPos < CachedTokens.size()) { // We're entering tokens into the middle of our cached token stream. We // can't represent that, so just insert the tokens into the buffer. CachedTokens.insert(CachedTokens.begin() + CachedLexPos, Toks, Toks + NumToks); if (OwnsTokens) delete [] Toks; return; } // New tokens are at the end of the cached token sequnece; insert the // token stream underneath the caching lexer. ExitCachingLexMode(); EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens); EnterCachingLexMode(); return; } // Create a macro expander to expand from the specified token stream. std::unique_ptr<TokenLexer> TokLexer; if (NumCachedTokenLexers == 0) { TokLexer = llvm::make_unique<TokenLexer>( Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this); } else { TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]); TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens); } // Save our current state. PushIncludeMacroStack(); CurDirLookup = nullptr; CurTokenLexer = std::move(TokLexer); if (CurLexerKind != CLK_LexAfterModuleImport) CurLexerKind = CLK_TokenLexer; } /// \brief Compute the relative path that names the given file relative to /// the given directory. static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir, const FileEntry *File, SmallString<128> &Result) { Result.clear(); StringRef FilePath = File->getDir()->getName(); StringRef Path = FilePath; while (!Path.empty()) { if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) { if (CurDir == Dir) { Result = FilePath.substr(Path.size()); llvm::sys::path::append(Result, llvm::sys::path::filename(File->getName())); return; } } Path = llvm::sys::path::parent_path(Path); } Result = File->getName(); } void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) { if (CurTokenLexer) { CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result); return; } if (CurLexer) { CurLexer->PropagateLineStartLeadingSpaceInfo(Result); return; } // FIXME: Handle other kinds of lexers? It generally shouldn't matter, // but it might if they're empty? } /// \brief Determine the location to use as the end of the buffer for a lexer. /// /// If the file ends with a newline, form the EOF token on the newline itself, /// rather than "on the line following it", which doesn't exist. This makes /// diagnostics relating to the end of file include the last file that the user /// actually typed, which is goodness. const char *Preprocessor::getCurLexerEndPos() { const char *EndPos = CurLexer->BufferEnd; if (EndPos != CurLexer->BufferStart && (EndPos[-1] == '\n' || EndPos[-1] == '\r')) { --EndPos; // Handle \n\r and \r\n: if (EndPos != CurLexer->BufferStart && (EndPos[-1] == '\n' || EndPos[-1] == '\r') && EndPos[-1] != EndPos[0]) --EndPos; } return EndPos; } /// HandleEndOfFile - This callback is invoked when the lexer hits the end of /// the current file. This either returns the EOF token or pops a level off /// the include stack and keeps going. bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) { assert(!CurTokenLexer && "Ending a file when currently in a macro!"); // See if this file had a controlling macro. if (CurPPLexer) { // Not ending a macro, ignore it. if (const IdentifierInfo *ControllingMacro = CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) { // Okay, this has a controlling macro, remember in HeaderFileInfo. if (const FileEntry *FE = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())) { HeaderInfo.SetFileControllingMacro(FE, ControllingMacro); if (MacroInfo *MI = getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro))) { MI->UsedForHeaderGuard = true; } if (const IdentifierInfo *DefinedMacro = CurPPLexer->MIOpt.GetDefinedMacro()) { if (!isMacroDefined(ControllingMacro) && DefinedMacro != ControllingMacro && HeaderInfo.FirstTimeLexingFile(FE)) { // If the edit distance between the two macros is more than 50%, // DefinedMacro may not be header guard, or can be header guard of // another header file. Therefore, it maybe defining something // completely different. This can be observed in the wild when // handling feature macros or header guards in different files. const StringRef ControllingMacroName = ControllingMacro->getName(); const StringRef DefinedMacroName = DefinedMacro->getName(); const size_t MaxHalfLength = std::max(ControllingMacroName.size(), DefinedMacroName.size()) / 2; const unsigned ED = ControllingMacroName.edit_distance( DefinedMacroName, true, MaxHalfLength); if (ED <= MaxHalfLength) { // Emit a warning for a bad header guard. Diag(CurPPLexer->MIOpt.GetMacroLocation(), diag::warn_header_guard) << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro; Diag(CurPPLexer->MIOpt.GetDefinedLocation(), diag::note_header_guard) << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro << ControllingMacro << FixItHint::CreateReplacement( CurPPLexer->MIOpt.GetDefinedLocation(), ControllingMacro->getName()); } } } } } } // Complain about reaching a true EOF within arc_cf_code_audited. // We don't want to complain about reaching the end of a macro // instantiation or a _Pragma. if (PragmaARCCFCodeAuditedLoc.isValid() && !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) { Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited); // Recover by leaving immediately. PragmaARCCFCodeAuditedLoc = SourceLocation(); } // Complain about reaching a true EOF within assume_nonnull. // We don't want to complain about reaching the end of a macro // instantiation or a _Pragma. if (PragmaAssumeNonNullLoc.isValid() && !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) { Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull); // Recover by leaving immediately. PragmaAssumeNonNullLoc = SourceLocation(); } // If this is a #include'd file, pop it off the include stack and continue // lexing the #includer file. if (!IncludeMacroStack.empty()) { // If we lexed the code-completion file, act as if we reached EOF. if (isCodeCompletionEnabled() && CurPPLexer && SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) == CodeCompletionFileLoc) { if (CurLexer) { Result.startToken(); CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); CurLexer.reset(); } else { assert(CurPTHLexer && "Got EOF but no current lexer set!"); CurPTHLexer->getEOF(Result); CurPTHLexer.reset(); } CurPPLexer = nullptr; return true; } if (!isEndOfMacro && CurPPLexer && SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) { // Notify SourceManager to record the number of FileIDs that were created // during lexing of the #include'd file. unsigned NumFIDs = SourceMgr.local_sloc_entry_size() - CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/; SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs); } FileID ExitedFID; if (Callbacks && !isEndOfMacro && CurPPLexer) ExitedFID = CurPPLexer->getFileID(); bool LeavingSubmodule = CurSubmodule && CurLexer; if (LeavingSubmodule) { // Notify the parser that we've left the module. const char *EndPos = getCurLexerEndPos(); Result.startToken(); CurLexer->BufferPtr = EndPos; CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end); Result.setAnnotationEndLoc(Result.getLocation()); Result.setAnnotationValue(CurSubmodule); // We're done with this submodule. LeaveSubmodule(); } // We're done with the #included file. RemoveTopOfLexerStack(); // Propagate info about start-of-line/leading white-space/etc. PropagateLineStartLeadingSpaceInfo(Result); // Notify the client, if desired, that we are in a new source file. if (Callbacks && !isEndOfMacro && CurPPLexer) { SrcMgr::CharacteristicKind FileType = SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation()); Callbacks->FileChanged(CurPPLexer->getSourceLocation(), PPCallbacks::ExitFile, FileType, ExitedFID); } // Client should lex another token unless we generated an EOM. return LeavingSubmodule; } // If this is the end of the main file, form an EOF token. if (CurLexer) { const char *EndPos = getCurLexerEndPos(); Result.startToken(); CurLexer->BufferPtr = EndPos; CurLexer->FormTokenWithChars(Result, EndPos, tok::eof); if (isCodeCompletionEnabled()) { // Inserting the code-completion point increases the source buffer by 1, // but the main FileID was created before inserting the point. // Compensate by reducing the EOF location by 1, otherwise the location // will point to the next FileID. // FIXME: This is hacky, the code-completion point should probably be // inserted before the main FileID is created. if (CurLexer->getFileLoc() == CodeCompletionFileLoc) Result.setLocation(Result.getLocation().getLocWithOffset(-1)); } if (!isIncrementalProcessingEnabled()) // We're done with lexing. CurLexer.reset(); } else { assert(CurPTHLexer && "Got EOF but no current lexer set!"); CurPTHLexer->getEOF(Result); CurPTHLexer.reset(); } if (!isIncrementalProcessingEnabled()) CurPPLexer = nullptr; if (TUKind == TU_Complete) { // This is the end of the top-level file. 'WarnUnusedMacroLocs' has // collected all macro locations that we need to warn because they are not // used. for (WarnUnusedMacroLocsTy::iterator I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); I!=E; ++I) Diag(*I, diag::pp_macro_not_used); } // If we are building a module that has an umbrella header, make sure that // each of the headers within the directory covered by the umbrella header // was actually included by the umbrella header. if (Module *Mod = getCurrentModule()) { if (Mod->getUmbrellaHeader()) { SourceLocation StartLoc = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); if (!getDiagnostics().isIgnored(diag::warn_uncovered_module_header, StartLoc)) { ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap(); const DirectoryEntry *Dir = Mod->getUmbrellaDir().Entry; vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); std::error_code EC; for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End; Entry != End && !EC; Entry.increment(EC)) { using llvm::StringSwitch; // Check whether this entry has an extension typically associated with // headers. if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->getName())) .Cases(".h", ".H", ".hh", ".hpp", true) .Default(false)) continue; if (const FileEntry *Header = getFileManager().getFile(Entry->getName())) if (!getSourceManager().hasFileInfo(Header)) { if (!ModMap.isHeaderInUnavailableModule(Header)) { // Find the relative path that would access this header. SmallString<128> RelativePath; computeRelativePath(FileMgr, Dir, Header, RelativePath); Diag(StartLoc, diag::warn_uncovered_module_header) << Mod->getFullModuleName() << RelativePath; } } } } } } return true; } /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer /// hits the end of its token stream. bool Preprocessor::HandleEndOfTokenLexer(Token &Result) { assert(CurTokenLexer && !CurPPLexer && "Ending a macro when currently in a #include file!"); if (!MacroExpandingLexersStack.empty() && MacroExpandingLexersStack.back().first == CurTokenLexer.get()) removeCachedMacroExpandedTokensOfLastLexer(); // Delete or cache the now-dead macro expander. if (NumCachedTokenLexers == TokenLexerCacheSize) CurTokenLexer.reset(); else TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer); // Handle this like a #include file being popped off the stack. return HandleEndOfFile(Result, true); } /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the /// lexer stack. This should only be used in situations where the current /// state of the top-of-stack lexer is unknown. void Preprocessor::RemoveTopOfLexerStack() { assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load"); if (CurTokenLexer) { // Delete or cache the now-dead macro expander. if (NumCachedTokenLexers == TokenLexerCacheSize) CurTokenLexer.reset(); else TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer); } PopIncludeMacroStack(); } /// HandleMicrosoftCommentPaste - When the macro expander pastes together a /// comment (/##/) in microsoft mode, this method handles updating the current /// state, returning the token on the next source line. void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) { assert(CurTokenLexer && !CurPPLexer && "Pasted comment can only be formed from macro"); // We handle this by scanning for the closest real lexer, switching it to // raw mode and preprocessor mode. This will cause it to return \n as an // explicit EOD token. PreprocessorLexer *FoundLexer = nullptr; bool LexerWasInPPMode = false; for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1); if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer. // Once we find a real lexer, mark it as raw mode (disabling macro // expansions) and preprocessor mode (return EOD). We know that the lexer // was *not* in raw mode before, because the macro that the comment came // from was expanded. However, it could have already been in preprocessor // mode (#if COMMENT) in which case we have to return it to that mode and // return EOD. FoundLexer = ISI.ThePPLexer; FoundLexer->LexingRawMode = true; LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective; FoundLexer->ParsingPreprocessorDirective = true; break; } // Okay, we either found and switched over the lexer, or we didn't find a // lexer. In either case, finish off the macro the comment came from, getting // the next token. if (!HandleEndOfTokenLexer(Tok)) Lex(Tok); // Discarding comments as long as we don't have EOF or EOD. This 'comments // out' the rest of the line, including any tokens that came from other macros // that were active, as in: // #define submacro a COMMENT b // submacro c // which should lex to 'a' only: 'b' and 'c' should be removed. while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) Lex(Tok); // If we got an eod token, then we successfully found the end of the line. if (Tok.is(tok::eod)) { assert(FoundLexer && "Can't get end of line without an active lexer"); // Restore the lexer back to normal mode instead of raw mode. FoundLexer->LexingRawMode = false; // If the lexer was already in preprocessor mode, just return the EOD token // to finish the preprocessor line. if (LexerWasInPPMode) return; // Otherwise, switch out of PP mode and return the next lexed token. FoundLexer->ParsingPreprocessorDirective = false; return Lex(Tok); } // If we got an EOF token, then we reached the end of the token stream but // didn't find an explicit \n. This can only happen if there was no lexer // active (an active lexer would return EOD at EOF if there was no \n in // preprocessor directive mode), so just return EOF as our token. assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode"); } void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc) { if (!getLangOpts().ModulesLocalVisibility) { // Just track that we entered this submodule. BuildingSubmoduleStack.push_back( BuildingSubmoduleInfo(M, ImportLoc, CurSubmoduleState)); return; } // Resolve as much of the module definition as we can now, before we enter // one of its headers. // FIXME: Can we enable Complain here? // FIXME: Can we do this when local visibility is disabled? ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap(); ModMap.resolveExports(M, /*Complain=*/false); ModMap.resolveUses(M, /*Complain=*/false); ModMap.resolveConflicts(M, /*Complain=*/false); // If this is the first time we've entered this module, set up its state. auto R = Submodules.insert(std::make_pair(M, SubmoduleState())); auto &State = R.first->second; bool FirstTime = R.second; if (FirstTime) { // Determine the set of starting macros for this submodule; take these // from the "null" module (the predefines buffer). // // FIXME: If we have local visibility but not modules enabled, the // NullSubmoduleState is polluted by #defines in the top-level source // file. auto &StartingMacros = NullSubmoduleState.Macros; // Restore to the starting state. // FIXME: Do this lazily, when each macro name is first referenced. for (auto &Macro : StartingMacros) { // Skip uninteresting macros. if (!Macro.second.getLatest() && Macro.second.getOverriddenMacros().empty()) continue; MacroState MS(Macro.second.getLatest()); MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros()); State.Macros.insert(std::make_pair(Macro.first, std::move(MS))); } } // Track that we entered this module. BuildingSubmoduleStack.push_back( BuildingSubmoduleInfo(M, ImportLoc, CurSubmoduleState)); // Switch to this submodule as the current submodule. CurSubmoduleState = &State; // This module is visible to itself. if (FirstTime) makeModuleVisible(M, ImportLoc); } void Preprocessor::LeaveSubmodule() { auto &Info = BuildingSubmoduleStack.back(); Module *LeavingMod = Info.M; SourceLocation ImportLoc = Info.ImportLoc; // Create ModuleMacros for any macros defined in this submodule. for (auto &Macro : CurSubmoduleState->Macros) { auto *II = const_cast<IdentifierInfo*>(Macro.first); // Find the starting point for the MacroDirective chain in this submodule. MacroDirective *OldMD = nullptr; if (getLangOpts().ModulesLocalVisibility) { // FIXME: It'd be better to start at the state from when we most recently // entered this submodule, but it doesn't really matter. auto &PredefMacros = NullSubmoduleState.Macros; auto PredefMacroIt = PredefMacros.find(Macro.first); if (PredefMacroIt == PredefMacros.end()) OldMD = nullptr; else OldMD = PredefMacroIt->second.getLatest(); } // This module may have exported a new macro. If so, create a ModuleMacro // representing that fact. bool ExplicitlyPublic = false; for (auto *MD = Macro.second.getLatest(); MD != OldMD; MD = MD->getPrevious()) { assert(MD && "broken macro directive chain"); // Stop on macros defined in other submodules we #included along the way. // There's no point doing this if we're tracking local submodule // visibility, since there can be no such directives in our list. if (!getLangOpts().ModulesLocalVisibility) { Module *Mod = getModuleContainingLocation(MD->getLocation()); if (Mod != LeavingMod) break; } if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) { // The latest visibility directive for a name in a submodule affects // all the directives that come before it. if (VisMD->isPublic()) ExplicitlyPublic = true; else if (!ExplicitlyPublic) // Private with no following public directive: not exported. break; } else { MacroInfo *Def = nullptr; if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) Def = DefMD->getInfo(); // FIXME: Issue a warning if multiple headers for the same submodule // define a macro, rather than silently ignoring all but the first. bool IsNew; // Don't bother creating a module macro if it would represent a #undef // that doesn't override anything. if (Def || !Macro.second.getOverriddenMacros().empty()) addModuleMacro(LeavingMod, II, Def, Macro.second.getOverriddenMacros(), IsNew); break; } } } // FIXME: Before we leave this submodule, we should parse all the other // headers within it. Otherwise, we're left with an inconsistent state // where we've made the module visible but don't yet have its complete // contents. // Put back the outer module's state, if we're tracking it. if (getLangOpts().ModulesLocalVisibility) CurSubmoduleState = Info.OuterSubmoduleState; BuildingSubmoduleStack.pop_back(); // A nested #include makes the included submodule visible. makeModuleVisible(LeavingMod, ImportLoc); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/UnicodeCharSets.h
//===--- UnicodeCharSets.h - Contains important sets of characters --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LIB_LEX_UNICODECHARSETS_H #define LLVM_CLANG_LIB_LEX_UNICODECHARSETS_H #include "llvm/Support/UnicodeCharRanges.h" // C11 D.1, C++11 [charname.allowed] static const llvm::sys::UnicodeCharRange C11AllowedIDCharRanges[] = { // 1 { 0x00A8, 0x00A8 }, { 0x00AA, 0x00AA }, { 0x00AD, 0x00AD }, { 0x00AF, 0x00AF }, { 0x00B2, 0x00B5 }, { 0x00B7, 0x00BA }, { 0x00BC, 0x00BE }, { 0x00C0, 0x00D6 }, { 0x00D8, 0x00F6 }, { 0x00F8, 0x00FF }, // 2 { 0x0100, 0x167F }, { 0x1681, 0x180D }, { 0x180F, 0x1FFF }, // 3 { 0x200B, 0x200D }, { 0x202A, 0x202E }, { 0x203F, 0x2040 }, { 0x2054, 0x2054 }, { 0x2060, 0x206F }, // 4 { 0x2070, 0x218F }, { 0x2460, 0x24FF }, { 0x2776, 0x2793 }, { 0x2C00, 0x2DFF }, { 0x2E80, 0x2FFF }, // 5 { 0x3004, 0x3007 }, { 0x3021, 0x302F }, { 0x3031, 0x303F }, // 6 { 0x3040, 0xD7FF }, // 7 { 0xF900, 0xFD3D }, { 0xFD40, 0xFDCF }, { 0xFDF0, 0xFE44 }, { 0xFE47, 0xFFFD }, // 8 { 0x10000, 0x1FFFD }, { 0x20000, 0x2FFFD }, { 0x30000, 0x3FFFD }, { 0x40000, 0x4FFFD }, { 0x50000, 0x5FFFD }, { 0x60000, 0x6FFFD }, { 0x70000, 0x7FFFD }, { 0x80000, 0x8FFFD }, { 0x90000, 0x9FFFD }, { 0xA0000, 0xAFFFD }, { 0xB0000, 0xBFFFD }, { 0xC0000, 0xCFFFD }, { 0xD0000, 0xDFFFD }, { 0xE0000, 0xEFFFD } }; // C++03 [extendid] // Note that this is not the same as C++98, but we don't distinguish C++98 // and C++03 in Clang. static const llvm::sys::UnicodeCharRange CXX03AllowedIDCharRanges[] = { // Latin { 0x00C0, 0x00D6 }, { 0x00D8, 0x00F6 }, { 0x00F8, 0x01F5 }, { 0x01FA, 0x0217 }, { 0x0250, 0x02A8 }, // Greek { 0x0384, 0x0384 }, { 0x0388, 0x038A }, { 0x038C, 0x038C }, { 0x038E, 0x03A1 }, { 0x03A3, 0x03CE }, { 0x03D0, 0x03D6 }, { 0x03DA, 0x03DA }, { 0x03DC, 0x03DC }, { 0x03DE, 0x03DE }, { 0x03E0, 0x03E0 }, { 0x03E2, 0x03F3 }, // Cyrillic { 0x0401, 0x040D }, { 0x040F, 0x044F }, { 0x0451, 0x045C }, { 0x045E, 0x0481 }, { 0x0490, 0x04C4 }, { 0x04C7, 0x04C8 }, { 0x04CB, 0x04CC }, { 0x04D0, 0x04EB }, { 0x04EE, 0x04F5 }, { 0x04F8, 0x04F9 }, // Armenian { 0x0531, 0x0556 }, { 0x0561, 0x0587 }, // Hebrew { 0x05D0, 0x05EA }, { 0x05F0, 0x05F4 }, // Arabic { 0x0621, 0x063A }, { 0x0640, 0x0652 }, { 0x0670, 0x06B7 }, { 0x06BA, 0x06BE }, { 0x06C0, 0x06CE }, { 0x06E5, 0x06E7 }, // Devanagari { 0x0905, 0x0939 }, { 0x0958, 0x0962 }, // Bangla // MS Change { 0x0985, 0x098C }, { 0x098F, 0x0990 }, { 0x0993, 0x09A8 }, { 0x09AA, 0x09B0 }, { 0x09B2, 0x09B2 }, { 0x09B6, 0x09B9 }, { 0x09DC, 0x09DD }, { 0x09DF, 0x09E1 }, { 0x09F0, 0x09F1 }, // Gurmukhi { 0x0A05, 0x0A0A }, { 0x0A0F, 0x0A10 }, { 0x0A13, 0x0A28 }, { 0x0A2A, 0x0A30 }, { 0x0A32, 0x0A33 }, { 0x0A35, 0x0A36 }, { 0x0A38, 0x0A39 }, { 0x0A59, 0x0A5C }, { 0x0A5E, 0x0A5E }, // Gujarti { 0x0A85, 0x0A8B }, { 0x0A8D, 0x0A8D }, { 0x0A8F, 0x0A91 }, { 0x0A93, 0x0AA8 }, { 0x0AAA, 0x0AB0 }, { 0x0AB2, 0x0AB3 }, { 0x0AB5, 0x0AB9 }, { 0x0AE0, 0x0AE0 }, // Oriya { 0x0B05, 0x0B0C }, { 0x0B0F, 0x0B10 }, { 0x0B13, 0x0B28 }, { 0x0B2A, 0x0B30 }, { 0x0B32, 0x0B33 }, { 0x0B36, 0x0B39 }, { 0x0B5C, 0x0B5D }, { 0x0B5F, 0x0B61 }, // Tamil { 0x0B85, 0x0B8A }, { 0x0B8E, 0x0B90 }, { 0x0B92, 0x0B95 }, { 0x0B99, 0x0B9A }, { 0x0B9C, 0x0B9C }, { 0x0B9E, 0x0B9F }, { 0x0BA3, 0x0BA4 }, { 0x0BA8, 0x0BAA }, { 0x0BAE, 0x0BB5 }, { 0x0BB7, 0x0BB9 }, // Telugu { 0x0C05, 0x0C0C }, { 0x0C0E, 0x0C10 }, { 0x0C12, 0x0C28 }, { 0x0C2A, 0x0C33 }, { 0x0C35, 0x0C39 }, { 0x0C60, 0x0C61 }, // Kannada { 0x0C85, 0x0C8C }, { 0x0C8E, 0x0C90 }, { 0x0C92, 0x0CA8 }, { 0x0CAA, 0x0CB3 }, { 0x0CB5, 0x0CB9 }, { 0x0CE0, 0x0CE1 }, // Malayam { 0x0D05, 0x0D0C }, { 0x0D0E, 0x0D10 }, { 0x0D12, 0x0D28 }, { 0x0D2A, 0x0D39 }, { 0x0D60, 0x0D61 }, // Thai { 0x0E01, 0x0E30 }, { 0x0E32, 0x0E33 }, { 0x0E40, 0x0E46 }, { 0x0E4F, 0x0E5B }, // Lao { 0x0E81, 0x0E82 }, { 0x0E84, 0x0E84 }, { 0x0E87, 0x0E87 }, { 0x0E88, 0x0E88 }, { 0x0E8A, 0x0E8A }, { 0x0E8D, 0x0E8D }, { 0x0E94, 0x0E97 }, { 0x0E99, 0x0E9F }, { 0x0EA1, 0x0EA3 }, { 0x0EA5, 0x0EA5 }, { 0x0EA7, 0x0EA7 }, { 0x0EAA, 0x0EAA }, { 0x0EAB, 0x0EAB }, { 0x0EAD, 0x0EB0 }, { 0x0EB2, 0x0EB2 }, { 0x0EB3, 0x0EB3 }, { 0x0EBD, 0x0EBD }, { 0x0EC0, 0x0EC4 }, { 0x0EC6, 0x0EC6 }, // Georgian { 0x10A0, 0x10C5 }, { 0x10D0, 0x10F6 }, // Hangul { 0x1100, 0x1159 }, { 0x1161, 0x11A2 }, { 0x11A8, 0x11F9 }, // Latin (2) { 0x1E00, 0x1E9A }, { 0x1EA0, 0x1EF9 }, // Greek (2) { 0x1F00, 0x1F15 }, { 0x1F18, 0x1F1D }, { 0x1F20, 0x1F45 }, { 0x1F48, 0x1F4D }, { 0x1F50, 0x1F57 }, { 0x1F59, 0x1F59 }, { 0x1F5B, 0x1F5B }, { 0x1F5D, 0x1F5D }, { 0x1F5F, 0x1F7D }, { 0x1F80, 0x1FB4 }, { 0x1FB6, 0x1FBC }, { 0x1FC2, 0x1FC4 }, { 0x1FC6, 0x1FCC }, { 0x1FD0, 0x1FD3 }, { 0x1FD6, 0x1FDB }, { 0x1FE0, 0x1FEC }, { 0x1FF2, 0x1FF4 }, { 0x1FF6, 0x1FFC }, // Hiragana { 0x3041, 0x3094 }, { 0x309B, 0x309E }, // Katakana { 0x30A1, 0x30FE }, // Bopmofo [sic] { 0x3105, 0x312C }, // CJK Unified Ideographs { 0x4E00, 0x9FA5 }, { 0xF900, 0xFA2D }, { 0xFB1F, 0xFB36 }, { 0xFB38, 0xFB3C }, { 0xFB3E, 0xFB3E }, { 0xFB40, 0xFB41 }, { 0xFB42, 0xFB44 }, { 0xFB46, 0xFBB1 }, { 0xFBD3, 0xFD3F }, { 0xFD50, 0xFD8F }, { 0xFD92, 0xFDC7 }, { 0xFDF0, 0xFDFB }, { 0xFE70, 0xFE72 }, { 0xFE74, 0xFE74 }, { 0xFE76, 0xFEFC }, { 0xFF21, 0xFF3A }, { 0xFF41, 0xFF5A }, { 0xFF66, 0xFFBE }, { 0xFFC2, 0xFFC7 }, { 0xFFCA, 0xFFCF }, { 0xFFD2, 0xFFD7 }, { 0xFFDA, 0xFFDC } }; // C99 Annex D static const llvm::sys::UnicodeCharRange C99AllowedIDCharRanges[] = { // Latin (1) { 0x00AA, 0x00AA }, // Special characters (1) { 0x00B5, 0x00B5 }, { 0x00B7, 0x00B7 }, // Latin (2) { 0x00BA, 0x00BA }, { 0x00C0, 0x00D6 }, { 0x00D8, 0x00F6 }, { 0x00F8, 0x01F5 }, { 0x01FA, 0x0217 }, { 0x0250, 0x02A8 }, // Special characters (2) { 0x02B0, 0x02B8 }, { 0x02BB, 0x02BB }, { 0x02BD, 0x02C1 }, { 0x02D0, 0x02D1 }, { 0x02E0, 0x02E4 }, { 0x037A, 0x037A }, // Greek (1) { 0x0386, 0x0386 }, { 0x0388, 0x038A }, { 0x038C, 0x038C }, { 0x038E, 0x03A1 }, { 0x03A3, 0x03CE }, { 0x03D0, 0x03D6 }, { 0x03DA, 0x03DA }, { 0x03DC, 0x03DC }, { 0x03DE, 0x03DE }, { 0x03E0, 0x03E0 }, { 0x03E2, 0x03F3 }, // Cyrillic { 0x0401, 0x040C }, { 0x040E, 0x044F }, { 0x0451, 0x045C }, { 0x045E, 0x0481 }, { 0x0490, 0x04C4 }, { 0x04C7, 0x04C8 }, { 0x04CB, 0x04CC }, { 0x04D0, 0x04EB }, { 0x04EE, 0x04F5 }, { 0x04F8, 0x04F9 }, // Armenian (1) { 0x0531, 0x0556 }, // Special characters (3) { 0x0559, 0x0559 }, // Armenian (2) { 0x0561, 0x0587 }, // Hebrew { 0x05B0, 0x05B9 }, { 0x05BB, 0x05BD }, { 0x05BF, 0x05BF }, { 0x05C1, 0x05C2 }, { 0x05D0, 0x05EA }, { 0x05F0, 0x05F2 }, // Arabic (1) { 0x0621, 0x063A }, { 0x0640, 0x0652 }, // Digits (1) { 0x0660, 0x0669 }, // Arabic (2) { 0x0670, 0x06B7 }, { 0x06BA, 0x06BE }, { 0x06C0, 0x06CE }, { 0x06D0, 0x06DC }, { 0x06E5, 0x06E8 }, { 0x06EA, 0x06ED }, // Digits (2) { 0x06F0, 0x06F9 }, // Devanagari and Special characeter 0x093D. { 0x0901, 0x0903 }, { 0x0905, 0x0939 }, { 0x093D, 0x094D }, { 0x0950, 0x0952 }, { 0x0958, 0x0963 }, // Digits (3) { 0x0966, 0x096F }, // Bangla (1) // MS Change { 0x0981, 0x0983 }, { 0x0985, 0x098C }, { 0x098F, 0x0990 }, { 0x0993, 0x09A8 }, { 0x09AA, 0x09B0 }, { 0x09B2, 0x09B2 }, { 0x09B6, 0x09B9 }, { 0x09BE, 0x09C4 }, { 0x09C7, 0x09C8 }, { 0x09CB, 0x09CD }, { 0x09DC, 0x09DD }, { 0x09DF, 0x09E3 }, // Digits (4) { 0x09E6, 0x09EF }, // Bangla (2) // MS Change { 0x09F0, 0x09F1 }, // Gurmukhi (1) { 0x0A02, 0x0A02 }, { 0x0A05, 0x0A0A }, { 0x0A0F, 0x0A10 }, { 0x0A13, 0x0A28 }, { 0x0A2A, 0x0A30 }, { 0x0A32, 0x0A33 }, { 0x0A35, 0x0A36 }, { 0x0A38, 0x0A39 }, { 0x0A3E, 0x0A42 }, { 0x0A47, 0x0A48 }, { 0x0A4B, 0x0A4D }, { 0x0A59, 0x0A5C }, { 0x0A5E, 0x0A5E }, // Digits (5) { 0x0A66, 0x0A6F }, // Gurmukhi (2) { 0x0A74, 0x0A74 }, // Gujarti { 0x0A81, 0x0A83 }, { 0x0A85, 0x0A8B }, { 0x0A8D, 0x0A8D }, { 0x0A8F, 0x0A91 }, { 0x0A93, 0x0AA8 }, { 0x0AAA, 0x0AB0 }, { 0x0AB2, 0x0AB3 }, { 0x0AB5, 0x0AB9 }, { 0x0ABD, 0x0AC5 }, { 0x0AC7, 0x0AC9 }, { 0x0ACB, 0x0ACD }, { 0x0AD0, 0x0AD0 }, { 0x0AE0, 0x0AE0 }, // Digits (6) { 0x0AE6, 0x0AEF }, // Oriya and Special character 0x0B3D { 0x0B01, 0x0B03 }, { 0x0B05, 0x0B0C }, { 0x0B0F, 0x0B10 }, { 0x0B13, 0x0B28 }, { 0x0B2A, 0x0B30 }, { 0x0B32, 0x0B33 }, { 0x0B36, 0x0B39 }, { 0x0B3D, 0x0B43 }, { 0x0B47, 0x0B48 }, { 0x0B4B, 0x0B4D }, { 0x0B5C, 0x0B5D }, { 0x0B5F, 0x0B61 }, // Digits (7) { 0x0B66, 0x0B6F }, // Tamil { 0x0B82, 0x0B83 }, { 0x0B85, 0x0B8A }, { 0x0B8E, 0x0B90 }, { 0x0B92, 0x0B95 }, { 0x0B99, 0x0B9A }, { 0x0B9C, 0x0B9C }, { 0x0B9E, 0x0B9F }, { 0x0BA3, 0x0BA4 }, { 0x0BA8, 0x0BAA }, { 0x0BAE, 0x0BB5 }, { 0x0BB7, 0x0BB9 }, { 0x0BBE, 0x0BC2 }, { 0x0BC6, 0x0BC8 }, { 0x0BCA, 0x0BCD }, // Digits (8) { 0x0BE7, 0x0BEF }, // Telugu { 0x0C01, 0x0C03 }, { 0x0C05, 0x0C0C }, { 0x0C0E, 0x0C10 }, { 0x0C12, 0x0C28 }, { 0x0C2A, 0x0C33 }, { 0x0C35, 0x0C39 }, { 0x0C3E, 0x0C44 }, { 0x0C46, 0x0C48 }, { 0x0C4A, 0x0C4D }, { 0x0C60, 0x0C61 }, // Digits (9) { 0x0C66, 0x0C6F }, // Kannada { 0x0C82, 0x0C83 }, { 0x0C85, 0x0C8C }, { 0x0C8E, 0x0C90 }, { 0x0C92, 0x0CA8 }, { 0x0CAA, 0x0CB3 }, { 0x0CB5, 0x0CB9 }, { 0x0CBE, 0x0CC4 }, { 0x0CC6, 0x0CC8 }, { 0x0CCA, 0x0CCD }, { 0x0CDE, 0x0CDE }, { 0x0CE0, 0x0CE1 }, // Digits (10) { 0x0CE6, 0x0CEF }, // Malayam { 0x0D02, 0x0D03 }, { 0x0D05, 0x0D0C }, { 0x0D0E, 0x0D10 }, { 0x0D12, 0x0D28 }, { 0x0D2A, 0x0D39 }, { 0x0D3E, 0x0D43 }, { 0x0D46, 0x0D48 }, { 0x0D4A, 0x0D4D }, { 0x0D60, 0x0D61 }, // Digits (11) { 0x0D66, 0x0D6F }, // Thai...including Digits { 0x0E50, 0x0E59 } { 0x0E01, 0x0E3A }, { 0x0E40, 0x0E5B }, // Lao (1) { 0x0E81, 0x0E82 }, { 0x0E84, 0x0E84 }, { 0x0E87, 0x0E88 }, { 0x0E8A, 0x0E8A }, { 0x0E8D, 0x0E8D }, { 0x0E94, 0x0E97 }, { 0x0E99, 0x0E9F }, { 0x0EA1, 0x0EA3 }, { 0x0EA5, 0x0EA5 }, { 0x0EA7, 0x0EA7 }, { 0x0EAA, 0x0EAB }, { 0x0EAD, 0x0EAE }, { 0x0EB0, 0x0EB9 }, { 0x0EBB, 0x0EBD }, { 0x0EC0, 0x0EC4 }, { 0x0EC6, 0x0EC6 }, { 0x0EC8, 0x0ECD }, // Digits (12) { 0x0ED0, 0x0ED9 }, // Lao (2) { 0x0EDC, 0x0EDD }, // Tibetan (1) { 0x0F00, 0x0F00 }, { 0x0F18, 0x0F19 }, // Digits (13) { 0x0F20, 0x0F33 }, // Tibetan (2) { 0x0F35, 0x0F35 }, { 0x0F37, 0x0F37 }, { 0x0F39, 0x0F39 }, { 0x0F3E, 0x0F47 }, { 0x0F49, 0x0F69 }, { 0x0F71, 0x0F84 }, { 0x0F86, 0x0F8B }, { 0x0F90, 0x0F95 }, { 0x0F97, 0x0F97 }, { 0x0F99, 0x0FAD }, { 0x0FB1, 0x0FB7 }, { 0x0FB9, 0x0FB9 }, // Georgian { 0x10A0, 0x10C5 }, { 0x10D0, 0x10F6 }, // Latin (3) { 0x1E00, 0x1E9B }, { 0x1EA0, 0x1EF9 }, // Greek (2) { 0x1F00, 0x1F15 }, { 0x1F18, 0x1F1D }, { 0x1F20, 0x1F45 }, { 0x1F48, 0x1F4D }, { 0x1F50, 0x1F57 }, { 0x1F59, 0x1F59 }, { 0x1F5B, 0x1F5B }, { 0x1F5D, 0x1F5D }, { 0x1F5F, 0x1F7D }, { 0x1F80, 0x1FB4 }, { 0x1FB6, 0x1FBC }, // Special characters (4) { 0x1FBE, 0x1FBE }, // Greek (3) { 0x1FC2, 0x1FC4 }, { 0x1FC6, 0x1FCC }, { 0x1FD0, 0x1FD3 }, { 0x1FD6, 0x1FDB }, { 0x1FE0, 0x1FEC }, { 0x1FF2, 0x1FF4 }, { 0x1FF6, 0x1FFC }, // Special characters (5) { 0x203F, 0x2040 }, // Latin (4) { 0x207F, 0x207F }, // Special characters (6) { 0x2102, 0x2102 }, { 0x2107, 0x2107 }, { 0x210A, 0x2113 }, { 0x2115, 0x2115 }, { 0x2118, 0x211D }, { 0x2124, 0x2124 }, { 0x2126, 0x2126 }, { 0x2128, 0x2128 }, { 0x212A, 0x2131 }, { 0x2133, 0x2138 }, { 0x2160, 0x2182 }, { 0x3005, 0x3007 }, { 0x3021, 0x3029 }, // Hiragana { 0x3041, 0x3093 }, { 0x309B, 0x309C }, // Katakana { 0x30A1, 0x30F6 }, { 0x30FB, 0x30FC }, // Bopmofo [sic] { 0x3105, 0x312C }, // CJK Unified Ideographs { 0x4E00, 0x9FA5 }, // Hangul, { 0xAC00, 0xD7A3 } }; // C11 D.2, C++11 [charname.disallowed] static const llvm::sys::UnicodeCharRange C11DisallowedInitialIDCharRanges[] = { { 0x0300, 0x036F }, { 0x1DC0, 0x1DFF }, { 0x20D0, 0x20FF }, { 0xFE20, 0xFE2F } }; // C99 6.4.2.1p3: The initial character [of an identifier] shall not be a // universal character name designating a digit. // C99 Annex D defines these characters as "Digits". static const llvm::sys::UnicodeCharRange C99DisallowedInitialIDCharRanges[] = { { 0x0660, 0x0669 }, { 0x06F0, 0x06F9 }, { 0x0966, 0x096F }, { 0x09E6, 0x09EF }, { 0x0A66, 0x0A6F }, { 0x0AE6, 0x0AEF }, { 0x0B66, 0x0B6F }, { 0x0BE7, 0x0BEF }, { 0x0C66, 0x0C6F }, { 0x0CE6, 0x0CEF }, { 0x0D66, 0x0D6F }, { 0x0E50, 0x0E59 }, { 0x0ED0, 0x0ED9 }, { 0x0F20, 0x0F33 } }; // Unicode v6.2, chapter 6.2, table 6-2. static const llvm::sys::UnicodeCharRange UnicodeWhitespaceCharRanges[] = { { 0x0085, 0x0085 }, { 0x00A0, 0x00A0 }, { 0x1680, 0x1680 }, { 0x180E, 0x180E }, { 0x2000, 0x200A }, { 0x2028, 0x2029 }, { 0x202F, 0x202F }, { 0x205F, 0x205F }, { 0x3000, 0x3000 } }; #endif
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/PPExpressions.cpp
//===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Preprocessor::EvaluateDirectiveExpression method, // which parses and evaluates integer constant expressions for #if directives. // //===----------------------------------------------------------------------===// // // FIXME: implement testing for #assert's. // //===----------------------------------------------------------------------===// #include "clang/Lex/Preprocessor.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Lex/MacroInfo.h" #include "llvm/ADT/APSInt.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/SaveAndRestore.h" using namespace clang; namespace { /// PPValue - Represents the value of a subexpression of a preprocessor /// conditional and the source range covered by it. class PPValue { SourceRange Range; public: llvm::APSInt Val; // Default ctor - Construct an 'invalid' PPValue. PPValue(unsigned BitWidth) : Val(BitWidth) {} unsigned getBitWidth() const { return Val.getBitWidth(); } bool isUnsigned() const { return Val.isUnsigned(); } const SourceRange &getRange() const { return Range; } void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); } void setRange(SourceLocation B, SourceLocation E) { Range.setBegin(B); Range.setEnd(E); } void setBegin(SourceLocation L) { Range.setBegin(L); } void setEnd(SourceLocation L) { Range.setEnd(L); } }; } static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, Token &PeekTok, bool ValueLive, Preprocessor &PP); /// DefinedTracker - This struct is used while parsing expressions to keep track /// of whether !defined(X) has been seen. /// /// With this simple scheme, we handle the basic forms: /// !defined(X) and !defined X /// but we also trivially handle (silly) stuff like: /// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)). struct DefinedTracker { /// Each time a Value is evaluated, it returns information about whether the /// parsed value is of the form defined(X), !defined(X) or is something else. enum TrackerState { DefinedMacro, // defined(X) NotDefinedMacro, // !defined(X) Unknown // Something else. } State; /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this /// indicates the macro that was checked. IdentifierInfo *TheMacro; }; /// EvaluateDefined - Process a 'defined(sym)' expression. static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT, bool ValueLive, Preprocessor &PP) { SourceLocation beginLoc(PeekTok.getLocation()); Result.setBegin(beginLoc); // Get the next token, don't expand it. PP.LexUnexpandedNonComment(PeekTok); // Two options, it can either be a pp-identifier or a (. SourceLocation LParenLoc; if (PeekTok.is(tok::l_paren)) { // Found a paren, remember we saw it and skip it. LParenLoc = PeekTok.getLocation(); PP.LexUnexpandedNonComment(PeekTok); } if (PeekTok.is(tok::code_completion)) { if (PP.getCodeCompletionHandler()) PP.getCodeCompletionHandler()->CodeCompleteMacroName(false); PP.setCodeCompletionReached(); PP.LexUnexpandedNonComment(PeekTok); } // If we don't have a pp-identifier now, this is an error. if (PP.CheckMacroName(PeekTok, MU_Other)) return true; // Otherwise, we got an identifier, is it defined to something? IdentifierInfo *II = PeekTok.getIdentifierInfo(); MacroDefinition Macro = PP.getMacroDefinition(II); Result.Val = !!Macro; Result.Val.setIsUnsigned(false); // Result is signed intmax_t. // If there is a macro, mark it used. if (Result.Val != 0 && ValueLive) PP.markMacroAsUsed(Macro.getMacroInfo()); // Save macro token for callback. Token macroToken(PeekTok); // If we are in parens, ensure we have a trailing ). if (LParenLoc.isValid()) { // Consume identifier. Result.setEnd(PeekTok.getLocation()); PP.LexUnexpandedNonComment(PeekTok); if (PeekTok.isNot(tok::r_paren)) { PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_after) << "'defined'" << tok::r_paren; PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; return true; } // Consume the ). Result.setEnd(PeekTok.getLocation()); PP.LexNonComment(PeekTok); } else { // Consume identifier. Result.setEnd(PeekTok.getLocation()); PP.LexNonComment(PeekTok); } // Invoke the 'defined' callback. if (PPCallbacks *Callbacks = PP.getPPCallbacks()) { Callbacks->Defined(macroToken, Macro, SourceRange(beginLoc, PeekTok.getLocation())); } // Success, remember that we saw defined(X). DT.State = DefinedTracker::DefinedMacro; DT.TheMacro = II; return false; } /// EvaluateValue - Evaluate the token PeekTok (and any others needed) and /// return the computed value in Result. Return true if there was an error /// parsing. This function also returns information about the form of the /// expression in DT. See above for information on what DT means. /// /// If ValueLive is false, then this value is being evaluated in a context where /// the result is not used. As such, avoid diagnostics that relate to /// evaluation. static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, bool ValueLive, Preprocessor &PP) { DT.State = DefinedTracker::Unknown; if (PeekTok.is(tok::code_completion)) { if (PP.getCodeCompletionHandler()) PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression(); PP.setCodeCompletionReached(); PP.LexNonComment(PeekTok); } // If this token's spelling is a pp-identifier, check to see if it is // 'defined' or if it is a macro. Note that we check here because many // keywords are pp-identifiers, so we can't check the kind. if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) { // Handle "defined X" and "defined(X)". if (II->isStr("defined")) return(EvaluateDefined(Result, PeekTok, DT, ValueLive, PP)); // If this identifier isn't 'defined' or one of the special // preprocessor keywords and it wasn't macro expanded, it turns // into a simple 0, unless it is the C++ keyword "true", in which case it // turns into "1". if (ValueLive && II->getTokenID() != tok::kw_true && II->getTokenID() != tok::kw_false) PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II; Result.Val = II->getTokenID() == tok::kw_true; Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0. Result.setRange(PeekTok.getLocation()); PP.LexNonComment(PeekTok); return false; } switch (PeekTok.getKind()) { default: // Non-value token. PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr); return true; case tok::eod: case tok::r_paren: // If there is no expression, report and exit. PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr); return true; case tok::numeric_constant: { SmallString<64> IntegerBuffer; bool NumberInvalid = false; StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer, &NumberInvalid); if (NumberInvalid) return true; // a diagnostic was already reported NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP); if (Literal.hadError) return true; // a diagnostic was already reported. if (Literal.isFloatingLiteral() || Literal.isImaginary) { PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal); return true; } assert(Literal.isIntegerLiteral() && "Unknown ppnumber"); // Complain about, and drop, any ud-suffix. if (Literal.hasUDSuffix()) PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1; // 'long long' is a C99 or C++11 feature. if (!PP.getLangOpts().C99 && Literal.isLongLong) { if (PP.getLangOpts().CPlusPlus) PP.Diag(PeekTok, PP.getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong); else PP.Diag(PeekTok, diag::ext_c99_longlong); } // Parse the integer literal into Result. if (Literal.GetIntegerValue(Result.Val)) { // Overflow parsing integer literal. if (ValueLive) PP.Diag(PeekTok, diag::err_integer_literal_too_large) << /* Unsigned */ 1; Result.Val.setIsUnsigned(true); } else { // Set the signedness of the result to match whether there was a U suffix // or not. Result.Val.setIsUnsigned(Literal.isUnsigned); // Detect overflow based on whether the value is signed. If signed // and if the value is too large, emit a warning "integer constant is so // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t // is 64-bits. if (!Literal.isUnsigned && Result.Val.isNegative()) { // Octal, hexadecimal, and binary literals are implicitly unsigned if // the value does not fit into a signed integer type. if (ValueLive && Literal.getRadix() == 10) PP.Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed); Result.Val.setIsUnsigned(true); } } // Consume the token. Result.setRange(PeekTok.getLocation()); PP.LexNonComment(PeekTok); return false; } case tok::char_constant: // 'x' case tok::wide_char_constant: // L'x' case tok::utf8_char_constant: // u8'x' case tok::utf16_char_constant: // u'x' case tok::utf32_char_constant: { // U'x' // Complain about, and drop, any ud-suffix. if (PeekTok.hasUDSuffix()) PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0; SmallString<32> CharBuffer; bool CharInvalid = false; StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid); if (CharInvalid) return true; CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), PeekTok.getLocation(), PP, PeekTok.getKind()); if (Literal.hadError()) return true; // A diagnostic was already emitted. // Character literals are always int or wchar_t, expand to intmax_t. const TargetInfo &TI = PP.getTargetInfo(); unsigned NumBits; if (Literal.isMultiChar()) NumBits = TI.getIntWidth(); else if (Literal.isWide()) NumBits = TI.getWCharWidth(); else if (Literal.isUTF16()) NumBits = TI.getChar16Width(); else if (Literal.isUTF32()) NumBits = TI.getChar32Width(); else NumBits = TI.getCharWidth(); // Set the width. llvm::APSInt Val(NumBits); // Set the value. Val = Literal.getValue(); // Set the signedness. UTF-16 and UTF-32 are always unsigned if (Literal.isWide()) Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType())); else if (!Literal.isUTF16() && !Literal.isUTF32()) Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned); if (Result.Val.getBitWidth() > Val.getBitWidth()) { Result.Val = Val.extend(Result.Val.getBitWidth()); } else { assert(Result.Val.getBitWidth() == Val.getBitWidth() && "intmax_t smaller than char/wchar_t?"); Result.Val = Val; } // Consume the token. Result.setRange(PeekTok.getLocation()); PP.LexNonComment(PeekTok); return false; } case tok::l_paren: { SourceLocation Start = PeekTok.getLocation(); PP.LexNonComment(PeekTok); // Eat the (. // Parse the value and if there are any binary operators involved, parse // them. if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; // If this is a silly value like (X), which doesn't need parens, check for // !(defined X). if (PeekTok.is(tok::r_paren)) { // Just use DT unmodified as our result. } else { // Otherwise, we have something like (x+y), and we consumed '(x'. if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP)) return true; if (PeekTok.isNot(tok::r_paren)) { PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen) << Result.getRange(); PP.Diag(Start, diag::note_matching) << tok::l_paren; return true; } DT.State = DefinedTracker::Unknown; } Result.setRange(Start, PeekTok.getLocation()); PP.LexNonComment(PeekTok); // Eat the ). return false; } case tok::plus: { SourceLocation Start = PeekTok.getLocation(); // Unary plus doesn't modify the value. PP.LexNonComment(PeekTok); if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; Result.setBegin(Start); return false; } case tok::minus: { SourceLocation Loc = PeekTok.getLocation(); PP.LexNonComment(PeekTok); if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; Result.setBegin(Loc); // C99 6.5.3.3p3: The sign of the result matches the sign of the operand. Result.Val = -Result.Val; // -MININT is the only thing that overflows. Unsigned never overflows. bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue(); // If this operator is live and overflowed, report the issue. if (Overflow && ValueLive) PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange(); DT.State = DefinedTracker::Unknown; return false; } case tok::tilde: { SourceLocation Start = PeekTok.getLocation(); PP.LexNonComment(PeekTok); if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; Result.setBegin(Start); // C99 6.5.3.3p4: The sign of the result matches the sign of the operand. Result.Val = ~Result.Val; DT.State = DefinedTracker::Unknown; return false; } case tok::exclaim: { SourceLocation Start = PeekTok.getLocation(); PP.LexNonComment(PeekTok); if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true; Result.setBegin(Start); Result.Val = !Result.Val; // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed. Result.Val.setIsUnsigned(false); if (DT.State == DefinedTracker::DefinedMacro) DT.State = DefinedTracker::NotDefinedMacro; else if (DT.State == DefinedTracker::NotDefinedMacro) DT.State = DefinedTracker::DefinedMacro; return false; } // FIXME: Handle #assert } } /// getPrecedence - Return the precedence of the specified binary operator /// token. This returns: /// ~0 - Invalid token. /// 14 -> 3 - various operators. /// 0 - 'eod' or ')' static unsigned getPrecedence(tok::TokenKind Kind) { switch (Kind) { default: return ~0U; case tok::percent: case tok::slash: case tok::star: return 14; case tok::plus: case tok::minus: return 13; case tok::lessless: case tok::greatergreater: return 12; case tok::lessequal: case tok::less: case tok::greaterequal: case tok::greater: return 11; case tok::exclaimequal: case tok::equalequal: return 10; case tok::amp: return 9; case tok::caret: return 8; case tok::pipe: return 7; case tok::ampamp: return 6; case tok::pipepipe: return 5; case tok::question: return 4; case tok::comma: return 3; case tok::colon: return 2; case tok::r_paren: return 0;// Lowest priority, end of expr. case tok::eod: return 0;// Lowest priority, end of directive. } } /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS. /// /// If ValueLive is false, then this value is being evaluated in a context where /// the result is not used. As such, avoid diagnostics that relate to /// evaluation, such as division by zero warnings. static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec, Token &PeekTok, bool ValueLive, Preprocessor &PP) { unsigned PeekPrec = getPrecedence(PeekTok.getKind()); // If this token isn't valid, report the error. if (PeekPrec == ~0U) { PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop) << LHS.getRange(); return true; } while (1) { // If this token has a lower precedence than we are allowed to parse, return // it so that higher levels of the recursion can parse it. if (PeekPrec < MinPrec) return false; tok::TokenKind Operator = PeekTok.getKind(); // If this is a short-circuiting operator, see if the RHS of the operator is // dead. Note that this cannot just clobber ValueLive. Consider // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In // this example, the RHS of the && being dead does not make the rest of the // expr dead. bool RHSIsLive; if (Operator == tok::ampamp && LHS.Val == 0) RHSIsLive = false; // RHS of "0 && x" is dead. else if (Operator == tok::pipepipe && LHS.Val != 0) RHSIsLive = false; // RHS of "1 || x" is dead. else if (Operator == tok::question && LHS.Val == 0) RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead. else RHSIsLive = ValueLive; // Consume the operator, remembering the operator's location for reporting. SourceLocation OpLoc = PeekTok.getLocation(); PP.LexNonComment(PeekTok); PPValue RHS(LHS.getBitWidth()); // Parse the RHS of the operator. DefinedTracker DT; if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true; // Remember the precedence of this operator and get the precedence of the // operator immediately to the right of the RHS. unsigned ThisPrec = PeekPrec; PeekPrec = getPrecedence(PeekTok.getKind()); // If this token isn't valid, report the error. if (PeekPrec == ~0U) { PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop) << RHS.getRange(); return true; } // Decide whether to include the next binop in this subexpression. For // example, when parsing x+y*z and looking at '*', we want to recursively // handle y*z as a single subexpression. We do this because the precedence // of * is higher than that of +. The only strange case we have to handle // here is for the ?: operator, where the precedence is actually lower than // the LHS of the '?'. The grammar rule is: // // conditional-expression ::= // logical-OR-expression ? expression : conditional-expression // where 'expression' is actually comma-expression. unsigned RHSPrec; if (Operator == tok::question) // The RHS of "?" should be maximally consumed as an expression. RHSPrec = getPrecedence(tok::comma); else // All others should munch while higher precedence. RHSPrec = ThisPrec+1; if (PeekPrec >= RHSPrec) { if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP)) return true; PeekPrec = getPrecedence(PeekTok.getKind()); } assert(PeekPrec <= ThisPrec && "Recursion didn't work!"); // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if // either operand is unsigned. llvm::APSInt Res(LHS.getBitWidth()); switch (Operator) { case tok::question: // No UAC for x and y in "x ? y : z". case tok::lessless: // Shift amount doesn't UAC with shift value. case tok::greatergreater: // Shift amount doesn't UAC with shift value. case tok::comma: // Comma operands are not subject to UACs. case tok::pipepipe: // Logical || does not do UACs. case tok::ampamp: // Logical && does not do UACs. break; // No UAC default: Res.setIsUnsigned(LHS.isUnsigned() || RHS.isUnsigned()); // If this just promoted something from signed to unsigned, and if the // value was negative, warn about it. if (ValueLive && Res.isUnsigned()) { if (!LHS.isUnsigned() && LHS.Val.isNegative()) PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive) << LHS.Val.toString(10, true) + " to " + LHS.Val.toString(10, false) << LHS.getRange() << RHS.getRange(); if (!RHS.isUnsigned() && RHS.Val.isNegative()) PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive) << RHS.Val.toString(10, true) + " to " + RHS.Val.toString(10, false) << LHS.getRange() << RHS.getRange(); } LHS.Val.setIsUnsigned(Res.isUnsigned()); RHS.Val.setIsUnsigned(Res.isUnsigned()); } bool Overflow = false; switch (Operator) { default: llvm_unreachable("Unknown operator token!"); case tok::percent: if (RHS.Val != 0) Res = LHS.Val % RHS.Val; else if (ValueLive) { PP.Diag(OpLoc, diag::err_pp_remainder_by_zero) << LHS.getRange() << RHS.getRange(); return true; } break; case tok::slash: if (RHS.Val != 0) { if (LHS.Val.isSigned()) Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false); else Res = LHS.Val / RHS.Val; } else if (ValueLive) { PP.Diag(OpLoc, diag::err_pp_division_by_zero) << LHS.getRange() << RHS.getRange(); return true; } break; case tok::star: if (Res.isSigned()) Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false); else Res = LHS.Val * RHS.Val; break; case tok::lessless: { // Determine whether overflow is about to happen. if (LHS.isUnsigned()) Res = LHS.Val.ushl_ov(RHS.Val, Overflow); else Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false); break; } case tok::greatergreater: { // Determine whether overflow is about to happen. unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue()); if (ShAmt >= LHS.getBitWidth()) Overflow = true, ShAmt = LHS.getBitWidth()-1; Res = LHS.Val >> ShAmt; break; } case tok::plus: if (LHS.isUnsigned()) Res = LHS.Val + RHS.Val; else Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false); break; case tok::minus: if (LHS.isUnsigned()) Res = LHS.Val - RHS.Val; else Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false); break; case tok::lessequal: Res = LHS.Val <= RHS.Val; Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) break; case tok::less: Res = LHS.Val < RHS.Val; Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) break; case tok::greaterequal: Res = LHS.Val >= RHS.Val; Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) break; case tok::greater: Res = LHS.Val > RHS.Val; Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed) break; case tok::exclaimequal: Res = LHS.Val != RHS.Val; Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed) break; case tok::equalequal: Res = LHS.Val == RHS.Val; Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed) break; case tok::amp: Res = LHS.Val & RHS.Val; break; case tok::caret: Res = LHS.Val ^ RHS.Val; break; case tok::pipe: Res = LHS.Val | RHS.Val; break; case tok::ampamp: Res = (LHS.Val != 0 && RHS.Val != 0); Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed) break; case tok::pipepipe: Res = (LHS.Val != 0 || RHS.Val != 0); Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed) break; case tok::comma: // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99 // if not being evaluated. if (!PP.getLangOpts().C99 || ValueLive) PP.Diag(OpLoc, diag::ext_pp_comma_expr) << LHS.getRange() << RHS.getRange(); Res = RHS.Val; // LHS = LHS,RHS -> RHS. break; case tok::question: { // Parse the : part of the expression. if (PeekTok.isNot(tok::colon)) { PP.Diag(PeekTok.getLocation(), diag::err_expected) << tok::colon << LHS.getRange() << RHS.getRange(); PP.Diag(OpLoc, diag::note_matching) << tok::question; return true; } // Consume the :. PP.LexNonComment(PeekTok); // Evaluate the value after the :. bool AfterColonLive = ValueLive && LHS.Val == 0; PPValue AfterColonVal(LHS.getBitWidth()); DefinedTracker DT; if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP)) return true; // Parse anything after the : with the same precedence as ?. We allow // things of equal precedence because ?: is right associative. if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec, PeekTok, AfterColonLive, PP)) return true; // Now that we have the condition, the LHS and the RHS of the :, evaluate. Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val; RHS.setEnd(AfterColonVal.getRange().getEnd()); // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if // either operand is unsigned. Res.setIsUnsigned(RHS.isUnsigned() || AfterColonVal.isUnsigned()); // Figure out the precedence of the token after the : part. PeekPrec = getPrecedence(PeekTok.getKind()); break; } case tok::colon: // Don't allow :'s to float around without being part of ?: exprs. PP.Diag(OpLoc, diag::err_pp_colon_without_question) << LHS.getRange() << RHS.getRange(); return true; } // If this operator is live and overflowed, report the issue. if (Overflow && ValueLive) PP.Diag(OpLoc, diag::warn_pp_expr_overflow) << LHS.getRange() << RHS.getRange(); // Put the result back into 'LHS' for our next iteration. LHS.Val = Res; LHS.setEnd(RHS.getRange().getEnd()); } } /// EvaluateDirectiveExpression - Evaluate an integer constant expression that /// may occur after a #if or #elif directive. If the expression is equivalent /// to "!defined(X)" return X in IfNDefMacro. bool Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) { SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true); // Save the current state of 'DisableMacroExpansion' and reset it to false. If // 'DisableMacroExpansion' is true, then we must be in a macro argument list // in which case a directive is undefined behavior. We want macros to be able // to recursively expand in order to get more gcc-list behavior, so we force // DisableMacroExpansion to false and restore it when we're done parsing the // expression. bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion; DisableMacroExpansion = false; // Peek ahead one token. Token Tok; LexNonComment(Tok); // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t. unsigned BitWidth = getTargetInfo().getIntMaxTWidth(); PPValue ResVal(BitWidth); DefinedTracker DT; if (EvaluateValue(ResVal, Tok, DT, true, *this)) { // Parse error, skip the rest of the macro line. if (Tok.isNot(tok::eod)) DiscardUntilEndOfDirective(); // Restore 'DisableMacroExpansion'. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; return false; } // If we are at the end of the expression after just parsing a value, there // must be no (unparenthesized) binary operators involved, so we can exit // directly. if (Tok.is(tok::eod)) { // If the expression we parsed was of the form !defined(macro), return the // macro in IfNDefMacro. if (DT.State == DefinedTracker::NotDefinedMacro) IfNDefMacro = DT.TheMacro; // Restore 'DisableMacroExpansion'. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; return ResVal.Val != 0; } // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the // operator and the stuff after it. if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question), Tok, true, *this)) { // Parse error, skip the rest of the macro line. if (Tok.isNot(tok::eod)) DiscardUntilEndOfDirective(); // Restore 'DisableMacroExpansion'. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; return false; } // If we aren't at the tok::eod token, something bad happened, like an extra // ')' token. if (Tok.isNot(tok::eod)) { Diag(Tok, diag::err_pp_expected_eol); DiscardUntilEndOfDirective(); } // Restore 'DisableMacroExpansion'. DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective; return ResVal.Val != 0; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/Pragma.cpp
//===--- Pragma.cpp - Pragma registration and handling --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PragmaHandler/PragmaTable interfaces and implements // pragma related methods of the Preprocessor class. // //===----------------------------------------------------------------------===// #include "clang/Lex/Pragma.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/ErrorHandling.h" #include <algorithm> using namespace clang; #include "llvm/Support/raw_ostream.h" // Out-of-line destructor to provide a home for the class. PragmaHandler::~PragmaHandler() { } //===----------------------------------------------------------------------===// // EmptyPragmaHandler Implementation. //===----------------------------------------------------------------------===// EmptyPragmaHandler::EmptyPragmaHandler() {} void EmptyPragmaHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) {} //===----------------------------------------------------------------------===// // PragmaNamespace Implementation. //===----------------------------------------------------------------------===// PragmaNamespace::~PragmaNamespace() { llvm::DeleteContainerSeconds(Handlers); } /// FindHandler - Check to see if there is already a handler for the /// specified name. If not, return the handler for the null identifier if it /// exists, otherwise return null. If IgnoreNull is true (the default) then /// the null handler isn't returned on failure to match. PragmaHandler *PragmaNamespace::FindHandler(StringRef Name, bool IgnoreNull) const { if (PragmaHandler *Handler = Handlers.lookup(Name)) return Handler; return IgnoreNull ? nullptr : Handlers.lookup(StringRef()); } void PragmaNamespace::AddPragma(PragmaHandler *Handler) { // HLSL Change Begins: Don't leak on exceptions std::unique_ptr<PragmaHandler> HandlerPtr(Handler); assert(!Handlers.lookup(Handler->getName()) && "A handler with this name is already registered in this namespace"); PragmaHandler*& MapHandler = Handlers[Handler->getName()]; MapHandler = HandlerPtr.release(); // HLSL Change Ends } void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) { assert(Handlers.lookup(Handler->getName()) && "Handler not registered in this namespace"); Handlers.erase(Handler->getName()); } void PragmaNamespace::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro // expand it, the user can have a STDC #define, that should not affect this. PP.LexUnexpandedToken(Tok); // Get the handler for this token. If there is no handler, ignore the pragma. PragmaHandler *Handler = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName() : StringRef(), /*IgnoreNull=*/false); if (!Handler) { PP.Diag(Tok, diag::warn_pragma_ignored); return; } // Otherwise, pass it down. Handler->HandlePragma(PP, Introducer, Tok); } //===----------------------------------------------------------------------===// // Preprocessor Pragma Directive Handling. //===----------------------------------------------------------------------===// /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the /// rest of the pragma, passing it to the registered pragma handlers. void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc, PragmaIntroducerKind Introducer) { if (Callbacks) Callbacks->PragmaDirective(IntroducerLoc, Introducer); if (!PragmasEnabled) return; ++NumPragma; // Invoke the first level of pragma handlers which reads the namespace id. Token Tok; PragmaHandlers->HandlePragma(*this, Introducer, Tok); // If the pragma handler didn't read the rest of the line, consume it now. if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective()) || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective)) DiscardUntilEndOfDirective(); } namespace { /// \brief Helper class for \see Preprocessor::Handle_Pragma. class LexingFor_PragmaRAII { Preprocessor &PP; bool InMacroArgPreExpansion; bool Failed; Token &OutTok; Token PragmaTok; public: LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion, Token &Tok) : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion), Failed(false), OutTok(Tok) { if (InMacroArgPreExpansion) { PragmaTok = OutTok; PP.EnableBacktrackAtThisPos(); } } ~LexingFor_PragmaRAII() { if (InMacroArgPreExpansion) { if (Failed) { PP.CommitBacktrackedTokens(); } else { PP.Backtrack(); OutTok = PragmaTok; } } } void failed() { Failed = true; } }; } /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then /// return the first token after the directive. The _Pragma token has just /// been read into 'Tok'. void Preprocessor::Handle_Pragma(Token &Tok) { // This works differently if we are pre-expanding a macro argument. // In that case we don't actually "activate" the pragma now, we only lex it // until we are sure it is lexically correct and then we backtrack so that // we activate the pragma whenever we encounter the tokens again in the token // stream. This ensures that we will activate it in the correct location // or that we will ignore it if it never enters the token stream, e.g: // // #define EMPTY(x) // #define INACTIVE(x) EMPTY(x) // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\"")) LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok); // Remember the pragma token location. SourceLocation PragmaLoc = Tok.getLocation(); // Read the '('. Lex(Tok); if (Tok.isNot(tok::l_paren)) { Diag(PragmaLoc, diag::err__Pragma_malformed); return _PragmaLexing.failed(); } // Read the '"..."'. Lex(Tok); if (!tok::isStringLiteral(Tok.getKind())) { Diag(PragmaLoc, diag::err__Pragma_malformed); // Skip this token, and the ')', if present. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof)) Lex(Tok); if (Tok.is(tok::r_paren)) Lex(Tok); return _PragmaLexing.failed(); } if (Tok.hasUDSuffix()) { Diag(Tok, diag::err_invalid_string_udl); // Skip this token, and the ')', if present. Lex(Tok); if (Tok.is(tok::r_paren)) Lex(Tok); return _PragmaLexing.failed(); } // Remember the string. Token StrTok = Tok; // Read the ')'. Lex(Tok); if (Tok.isNot(tok::r_paren)) { Diag(PragmaLoc, diag::err__Pragma_malformed); return _PragmaLexing.failed(); } if (InMacroArgPreExpansion) return; SourceLocation RParenLoc = Tok.getLocation(); std::string StrVal = getSpelling(StrTok); // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1: // "The string literal is destringized by deleting any encoding prefix, // deleting the leading and trailing double-quotes, replacing each escape // sequence \" by a double-quote, and replacing each escape sequence \\ by a // single backslash." if (StrVal[0] == 'L' || StrVal[0] == 'U' || (StrVal[0] == 'u' && StrVal[1] != '8')) StrVal.erase(StrVal.begin()); else if (StrVal[0] == 'u') StrVal.erase(StrVal.begin(), StrVal.begin() + 2); if (StrVal[0] == 'R') { // FIXME: C++11 does not specify how to handle raw-string-literals here. // We strip off the 'R', the quotes, the d-char-sequences, and the parens. assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' && "Invalid raw string token!"); // Measure the length of the d-char-sequence. unsigned NumDChars = 0; while (StrVal[2 + NumDChars] != '(') { assert(NumDChars < (StrVal.size() - 5) / 2 && "Invalid raw string token!"); ++NumDChars; } assert(StrVal[StrVal.size() - 2 - NumDChars] == ')'); // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the // parens below. StrVal.erase(0, 2 + NumDChars); StrVal.erase(StrVal.size() - 1 - NumDChars); } else { assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && "Invalid string token!"); // Remove escaped quotes and escapes. unsigned ResultPos = 1; for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) { // Skip escapes. \\ -> '\' and \" -> '"'. if (StrVal[i] == '\\' && i + 1 < e && (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"')) ++i; StrVal[ResultPos++] = StrVal[i]; } StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1); } // Remove the front quote, replacing it with a space, so that the pragma // contents appear to have a space before them. StrVal[0] = ' '; // Replace the terminating quote with a \n. StrVal[StrVal.size()-1] = '\n'; // Plop the string (including the newline and trailing null) into a buffer // where we can lex it. Token TmpTok; TmpTok.startToken(); CreateString(StrVal, TmpTok); SourceLocation TokLoc = TmpTok.getLocation(); // Make and enter a lexer object so that we lex and expand the tokens just // like any others. Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc, StrVal.size(), *this); EnterSourceFileWithLexer(TL, nullptr); // With everything set up, lex this as a #pragma directive. HandlePragmaDirective(PragmaLoc, PIK__Pragma); // Finally, return whatever came after the pragma directive. return Lex(Tok); } /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text /// is not enclosed within a string literal. void Preprocessor::HandleMicrosoft__pragma(Token &Tok) { // Remember the pragma token location. SourceLocation PragmaLoc = Tok.getLocation(); // Read the '('. Lex(Tok); if (Tok.isNot(tok::l_paren)) { Diag(PragmaLoc, diag::err__Pragma_malformed); return; } // Get the tokens enclosed within the __pragma(), as well as the final ')'. SmallVector<Token, 32> PragmaToks; int NumParens = 0; Lex(Tok); while (Tok.isNot(tok::eof)) { PragmaToks.push_back(Tok); if (Tok.is(tok::l_paren)) NumParens++; else if (Tok.is(tok::r_paren) && NumParens-- == 0) break; Lex(Tok); } if (Tok.is(tok::eof)) { Diag(PragmaLoc, diag::err_unterminated___pragma); return; } PragmaToks.front().setFlag(Token::LeadingSpace); // Replace the ')' with an EOD to mark the end of the pragma. PragmaToks.back().setKind(tok::eod); Token *TokArray = new Token[PragmaToks.size()]; std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray); // Push the tokens onto the stack. EnterTokenStream(TokArray, PragmaToks.size(), true, true); // With everything set up, lex this as a #pragma directive. HandlePragmaDirective(PragmaLoc, PIK___pragma); // Finally, return whatever came after the pragma directive. return Lex(Tok); } /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'. /// void Preprocessor::HandlePragmaOnce(Token &OnceTok) { if (isInPrimaryFile()) { Diag(OnceTok, diag::pp_pragma_once_in_main_file); return; } // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. // Mark the file as a once-only file now. HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry()); } void Preprocessor::HandlePragmaMark() { assert(CurPPLexer && "No current lexer?"); if (CurLexer) CurLexer->ReadToEndOfLine(); else CurPTHLexer->DiscardToEndOfLine(); } /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'. /// void Preprocessor::HandlePragmaPoison(Token &PoisonTok) { Token Tok; while (1) { // Read the next token to poison. While doing this, pretend that we are // skipping while reading the identifier to poison. // This avoids errors on code like: // #pragma GCC poison X // #pragma GCC poison X if (CurPPLexer) CurPPLexer->LexingRawMode = true; LexUnexpandedToken(Tok); if (CurPPLexer) CurPPLexer->LexingRawMode = false; // If we reached the end of line, we're done. if (Tok.is(tok::eod)) return; // Can only poison identifiers. if (Tok.isNot(tok::raw_identifier)) { Diag(Tok, diag::err_pp_invalid_poison); return; } // Look up the identifier info for the token. We disabled identifier lookup // by saying we're skipping contents, so we need to do this manually. IdentifierInfo *II = LookUpIdentifierInfo(Tok); // Already poisoned. if (II->isPoisoned()) continue; // If this is a macro identifier, emit a warning. if (isMacroDefined(II)) Diag(Tok, diag::pp_poisoning_existing_macro); // Finally, poison it! II->setIsPoisoned(); if (II->isFromAST()) II->setChangedSinceDeserialization(); } } /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know /// that the whole directive has been parsed. void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) { if (isInPrimaryFile()) { Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file); return; } // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc. PreprocessorLexer *TheLexer = getCurrentFileLexer(); // Mark the file as a system header. HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry()); PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation()); if (PLoc.isInvalid()) return; unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename()); // Notify the client, if desired, that we are in a new source file. if (Callbacks) Callbacks->FileChanged(SysHeaderTok.getLocation(), PPCallbacks::SystemHeaderPragma, SrcMgr::C_System); // Emit a line marker. This will change any source locations from this point // forward to realize they are in a system header. // Create a line note with this information. SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1, FilenameID, /*IsEntry=*/false, /*IsExit=*/false, /*IsSystem=*/true, /*IsExternC=*/false); } /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah. /// void Preprocessor::HandlePragmaDependency(Token &DependencyTok) { Token FilenameTok; CurPPLexer->LexIncludeFilename(FilenameTok); // If the token kind is EOD, the error has already been diagnosed. if (FilenameTok.is(tok::eod)) return; // Reserve a buffer to get the spelling. SmallString<128> FilenameBuffer; bool Invalid = false; StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid); if (Invalid) return; bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename); // If GetIncludeFilenameSpelling set the start ptr to null, there was an // error. if (Filename.empty()) return; // Search include directories for this file. const DirectoryLookup *CurDir; const FileEntry *File = LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr, nullptr, CurDir, nullptr, nullptr, nullptr); if (!File) { if (!SuppressIncludeNotFoundError) Diag(FilenameTok, diag::err_pp_file_not_found) << Filename; return; } const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry(); // If this file is older than the file it depends on, emit a diagnostic. if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) { // Lex tokens at the end of the message and include them in the message. std::string Message; Lex(DependencyTok); while (DependencyTok.isNot(tok::eod)) { Message += getSpelling(DependencyTok) + " "; Lex(DependencyTok); } // Remove the trailing ' ' if present. if (!Message.empty()) Message.erase(Message.end()-1); Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message; } } /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro. /// Return the IdentifierInfo* associated with the macro to push or pop. IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) { // Remember the pragma token location. Token PragmaTok = Tok; // Read the '('. Lex(Tok); if (Tok.isNot(tok::l_paren)) { Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) << getSpelling(PragmaTok); return nullptr; } // Read the macro name string. Lex(Tok); if (Tok.isNot(tok::string_literal)) { Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) << getSpelling(PragmaTok); return nullptr; } if (Tok.hasUDSuffix()) { Diag(Tok, diag::err_invalid_string_udl); return nullptr; } // Remember the macro string. std::string StrVal = getSpelling(Tok); // Read the ')'. Lex(Tok); if (Tok.isNot(tok::r_paren)) { Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed) << getSpelling(PragmaTok); return nullptr; } assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' && "Invalid string token!"); // Create a Token from the string. Token MacroTok; MacroTok.startToken(); MacroTok.setKind(tok::raw_identifier); CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok); // Get the IdentifierInfo of MacroToPushTok. return LookUpIdentifierInfo(MacroTok); } /// \brief Handle \#pragma push_macro. /// /// The syntax is: /// \code /// #pragma push_macro("macro") /// \endcode void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) { // Parse the pragma directive and get the macro IdentifierInfo*. IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok); if (!IdentInfo) return; // Get the MacroInfo associated with IdentInfo. MacroInfo *MI = getMacroInfo(IdentInfo); if (MI) { // Allow the original MacroInfo to be redefined later. MI->setIsAllowRedefinitionsWithoutWarning(true); } // Push the cloned MacroInfo so we can retrieve it later. PragmaPushMacroInfo[IdentInfo].push_back(MI); } /// \brief Handle \#pragma pop_macro. /// /// The syntax is: /// \code /// #pragma pop_macro("macro") /// \endcode void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) { SourceLocation MessageLoc = PopMacroTok.getLocation(); // Parse the pragma directive and get the macro IdentifierInfo*. IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok); if (!IdentInfo) return; // Find the vector<MacroInfo*> associated with the macro. llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter = PragmaPushMacroInfo.find(IdentInfo); if (iter != PragmaPushMacroInfo.end()) { // Forget the MacroInfo currently associated with IdentInfo. if (MacroInfo *MI = getMacroInfo(IdentInfo)) { if (MI->isWarnIfUnused()) WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc)); } // Get the MacroInfo we want to reinstall. MacroInfo *MacroToReInstall = iter->second.back(); if (MacroToReInstall) // Reinstall the previously pushed macro. appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc); // Pop PragmaPushMacroInfo stack. iter->second.pop_back(); if (iter->second.size() == 0) PragmaPushMacroInfo.erase(iter); } else { Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push) << IdentInfo->getName(); } } void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) { // We will either get a quoted filename or a bracketed filename, and we // have to track which we got. The first filename is the source name, // and the second name is the mapped filename. If the first is quoted, // the second must be as well (cannot mix and match quotes and brackets). // Get the open paren Lex(Tok); if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::warn_pragma_include_alias_expected) << "("; return; } // We expect either a quoted string literal, or a bracketed name Token SourceFilenameTok; CurPPLexer->LexIncludeFilename(SourceFilenameTok); if (SourceFilenameTok.is(tok::eod)) { // The diagnostic has already been handled return; } StringRef SourceFileName; SmallString<128> FileNameBuffer; if (SourceFilenameTok.is(tok::string_literal) || SourceFilenameTok.is(tok::angle_string_literal)) { SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer); } else if (SourceFilenameTok.is(tok::less)) { // This could be a path instead of just a name FileNameBuffer.push_back('<'); SourceLocation End; if (ConcatenateIncludeName(FileNameBuffer, End)) return; // Diagnostic already emitted SourceFileName = FileNameBuffer; } else { Diag(Tok, diag::warn_pragma_include_alias_expected_filename); return; } FileNameBuffer.clear(); // Now we expect a comma, followed by another include name Lex(Tok); if (Tok.isNot(tok::comma)) { Diag(Tok, diag::warn_pragma_include_alias_expected) << ","; return; } Token ReplaceFilenameTok; CurPPLexer->LexIncludeFilename(ReplaceFilenameTok); if (ReplaceFilenameTok.is(tok::eod)) { // The diagnostic has already been handled return; } StringRef ReplaceFileName; if (ReplaceFilenameTok.is(tok::string_literal) || ReplaceFilenameTok.is(tok::angle_string_literal)) { ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer); } else if (ReplaceFilenameTok.is(tok::less)) { // This could be a path instead of just a name FileNameBuffer.push_back('<'); SourceLocation End; if (ConcatenateIncludeName(FileNameBuffer, End)) return; // Diagnostic already emitted ReplaceFileName = FileNameBuffer; } else { Diag(Tok, diag::warn_pragma_include_alias_expected_filename); return; } // Finally, we expect the closing paren Lex(Tok); if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::warn_pragma_include_alias_expected) << ")"; return; } // Now that we have the source and target filenames, we need to make sure // they're both of the same type (angled vs non-angled) StringRef OriginalSource = SourceFileName; bool SourceIsAngled = GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(), SourceFileName); bool ReplaceIsAngled = GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(), ReplaceFileName); if (!SourceFileName.empty() && !ReplaceFileName.empty() && (SourceIsAngled != ReplaceIsAngled)) { unsigned int DiagID; if (SourceIsAngled) DiagID = diag::warn_pragma_include_alias_mismatch_angle; else DiagID = diag::warn_pragma_include_alias_mismatch_quote; Diag(SourceFilenameTok.getLocation(), DiagID) << SourceFileName << ReplaceFileName; return; } // Now we can let the include handler know about this mapping getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName); } /// AddPragmaHandler - Add the specified pragma handler to the preprocessor. /// If 'Namespace' is non-null, then it is a token required to exist on the /// pragma line before the pragma string starts, e.g. "STDC" or "GCC". void Preprocessor::AddPragmaHandler(StringRef Namespace, PragmaHandler *Handler) { std::unique_ptr<PragmaHandler> HandlerPtr(Handler); // HLSL Change: Don't leak on exceptions PragmaNamespace *InsertNS = PragmaHandlers.get(); // If this is specified to be in a namespace, step down into it. if (!Namespace.empty()) { // If there is already a pragma handler with the name of this namespace, // we either have an error (directive with the same name as a namespace) or // we already have the namespace to insert into. if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) { InsertNS = Existing->getIfNamespace(); assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma" " handler with the same name!"); } else { // Otherwise, this namespace doesn't exist yet, create and insert the // handler for it. InsertNS = new PragmaNamespace(Namespace); PragmaHandlers->AddPragma(InsertNS); } } // Check to make sure we don't already have a pragma for this identifier. assert(!InsertNS->FindHandler(Handler->getName()) && "Pragma handler already exists for this identifier!"); InsertNS->AddPragma(HandlerPtr.release()); // HLSL Change: Don't leak on exceptions } /// RemovePragmaHandler - Remove the specific pragma handler from the /// preprocessor. If \arg Namespace is non-null, then it should be the /// namespace that \arg Handler was added to. It is an error to remove /// a handler that has not been registered. void Preprocessor::RemovePragmaHandler(StringRef Namespace, PragmaHandler *Handler) { PragmaNamespace *NS = PragmaHandlers.get(); // If this is specified to be in a namespace, step down into it. if (!Namespace.empty()) { PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace); assert(Existing && "Namespace containing handler does not exist!"); NS = Existing->getIfNamespace(); assert(NS && "Invalid namespace, registered as a regular pragma handler!"); } NS->RemovePragmaHandler(Handler); // If this is a non-default namespace and it is now empty, remove it. if (NS != PragmaHandlers.get() && NS->IsEmpty()) { PragmaHandlers->RemovePragmaHandler(NS); delete NS; } } bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) { Token Tok; LexUnexpandedToken(Tok); if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::ext_on_off_switch_syntax); return true; } IdentifierInfo *II = Tok.getIdentifierInfo(); if (II->isStr("ON")) Result = tok::OOS_ON; else if (II->isStr("OFF")) Result = tok::OOS_OFF; else if (II->isStr("DEFAULT")) Result = tok::OOS_DEFAULT; else { Diag(Tok, diag::ext_on_off_switch_syntax); return true; } // Verify that this is followed by EOD. LexUnexpandedToken(Tok); if (Tok.isNot(tok::eod)) Diag(Tok, diag::ext_pragma_syntax_eod); return false; } namespace { /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included. struct PragmaOnceHandler : public PragmaHandler { PragmaOnceHandler() : PragmaHandler("once") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &OnceTok) override { PP.CheckEndOfDirective("pragma once"); PP.HandlePragmaOnce(OnceTok); } }; /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the /// rest of the line is not lexed. struct PragmaMarkHandler : public PragmaHandler { PragmaMarkHandler() : PragmaHandler("mark") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &MarkTok) override { PP.HandlePragmaMark(); } }; /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable. struct PragmaPoisonHandler : public PragmaHandler { PragmaPoisonHandler() : PragmaHandler("poison") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &PoisonTok) override { PP.HandlePragmaPoison(PoisonTok); } }; /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file /// as a system header, which silences warnings in it. struct PragmaSystemHeaderHandler : public PragmaHandler { PragmaSystemHeaderHandler() : PragmaHandler("system_header") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &SHToken) override { PP.HandlePragmaSystemHeader(SHToken); PP.CheckEndOfDirective("pragma"); } }; struct PragmaDependencyHandler : public PragmaHandler { PragmaDependencyHandler() : PragmaHandler("dependency") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &DepToken) override { PP.HandlePragmaDependency(DepToken); } }; struct PragmaDebugHandler : public PragmaHandler { PragmaDebugHandler() : PragmaHandler("__debug") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &DepToken) override { Token Tok; PP.LexUnexpandedToken(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); return; } IdentifierInfo *II = Tok.getIdentifierInfo(); if (II->isStr("assert")) { llvm_unreachable("This is an assertion!"); } else if (II->isStr("crash")) { LLVM_BUILTIN_TRAP; } else if (II->isStr("parser_crash")) { Token Crasher; Crasher.startToken(); Crasher.setKind(tok::annot_pragma_parser_crash); Crasher.setAnnotationRange(SourceRange(Tok.getLocation())); PP.EnterToken(Crasher); } else if (II->isStr("llvm_fatal_error")) { llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error"); } else if (II->isStr("llvm_unreachable")) { llvm_unreachable("#pragma clang __debug llvm_unreachable"); } else if (II->isStr("macro")) { Token MacroName; PP.LexUnexpandedToken(MacroName); auto *MacroII = MacroName.getIdentifierInfo(); if (MacroII) PP.dumpMacroInfo(MacroII); else PP.Diag(MacroName, diag::warn_pragma_diagnostic_invalid); } else if (II->isStr("overflow_stack")) { DebugOverflowStack(); } else if (II->isStr("handle_crash")) { llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent(); if (CRC) CRC->HandleCrash(); } else if (II->isStr("captured")) { HandleCaptured(PP); } else { PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command) << II->getName(); } PPCallbacks *Callbacks = PP.getPPCallbacks(); if (Callbacks) Callbacks->PragmaDebug(Tok.getLocation(), II->getName()); } void HandleCaptured(Preprocessor &PP) { // Skip if emitting preprocessed output. if (PP.isPreprocessedOutput()) return; Token Tok; PP.LexUnexpandedToken(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma clang __debug captured"; return; } SourceLocation NameLoc = Tok.getLocation(); Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1); Toks->startToken(); Toks->setKind(tok::annot_pragma_captured); Toks->setLocation(NameLoc); PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false); } // Disable MSVC warning about runtime stack overflow. #ifdef _MSC_VER #pragma warning(disable : 4717) #endif static void DebugOverflowStack() { void (*volatile Self)() = DebugOverflowStack; Self(); } #ifdef _MSC_VER #pragma warning(default : 4717) #endif }; /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"' struct PragmaDiagnosticHandler : public PragmaHandler { private: const char *Namespace; public: explicit PragmaDiagnosticHandler(const char *NS) : PragmaHandler("diagnostic"), Namespace(NS) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &DiagToken) override { SourceLocation DiagLoc = DiagToken.getLocation(); Token Tok; PP.LexUnexpandedToken(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); return; } IdentifierInfo *II = Tok.getIdentifierInfo(); PPCallbacks *Callbacks = PP.getPPCallbacks(); if (II->isStr("pop")) { if (!PP.getDiagnostics().popMappings(DiagLoc)) PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop); else if (Callbacks) Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace); return; } else if (II->isStr("push")) { PP.getDiagnostics().pushMappings(DiagLoc); if (Callbacks) Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace); return; } diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName()) .Case("ignored", diag::Severity::Ignored) .Case("warning", diag::Severity::Warning) .Case("error", diag::Severity::Error) .Case("fatal", diag::Severity::Fatal) .Default(diag::Severity()); if (SV == diag::Severity()) { PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid); return; } PP.LexUnexpandedToken(Tok); SourceLocation StringLoc = Tok.getLocation(); std::string WarningName; if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic", /*MacroExpansion=*/false)) return; if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token); return; } if (WarningName.size() < 3 || WarningName[0] != '-' || (WarningName[1] != 'W' && WarningName[1] != 'R')) { PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option); return; } if (PP.getDiagnostics().setSeverityForGroup( WarningName[1] == 'W' ? diag::Flavor::WarningOrError : diag::Flavor::Remark, WarningName.substr(2), SV, DiagLoc)) PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning) << WarningName; else if (Callbacks) Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName); } }; /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's /// diagnostics, so we don't really implement this pragma. We parse it and /// ignore it to avoid -Wunknown-pragma warnings. struct PragmaWarningHandler : public PragmaHandler { PragmaWarningHandler() : PragmaHandler("warning") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) override { // Parse things like: // warning(push, 1) // warning(pop) // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9) SourceLocation DiagLoc = Tok.getLocation(); PPCallbacks *Callbacks = PP.getPPCallbacks(); PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(Tok, diag::warn_pragma_warning_expected) << "("; return; } PP.Lex(Tok); IdentifierInfo *II = Tok.getIdentifierInfo(); if (II && II->isStr("push")) { // #pragma warning( push[ ,n ] ) int Level = -1; PP.Lex(Tok); if (Tok.is(tok::comma)) { PP.Lex(Tok); uint64_t Value; if (Tok.is(tok::numeric_constant) && PP.parseSimpleIntegerLiteral(Tok, Value)) Level = int(Value); if (Level < 0 || Level > 4) { PP.Diag(Tok, diag::warn_pragma_warning_push_level); return; } } if (Callbacks) Callbacks->PragmaWarningPush(DiagLoc, Level); } else if (II && II->isStr("pop")) { // #pragma warning( pop ) PP.Lex(Tok); if (Callbacks) Callbacks->PragmaWarningPop(DiagLoc); } else { // #pragma warning( warning-specifier : warning-number-list // [; warning-specifier : warning-number-list...] ) while (true) { II = Tok.getIdentifierInfo(); if (!II && !Tok.is(tok::numeric_constant)) { PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); return; } // Figure out which warning specifier this is. bool SpecifierValid; StringRef Specifier; llvm::SmallString<1> SpecifierBuf; if (II) { Specifier = II->getName(); SpecifierValid = llvm::StringSwitch<bool>(Specifier) .Cases("default", "disable", "error", "once", "suppress", true) .Default(false); // If we read a correct specifier, snatch next token (that should be // ":", checked later). if (SpecifierValid) PP.Lex(Tok); } else { // Token is a numeric constant. It should be either 1, 2, 3 or 4. uint64_t Value; Specifier = PP.getSpelling(Tok, SpecifierBuf); if (PP.parseSimpleIntegerLiteral(Tok, Value)) { SpecifierValid = (Value >= 1) && (Value <= 4); } else SpecifierValid = false; // Next token already snatched by parseSimpleIntegerLiteral. } if (!SpecifierValid) { PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid); return; } if (Tok.isNot(tok::colon)) { PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":"; return; } // Collect the warning ids. SmallVector<int, 4> Ids; PP.Lex(Tok); while (Tok.is(tok::numeric_constant)) { uint64_t Value; if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 || Value > INT_MAX) { PP.Diag(Tok, diag::warn_pragma_warning_expected_number); return; } Ids.push_back(int(Value)); } if (Callbacks) Callbacks->PragmaWarning(DiagLoc, Specifier, Ids); // Parse the next specifier if there is a semicolon. if (Tok.isNot(tok::semi)) break; PP.Lex(Tok); } } if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")"; return; } PP.Lex(Tok); if (Tok.isNot(tok::eod)) PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning"; } }; /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")". struct PragmaIncludeAliasHandler : public PragmaHandler { PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &IncludeAliasTok) override { PP.HandlePragmaIncludeAlias(IncludeAliasTok); } }; /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message /// extension. The syntax is: /// \code /// #pragma message(string) /// \endcode /// OR, in GCC mode: /// \code /// #pragma message string /// \endcode /// string is a string, which is fully macro expanded, and permits string /// concatenation, embedded escape characters, etc... See MSDN for more details. /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same /// form as \#pragma message. struct PragmaMessageHandler : public PragmaHandler { private: const PPCallbacks::PragmaMessageKind Kind; const StringRef Namespace; static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind, bool PragmaNameOnly = false) { switch (Kind) { case PPCallbacks::PMK_Message: return PragmaNameOnly ? "message" : "pragma message"; case PPCallbacks::PMK_Warning: return PragmaNameOnly ? "warning" : "pragma warning"; case PPCallbacks::PMK_Error: return PragmaNameOnly ? "error" : "pragma error"; } llvm_unreachable("Unknown PragmaMessageKind!"); } public: PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind, StringRef Namespace = StringRef()) : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) override { SourceLocation MessageLoc = Tok.getLocation(); PP.Lex(Tok); bool ExpectClosingParen = false; switch (Tok.getKind()) { case tok::l_paren: // We have a MSVC style pragma message. ExpectClosingParen = true; // Read the string. PP.Lex(Tok); break; case tok::string_literal: // We have a GCC style pragma message, and we just read the string. break; default: PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind; return; } std::string MessageString; if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind), /*MacroExpansion=*/true)) return; if (ExpectClosingParen) { if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind; return; } PP.Lex(Tok); // eat the r_paren. } if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind; return; } // Output the message. PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error) ? diag::err_pragma_message : diag::warn_pragma_message) << MessageString; // If the pragma is lexically sound, notify any interested PPCallbacks. if (PPCallbacks *Callbacks = PP.getPPCallbacks()) Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString); } }; /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the /// macro on the top of the stack. struct PragmaPushMacroHandler : public PragmaHandler { PragmaPushMacroHandler() : PragmaHandler("push_macro") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &PushMacroTok) override { PP.HandlePragmaPushMacro(PushMacroTok); } }; /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the /// macro to the value on the top of the stack. struct PragmaPopMacroHandler : public PragmaHandler { PragmaPopMacroHandler() : PragmaHandler("pop_macro") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &PopMacroTok) override { PP.HandlePragmaPopMacro(PopMacroTok); } }; // Pragma STDC implementations. /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...". struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler { PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) override { tok::OnOffSwitch OOS; if (PP.LexOnOffSwitch(OOS)) return; if (OOS == tok::OOS_ON) PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported); } }; /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...". struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler { PragmaSTDC_CX_LIMITED_RANGEHandler() : PragmaHandler("CX_LIMITED_RANGE") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) override { tok::OnOffSwitch OOS; PP.LexOnOffSwitch(OOS); } }; /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...". struct PragmaSTDC_UnknownHandler : public PragmaHandler { PragmaSTDC_UnknownHandler() {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &UnknownTok) override { // C99 6.10.6p2, unknown forms are not allowed. PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored); } }; /// PragmaARCCFCodeAuditedHandler - /// \#pragma clang arc_cf_code_audited begin/end struct PragmaARCCFCodeAuditedHandler : public PragmaHandler { PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &NameTok) override { SourceLocation Loc = NameTok.getLocation(); bool IsBegin; Token Tok; // Lex the 'begin' or 'end'. PP.LexUnexpandedToken(Tok); const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo(); if (BeginEnd && BeginEnd->isStr("begin")) { IsBegin = true; } else if (BeginEnd && BeginEnd->isStr("end")) { IsBegin = false; } else { PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax); return; } // Verify that this is followed by EOD. PP.LexUnexpandedToken(Tok); if (Tok.isNot(tok::eod)) PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; // The start location of the active audit. SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc(); // The start location we want after processing this. SourceLocation NewLoc; if (IsBegin) { // Complain about attempts to re-enter an audit. if (BeginLoc.isValid()) { PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited); PP.Diag(BeginLoc, diag::note_pragma_entered_here); } NewLoc = Loc; } else { // Complain about attempts to leave an audit that doesn't exist. if (!BeginLoc.isValid()) { PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited); return; } NewLoc = SourceLocation(); } PP.setPragmaARCCFCodeAuditedLoc(NewLoc); } }; /// PragmaAssumeNonNullHandler - /// \#pragma clang assume_nonnull begin/end struct PragmaAssumeNonNullHandler : public PragmaHandler { PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &NameTok) override { SourceLocation Loc = NameTok.getLocation(); bool IsBegin; Token Tok; // Lex the 'begin' or 'end'. PP.LexUnexpandedToken(Tok); const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo(); if (BeginEnd && BeginEnd->isStr("begin")) { IsBegin = true; } else if (BeginEnd && BeginEnd->isStr("end")) { IsBegin = false; } else { PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax); return; } // Verify that this is followed by EOD. PP.LexUnexpandedToken(Tok); if (Tok.isNot(tok::eod)) PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma"; // The start location of the active audit. SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc(); // The start location we want after processing this. SourceLocation NewLoc; if (IsBegin) { // Complain about attempts to re-enter an audit. if (BeginLoc.isValid()) { PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull); PP.Diag(BeginLoc, diag::note_pragma_entered_here); } NewLoc = Loc; } else { // Complain about attempts to leave an audit that doesn't exist. if (!BeginLoc.isValid()) { PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull); return; } NewLoc = SourceLocation(); } PP.setPragmaAssumeNonNullLoc(NewLoc); } }; /// \brief Handle "\#pragma region [...]" /// /// The syntax is /// \code /// #pragma region [optional name] /// #pragma endregion [optional comment] /// \endcode /// /// \note This is /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a> /// pragma, just skipped by compiler. struct PragmaRegionHandler : public PragmaHandler { PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { } void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &NameTok) override { // #pragma region: endregion matches can be verified // __pragma(region): no sense, but ignored by msvc // _Pragma is not valid for MSVC, but there isn't any point // to handle a _Pragma differently. } }; } // end anonymous namespace /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas: /// \#pragma GCC poison/system_header/dependency and \#pragma once. void Preprocessor::RegisterBuiltinPragmas() { // HLSL Change Starts - pick only the pragma handlers we care about if (LangOpts.HLSL) { // TODO: add HLSL-specific pragma handlers AddPragmaHandler(new PragmaOnceHandler()); AddPragmaHandler(new PragmaMarkHandler()); AddPragmaHandler("dxc", new PragmaDiagnosticHandler("dxc")); AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message)); AddPragmaHandler(new PragmaRegionHandler("region")); AddPragmaHandler(new PragmaRegionHandler("endregion")); return; } // HLSL Change Ends AddPragmaHandler(new PragmaOnceHandler()); AddPragmaHandler(new PragmaMarkHandler()); AddPragmaHandler(new PragmaPushMacroHandler()); AddPragmaHandler(new PragmaPopMacroHandler()); AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message)); // #pragma GCC ... AddPragmaHandler("GCC", new PragmaPoisonHandler()); AddPragmaHandler("GCC", new PragmaSystemHeaderHandler()); AddPragmaHandler("GCC", new PragmaDependencyHandler()); AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC")); AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning, "GCC")); AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error, "GCC")); // #pragma clang ... AddPragmaHandler("clang", new PragmaPoisonHandler()); AddPragmaHandler("clang", new PragmaSystemHeaderHandler()); AddPragmaHandler("clang", new PragmaDebugHandler()); AddPragmaHandler("clang", new PragmaDependencyHandler()); AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang")); AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler()); AddPragmaHandler("clang", new PragmaAssumeNonNullHandler()); AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler()); AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler()); AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler()); // MS extensions. if (LangOpts.MicrosoftExt) { AddPragmaHandler(new PragmaWarningHandler()); AddPragmaHandler(new PragmaIncludeAliasHandler()); AddPragmaHandler(new PragmaRegionHandler("region")); AddPragmaHandler(new PragmaRegionHandler("endregion")); } } /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise /// warn about those pragmas being unknown. void Preprocessor::IgnorePragmas() { AddPragmaHandler(new EmptyPragmaHandler()); // Also ignore all pragmas in all namespaces created // in Preprocessor::RegisterBuiltinPragmas(). AddPragmaHandler("GCC", new EmptyPragmaHandler()); AddPragmaHandler("clang", new EmptyPragmaHandler()); if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) { // Preprocessor::RegisterBuiltinPragmas() already registers // PragmaSTDC_UnknownHandler as the empty handler, so remove it first, // otherwise there will be an assert about a duplicate handler. PragmaNamespace *STDCNamespace = NS->getIfNamespace(); assert(STDCNamespace && "Invalid namespace, registered as a regular pragma handler!"); if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) { RemovePragmaHandler("STDC", Existing); delete Existing; } } AddPragmaHandler("STDC", new EmptyPragmaHandler()); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/ScratchBuffer.cpp
//===--- ScratchBuffer.cpp - Scratch space for forming tokens -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ScratchBuffer interface. // //===----------------------------------------------------------------------===// #include "clang/Lex/ScratchBuffer.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/MemoryBuffer.h" #include <cstring> using namespace clang; // ScratchBufSize - The size of each chunk of scratch memory. Slightly less //than a page, almost certainly enough for anything. :) static const unsigned ScratchBufSize = 4060; ScratchBuffer::ScratchBuffer(SourceManager &SM) : SourceMgr(SM), CurBuffer(nullptr) { // Set BytesUsed so that the first call to getToken will require an alloc. BytesUsed = ScratchBufSize; } /// getToken - Splat the specified text into a temporary MemoryBuffer and /// return a SourceLocation that refers to the token. This is just like the /// method below, but returns a location that indicates the physloc of the /// token. SourceLocation ScratchBuffer::getToken(const char *Buf, unsigned Len, const char *&DestPtr) { if (BytesUsed+Len+2 > ScratchBufSize) AllocScratchBuffer(Len+2); // Prefix the token with a \n, so that it looks like it is the first thing on // its own virtual line in caret diagnostics. CurBuffer[BytesUsed++] = '\n'; // Return a pointer to the character data. DestPtr = CurBuffer+BytesUsed; // Copy the token data into the buffer. memcpy(CurBuffer+BytesUsed, Buf, Len); // Remember that we used these bytes. BytesUsed += Len+1; // Add a NUL terminator to the token. This keeps the tokens separated, in // case they get relexed, and puts them on their own virtual lines in case a // diagnostic points to one. CurBuffer[BytesUsed-1] = '\0'; return BufferStartLoc.getLocWithOffset(BytesUsed-Len-1); } void ScratchBuffer::AllocScratchBuffer(unsigned RequestLen) { // Only pay attention to the requested length if it is larger than our default // page size. If it is, we allocate an entire chunk for it. This is to // support gigantic tokens, which almost certainly won't happen. :) if (RequestLen < ScratchBufSize) RequestLen = ScratchBufSize; // Get scratch buffer. Zero-initialize it so it can be dumped into a PCH file // deterministically. std::unique_ptr<llvm::MemoryBuffer> OwnBuf = llvm::MemoryBuffer::getNewMemBuffer(RequestLen, "<scratch space>"); llvm::MemoryBuffer &Buf = *OwnBuf; FileID FID = SourceMgr.createFileID(std::move(OwnBuf)); BufferStartLoc = SourceMgr.getLocForStartOfFile(FID); CurBuffer = const_cast<char*>(Buf.getBufferStart()); BytesUsed = 0; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/MacroArgs.cpp
//===--- MacroArgs.cpp - Formal argument info for Macros ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the MacroArgs interface. // //===----------------------------------------------------------------------===// #include "clang/Lex/MacroArgs.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/SaveAndRestore.h" #include <algorithm> using namespace clang; /// MacroArgs ctor function - This destroys the vector passed in. MacroArgs *MacroArgs::create(const MacroInfo *MI, ArrayRef<Token> UnexpArgTokens, bool VarargsElided, Preprocessor &PP) { assert(MI->isFunctionLike() && "Can't have args for an object-like macro!"); MacroArgs **ResultEnt = nullptr; unsigned ClosestMatch = ~0U; // See if we have an entry with a big enough argument list to reuse on the // free list. If so, reuse it. for (MacroArgs **Entry = &PP.MacroArgCache; *Entry; Entry = &(*Entry)->ArgCache) if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() && (*Entry)->NumUnexpArgTokens < ClosestMatch) { ResultEnt = Entry; // If we have an exact match, use it. if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size()) break; // Otherwise, use the best fit. ClosestMatch = (*Entry)->NumUnexpArgTokens; } MacroArgs *Result; if (!ResultEnt) { // Allocate memory for a MacroArgs object with the lexer tokens at the end. Result = (MacroArgs*)malloc(sizeof(MacroArgs) + UnexpArgTokens.size() * sizeof(Token)); // Construct the MacroArgs object. new (Result) MacroArgs(UnexpArgTokens.size(), VarargsElided); } else { Result = *ResultEnt; // Unlink this node from the preprocessors singly linked list. *ResultEnt = Result->ArgCache; Result->NumUnexpArgTokens = UnexpArgTokens.size(); Result->VarargsElided = VarargsElided; } // Copy the actual unexpanded tokens to immediately after the result ptr. if (!UnexpArgTokens.empty()) std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(), const_cast<Token*>(Result->getUnexpArgument(0))); return Result; } /// destroy - Destroy and deallocate the memory for this object. /// void MacroArgs::destroy(Preprocessor &PP) { StringifiedArgs.clear(); // Don't clear PreExpArgTokens, just clear the entries. Clearing the entries // would deallocate the element vectors. for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i) PreExpArgTokens[i].clear(); // Add this to the preprocessor's free list. ArgCache = PP.MacroArgCache; PP.MacroArgCache = this; } /// deallocate - This should only be called by the Preprocessor when managing /// its freelist. MacroArgs *MacroArgs::deallocate() { MacroArgs *Next = ArgCache; // Run the dtor to deallocate the vectors. this->~MacroArgs(); // Release the memory for the object. free(this); return Next; } /// getArgLength - Given a pointer to an expanded or unexpanded argument, /// return the number of tokens, not counting the EOF, that make up the /// argument. unsigned MacroArgs::getArgLength(const Token *ArgPtr) { unsigned NumArgTokens = 0; for (; ArgPtr->isNot(tok::eof); ++ArgPtr) ++NumArgTokens; return NumArgTokens; } /// getUnexpArgument - Return the unexpanded tokens for the specified formal. /// const Token *MacroArgs::getUnexpArgument(unsigned Arg) const { // The unexpanded argument tokens start immediately after the MacroArgs object // in memory. const Token *Start = (const Token *)(this+1); const Token *Result = Start; // Scan to find Arg. for (; Arg; ++Result) { assert(Result < Start+NumUnexpArgTokens && "Invalid arg #"); if (Result->is(tok::eof)) --Arg; } assert(Result < Start+NumUnexpArgTokens && "Invalid arg #"); return Result; } /// ArgNeedsPreexpansion - If we can prove that the argument won't be affected /// by pre-expansion, return false. Otherwise, conservatively return true. bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok, Preprocessor &PP) const { // If there are no identifiers in the argument list, or if the identifiers are // known to not be macros, pre-expansion won't modify it. for (; ArgTok->isNot(tok::eof); ++ArgTok) if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) if (II->hasMacroDefinition()) // Return true even though the macro could be a function-like macro // without a following '(' token, or could be disabled, or not visible. return true; return false; } /// getPreExpArgument - Return the pre-expanded form of the specified /// argument. const std::vector<Token> & MacroArgs::getPreExpArgument(unsigned Arg, const MacroInfo *MI, Preprocessor &PP) { assert(Arg < MI->getNumArgs() && "Invalid argument number!"); // If we have already computed this, return it. if (PreExpArgTokens.size() < MI->getNumArgs()) PreExpArgTokens.resize(MI->getNumArgs()); std::vector<Token> &Result = PreExpArgTokens[Arg]; if (!Result.empty()) return Result; SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true); const Token *AT = getUnexpArgument(Arg); unsigned NumToks = getArgLength(AT)+1; // Include the EOF. // Otherwise, we have to pre-expand this argument, populating Result. To do // this, we set up a fake TokenLexer to lex from the unexpanded argument // list. With this installed, we lex expanded tokens until we hit the EOF // token at the end of the unexp list. PP.EnterTokenStream(AT, NumToks, false /*disable expand*/, false /*owns tokens*/); // Lex all of the macro-expanded tokens into Result. do { Result.push_back(Token()); Token &Tok = Result.back(); PP.Lex(Tok); } while (Result.back().isNot(tok::eof)); // Pop the token stream off the top of the stack. We know that the internal // pointer inside of it is to the "end" of the token stream, but the stack // will not otherwise be popped until the next token is lexed. The problem is // that the token may be lexed sometime after the vector of tokens itself is // destroyed, which would be badness. if (PP.InCachingLexMode()) PP.ExitCachingLexMode(); PP.RemoveTopOfLexerStack(); return Result; } /// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of /// tokens into the literal string token that should be produced by the C # /// preprocessor operator. If Charify is true, then it should be turned into /// a character literal for the Microsoft charize (#@) extension. /// Token MacroArgs::StringifyArgument(const Token *ArgToks, Preprocessor &PP, bool Charify, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd) { Token Tok; Tok.startToken(); Tok.setKind(Charify ? tok::char_constant : tok::string_literal); const Token *ArgTokStart = ArgToks; // Stringify all the tokens. SmallString<128> Result; Result += "\""; bool isFirst = true; for (; ArgToks->isNot(tok::eof); ++ArgToks) { const Token &Tok = *ArgToks; if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine())) Result += ' '; isFirst = false; // If this is a string or character constant, escape the token as specified // by 6.10.3.2p2. if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc. Tok.is(tok::char_constant) || // 'x' Tok.is(tok::wide_char_constant) || // L'x'. Tok.is(tok::utf8_char_constant) || // u8'x'. Tok.is(tok::utf16_char_constant) || // u'x'. Tok.is(tok::utf32_char_constant)) { // U'x'. bool Invalid = false; std::string TokStr = PP.getSpelling(Tok, &Invalid); if (!Invalid) { std::string Str = Lexer::Stringify(TokStr); Result.append(Str.begin(), Str.end()); } } else if (Tok.is(tok::code_completion)) { PP.CodeCompleteNaturalLanguage(); } else { // Otherwise, just append the token. Do some gymnastics to get the token // in place and avoid copies where possible. unsigned CurStrLen = Result.size(); Result.resize(CurStrLen+Tok.getLength()); const char *BufPtr = Result.data() + CurStrLen; bool Invalid = false; unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid); if (!Invalid) { // If getSpelling returned a pointer to an already uniqued version of // the string instead of filling in BufPtr, memcpy it onto our string. if (ActualTokLen && BufPtr != &Result[CurStrLen]) memcpy(&Result[CurStrLen], BufPtr, ActualTokLen); // If the token was dirty, the spelling may be shorter than the token. if (ActualTokLen != Tok.getLength()) Result.resize(CurStrLen+ActualTokLen); } } } // If the last character of the string is a \, and if it isn't escaped, this // is an invalid string literal, diagnose it as specified in C99. if (Result.back() == '\\') { // Count the number of consequtive \ characters. If even, then they are // just escaped backslashes, otherwise it's an error. unsigned FirstNonSlash = Result.size()-2; // Guaranteed to find the starting " if nothing else. while (Result[FirstNonSlash] == '\\') --FirstNonSlash; if ((Result.size()-1-FirstNonSlash) & 1) { // Diagnose errors for things like: #define F(X) #X / F(\) PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal); Result.pop_back(); // remove one of the \'s. } } Result += '"'; // If this is the charify operation and the result is not a legal character // constant, diagnose it. if (Charify) { // First step, turn double quotes into single quotes: Result[0] = '\''; Result[Result.size()-1] = '\''; // Check for bogus character. bool isBad = false; if (Result.size() == 3) isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above. else isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x' if (isBad) { PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify); Result = "' '"; // Use something arbitrary, but legal. } } PP.CreateString(Result, Tok, ExpansionLocStart, ExpansionLocEnd); return Tok; } /// getStringifiedArgument - Compute, cache, and return the specified argument /// that has been 'stringified' as required by the # operator. const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo, Preprocessor &PP, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd) { assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!"); if (StringifiedArgs.empty()) { StringifiedArgs.resize(getNumArguments()); memset((void*)&StringifiedArgs[0], 0, sizeof(StringifiedArgs[0])*getNumArguments()); } if (StringifiedArgs[ArgNo].isNot(tok::string_literal)) StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP, /*Charify=*/false, ExpansionLocStart, ExpansionLocEnd); return StringifiedArgs[ArgNo]; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Lex/PreprocessorLexer.cpp
//===--- PreprocessorLexer.cpp - C Language Family Lexer ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the PreprocessorLexer and Token interfaces. // //===----------------------------------------------------------------------===// #include "clang/Lex/PreprocessorLexer.h" #include "clang/Basic/SourceManager.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/Preprocessor.h" using namespace clang; void PreprocessorLexer::anchor() { } PreprocessorLexer::PreprocessorLexer(Preprocessor *pp, FileID fid) : PP(pp), FID(fid), InitialNumSLocEntries(0), ParsingPreprocessorDirective(false), ParsingFilename(false), LexingRawMode(false) { if (pp) InitialNumSLocEntries = pp->getSourceManager().local_sloc_entry_size(); } /// \brief After the preprocessor has parsed a \#include, lex and /// (potentially) macro expand the filename. void PreprocessorLexer::LexIncludeFilename(Token &FilenameTok) { assert(ParsingPreprocessorDirective && ParsingFilename == false && "Must be in a preprocessing directive!"); // We are now parsing a filename! ParsingFilename = true; // Lex the filename. if (LexingRawMode) IndirectLex(FilenameTok); else PP->Lex(FilenameTok); // We should have obtained the filename now. ParsingFilename = false; // No filename? if (FilenameTok.is(tok::eod)) PP->Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); } /// getFileEntry - Return the FileEntry corresponding to this FileID. Like /// getFileID(), this only works for lexers with attached preprocessors. const FileEntry *PreprocessorLexer::getFileEntry() const { return PP->getSourceManager().getFileEntryForID(getFileID()); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/Targets.cpp
//===--- Targets.cpp - Implement -arch option and targets -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements construction of a TargetInfo object from a // target triple. // //===----------------------------------------------------------------------===// #include "clang/Basic/TargetInfo.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/MacroBuilder.h" #include "clang/Basic/TargetBuiltins.h" #include "clang/Basic/TargetOptions.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Triple.h" #include "llvm/MC/MCSectionMachO.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/TargetParser.h" #include <algorithm> #include <memory> using namespace clang; //===----------------------------------------------------------------------===// // Common code shared among targets. //===----------------------------------------------------------------------===// #if 0 // HLSL Change Starts - remove unsupported targets /// DefineStd - Define a macro name and standard variants. For example if /// MacroName is "unix", then this will define "__unix", "__unix__", and "unix" /// when in GNU mode. static void DefineStd(MacroBuilder &Builder, StringRef MacroName, const LangOptions &Opts) { assert(MacroName[0] != '_' && "Identifier should be in the user's namespace"); // If in GNU mode (e.g. -std=gnu99 but not -std=c99) define the raw identifier // in the user's namespace. if (Opts.GNUMode) Builder.defineMacro(MacroName); // Define __unix. Builder.defineMacro("__" + MacroName); // Define __unix__. Builder.defineMacro("__" + MacroName + "__"); } static void defineCPUMacros(MacroBuilder &Builder, StringRef CPUName, bool Tuning = true) { Builder.defineMacro("__" + CPUName); Builder.defineMacro("__" + CPUName + "__"); if (Tuning) Builder.defineMacro("__tune_" + CPUName + "__"); } #endif // HLSL Change Ends - remove unsupported targets //===----------------------------------------------------------------------===// // Defines specific to certain operating systems. //===----------------------------------------------------------------------===// namespace { template<typename TgtInfo> class OSTargetInfo : public TgtInfo { protected: virtual void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const=0; public: OSTargetInfo(const llvm::Triple &Triple) : TgtInfo(Triple) {} void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { TgtInfo::getTargetDefines(Opts, Builder); getOSDefines(Opts, TgtInfo::getTriple(), Builder); } }; } // end anonymous namespace #if 0 // HLSL Change Starts - remove unsupported targets static void getDarwinDefines(MacroBuilder &Builder, const LangOptions &Opts, const llvm::Triple &Triple, StringRef &PlatformName, VersionTuple &PlatformMinVersion) { Builder.defineMacro("__APPLE_CC__", "6000"); Builder.defineMacro("__APPLE__"); Builder.defineMacro("OBJC_NEW_PROPERTIES"); // AddressSanitizer doesn't play well with source fortification, which is on // by default on Darwin. if (Opts.Sanitize.has(SanitizerKind::Address)) Builder.defineMacro("_FORTIFY_SOURCE", "0"); if (!Opts.ObjCAutoRefCount) { // __weak is always defined, for use in blocks and with objc pointers. Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))"); // Darwin defines __strong even in C mode (just to nothing). if (Opts.getGC() != LangOptions::NonGC) Builder.defineMacro("__strong", "__attribute__((objc_gc(strong)))"); else Builder.defineMacro("__strong", ""); // __unsafe_unretained is defined to nothing in non-ARC mode. We even // allow this in C, since one might have block pointers in structs that // are used in pure C code and in Objective-C ARC. Builder.defineMacro("__unsafe_unretained", ""); } if (Opts.Static) Builder.defineMacro("__STATIC__"); else Builder.defineMacro("__DYNAMIC__"); if (Opts.POSIXThreads) Builder.defineMacro("_REENTRANT"); // Get the platform type and version number from the triple. unsigned Maj, Min, Rev; if (Triple.isMacOSX()) { Triple.getMacOSXVersion(Maj, Min, Rev); PlatformName = "macosx"; } else { Triple.getOSVersion(Maj, Min, Rev); PlatformName = llvm::Triple::getOSTypeName(Triple.getOS()); } // If -target arch-pc-win32-macho option specified, we're // generating code for Win32 ABI. No need to emit // __ENVIRONMENT_XX_OS_VERSION_MIN_REQUIRED__. if (PlatformName == "win32") { PlatformMinVersion = VersionTuple(Maj, Min, Rev); return; } // Set the appropriate OS version define. if (Triple.isiOS()) { assert(Maj < 10 && Min < 100 && Rev < 100 && "Invalid version!"); char Str[6]; Str[0] = '0' + Maj; Str[1] = '0' + (Min / 10); Str[2] = '0' + (Min % 10); Str[3] = '0' + (Rev / 10); Str[4] = '0' + (Rev % 10); Str[5] = '\0'; Builder.defineMacro("__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__", Str); } else if (Triple.isMacOSX()) { // Note that the Driver allows versions which aren't representable in the // define (because we only get a single digit for the minor and micro // revision numbers). So, we limit them to the maximum representable // version. assert(Maj < 100 && Min < 100 && Rev < 100 && "Invalid version!"); char Str[7]; if (Maj < 10 || (Maj == 10 && Min < 10)) { Str[0] = '0' + (Maj / 10); Str[1] = '0' + (Maj % 10); Str[2] = '0' + std::min(Min, 9U); Str[3] = '0' + std::min(Rev, 9U); Str[4] = '\0'; } else { // Handle versions > 10.9. Str[0] = '0' + (Maj / 10); Str[1] = '0' + (Maj % 10); Str[2] = '0' + (Min / 10); Str[3] = '0' + (Min % 10); Str[4] = '0' + (Rev / 10); Str[5] = '0' + (Rev % 10); Str[6] = '\0'; } Builder.defineMacro("__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__", Str); } // Tell users about the kernel if there is one. if (Triple.isOSDarwin()) Builder.defineMacro("__MACH__"); PlatformMinVersion = VersionTuple(Maj, Min, Rev); } namespace { // CloudABI Target template <typename Target> class CloudABITargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { Builder.defineMacro("__CloudABI__"); Builder.defineMacro("__ELF__"); // CloudABI uses ISO/IEC 10646:2012 for wchar_t, char16_t and char32_t. Builder.defineMacro("__STDC_ISO_10646__", "201206L"); Builder.defineMacro("__STDC_UTF_16__"); Builder.defineMacro("__STDC_UTF_32__"); } public: CloudABITargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; } }; template<typename Target> class DarwinTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { getDarwinDefines(Builder, Opts, Triple, this->PlatformName, this->PlatformMinVersion); } public: DarwinTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->TLSSupported = Triple.isMacOSX() && !Triple.isMacOSXVersionLT(10, 7); this->MCountName = "\01mcount"; } std::string isValidSectionSpecifier(StringRef SR) const override { // Let MCSectionMachO validate this. StringRef Segment, Section; unsigned TAA, StubSize; bool HasTAA; return llvm::MCSectionMachO::ParseSectionSpecifier(SR, Segment, Section, TAA, HasTAA, StubSize); } const char *getStaticInitSectionSpecifier() const override { // FIXME: We should return 0 when building kexts. return "__TEXT,__StaticInit,regular,pure_instructions"; } /// Darwin does not support protected visibility. Darwin's "default" /// is very similar to ELF's "protected"; Darwin requires a "weak" /// attribute on declarations that can be dynamically replaced. bool hasProtectedVisibility() const override { return false; } }; // DragonFlyBSD Target template<typename Target> class DragonFlyBSDTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // DragonFly defines; list based off of gcc output Builder.defineMacro("__DragonFly__"); Builder.defineMacro("__DragonFly_cc_version", "100001"); Builder.defineMacro("__ELF__"); Builder.defineMacro("__KPRINTF_ATTRIBUTE__"); Builder.defineMacro("__tune_i386__"); DefineStd(Builder, "unix", Opts); } public: DragonFlyBSDTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; switch (Triple.getArch()) { default: case llvm::Triple::x86: case llvm::Triple::x86_64: this->MCountName = ".mcount"; break; } } }; // FreeBSD Target template<typename Target> class FreeBSDTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // FreeBSD defines; list based off of gcc output unsigned Release = Triple.getOSMajorVersion(); if (Release == 0U) Release = 8; Builder.defineMacro("__FreeBSD__", Twine(Release)); Builder.defineMacro("__FreeBSD_cc_version", Twine(Release * 100000U + 1U)); Builder.defineMacro("__KPRINTF_ATTRIBUTE__"); DefineStd(Builder, "unix", Opts); Builder.defineMacro("__ELF__"); // On FreeBSD, wchar_t contains the number of the code point as // used by the character set of the locale. These character sets are // not necessarily a superset of ASCII. // // FIXME: This is wrong; the macro refers to the numerical values // of wchar_t *literals*, which are not locale-dependent. However, // FreeBSD systems apparently depend on us getting this wrong, and // setting this to 1 is conforming even if all the basic source // character literals have the same encoding as char and wchar_t. Builder.defineMacro("__STDC_MB_MIGHT_NEQ_WC__", "1"); } public: FreeBSDTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; switch (Triple.getArch()) { default: case llvm::Triple::x86: case llvm::Triple::x86_64: this->MCountName = ".mcount"; break; case llvm::Triple::mips: case llvm::Triple::mipsel: case llvm::Triple::ppc: case llvm::Triple::ppc64: case llvm::Triple::ppc64le: this->MCountName = "_mcount"; break; case llvm::Triple::arm: this->MCountName = "__mcount"; break; } } }; // GNU/kFreeBSD Target template<typename Target> class KFreeBSDTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // GNU/kFreeBSD defines; list based off of gcc output DefineStd(Builder, "unix", Opts); Builder.defineMacro("__FreeBSD_kernel__"); Builder.defineMacro("__GLIBC__"); Builder.defineMacro("__ELF__"); if (Opts.POSIXThreads) Builder.defineMacro("_REENTRANT"); if (Opts.CPlusPlus) Builder.defineMacro("_GNU_SOURCE"); } public: KFreeBSDTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; } }; // Minix Target template<typename Target> class MinixTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // Minix defines Builder.defineMacro("__minix", "3"); Builder.defineMacro("_EM_WSIZE", "4"); Builder.defineMacro("_EM_PSIZE", "4"); Builder.defineMacro("_EM_SSIZE", "2"); Builder.defineMacro("_EM_LSIZE", "4"); Builder.defineMacro("_EM_FSIZE", "4"); Builder.defineMacro("_EM_DSIZE", "8"); Builder.defineMacro("__ELF__"); DefineStd(Builder, "unix", Opts); } public: MinixTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; } }; // Linux target template<typename Target> class LinuxTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // Linux defines; list based off of gcc output DefineStd(Builder, "unix", Opts); DefineStd(Builder, "linux", Opts); Builder.defineMacro("__gnu_linux__"); Builder.defineMacro("__ELF__"); if (Triple.getEnvironment() == llvm::Triple::Android) { Builder.defineMacro("__ANDROID__", "1"); unsigned Maj, Min, Rev; Triple.getEnvironmentVersion(Maj, Min, Rev); this->PlatformName = "android"; this->PlatformMinVersion = VersionTuple(Maj, Min, Rev); } if (Opts.POSIXThreads) Builder.defineMacro("_REENTRANT"); if (Opts.CPlusPlus) Builder.defineMacro("_GNU_SOURCE"); } public: LinuxTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; this->WIntType = TargetInfo::UnsignedInt; switch (Triple.getArch()) { default: break; case llvm::Triple::ppc: case llvm::Triple::ppc64: case llvm::Triple::ppc64le: this->MCountName = "_mcount"; break; } } const char *getStaticInitSectionSpecifier() const override { return ".text.startup"; } }; // NetBSD Target template<typename Target> class NetBSDTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // NetBSD defines; list based off of gcc output Builder.defineMacro("__NetBSD__"); Builder.defineMacro("__unix__"); Builder.defineMacro("__ELF__"); if (Opts.POSIXThreads) Builder.defineMacro("_POSIX_THREADS"); switch (Triple.getArch()) { default: break; case llvm::Triple::arm: case llvm::Triple::armeb: case llvm::Triple::thumb: case llvm::Triple::thumbeb: Builder.defineMacro("__ARM_DWARF_EH__"); break; } } public: NetBSDTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; this->MCountName = "_mcount"; } }; // OpenBSD Target template<typename Target> class OpenBSDTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // OpenBSD defines; list based off of gcc output Builder.defineMacro("__OpenBSD__"); DefineStd(Builder, "unix", Opts); Builder.defineMacro("__ELF__"); if (Opts.POSIXThreads) Builder.defineMacro("_REENTRANT"); } public: OpenBSDTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; this->TLSSupported = false; switch (Triple.getArch()) { default: case llvm::Triple::x86: case llvm::Triple::x86_64: case llvm::Triple::arm: case llvm::Triple::sparc: this->MCountName = "__mcount"; break; case llvm::Triple::mips64: case llvm::Triple::mips64el: case llvm::Triple::ppc: case llvm::Triple::sparcv9: this->MCountName = "_mcount"; break; } } }; // Bitrig Target template<typename Target> class BitrigTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // Bitrig defines; list based off of gcc output Builder.defineMacro("__Bitrig__"); DefineStd(Builder, "unix", Opts); Builder.defineMacro("__ELF__"); if (Opts.POSIXThreads) Builder.defineMacro("_REENTRANT"); switch (Triple.getArch()) { default: break; case llvm::Triple::arm: case llvm::Triple::armeb: case llvm::Triple::thumb: case llvm::Triple::thumbeb: Builder.defineMacro("__ARM_DWARF_EH__"); break; } } public: BitrigTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; this->MCountName = "__mcount"; } }; // PSP Target template<typename Target> class PSPTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // PSP defines; list based on the output of the pspdev gcc toolchain. Builder.defineMacro("PSP"); Builder.defineMacro("_PSP"); Builder.defineMacro("__psp__"); Builder.defineMacro("__ELF__"); } public: PSPTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; } }; // PS3 PPU Target template<typename Target> class PS3PPUTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // PS3 PPU defines. Builder.defineMacro("__PPC__"); Builder.defineMacro("__PPU__"); Builder.defineMacro("__CELLOS_LV2__"); Builder.defineMacro("__ELF__"); Builder.defineMacro("__LP32__"); Builder.defineMacro("_ARCH_PPC64"); Builder.defineMacro("__powerpc64__"); } public: PS3PPUTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; this->LongWidth = this->LongAlign = 32; this->PointerWidth = this->PointerAlign = 32; this->IntMaxType = TargetInfo::SignedLongLong; this->Int64Type = TargetInfo::SignedLongLong; this->SizeType = TargetInfo::UnsignedInt; this->DescriptionString = "E-m:e-p:32:32-i64:64-n32:64"; } }; template <typename Target> class PS4OSTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { Builder.defineMacro("__FreeBSD__", "9"); Builder.defineMacro("__FreeBSD_cc_version", "900001"); Builder.defineMacro("__KPRINTF_ATTRIBUTE__"); DefineStd(Builder, "unix", Opts); Builder.defineMacro("__ELF__"); Builder.defineMacro("__PS4__"); } public: PS4OSTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->WCharType = this->UnsignedShort; // On PS4, TLS variable cannot be aligned to more than 32 bytes (256 bits). this->MaxTLSAlign = 256; this->UserLabelPrefix = ""; switch (Triple.getArch()) { default: case llvm::Triple::x86_64: this->MCountName = ".mcount"; break; } } }; // Solaris target template<typename Target> class SolarisTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { DefineStd(Builder, "sun", Opts); DefineStd(Builder, "unix", Opts); Builder.defineMacro("__ELF__"); Builder.defineMacro("__svr4__"); Builder.defineMacro("__SVR4"); // Solaris headers require _XOPEN_SOURCE to be set to 600 for C99 and // newer, but to 500 for everything else. feature_test.h has a check to // ensure that you are not using C99 with an old version of X/Open or C89 // with a new version. if (Opts.C99) Builder.defineMacro("_XOPEN_SOURCE", "600"); else Builder.defineMacro("_XOPEN_SOURCE", "500"); if (Opts.CPlusPlus) Builder.defineMacro("__C99FEATURES__"); Builder.defineMacro("_LARGEFILE_SOURCE"); Builder.defineMacro("_LARGEFILE64_SOURCE"); Builder.defineMacro("__EXTENSIONS__"); Builder.defineMacro("_REENTRANT"); } public: SolarisTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; this->WCharType = this->SignedInt; // FIXME: WIntType should be SignedLong } }; // Windows target template<typename Target> class WindowsTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { Builder.defineMacro("_WIN32"); } void getVisualStudioDefines(const LangOptions &Opts, MacroBuilder &Builder) const { if (Opts.CPlusPlus) { if (Opts.RTTIData) Builder.defineMacro("_CPPRTTI"); if (Opts.CXXExceptions) Builder.defineMacro("_CPPUNWIND"); } if (!Opts.CharIsSigned) Builder.defineMacro("_CHAR_UNSIGNED"); // FIXME: POSIXThreads isn't exactly the option this should be defined for, // but it works for now. if (Opts.POSIXThreads) Builder.defineMacro("_MT"); if (Opts.MSCompatibilityVersion) { Builder.defineMacro("_MSC_VER", Twine(Opts.MSCompatibilityVersion / 100000)); Builder.defineMacro("_MSC_FULL_VER", Twine(Opts.MSCompatibilityVersion)); // FIXME We cannot encode the revision information into 32-bits Builder.defineMacro("_MSC_BUILD", Twine(1)); if (Opts.CPlusPlus11 && Opts.isCompatibleWithMSVC(LangOptions::MSVC2015)) Builder.defineMacro("_HAS_CHAR16_T_LANGUAGE_SUPPORT", Twine(1)); } if (Opts.MicrosoftExt) { Builder.defineMacro("_MSC_EXTENSIONS"); if (Opts.CPlusPlus11) { Builder.defineMacro("_RVALUE_REFERENCES_V2_SUPPORTED"); Builder.defineMacro("_RVALUE_REFERENCES_SUPPORTED"); Builder.defineMacro("_NATIVE_NULLPTR_SUPPORTED"); } } Builder.defineMacro("_INTEGRAL_MAX_BITS", "64"); } public: WindowsTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {} }; template <typename Target> class NaClTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { if (Opts.POSIXThreads) Builder.defineMacro("_REENTRANT"); if (Opts.CPlusPlus) Builder.defineMacro("_GNU_SOURCE"); DefineStd(Builder, "unix", Opts); Builder.defineMacro("__ELF__"); Builder.defineMacro("__native_client__"); } public: NaClTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; this->LongAlign = 32; this->LongWidth = 32; this->PointerAlign = 32; this->PointerWidth = 32; this->IntMaxType = TargetInfo::SignedLongLong; this->Int64Type = TargetInfo::SignedLongLong; this->DoubleAlign = 64; this->LongDoubleWidth = 64; this->LongDoubleAlign = 64; this->LongLongWidth = 64; this->LongLongAlign = 64; this->SizeType = TargetInfo::UnsignedInt; this->PtrDiffType = TargetInfo::SignedInt; this->IntPtrType = TargetInfo::SignedInt; // RegParmMax is inherited from the underlying architecture this->LongDoubleFormat = &llvm::APFloat::IEEEdouble; if (Triple.getArch() == llvm::Triple::arm) { // Handled in ARM's setABI(). } else if (Triple.getArch() == llvm::Triple::x86) { this->DescriptionString = "e-m:e-p:32:32-i64:64-n8:16:32-S128"; } else if (Triple.getArch() == llvm::Triple::x86_64) { this->DescriptionString = "e-m:e-p:32:32-i64:64-n8:16:32:64-S128"; } else if (Triple.getArch() == llvm::Triple::mipsel) { // Handled on mips' setDescriptionString. } else { assert(Triple.getArch() == llvm::Triple::le32); this->DescriptionString = "e-p:32:32-i64:64"; } } }; //===----------------------------------------------------------------------===// // Specific target implementations. //===----------------------------------------------------------------------===// // PPC abstract base class class PPCTargetInfo : public TargetInfo { static const Builtin::Info BuiltinInfo[]; static const char * const GCCRegNames[]; static const TargetInfo::GCCRegAlias GCCRegAliases[]; std::string CPU; // Target cpu features. bool HasVSX; bool HasP8Vector; bool HasP8Crypto; bool HasDirectMove; bool HasQPX; bool HasHTM; bool HasBPERMD; bool HasExtDiv; protected: std::string ABI; public: PPCTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple), HasVSX(false), HasP8Vector(false), HasP8Crypto(false), HasDirectMove(false), HasQPX(false), HasHTM(false), HasBPERMD(false), HasExtDiv(false) { BigEndian = (Triple.getArch() != llvm::Triple::ppc64le); SimdDefaultAlign = 128; LongDoubleWidth = LongDoubleAlign = 128; LongDoubleFormat = &llvm::APFloat::PPCDoubleDouble; } /// \brief Flags for architecture specific defines. typedef enum { ArchDefineNone = 0, ArchDefineName = 1 << 0, // <name> is substituted for arch name. ArchDefinePpcgr = 1 << 1, ArchDefinePpcsq = 1 << 2, ArchDefine440 = 1 << 3, ArchDefine603 = 1 << 4, ArchDefine604 = 1 << 5, ArchDefinePwr4 = 1 << 6, ArchDefinePwr5 = 1 << 7, ArchDefinePwr5x = 1 << 8, ArchDefinePwr6 = 1 << 9, ArchDefinePwr6x = 1 << 10, ArchDefinePwr7 = 1 << 11, ArchDefinePwr8 = 1 << 12, ArchDefineA2 = 1 << 13, ArchDefineA2q = 1 << 14 } ArchDefineTypes; // Note: GCC recognizes the following additional cpus: // 401, 403, 405, 405fp, 440fp, 464, 464fp, 476, 476fp, 505, 740, 801, // 821, 823, 8540, 8548, e300c2, e300c3, e500mc64, e6500, 860, cell, // titan, rs64. bool setCPU(const std::string &Name) override { bool CPUKnown = llvm::StringSwitch<bool>(Name) .Case("generic", true) .Case("440", true) .Case("450", true) .Case("601", true) .Case("602", true) .Case("603", true) .Case("603e", true) .Case("603ev", true) .Case("604", true) .Case("604e", true) .Case("620", true) .Case("630", true) .Case("g3", true) .Case("7400", true) .Case("g4", true) .Case("7450", true) .Case("g4+", true) .Case("750", true) .Case("970", true) .Case("g5", true) .Case("a2", true) .Case("a2q", true) .Case("e500mc", true) .Case("e5500", true) .Case("power3", true) .Case("pwr3", true) .Case("power4", true) .Case("pwr4", true) .Case("power5", true) .Case("pwr5", true) .Case("power5x", true) .Case("pwr5x", true) .Case("power6", true) .Case("pwr6", true) .Case("power6x", true) .Case("pwr6x", true) .Case("power7", true) .Case("pwr7", true) .Case("power8", true) .Case("pwr8", true) .Case("powerpc", true) .Case("ppc", true) .Case("powerpc64", true) .Case("ppc64", true) .Case("powerpc64le", true) .Case("ppc64le", true) .Default(false); if (CPUKnown) CPU = Name; return CPUKnown; } StringRef getABI() const override { return ABI; } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::PPC::LastTSBuiltin-Builtin::FirstTSBuiltin; } bool isCLZForZeroUndef() const override { return false; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override; void getDefaultFeatures(llvm::StringMap<bool> &Features) const override; bool handleTargetFeatures(std::vector<std::string> &Features, DiagnosticsEngine &Diags) override; bool hasFeature(StringRef Feature) const override; void setFeatureEnabled(llvm::StringMap<bool> &Features, StringRef Name, bool Enabled) const override; void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override; void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override; bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const override { switch (*Name) { default: return false; case 'O': // Zero break; case 'b': // Base register case 'f': // Floating point register Info.setAllowsRegister(); break; // FIXME: The following are added to allow parsing. // I just took a guess at what the actions should be. // Also, is more specific checking needed? I.e. specific registers? case 'd': // Floating point register (containing 64-bit value) case 'v': // Altivec vector register Info.setAllowsRegister(); break; case 'w': switch (Name[1]) { case 'd':// VSX vector register to hold vector double data case 'f':// VSX vector register to hold vector float data case 's':// VSX vector register to hold scalar float data case 'a':// Any VSX register case 'c':// An individual CR bit break; default: return false; } Info.setAllowsRegister(); Name++; // Skip over 'w'. break; case 'h': // `MQ', `CTR', or `LINK' register case 'q': // `MQ' register case 'c': // `CTR' register case 'l': // `LINK' register case 'x': // `CR' register (condition register) number 0 case 'y': // `CR' register (condition register) case 'z': // `XER[CA]' carry bit (part of the XER register) Info.setAllowsRegister(); break; case 'I': // Signed 16-bit constant case 'J': // Unsigned 16-bit constant shifted left 16 bits // (use `L' instead for SImode constants) case 'K': // Unsigned 16-bit constant case 'L': // Signed 16-bit constant shifted left 16 bits case 'M': // Constant larger than 31 case 'N': // Exact power of 2 case 'P': // Constant whose negation is a signed 16-bit constant case 'G': // Floating point constant that can be loaded into a // register with one instruction per word case 'H': // Integer/Floating point constant that can be loaded // into a register using three instructions break; case 'm': // Memory operand. Note that on PowerPC targets, m can // include addresses that update the base register. It // is therefore only safe to use `m' in an asm statement // if that asm statement accesses the operand exactly once. // The asm statement must also use `%U<opno>' as a // placeholder for the "update" flag in the corresponding // load or store instruction. For example: // asm ("st%U0 %1,%0" : "=m" (mem) : "r" (val)); // is correct but: // asm ("st %1,%0" : "=m" (mem) : "r" (val)); // is not. Use es rather than m if you don't want the base // register to be updated. case 'e': if (Name[1] != 's') return false; // es: A "stable" memory operand; that is, one which does not // include any automodification of the base register. Unlike // `m', this constraint can be used in asm statements that // might access the operand several times, or that might not // access it at all. Info.setAllowsMemory(); Name++; // Skip over 'e'. break; case 'Q': // Memory operand that is an offset from a register (it is // usually better to use `m' or `es' in asm statements) case 'Z': // Memory operand that is an indexed or indirect from a // register (it is usually better to use `m' or `es' in // asm statements) Info.setAllowsMemory(); Info.setAllowsRegister(); break; case 'R': // AIX TOC entry case 'a': // Address operand that is an indexed or indirect from a // register (`p' is preferable for asm statements) case 'S': // Constant suitable as a 64-bit mask operand case 'T': // Constant suitable as a 32-bit mask operand case 'U': // System V Release 4 small data area reference case 't': // AND masks that can be performed by two rldic{l, r} // instructions case 'W': // Vector constant that does not require memory case 'j': // Vector constant that is all zeros. break; // End FIXME. } return true; } std::string convertConstraint(const char *&Constraint) const override { std::string R; switch (*Constraint) { case 'e': case 'w': // Two-character constraint; add "^" hint for later parsing. R = std::string("^") + std::string(Constraint, 2); Constraint++; break; default: return TargetInfo::convertConstraint(Constraint); } return R; } const char *getClobbers() const override { return ""; } int getEHDataRegisterNumber(unsigned RegNo) const override { if (RegNo == 0) return 3; if (RegNo == 1) return 4; return -1; } bool hasSjLjLowering() const override { return true; } bool useFloat128ManglingForLongDouble() const override { return LongDoubleWidth == 128 && LongDoubleFormat == &llvm::APFloat::PPCDoubleDouble && getTriple().isOSBinFormatELF(); } }; const Builtin::Info PPCTargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER,\ ALL_LANGUAGES }, #include "clang/Basic/BuiltinsPPC.def" }; /// handleTargetFeatures - Perform initialization based on the user /// configured set of features. bool PPCTargetInfo::handleTargetFeatures(std::vector<std::string> &Features, DiagnosticsEngine &Diags) { for (unsigned i = 0, e = Features.size(); i !=e; ++i) { // Ignore disabled features. if (Features[i][0] == '-') continue; StringRef Feature = StringRef(Features[i]).substr(1); if (Feature == "vsx") { HasVSX = true; continue; } if (Feature == "bpermd") { HasBPERMD = true; continue; } if (Feature == "extdiv") { HasExtDiv = true; continue; } if (Feature == "power8-vector") { HasP8Vector = true; continue; } if (Feature == "crypto") { HasP8Crypto = true; continue; } if (Feature == "direct-move") { HasDirectMove = true; continue; } if (Feature == "qpx") { HasQPX = true; continue; } if (Feature == "htm") { HasHTM = true; continue; } // TODO: Finish this list and add an assert that we've handled them // all. } if (!HasVSX && (HasP8Vector || HasDirectMove)) { if (HasP8Vector) Diags.Report(diag::err_opt_not_valid_with_opt) << "-mpower8-vector" << "-mno-vsx"; else if (HasDirectMove) Diags.Report(diag::err_opt_not_valid_with_opt) << "-mdirect-move" << "-mno-vsx"; return false; } return true; } /// PPCTargetInfo::getTargetDefines - Return a set of the PowerPC-specific /// #defines that are not tied to a specific subtarget. void PPCTargetInfo::getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const { // Target identification. Builder.defineMacro("__ppc__"); Builder.defineMacro("__PPC__"); Builder.defineMacro("_ARCH_PPC"); Builder.defineMacro("__powerpc__"); Builder.defineMacro("__POWERPC__"); if (PointerWidth == 64) { Builder.defineMacro("_ARCH_PPC64"); Builder.defineMacro("__powerpc64__"); Builder.defineMacro("__ppc64__"); Builder.defineMacro("__PPC64__"); } // Target properties. if (getTriple().getArch() == llvm::Triple::ppc64le) { Builder.defineMacro("_LITTLE_ENDIAN"); } else { if (getTriple().getOS() != llvm::Triple::NetBSD && getTriple().getOS() != llvm::Triple::OpenBSD) Builder.defineMacro("_BIG_ENDIAN"); } // ABI options. if (ABI == "elfv1" || ABI == "elfv1-qpx") Builder.defineMacro("_CALL_ELF", "1"); if (ABI == "elfv2") Builder.defineMacro("_CALL_ELF", "2"); // Subtarget options. Builder.defineMacro("__NATURAL_ALIGNMENT__"); Builder.defineMacro("__REGISTER_PREFIX__", ""); // FIXME: Should be controlled by command line option. if (LongDoubleWidth == 128) Builder.defineMacro("__LONG_DOUBLE_128__"); if (Opts.AltiVec) { Builder.defineMacro("__VEC__", "10206"); Builder.defineMacro("__ALTIVEC__"); } // CPU identification. ArchDefineTypes defs = (ArchDefineTypes)llvm::StringSwitch<int>(CPU) .Case("440", ArchDefineName) .Case("450", ArchDefineName | ArchDefine440) .Case("601", ArchDefineName) .Case("602", ArchDefineName | ArchDefinePpcgr) .Case("603", ArchDefineName | ArchDefinePpcgr) .Case("603e", ArchDefineName | ArchDefine603 | ArchDefinePpcgr) .Case("603ev", ArchDefineName | ArchDefine603 | ArchDefinePpcgr) .Case("604", ArchDefineName | ArchDefinePpcgr) .Case("604e", ArchDefineName | ArchDefine604 | ArchDefinePpcgr) .Case("620", ArchDefineName | ArchDefinePpcgr) .Case("630", ArchDefineName | ArchDefinePpcgr) .Case("7400", ArchDefineName | ArchDefinePpcgr) .Case("7450", ArchDefineName | ArchDefinePpcgr) .Case("750", ArchDefineName | ArchDefinePpcgr) .Case("970", ArchDefineName | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("a2", ArchDefineA2) .Case("a2q", ArchDefineName | ArchDefineA2 | ArchDefineA2q) .Case("pwr3", ArchDefinePpcgr) .Case("pwr4", ArchDefineName | ArchDefinePpcgr | ArchDefinePpcsq) .Case("pwr5", ArchDefineName | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("pwr5x", ArchDefineName | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("pwr6", ArchDefineName | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("pwr6x", ArchDefineName | ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("pwr7", ArchDefineName | ArchDefinePwr6x | ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("pwr8", ArchDefineName | ArchDefinePwr7 | ArchDefinePwr6x | ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("power3", ArchDefinePpcgr) .Case("power4", ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("power5", ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("power5x", ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("power6", ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("power6x", ArchDefinePwr6x | ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("power7", ArchDefinePwr7 | ArchDefinePwr6x | ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Case("power8", ArchDefinePwr8 | ArchDefinePwr7 | ArchDefinePwr6x | ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq) .Default(ArchDefineNone); if (defs & ArchDefineName) Builder.defineMacro(Twine("_ARCH_", StringRef(CPU).upper())); if (defs & ArchDefinePpcgr) Builder.defineMacro("_ARCH_PPCGR"); if (defs & ArchDefinePpcsq) Builder.defineMacro("_ARCH_PPCSQ"); if (defs & ArchDefine440) Builder.defineMacro("_ARCH_440"); if (defs & ArchDefine603) Builder.defineMacro("_ARCH_603"); if (defs & ArchDefine604) Builder.defineMacro("_ARCH_604"); if (defs & ArchDefinePwr4) Builder.defineMacro("_ARCH_PWR4"); if (defs & ArchDefinePwr5) Builder.defineMacro("_ARCH_PWR5"); if (defs & ArchDefinePwr5x) Builder.defineMacro("_ARCH_PWR5X"); if (defs & ArchDefinePwr6) Builder.defineMacro("_ARCH_PWR6"); if (defs & ArchDefinePwr6x) Builder.defineMacro("_ARCH_PWR6X"); if (defs & ArchDefinePwr7) Builder.defineMacro("_ARCH_PWR7"); if (defs & ArchDefinePwr8) Builder.defineMacro("_ARCH_PWR8"); if (defs & ArchDefineA2) Builder.defineMacro("_ARCH_A2"); if (defs & ArchDefineA2q) { Builder.defineMacro("_ARCH_A2Q"); Builder.defineMacro("_ARCH_QP"); } if (getTriple().getVendor() == llvm::Triple::BGQ) { Builder.defineMacro("__bg__"); Builder.defineMacro("__THW_BLUEGENE__"); Builder.defineMacro("__bgq__"); Builder.defineMacro("__TOS_BGQ__"); } if (HasVSX) Builder.defineMacro("__VSX__"); if (HasP8Vector) Builder.defineMacro("__POWER8_VECTOR__"); if (HasP8Crypto) Builder.defineMacro("__CRYPTO__"); if (HasHTM) Builder.defineMacro("__HTM__"); if (getTriple().getArch() == llvm::Triple::ppc64le || (defs & ArchDefinePwr8) || (CPU == "pwr8")) { Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4"); if (PointerWidth == 64) Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8"); } // FIXME: The following are not yet generated here by Clang, but are // generated by GCC: // // _SOFT_FLOAT_ // __RECIP_PRECISION__ // __APPLE_ALTIVEC__ // __RECIP__ // __RECIPF__ // __RSQRTE__ // __RSQRTEF__ // _SOFT_DOUBLE_ // __NO_LWSYNC__ // __HAVE_BSWAP__ // __LONGDOUBLE128 // __CMODEL_MEDIUM__ // __CMODEL_LARGE__ // _CALL_SYSV // _CALL_DARWIN // __NO_FPRS__ } void PPCTargetInfo::getDefaultFeatures(llvm::StringMap<bool> &Features) const { Features["altivec"] = llvm::StringSwitch<bool>(CPU) .Case("7400", true) .Case("g4", true) .Case("7450", true) .Case("g4+", true) .Case("970", true) .Case("g5", true) .Case("pwr6", true) .Case("pwr7", true) .Case("pwr8", true) .Case("ppc64", true) .Case("ppc64le", true) .Default(false); Features["qpx"] = (CPU == "a2q"); Features["crypto"] = llvm::StringSwitch<bool>(CPU) .Case("ppc64le", true) .Case("pwr8", true) .Default(false); Features["power8-vector"] = llvm::StringSwitch<bool>(CPU) .Case("ppc64le", true) .Case("pwr8", true) .Default(false); Features["bpermd"] = llvm::StringSwitch<bool>(CPU) .Case("ppc64le", true) .Case("pwr8", true) .Case("pwr7", true) .Default(false); Features["extdiv"] = llvm::StringSwitch<bool>(CPU) .Case("ppc64le", true) .Case("pwr8", true) .Case("pwr7", true) .Default(false); Features["direct-move"] = llvm::StringSwitch<bool>(CPU) .Case("ppc64le", true) .Case("pwr8", true) .Default(false); Features["vsx"] = llvm::StringSwitch<bool>(CPU) .Case("ppc64le", true) .Case("pwr8", true) .Case("pwr7", true) .Default(false); } bool PPCTargetInfo::hasFeature(StringRef Feature) const { return llvm::StringSwitch<bool>(Feature) .Case("powerpc", true) .Case("vsx", HasVSX) .Case("power8-vector", HasP8Vector) .Case("crypto", HasP8Crypto) .Case("direct-move", HasDirectMove) .Case("qpx", HasQPX) .Case("htm", HasHTM) .Case("bpermd", HasBPERMD) .Case("extdiv", HasExtDiv) .Default(false); } /* There is no clear way for the target to know which of the features in the final feature vector came from defaults and which are actually specified by the user. To that end, we use the fact that this function is not called on default features - only user specified ones. By the first time this function is called, the default features are populated. We then keep track of the features that the user specified so that we can ensure we do not override a user's request (only defaults). For example: -mcpu=pwr8 -mno-vsx (should disable vsx and everything that depends on it) -mcpu=pwr8 -mdirect-move -mno-vsx (should actually be diagnosed) NOTE: Do not call this from PPCTargetInfo::getDefaultFeatures */ void PPCTargetInfo::setFeatureEnabled(llvm::StringMap<bool> &Features, StringRef Name, bool Enabled) const { static llvm::StringMap<bool> ExplicitFeatures; ExplicitFeatures[Name] = Enabled; // At this point, -mno-vsx turns off the dependent features but we respect // the user's requests. if (!Enabled && Name == "vsx") { Features["direct-move"] = ExplicitFeatures["direct-move"]; Features["power8-vector"] = ExplicitFeatures["power8-vector"]; } if ((Enabled && Name == "power8-vector") || (Enabled && Name == "direct-move")) { if (ExplicitFeatures.find("vsx") == ExplicitFeatures.end()) { Features["vsx"] = true; } } Features[Name] = Enabled; } const char * const PPCTargetInfo::GCCRegNames[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15", "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23", "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31", "mq", "lr", "ctr", "ap", "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "xer", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31", "vrsave", "vscr", "spe_acc", "spefscr", "sfp" }; void PPCTargetInfo::getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } const TargetInfo::GCCRegAlias PPCTargetInfo::GCCRegAliases[] = { // While some of these aliases do map to different registers // they still share the same register name. { { "0" }, "r0" }, { { "1"}, "r1" }, { { "2" }, "r2" }, { { "3" }, "r3" }, { { "4" }, "r4" }, { { "5" }, "r5" }, { { "6" }, "r6" }, { { "7" }, "r7" }, { { "8" }, "r8" }, { { "9" }, "r9" }, { { "10" }, "r10" }, { { "11" }, "r11" }, { { "12" }, "r12" }, { { "13" }, "r13" }, { { "14" }, "r14" }, { { "15" }, "r15" }, { { "16" }, "r16" }, { { "17" }, "r17" }, { { "18" }, "r18" }, { { "19" }, "r19" }, { { "20" }, "r20" }, { { "21" }, "r21" }, { { "22" }, "r22" }, { { "23" }, "r23" }, { { "24" }, "r24" }, { { "25" }, "r25" }, { { "26" }, "r26" }, { { "27" }, "r27" }, { { "28" }, "r28" }, { { "29" }, "r29" }, { { "30" }, "r30" }, { { "31" }, "r31" }, { { "fr0" }, "f0" }, { { "fr1" }, "f1" }, { { "fr2" }, "f2" }, { { "fr3" }, "f3" }, { { "fr4" }, "f4" }, { { "fr5" }, "f5" }, { { "fr6" }, "f6" }, { { "fr7" }, "f7" }, { { "fr8" }, "f8" }, { { "fr9" }, "f9" }, { { "fr10" }, "f10" }, { { "fr11" }, "f11" }, { { "fr12" }, "f12" }, { { "fr13" }, "f13" }, { { "fr14" }, "f14" }, { { "fr15" }, "f15" }, { { "fr16" }, "f16" }, { { "fr17" }, "f17" }, { { "fr18" }, "f18" }, { { "fr19" }, "f19" }, { { "fr20" }, "f20" }, { { "fr21" }, "f21" }, { { "fr22" }, "f22" }, { { "fr23" }, "f23" }, { { "fr24" }, "f24" }, { { "fr25" }, "f25" }, { { "fr26" }, "f26" }, { { "fr27" }, "f27" }, { { "fr28" }, "f28" }, { { "fr29" }, "f29" }, { { "fr30" }, "f30" }, { { "fr31" }, "f31" }, { { "cc" }, "cr0" }, }; void PPCTargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const { Aliases = GCCRegAliases; NumAliases = llvm::array_lengthof(GCCRegAliases); } class PPC32TargetInfo : public PPCTargetInfo { public: PPC32TargetInfo(const llvm::Triple &Triple) : PPCTargetInfo(Triple) { DescriptionString = "E-m:e-p:32:32-i64:64-n32"; switch (getTriple().getOS()) { case llvm::Triple::Linux: case llvm::Triple::FreeBSD: case llvm::Triple::NetBSD: SizeType = UnsignedInt; PtrDiffType = SignedInt; IntPtrType = SignedInt; break; default: break; } if (getTriple().getOS() == llvm::Triple::FreeBSD) { LongDoubleWidth = LongDoubleAlign = 64; LongDoubleFormat = &llvm::APFloat::IEEEdouble; } // PPC32 supports atomics up to 4 bytes. MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32; } BuiltinVaListKind getBuiltinVaListKind() const override { // This is the ELF definition, and is overridden by the Darwin sub-target return TargetInfo::PowerABIBuiltinVaList; } }; // Note: ABI differences may eventually require us to have a separate // TargetInfo for little endian. class PPC64TargetInfo : public PPCTargetInfo { public: PPC64TargetInfo(const llvm::Triple &Triple) : PPCTargetInfo(Triple) { LongWidth = LongAlign = PointerWidth = PointerAlign = 64; IntMaxType = SignedLong; Int64Type = SignedLong; if ((Triple.getArch() == llvm::Triple::ppc64le)) { DescriptionString = "e-m:e-i64:64-n32:64"; ABI = "elfv2"; } else { DescriptionString = "E-m:e-i64:64-n32:64"; ABI = "elfv1"; } switch (getTriple().getOS()) { case llvm::Triple::FreeBSD: LongDoubleWidth = LongDoubleAlign = 64; LongDoubleFormat = &llvm::APFloat::IEEEdouble; break; case llvm::Triple::NetBSD: IntMaxType = SignedLongLong; Int64Type = SignedLongLong; break; default: break; } // PPC64 supports atomics up to 8 bytes. MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::CharPtrBuiltinVaList; } // PPC64 Linux-specific ABI options. bool setABI(const std::string &Name) override { if (Name == "elfv1" || Name == "elfv1-qpx" || Name == "elfv2") { ABI = Name; return true; } return false; } }; class DarwinPPC32TargetInfo : public DarwinTargetInfo<PPC32TargetInfo> { public: DarwinPPC32TargetInfo(const llvm::Triple &Triple) : DarwinTargetInfo<PPC32TargetInfo>(Triple) { HasAlignMac68kSupport = true; BoolWidth = BoolAlign = 32; //XXX support -mone-byte-bool? PtrDiffType = SignedInt; // for http://llvm.org/bugs/show_bug.cgi?id=15726 LongLongAlign = 32; SuitableAlign = 128; DescriptionString = "E-m:o-p:32:32-f64:32:64-n32"; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::CharPtrBuiltinVaList; } }; class DarwinPPC64TargetInfo : public DarwinTargetInfo<PPC64TargetInfo> { public: DarwinPPC64TargetInfo(const llvm::Triple &Triple) : DarwinTargetInfo<PPC64TargetInfo>(Triple) { HasAlignMac68kSupport = true; SuitableAlign = 128; DescriptionString = "E-m:o-i64:64-n32:64"; } }; static const unsigned NVPTXAddrSpaceMap[] = { 1, // opencl_global 3, // opencl_local 4, // opencl_constant // FIXME: generic has to be added to the target 0, // opencl_generic 1, // cuda_device 4, // cuda_constant 3, // cuda_shared }; class NVPTXTargetInfo : public TargetInfo { static const char * const GCCRegNames[]; static const Builtin::Info BuiltinInfo[]; // The GPU profiles supported by the NVPTX backend enum GPUKind { GK_NONE, GK_SM20, GK_SM21, GK_SM30, GK_SM35, GK_SM37, } GPU; public: NVPTXTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { BigEndian = false; TLSSupported = false; LongWidth = LongAlign = 64; AddrSpaceMap = &NVPTXAddrSpaceMap; UseAddrSpaceMapMangling = true; // Define available target features // These must be defined in sorted order! NoAsmVariants = true; // Set the default GPU to sm20 GPU = GK_SM20; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { Builder.defineMacro("__PTX__"); Builder.defineMacro("__NVPTX__"); if (Opts.CUDAIsDevice) { // Set __CUDA_ARCH__ for the GPU specified. std::string CUDAArchCode; switch (GPU) { case GK_SM20: CUDAArchCode = "200"; break; case GK_SM21: CUDAArchCode = "210"; break; case GK_SM30: CUDAArchCode = "300"; break; case GK_SM35: CUDAArchCode = "350"; break; case GK_SM37: CUDAArchCode = "370"; break; default: llvm_unreachable("Unhandled target CPU"); } Builder.defineMacro("__CUDA_ARCH__", CUDAArchCode); } } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::NVPTX::LastTSBuiltin-Builtin::FirstTSBuiltin; } bool hasFeature(StringRef Feature) const override { return Feature == "ptx" || Feature == "nvptx"; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override; void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override { // No aliases. Aliases = nullptr; NumAliases = 0; } bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const override { switch (*Name) { default: return false; case 'c': case 'h': case 'r': case 'l': case 'f': case 'd': Info.setAllowsRegister(); return true; } } const char *getClobbers() const override { // FIXME: Is this really right? return ""; } BuiltinVaListKind getBuiltinVaListKind() const override { // FIXME: implement return TargetInfo::CharPtrBuiltinVaList; } bool setCPU(const std::string &Name) override { GPU = llvm::StringSwitch<GPUKind>(Name) .Case("sm_20", GK_SM20) .Case("sm_21", GK_SM21) .Case("sm_30", GK_SM30) .Case("sm_35", GK_SM35) .Case("sm_37", GK_SM37) .Default(GK_NONE); return GPU != GK_NONE; } }; const Builtin::Info NVPTXTargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER,\ ALL_LANGUAGES }, #include "clang/Basic/BuiltinsNVPTX.def" }; const char * const NVPTXTargetInfo::GCCRegNames[] = { "r0" }; void NVPTXTargetInfo::getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } class NVPTX32TargetInfo : public NVPTXTargetInfo { public: NVPTX32TargetInfo(const llvm::Triple &Triple) : NVPTXTargetInfo(Triple) { PointerWidth = PointerAlign = 32; SizeType = TargetInfo::UnsignedInt; PtrDiffType = TargetInfo::SignedInt; IntPtrType = TargetInfo::SignedInt; DescriptionString = "e-p:32:32-i64:64-v16:16-v32:32-n16:32:64"; } }; class NVPTX64TargetInfo : public NVPTXTargetInfo { public: NVPTX64TargetInfo(const llvm::Triple &Triple) : NVPTXTargetInfo(Triple) { PointerWidth = PointerAlign = 64; SizeType = TargetInfo::UnsignedLong; PtrDiffType = TargetInfo::SignedLong; IntPtrType = TargetInfo::SignedLong; DescriptionString = "e-i64:64-v16:16-v32:32-n16:32:64"; } }; static const unsigned AMDGPUAddrSpaceMap[] = { 1, // opencl_global 3, // opencl_local 2, // opencl_constant 4, // opencl_generic 1, // cuda_device 2, // cuda_constant 3 // cuda_shared }; // If you edit the description strings, make sure you update // getPointerWidthV(). static const char *DescriptionStringR600 = "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"; static const char *DescriptionStringR600DoubleOps = "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"; static const char *DescriptionStringSI = "e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32-p24:64:64" "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128" "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"; class AMDGPUTargetInfo : public TargetInfo { static const Builtin::Info BuiltinInfo[]; static const char * const GCCRegNames[]; /// \brief The GPU profiles supported by the AMDGPU target. enum GPUKind { GK_NONE, GK_R600, GK_R600_DOUBLE_OPS, GK_R700, GK_R700_DOUBLE_OPS, GK_EVERGREEN, GK_EVERGREEN_DOUBLE_OPS, GK_NORTHERN_ISLANDS, GK_CAYMAN, GK_SOUTHERN_ISLANDS, GK_SEA_ISLANDS, GK_VOLCANIC_ISLANDS } GPU; bool hasFP64:1; bool hasFMAF:1; bool hasLDEXPF:1; public: AMDGPUTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { if (Triple.getArch() == llvm::Triple::amdgcn) { DescriptionString = DescriptionStringSI; GPU = GK_SOUTHERN_ISLANDS; hasFP64 = true; hasFMAF = true; hasLDEXPF = true; } else { DescriptionString = DescriptionStringR600; GPU = GK_R600; hasFP64 = false; hasFMAF = false; hasLDEXPF = false; } AddrSpaceMap = &AMDGPUAddrSpaceMap; UseAddrSpaceMapMangling = true; } uint64_t getPointerWidthV(unsigned AddrSpace) const override { if (GPU <= GK_CAYMAN) return 32; switch(AddrSpace) { default: return 64; case 0: case 3: case 5: return 32; } } const char * getClobbers() const override { return ""; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override; void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override { Aliases = nullptr; NumAliases = 0; } bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override { return true; } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::AMDGPU::LastTSBuiltin - Builtin::FirstTSBuiltin; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { Builder.defineMacro("__R600__"); if (hasFMAF) Builder.defineMacro("__HAS_FMAF__"); if (hasLDEXPF) Builder.defineMacro("__HAS_LDEXPF__"); if (hasFP64 && Opts.OpenCL) { Builder.defineMacro("cl_khr_fp64"); } } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::CharPtrBuiltinVaList; } bool setCPU(const std::string &Name) override { GPU = llvm::StringSwitch<GPUKind>(Name) .Case("r600" , GK_R600) .Case("rv610", GK_R600) .Case("rv620", GK_R600) .Case("rv630", GK_R600) .Case("rv635", GK_R600) .Case("rs780", GK_R600) .Case("rs880", GK_R600) .Case("rv670", GK_R600_DOUBLE_OPS) .Case("rv710", GK_R700) .Case("rv730", GK_R700) .Case("rv740", GK_R700_DOUBLE_OPS) .Case("rv770", GK_R700_DOUBLE_OPS) .Case("palm", GK_EVERGREEN) .Case("cedar", GK_EVERGREEN) .Case("sumo", GK_EVERGREEN) .Case("sumo2", GK_EVERGREEN) .Case("redwood", GK_EVERGREEN) .Case("juniper", GK_EVERGREEN) .Case("hemlock", GK_EVERGREEN_DOUBLE_OPS) .Case("cypress", GK_EVERGREEN_DOUBLE_OPS) .Case("barts", GK_NORTHERN_ISLANDS) .Case("turks", GK_NORTHERN_ISLANDS) .Case("caicos", GK_NORTHERN_ISLANDS) .Case("cayman", GK_CAYMAN) .Case("aruba", GK_CAYMAN) .Case("tahiti", GK_SOUTHERN_ISLANDS) .Case("pitcairn", GK_SOUTHERN_ISLANDS) .Case("verde", GK_SOUTHERN_ISLANDS) .Case("oland", GK_SOUTHERN_ISLANDS) .Case("hainan", GK_SOUTHERN_ISLANDS) .Case("bonaire", GK_SEA_ISLANDS) .Case("kabini", GK_SEA_ISLANDS) .Case("kaveri", GK_SEA_ISLANDS) .Case("hawaii", GK_SEA_ISLANDS) .Case("mullins", GK_SEA_ISLANDS) .Case("tonga", GK_VOLCANIC_ISLANDS) .Case("iceland", GK_VOLCANIC_ISLANDS) .Case("carrizo", GK_VOLCANIC_ISLANDS) .Default(GK_NONE); if (GPU == GK_NONE) { return false; } // Set the correct data layout switch (GPU) { case GK_NONE: case GK_R600: case GK_R700: case GK_EVERGREEN: case GK_NORTHERN_ISLANDS: DescriptionString = DescriptionStringR600; hasFP64 = false; hasFMAF = false; hasLDEXPF = false; break; case GK_R600_DOUBLE_OPS: case GK_R700_DOUBLE_OPS: case GK_EVERGREEN_DOUBLE_OPS: case GK_CAYMAN: DescriptionString = DescriptionStringR600DoubleOps; hasFP64 = true; hasFMAF = true; hasLDEXPF = false; break; case GK_SOUTHERN_ISLANDS: case GK_SEA_ISLANDS: case GK_VOLCANIC_ISLANDS: DescriptionString = DescriptionStringSI; hasFP64 = true; hasFMAF = true; hasLDEXPF = true; break; } return true; } }; const Builtin::Info AMDGPUTargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) \ { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #include "clang/Basic/BuiltinsAMDGPU.def" }; const char * const AMDGPUTargetInfo::GCCRegNames[] = { "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31", "v32", "v33", "v34", "v35", "v36", "v37", "v38", "v39", "v40", "v41", "v42", "v43", "v44", "v45", "v46", "v47", "v48", "v49", "v50", "v51", "v52", "v53", "v54", "v55", "v56", "v57", "v58", "v59", "v60", "v61", "v62", "v63", "v64", "v65", "v66", "v67", "v68", "v69", "v70", "v71", "v72", "v73", "v74", "v75", "v76", "v77", "v78", "v79", "v80", "v81", "v82", "v83", "v84", "v85", "v86", "v87", "v88", "v89", "v90", "v91", "v92", "v93", "v94", "v95", "v96", "v97", "v98", "v99", "v100", "v101", "v102", "v103", "v104", "v105", "v106", "v107", "v108", "v109", "v110", "v111", "v112", "v113", "v114", "v115", "v116", "v117", "v118", "v119", "v120", "v121", "v122", "v123", "v124", "v125", "v126", "v127", "v128", "v129", "v130", "v131", "v132", "v133", "v134", "v135", "v136", "v137", "v138", "v139", "v140", "v141", "v142", "v143", "v144", "v145", "v146", "v147", "v148", "v149", "v150", "v151", "v152", "v153", "v154", "v155", "v156", "v157", "v158", "v159", "v160", "v161", "v162", "v163", "v164", "v165", "v166", "v167", "v168", "v169", "v170", "v171", "v172", "v173", "v174", "v175", "v176", "v177", "v178", "v179", "v180", "v181", "v182", "v183", "v184", "v185", "v186", "v187", "v188", "v189", "v190", "v191", "v192", "v193", "v194", "v195", "v196", "v197", "v198", "v199", "v200", "v201", "v202", "v203", "v204", "v205", "v206", "v207", "v208", "v209", "v210", "v211", "v212", "v213", "v214", "v215", "v216", "v217", "v218", "v219", "v220", "v221", "v222", "v223", "v224", "v225", "v226", "v227", "v228", "v229", "v230", "v231", "v232", "v233", "v234", "v235", "v236", "v237", "v238", "v239", "v240", "v241", "v242", "v243", "v244", "v245", "v246", "v247", "v248", "v249", "v250", "v251", "v252", "v253", "v254", "v255", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31", "s32", "s33", "s34", "s35", "s36", "s37", "s38", "s39", "s40", "s41", "s42", "s43", "s44", "s45", "s46", "s47", "s48", "s49", "s50", "s51", "s52", "s53", "s54", "s55", "s56", "s57", "s58", "s59", "s60", "s61", "s62", "s63", "s64", "s65", "s66", "s67", "s68", "s69", "s70", "s71", "s72", "s73", "s74", "s75", "s76", "s77", "s78", "s79", "s80", "s81", "s82", "s83", "s84", "s85", "s86", "s87", "s88", "s89", "s90", "s91", "s92", "s93", "s94", "s95", "s96", "s97", "s98", "s99", "s100", "s101", "s102", "s103", "s104", "s105", "s106", "s107", "s108", "s109", "s110", "s111", "s112", "s113", "s114", "s115", "s116", "s117", "s118", "s119", "s120", "s121", "s122", "s123", "s124", "s125", "s126", "s127" "exec", "vcc", "scc", "m0", "flat_scr", "exec_lo", "exec_hi", "vcc_lo", "vcc_hi", "flat_scr_lo", "flat_scr_hi" }; void AMDGPUTargetInfo::getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } // Namespace for x86 abstract base class const Builtin::Info BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER,\ ALL_LANGUAGES }, #include "clang/Basic/BuiltinsX86.def" }; static const char* const GCCRegNames[] = { "ax", "dx", "cx", "bx", "si", "di", "bp", "sp", "st", "st(1)", "st(2)", "st(3)", "st(4)", "st(5)", "st(6)", "st(7)", "argp", "flags", "fpcr", "fpsr", "dirflag", "frame", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15", "ymm0", "ymm1", "ymm2", "ymm3", "ymm4", "ymm5", "ymm6", "ymm7", "ymm8", "ymm9", "ymm10", "ymm11", "ymm12", "ymm13", "ymm14", "ymm15", }; const TargetInfo::AddlRegName AddlRegNames[] = { { { "al", "ah", "eax", "rax" }, 0 }, { { "bl", "bh", "ebx", "rbx" }, 3 }, { { "cl", "ch", "ecx", "rcx" }, 2 }, { { "dl", "dh", "edx", "rdx" }, 1 }, { { "esi", "rsi" }, 4 }, { { "edi", "rdi" }, 5 }, { { "esp", "rsp" }, 7 }, { { "ebp", "rbp" }, 6 }, }; // X86 target abstract base class; x86-32 and x86-64 are very close, so // most of the implementation can be shared. class X86TargetInfo : public TargetInfo { enum X86SSEEnum { NoSSE, SSE1, SSE2, SSE3, SSSE3, SSE41, SSE42, AVX, AVX2, AVX512F } SSELevel; enum MMX3DNowEnum { NoMMX3DNow, MMX, AMD3DNow, AMD3DNowAthlon } MMX3DNowLevel; enum XOPEnum { NoXOP, SSE4A, FMA4, XOP } XOPLevel; bool HasAES; bool HasPCLMUL; bool HasLZCNT; bool HasRDRND; bool HasFSGSBASE; bool HasBMI; bool HasBMI2; bool HasPOPCNT; bool HasRTM; bool HasPRFCHW; bool HasRDSEED; bool HasADX; bool HasTBM; bool HasFMA; bool HasF16C; bool HasAVX512CD, HasAVX512ER, HasAVX512PF, HasAVX512DQ, HasAVX512BW, HasAVX512VL; bool HasSHA; bool HasCX16; /// \brief Enumeration of all of the X86 CPUs supported by Clang. /// /// Each enumeration represents a particular CPU supported by Clang. These /// loosely correspond to the options passed to '-march' or '-mtune' flags. enum CPUKind { CK_Generic, /// \name i386 /// i386-generation processors. //@{ CK_i386, //@} /// \name i486 /// i486-generation processors. //@{ CK_i486, CK_WinChipC6, CK_WinChip2, CK_C3, //@} /// \name i586 /// i586-generation processors, P5 microarchitecture based. //@{ CK_i586, CK_Pentium, CK_PentiumMMX, //@} /// \name i686 /// i686-generation processors, P6 / Pentium M microarchitecture based. //@{ CK_i686, CK_PentiumPro, CK_Pentium2, CK_Pentium3, CK_Pentium3M, CK_PentiumM, CK_C3_2, /// This enumerator is a bit odd, as GCC no longer accepts -march=yonah. /// Clang however has some logic to suport this. // FIXME: Warn, deprecate, and potentially remove this. CK_Yonah, //@} /// \name Netburst /// Netburst microarchitecture based processors. //@{ CK_Pentium4, CK_Pentium4M, CK_Prescott, CK_Nocona, //@} /// \name Core /// Core microarchitecture based processors. //@{ CK_Core2, /// This enumerator, like \see CK_Yonah, is a bit odd. It is another /// codename which GCC no longer accepts as an option to -march, but Clang /// has some logic for recognizing it. // FIXME: Warn, deprecate, and potentially remove this. CK_Penryn, //@} /// \name Atom /// Atom processors //@{ CK_Bonnell, CK_Silvermont, //@} /// \name Nehalem /// Nehalem microarchitecture based processors. CK_Nehalem, /// \name Westmere /// Westmere microarchitecture based processors. CK_Westmere, /// \name Sandy Bridge /// Sandy Bridge microarchitecture based processors. CK_SandyBridge, /// \name Ivy Bridge /// Ivy Bridge microarchitecture based processors. CK_IvyBridge, /// \name Haswell /// Haswell microarchitecture based processors. CK_Haswell, /// \name Broadwell /// Broadwell microarchitecture based processors. CK_Broadwell, /// \name Skylake /// Skylake microarchitecture based processors. CK_Skylake, /// \name Knights Landing /// Knights Landing processor. CK_KNL, /// \name K6 /// K6 architecture processors. //@{ CK_K6, CK_K6_2, CK_K6_3, //@} /// \name K7 /// K7 architecture processors. //@{ CK_Athlon, CK_AthlonThunderbird, CK_Athlon4, CK_AthlonXP, CK_AthlonMP, //@} /// \name K8 /// K8 architecture processors. //@{ CK_Athlon64, CK_Athlon64SSE3, CK_AthlonFX, CK_K8, CK_K8SSE3, CK_Opteron, CK_OpteronSSE3, CK_AMDFAM10, //@} /// \name Bobcat /// Bobcat architecture processors. //@{ CK_BTVER1, CK_BTVER2, //@} /// \name Bulldozer /// Bulldozer architecture processors. //@{ CK_BDVER1, CK_BDVER2, CK_BDVER3, CK_BDVER4, //@} /// This specification is deprecated and will be removed in the future. /// Users should prefer \see CK_K8. // FIXME: Warn on this when the CPU is set to it. //@{ CK_x86_64, //@} /// \name Geode /// Geode processors. //@{ CK_Geode //@} } CPU; enum FPMathKind { FP_Default, FP_SSE, FP_387 } FPMath; public: X86TargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple), SSELevel(NoSSE), MMX3DNowLevel(NoMMX3DNow), XOPLevel(NoXOP), HasAES(false), HasPCLMUL(false), HasLZCNT(false), HasRDRND(false), HasFSGSBASE(false), HasBMI(false), HasBMI2(false), HasPOPCNT(false), HasRTM(false), HasPRFCHW(false), HasRDSEED(false), HasADX(false), HasTBM(false), HasFMA(false), HasF16C(false), HasAVX512CD(false), HasAVX512ER(false), HasAVX512PF(false), HasAVX512DQ(false), HasAVX512BW(false), HasAVX512VL(false), HasSHA(false), HasCX16(false), CPU(CK_Generic), FPMath(FP_Default) { BigEndian = false; LongDoubleFormat = &llvm::APFloat::x87DoubleExtended; } unsigned getFloatEvalMethod() const override { // X87 evaluates with 80 bits "long double" precision. return SSELevel == NoSSE ? 2 : 0; } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::X86::LastTSBuiltin-Builtin::FirstTSBuiltin; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override { Aliases = nullptr; NumAliases = 0; } void getGCCAddlRegNames(const AddlRegName *&Names, unsigned &NumNames) const override { Names = AddlRegNames; NumNames = llvm::array_lengthof(AddlRegNames); } bool validateCpuSupports(StringRef Name) const override; bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override; bool validateOutputSize(StringRef Constraint, unsigned Size) const override; bool validateInputSize(StringRef Constraint, unsigned Size) const override; virtual bool validateOperandSize(StringRef Constraint, unsigned Size) const; std::string convertConstraint(const char *&Constraint) const override; const char *getClobbers() const override { return "~{dirflag},~{fpsr},~{flags}"; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override; static void setSSELevel(llvm::StringMap<bool> &Features, X86SSEEnum Level, bool Enabled); static void setMMXLevel(llvm::StringMap<bool> &Features, MMX3DNowEnum Level, bool Enabled); static void setXOPLevel(llvm::StringMap<bool> &Features, XOPEnum Level, bool Enabled); void setFeatureEnabled(llvm::StringMap<bool> &Features, StringRef Name, bool Enabled) const override { setFeatureEnabledImpl(Features, Name, Enabled); } // This exists purely to cut down on the number of virtual calls in // getDefaultFeatures which calls this repeatedly. static void setFeatureEnabledImpl(llvm::StringMap<bool> &Features, StringRef Name, bool Enabled); void getDefaultFeatures(llvm::StringMap<bool> &Features) const override; bool hasFeature(StringRef Feature) const override; bool handleTargetFeatures(std::vector<std::string> &Features, DiagnosticsEngine &Diags) override; StringRef getABI() const override { if (getTriple().getArch() == llvm::Triple::x86_64 && SSELevel >= AVX512F) return "avx512"; else if (getTriple().getArch() == llvm::Triple::x86_64 && SSELevel >= AVX) return "avx"; else if (getTriple().getArch() == llvm::Triple::x86 && MMX3DNowLevel == NoMMX3DNow) return "no-mmx"; return ""; } bool setCPU(const std::string &Name) override { CPU = llvm::StringSwitch<CPUKind>(Name) .Case("i386", CK_i386) .Case("i486", CK_i486) .Case("winchip-c6", CK_WinChipC6) .Case("winchip2", CK_WinChip2) .Case("c3", CK_C3) .Case("i586", CK_i586) .Case("pentium", CK_Pentium) .Case("pentium-mmx", CK_PentiumMMX) .Case("i686", CK_i686) .Case("pentiumpro", CK_PentiumPro) .Case("pentium2", CK_Pentium2) .Case("pentium3", CK_Pentium3) .Case("pentium3m", CK_Pentium3M) .Case("pentium-m", CK_PentiumM) .Case("c3-2", CK_C3_2) .Case("yonah", CK_Yonah) .Case("pentium4", CK_Pentium4) .Case("pentium4m", CK_Pentium4M) .Case("prescott", CK_Prescott) .Case("nocona", CK_Nocona) .Case("core2", CK_Core2) .Case("penryn", CK_Penryn) .Case("bonnell", CK_Bonnell) .Case("atom", CK_Bonnell) // Legacy name. .Case("silvermont", CK_Silvermont) .Case("slm", CK_Silvermont) // Legacy name. .Case("nehalem", CK_Nehalem) .Case("corei7", CK_Nehalem) // Legacy name. .Case("westmere", CK_Westmere) .Case("sandybridge", CK_SandyBridge) .Case("corei7-avx", CK_SandyBridge) // Legacy name. .Case("ivybridge", CK_IvyBridge) .Case("core-avx-i", CK_IvyBridge) // Legacy name. .Case("haswell", CK_Haswell) .Case("core-avx2", CK_Haswell) // Legacy name. .Case("broadwell", CK_Broadwell) .Case("skylake", CK_Skylake) .Case("skx", CK_Skylake) // Legacy name. .Case("knl", CK_KNL) .Case("k6", CK_K6) .Case("k6-2", CK_K6_2) .Case("k6-3", CK_K6_3) .Case("athlon", CK_Athlon) .Case("athlon-tbird", CK_AthlonThunderbird) .Case("athlon-4", CK_Athlon4) .Case("athlon-xp", CK_AthlonXP) .Case("athlon-mp", CK_AthlonMP) .Case("athlon64", CK_Athlon64) .Case("athlon64-sse3", CK_Athlon64SSE3) .Case("athlon-fx", CK_AthlonFX) .Case("k8", CK_K8) .Case("k8-sse3", CK_K8SSE3) .Case("opteron", CK_Opteron) .Case("opteron-sse3", CK_OpteronSSE3) .Case("barcelona", CK_AMDFAM10) .Case("amdfam10", CK_AMDFAM10) .Case("btver1", CK_BTVER1) .Case("btver2", CK_BTVER2) .Case("bdver1", CK_BDVER1) .Case("bdver2", CK_BDVER2) .Case("bdver3", CK_BDVER3) .Case("bdver4", CK_BDVER4) .Case("x86-64", CK_x86_64) .Case("geode", CK_Geode) .Default(CK_Generic); // Perform any per-CPU checks necessary to determine if this CPU is // acceptable. // FIXME: This results in terrible diagnostics. Clang just says the CPU is // invalid without explaining *why*. switch (CPU) { case CK_Generic: // No processor selected! return false; case CK_i386: case CK_i486: case CK_WinChipC6: case CK_WinChip2: case CK_C3: case CK_i586: case CK_Pentium: case CK_PentiumMMX: case CK_i686: case CK_PentiumPro: case CK_Pentium2: case CK_Pentium3: case CK_Pentium3M: case CK_PentiumM: case CK_Yonah: case CK_C3_2: case CK_Pentium4: case CK_Pentium4M: case CK_Prescott: case CK_K6: case CK_K6_2: case CK_K6_3: case CK_Athlon: case CK_AthlonThunderbird: case CK_Athlon4: case CK_AthlonXP: case CK_AthlonMP: case CK_Geode: // Only accept certain architectures when compiling in 32-bit mode. if (getTriple().getArch() != llvm::Triple::x86) return false; // Fallthrough case CK_Nocona: case CK_Core2: case CK_Penryn: case CK_Bonnell: case CK_Silvermont: case CK_Nehalem: case CK_Westmere: case CK_SandyBridge: case CK_IvyBridge: case CK_Haswell: case CK_Broadwell: case CK_Skylake: case CK_KNL: case CK_Athlon64: case CK_Athlon64SSE3: case CK_AthlonFX: case CK_K8: case CK_K8SSE3: case CK_Opteron: case CK_OpteronSSE3: case CK_AMDFAM10: case CK_BTVER1: case CK_BTVER2: case CK_BDVER1: case CK_BDVER2: case CK_BDVER3: case CK_BDVER4: case CK_x86_64: return true; } llvm_unreachable("Unhandled CPU kind"); } bool setFPMath(StringRef Name) override; CallingConvCheckResult checkCallingConvention(CallingConv CC) const override { // We accept all non-ARM calling conventions return (CC == CC_X86ThisCall || CC == CC_X86FastCall || CC == CC_X86StdCall || CC == CC_X86VectorCall || CC == CC_C || CC == CC_X86Pascal || CC == CC_IntelOclBicc) ? CCCR_OK : CCCR_Warning; } CallingConv getDefaultCallingConv(CallingConvMethodType MT) const override { return MT == CCMT_Member ? CC_X86ThisCall : CC_C; } bool hasSjLjLowering() const override { return true; } }; bool X86TargetInfo::setFPMath(StringRef Name) { if (Name == "387") { FPMath = FP_387; return true; } if (Name == "sse") { FPMath = FP_SSE; return true; } return false; } void X86TargetInfo::getDefaultFeatures(llvm::StringMap<bool> &Features) const { // FIXME: This *really* should not be here. // X86_64 always has SSE2. if (getTriple().getArch() == llvm::Triple::x86_64) setFeatureEnabledImpl(Features, "sse2", true); switch (CPU) { case CK_Generic: case CK_i386: case CK_i486: case CK_i586: case CK_Pentium: case CK_i686: case CK_PentiumPro: break; case CK_PentiumMMX: case CK_Pentium2: case CK_K6: case CK_WinChipC6: setFeatureEnabledImpl(Features, "mmx", true); break; case CK_Pentium3: case CK_Pentium3M: case CK_C3_2: setFeatureEnabledImpl(Features, "sse", true); break; case CK_PentiumM: case CK_Pentium4: case CK_Pentium4M: case CK_x86_64: setFeatureEnabledImpl(Features, "sse2", true); break; case CK_Yonah: case CK_Prescott: case CK_Nocona: setFeatureEnabledImpl(Features, "sse3", true); setFeatureEnabledImpl(Features, "cx16", true); break; case CK_Core2: case CK_Bonnell: setFeatureEnabledImpl(Features, "ssse3", true); setFeatureEnabledImpl(Features, "cx16", true); break; case CK_Penryn: setFeatureEnabledImpl(Features, "sse4.1", true); setFeatureEnabledImpl(Features, "cx16", true); break; case CK_Skylake: setFeatureEnabledImpl(Features, "avx512f", true); setFeatureEnabledImpl(Features, "avx512cd", true); setFeatureEnabledImpl(Features, "avx512dq", true); setFeatureEnabledImpl(Features, "avx512bw", true); setFeatureEnabledImpl(Features, "avx512vl", true); // FALLTHROUGH case CK_Broadwell: setFeatureEnabledImpl(Features, "rdseed", true); setFeatureEnabledImpl(Features, "adx", true); // FALLTHROUGH case CK_Haswell: setFeatureEnabledImpl(Features, "avx2", true); setFeatureEnabledImpl(Features, "lzcnt", true); setFeatureEnabledImpl(Features, "bmi", true); setFeatureEnabledImpl(Features, "bmi2", true); setFeatureEnabledImpl(Features, "rtm", true); setFeatureEnabledImpl(Features, "fma", true); // FALLTHROUGH case CK_IvyBridge: setFeatureEnabledImpl(Features, "rdrnd", true); setFeatureEnabledImpl(Features, "f16c", true); setFeatureEnabledImpl(Features, "fsgsbase", true); // FALLTHROUGH case CK_SandyBridge: setFeatureEnabledImpl(Features, "avx", true); // FALLTHROUGH case CK_Westmere: case CK_Silvermont: setFeatureEnabledImpl(Features, "aes", true); setFeatureEnabledImpl(Features, "pclmul", true); // FALLTHROUGH case CK_Nehalem: setFeatureEnabledImpl(Features, "sse4.2", true); setFeatureEnabledImpl(Features, "cx16", true); break; case CK_KNL: setFeatureEnabledImpl(Features, "avx512f", true); setFeatureEnabledImpl(Features, "avx512cd", true); setFeatureEnabledImpl(Features, "avx512er", true); setFeatureEnabledImpl(Features, "avx512pf", true); setFeatureEnabledImpl(Features, "rdseed", true); setFeatureEnabledImpl(Features, "adx", true); setFeatureEnabledImpl(Features, "lzcnt", true); setFeatureEnabledImpl(Features, "bmi", true); setFeatureEnabledImpl(Features, "bmi2", true); setFeatureEnabledImpl(Features, "rtm", true); setFeatureEnabledImpl(Features, "fma", true); setFeatureEnabledImpl(Features, "rdrnd", true); setFeatureEnabledImpl(Features, "f16c", true); setFeatureEnabledImpl(Features, "fsgsbase", true); setFeatureEnabledImpl(Features, "aes", true); setFeatureEnabledImpl(Features, "pclmul", true); setFeatureEnabledImpl(Features, "cx16", true); break; case CK_K6_2: case CK_K6_3: case CK_WinChip2: case CK_C3: setFeatureEnabledImpl(Features, "3dnow", true); break; case CK_Athlon: case CK_AthlonThunderbird: case CK_Geode: setFeatureEnabledImpl(Features, "3dnowa", true); break; case CK_Athlon4: case CK_AthlonXP: case CK_AthlonMP: setFeatureEnabledImpl(Features, "sse", true); setFeatureEnabledImpl(Features, "3dnowa", true); break; case CK_K8: case CK_Opteron: case CK_Athlon64: case CK_AthlonFX: setFeatureEnabledImpl(Features, "sse2", true); setFeatureEnabledImpl(Features, "3dnowa", true); break; case CK_AMDFAM10: setFeatureEnabledImpl(Features, "sse4a", true); setFeatureEnabledImpl(Features, "lzcnt", true); setFeatureEnabledImpl(Features, "popcnt", true); // FALLTHROUGH case CK_K8SSE3: case CK_OpteronSSE3: case CK_Athlon64SSE3: setFeatureEnabledImpl(Features, "sse3", true); setFeatureEnabledImpl(Features, "3dnowa", true); break; case CK_BTVER2: setFeatureEnabledImpl(Features, "avx", true); setFeatureEnabledImpl(Features, "aes", true); setFeatureEnabledImpl(Features, "pclmul", true); setFeatureEnabledImpl(Features, "bmi", true); setFeatureEnabledImpl(Features, "f16c", true); // FALLTHROUGH case CK_BTVER1: setFeatureEnabledImpl(Features, "ssse3", true); setFeatureEnabledImpl(Features, "sse4a", true); setFeatureEnabledImpl(Features, "lzcnt", true); setFeatureEnabledImpl(Features, "popcnt", true); setFeatureEnabledImpl(Features, "prfchw", true); setFeatureEnabledImpl(Features, "cx16", true); break; case CK_BDVER4: setFeatureEnabledImpl(Features, "avx2", true); setFeatureEnabledImpl(Features, "bmi2", true); // FALLTHROUGH case CK_BDVER3: setFeatureEnabledImpl(Features, "fsgsbase", true); // FALLTHROUGH case CK_BDVER2: setFeatureEnabledImpl(Features, "bmi", true); setFeatureEnabledImpl(Features, "fma", true); setFeatureEnabledImpl(Features, "f16c", true); setFeatureEnabledImpl(Features, "tbm", true); // FALLTHROUGH case CK_BDVER1: // xop implies avx, sse4a and fma4. setFeatureEnabledImpl(Features, "xop", true); setFeatureEnabledImpl(Features, "lzcnt", true); setFeatureEnabledImpl(Features, "aes", true); setFeatureEnabledImpl(Features, "pclmul", true); setFeatureEnabledImpl(Features, "prfchw", true); setFeatureEnabledImpl(Features, "cx16", true); break; } } void X86TargetInfo::setSSELevel(llvm::StringMap<bool> &Features, X86SSEEnum Level, bool Enabled) { if (Enabled) { switch (Level) { case AVX512F: Features["avx512f"] = true; case AVX2: Features["avx2"] = true; case AVX: Features["avx"] = true; case SSE42: Features["sse4.2"] = true; case SSE41: Features["sse4.1"] = true; case SSSE3: Features["ssse3"] = true; case SSE3: Features["sse3"] = true; case SSE2: Features["sse2"] = true; case SSE1: Features["sse"] = true; case NoSSE: break; } return; } switch (Level) { case NoSSE: case SSE1: Features["sse"] = false; case SSE2: Features["sse2"] = Features["pclmul"] = Features["aes"] = Features["sha"] = false; case SSE3: Features["sse3"] = false; setXOPLevel(Features, NoXOP, false); case SSSE3: Features["ssse3"] = false; case SSE41: Features["sse4.1"] = false; case SSE42: Features["sse4.2"] = false; case AVX: Features["fma"] = Features["avx"] = Features["f16c"] = false; setXOPLevel(Features, FMA4, false); case AVX2: Features["avx2"] = false; case AVX512F: Features["avx512f"] = Features["avx512cd"] = Features["avx512er"] = Features["avx512pf"] = Features["avx512dq"] = Features["avx512bw"] = Features["avx512vl"] = false; } } void X86TargetInfo::setMMXLevel(llvm::StringMap<bool> &Features, MMX3DNowEnum Level, bool Enabled) { if (Enabled) { switch (Level) { case AMD3DNowAthlon: Features["3dnowa"] = true; case AMD3DNow: Features["3dnow"] = true; case MMX: Features["mmx"] = true; case NoMMX3DNow: break; } return; } switch (Level) { case NoMMX3DNow: case MMX: Features["mmx"] = false; case AMD3DNow: Features["3dnow"] = false; case AMD3DNowAthlon: Features["3dnowa"] = false; } } void X86TargetInfo::setXOPLevel(llvm::StringMap<bool> &Features, XOPEnum Level, bool Enabled) { if (Enabled) { switch (Level) { case XOP: Features["xop"] = true; case FMA4: Features["fma4"] = true; setSSELevel(Features, AVX, true); case SSE4A: Features["sse4a"] = true; setSSELevel(Features, SSE3, true); case NoXOP: break; } return; } switch (Level) { case NoXOP: case SSE4A: Features["sse4a"] = false; case FMA4: Features["fma4"] = false; case XOP: Features["xop"] = false; } } void X86TargetInfo::setFeatureEnabledImpl(llvm::StringMap<bool> &Features, StringRef Name, bool Enabled) { // This is a bit of a hack to deal with the sse4 target feature when used // as part of the target attribute. We handle sse4 correctly everywhere // else. See below for more information on how we handle the sse4 options. if (Name != "sse4") Features[Name] = Enabled; if (Name == "mmx") { setMMXLevel(Features, MMX, Enabled); } else if (Name == "sse") { setSSELevel(Features, SSE1, Enabled); } else if (Name == "sse2") { setSSELevel(Features, SSE2, Enabled); } else if (Name == "sse3") { setSSELevel(Features, SSE3, Enabled); } else if (Name == "ssse3") { setSSELevel(Features, SSSE3, Enabled); } else if (Name == "sse4.2") { setSSELevel(Features, SSE42, Enabled); } else if (Name == "sse4.1") { setSSELevel(Features, SSE41, Enabled); } else if (Name == "3dnow") { setMMXLevel(Features, AMD3DNow, Enabled); } else if (Name == "3dnowa") { setMMXLevel(Features, AMD3DNowAthlon, Enabled); } else if (Name == "aes") { if (Enabled) setSSELevel(Features, SSE2, Enabled); } else if (Name == "pclmul") { if (Enabled) setSSELevel(Features, SSE2, Enabled); } else if (Name == "avx") { setSSELevel(Features, AVX, Enabled); } else if (Name == "avx2") { setSSELevel(Features, AVX2, Enabled); } else if (Name == "avx512f") { setSSELevel(Features, AVX512F, Enabled); } else if (Name == "avx512cd" || Name == "avx512er" || Name == "avx512pf" || Name == "avx512dq" || Name == "avx512bw" || Name == "avx512vl") { if (Enabled) setSSELevel(Features, AVX512F, Enabled); } else if (Name == "fma") { if (Enabled) setSSELevel(Features, AVX, Enabled); } else if (Name == "fma4") { setXOPLevel(Features, FMA4, Enabled); } else if (Name == "xop") { setXOPLevel(Features, XOP, Enabled); } else if (Name == "sse4a") { setXOPLevel(Features, SSE4A, Enabled); } else if (Name == "f16c") { if (Enabled) setSSELevel(Features, AVX, Enabled); } else if (Name == "sha") { if (Enabled) setSSELevel(Features, SSE2, Enabled); } else if (Name == "sse4") { // We can get here via the __target__ attribute since that's not controlled // via the -msse4/-mno-sse4 command line alias. Handle this the same way // here - turn on the sse4.2 if enabled, turn off the sse4.1 level if // disabled. if (Enabled) setSSELevel(Features, SSE42, Enabled); else setSSELevel(Features, SSE41, Enabled); } } /// handleTargetFeatures - Perform initialization based on the user /// configured set of features. bool X86TargetInfo::handleTargetFeatures(std::vector<std::string> &Features, DiagnosticsEngine &Diags) { // Remember the maximum enabled sselevel. for (unsigned i = 0, e = Features.size(); i !=e; ++i) { // Ignore disabled features. if (Features[i][0] == '-') continue; StringRef Feature = StringRef(Features[i]).substr(1); if (Feature == "aes") { HasAES = true; continue; } if (Feature == "pclmul") { HasPCLMUL = true; continue; } if (Feature == "lzcnt") { HasLZCNT = true; continue; } if (Feature == "rdrnd") { HasRDRND = true; continue; } if (Feature == "fsgsbase") { HasFSGSBASE = true; continue; } if (Feature == "bmi") { HasBMI = true; continue; } if (Feature == "bmi2") { HasBMI2 = true; continue; } if (Feature == "popcnt") { HasPOPCNT = true; continue; } if (Feature == "rtm") { HasRTM = true; continue; } if (Feature == "prfchw") { HasPRFCHW = true; continue; } if (Feature == "rdseed") { HasRDSEED = true; continue; } if (Feature == "adx") { HasADX = true; continue; } if (Feature == "tbm") { HasTBM = true; continue; } if (Feature == "fma") { HasFMA = true; continue; } if (Feature == "f16c") { HasF16C = true; continue; } if (Feature == "avx512cd") { HasAVX512CD = true; continue; } if (Feature == "avx512er") { HasAVX512ER = true; continue; } if (Feature == "avx512pf") { HasAVX512PF = true; continue; } if (Feature == "avx512dq") { HasAVX512DQ = true; continue; } if (Feature == "avx512bw") { HasAVX512BW = true; continue; } if (Feature == "avx512vl") { HasAVX512VL = true; continue; } if (Feature == "sha") { HasSHA = true; continue; } if (Feature == "cx16") { HasCX16 = true; continue; } assert(Features[i][0] == '+' && "Invalid target feature!"); X86SSEEnum Level = llvm::StringSwitch<X86SSEEnum>(Feature) .Case("avx512f", AVX512F) .Case("avx2", AVX2) .Case("avx", AVX) .Case("sse4.2", SSE42) .Case("sse4.1", SSE41) .Case("ssse3", SSSE3) .Case("sse3", SSE3) .Case("sse2", SSE2) .Case("sse", SSE1) .Default(NoSSE); SSELevel = std::max(SSELevel, Level); MMX3DNowEnum ThreeDNowLevel = llvm::StringSwitch<MMX3DNowEnum>(Feature) .Case("3dnowa", AMD3DNowAthlon) .Case("3dnow", AMD3DNow) .Case("mmx", MMX) .Default(NoMMX3DNow); MMX3DNowLevel = std::max(MMX3DNowLevel, ThreeDNowLevel); XOPEnum XLevel = llvm::StringSwitch<XOPEnum>(Feature) .Case("xop", XOP) .Case("fma4", FMA4) .Case("sse4a", SSE4A) .Default(NoXOP); XOPLevel = std::max(XOPLevel, XLevel); } // Enable popcnt if sse4.2 is enabled and popcnt is not explicitly disabled. // Can't do this earlier because we need to be able to explicitly enable // popcnt and still disable sse4.2. if (!HasPOPCNT && SSELevel >= SSE42 && std::find(Features.begin(), Features.end(), "-popcnt") == Features.end()){ HasPOPCNT = true; Features.push_back("+popcnt"); } // Enable prfchw if 3DNow! is enabled and prfchw is not explicitly disabled. if (!HasPRFCHW && MMX3DNowLevel >= AMD3DNow && std::find(Features.begin(), Features.end(), "-prfchw") == Features.end()){ HasPRFCHW = true; Features.push_back("+prfchw"); } // LLVM doesn't have a separate switch for fpmath, so only accept it if it // matches the selected sse level. if (FPMath == FP_SSE && SSELevel < SSE1) { Diags.Report(diag::err_target_unsupported_fpmath) << "sse"; return false; } else if (FPMath == FP_387 && SSELevel >= SSE1) { Diags.Report(diag::err_target_unsupported_fpmath) << "387"; return false; } // Don't tell the backend if we're turning off mmx; it will end up disabling // SSE, which we don't want. // Additionally, if SSE is enabled and mmx is not explicitly disabled, // then enable MMX. std::vector<std::string>::iterator it; it = std::find(Features.begin(), Features.end(), "-mmx"); if (it != Features.end()) Features.erase(it); else if (SSELevel > NoSSE) MMX3DNowLevel = std::max(MMX3DNowLevel, MMX); SimdDefaultAlign = (getABI() == "avx512") ? 512 : (getABI() == "avx") ? 256 : 128; return true; } /// X86TargetInfo::getTargetDefines - Return the set of the X86-specific macro /// definitions for this particular subtarget. void X86TargetInfo::getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const { // Target identification. if (getTriple().getArch() == llvm::Triple::x86_64) { Builder.defineMacro("__amd64__"); Builder.defineMacro("__amd64"); Builder.defineMacro("__x86_64"); Builder.defineMacro("__x86_64__"); if (getTriple().getArchName() == "x86_64h") { Builder.defineMacro("__x86_64h"); Builder.defineMacro("__x86_64h__"); } } else { DefineStd(Builder, "i386", Opts); } // Subtarget options. // FIXME: We are hard-coding the tune parameters based on the CPU, but they // truly should be based on -mtune options. switch (CPU) { case CK_Generic: break; case CK_i386: // The rest are coming from the i386 define above. Builder.defineMacro("__tune_i386__"); break; case CK_i486: case CK_WinChipC6: case CK_WinChip2: case CK_C3: defineCPUMacros(Builder, "i486"); break; case CK_PentiumMMX: Builder.defineMacro("__pentium_mmx__"); Builder.defineMacro("__tune_pentium_mmx__"); // Fallthrough case CK_i586: case CK_Pentium: defineCPUMacros(Builder, "i586"); defineCPUMacros(Builder, "pentium"); break; case CK_Pentium3: case CK_Pentium3M: case CK_PentiumM: Builder.defineMacro("__tune_pentium3__"); // Fallthrough case CK_Pentium2: case CK_C3_2: Builder.defineMacro("__tune_pentium2__"); // Fallthrough case CK_PentiumPro: Builder.defineMacro("__tune_i686__"); Builder.defineMacro("__tune_pentiumpro__"); // Fallthrough case CK_i686: Builder.defineMacro("__i686"); Builder.defineMacro("__i686__"); // Strangely, __tune_i686__ isn't defined by GCC when CPU == i686. Builder.defineMacro("__pentiumpro"); Builder.defineMacro("__pentiumpro__"); break; case CK_Pentium4: case CK_Pentium4M: defineCPUMacros(Builder, "pentium4"); break; case CK_Yonah: case CK_Prescott: case CK_Nocona: defineCPUMacros(Builder, "nocona"); break; case CK_Core2: case CK_Penryn: defineCPUMacros(Builder, "core2"); break; case CK_Bonnell: defineCPUMacros(Builder, "atom"); break; case CK_Silvermont: defineCPUMacros(Builder, "slm"); break; case CK_Nehalem: case CK_Westmere: case CK_SandyBridge: case CK_IvyBridge: case CK_Haswell: case CK_Broadwell: // FIXME: Historically, we defined this legacy name, it would be nice to // remove it at some point. We've never exposed fine-grained names for // recent primary x86 CPUs, and we should keep it that way. defineCPUMacros(Builder, "corei7"); break; case CK_Skylake: // FIXME: Historically, we defined this legacy name, it would be nice to // remove it at some point. This is the only fine-grained CPU macro in the // main intel CPU line, and it would be better to not have these and force // people to use ISA macros. defineCPUMacros(Builder, "skx"); break; case CK_KNL: defineCPUMacros(Builder, "knl"); break; case CK_K6_2: Builder.defineMacro("__k6_2__"); Builder.defineMacro("__tune_k6_2__"); // Fallthrough case CK_K6_3: if (CPU != CK_K6_2) { // In case of fallthrough // FIXME: GCC may be enabling these in cases where some other k6 // architecture is specified but -m3dnow is explicitly provided. The // exact semantics need to be determined and emulated here. Builder.defineMacro("__k6_3__"); Builder.defineMacro("__tune_k6_3__"); } // Fallthrough case CK_K6: defineCPUMacros(Builder, "k6"); break; case CK_Athlon: case CK_AthlonThunderbird: case CK_Athlon4: case CK_AthlonXP: case CK_AthlonMP: defineCPUMacros(Builder, "athlon"); if (SSELevel != NoSSE) { Builder.defineMacro("__athlon_sse__"); Builder.defineMacro("__tune_athlon_sse__"); } break; case CK_K8: case CK_K8SSE3: case CK_x86_64: case CK_Opteron: case CK_OpteronSSE3: case CK_Athlon64: case CK_Athlon64SSE3: case CK_AthlonFX: defineCPUMacros(Builder, "k8"); break; case CK_AMDFAM10: defineCPUMacros(Builder, "amdfam10"); break; case CK_BTVER1: defineCPUMacros(Builder, "btver1"); break; case CK_BTVER2: defineCPUMacros(Builder, "btver2"); break; case CK_BDVER1: defineCPUMacros(Builder, "bdver1"); break; case CK_BDVER2: defineCPUMacros(Builder, "bdver2"); break; case CK_BDVER3: defineCPUMacros(Builder, "bdver3"); break; case CK_BDVER4: defineCPUMacros(Builder, "bdver4"); break; case CK_Geode: defineCPUMacros(Builder, "geode"); break; } // Target properties. Builder.defineMacro("__REGISTER_PREFIX__", ""); // Define __NO_MATH_INLINES on linux/x86 so that we don't get inline // functions in glibc header files that use FP Stack inline asm which the // backend can't deal with (PR879). Builder.defineMacro("__NO_MATH_INLINES"); if (HasAES) Builder.defineMacro("__AES__"); if (HasPCLMUL) Builder.defineMacro("__PCLMUL__"); if (HasLZCNT) Builder.defineMacro("__LZCNT__"); if (HasRDRND) Builder.defineMacro("__RDRND__"); if (HasFSGSBASE) Builder.defineMacro("__FSGSBASE__"); if (HasBMI) Builder.defineMacro("__BMI__"); if (HasBMI2) Builder.defineMacro("__BMI2__"); if (HasPOPCNT) Builder.defineMacro("__POPCNT__"); if (HasRTM) Builder.defineMacro("__RTM__"); if (HasPRFCHW) Builder.defineMacro("__PRFCHW__"); if (HasRDSEED) Builder.defineMacro("__RDSEED__"); if (HasADX) Builder.defineMacro("__ADX__"); if (HasTBM) Builder.defineMacro("__TBM__"); switch (XOPLevel) { case XOP: Builder.defineMacro("__XOP__"); case FMA4: Builder.defineMacro("__FMA4__"); case SSE4A: Builder.defineMacro("__SSE4A__"); case NoXOP: break; } if (HasFMA) Builder.defineMacro("__FMA__"); if (HasF16C) Builder.defineMacro("__F16C__"); if (HasAVX512CD) Builder.defineMacro("__AVX512CD__"); if (HasAVX512ER) Builder.defineMacro("__AVX512ER__"); if (HasAVX512PF) Builder.defineMacro("__AVX512PF__"); if (HasAVX512DQ) Builder.defineMacro("__AVX512DQ__"); if (HasAVX512BW) Builder.defineMacro("__AVX512BW__"); if (HasAVX512VL) Builder.defineMacro("__AVX512VL__"); if (HasSHA) Builder.defineMacro("__SHA__"); if (HasCX16) Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16"); // Each case falls through to the previous one here. switch (SSELevel) { case AVX512F: Builder.defineMacro("__AVX512F__"); case AVX2: Builder.defineMacro("__AVX2__"); case AVX: Builder.defineMacro("__AVX__"); case SSE42: Builder.defineMacro("__SSE4_2__"); case SSE41: Builder.defineMacro("__SSE4_1__"); case SSSE3: Builder.defineMacro("__SSSE3__"); case SSE3: Builder.defineMacro("__SSE3__"); case SSE2: Builder.defineMacro("__SSE2__"); Builder.defineMacro("__SSE2_MATH__"); // -mfp-math=sse always implied. case SSE1: Builder.defineMacro("__SSE__"); Builder.defineMacro("__SSE_MATH__"); // -mfp-math=sse always implied. case NoSSE: break; } if (Opts.MicrosoftExt && getTriple().getArch() == llvm::Triple::x86) { switch (SSELevel) { case AVX512F: case AVX2: case AVX: case SSE42: case SSE41: case SSSE3: case SSE3: case SSE2: Builder.defineMacro("_M_IX86_FP", Twine(2)); break; case SSE1: Builder.defineMacro("_M_IX86_FP", Twine(1)); break; default: Builder.defineMacro("_M_IX86_FP", Twine(0)); } } // Each case falls through to the previous one here. switch (MMX3DNowLevel) { case AMD3DNowAthlon: Builder.defineMacro("__3dNOW_A__"); case AMD3DNow: Builder.defineMacro("__3dNOW__"); case MMX: Builder.defineMacro("__MMX__"); case NoMMX3DNow: break; } if (CPU >= CK_i486) { Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4"); } if (CPU >= CK_i586) Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8"); } bool X86TargetInfo::hasFeature(StringRef Feature) const { return llvm::StringSwitch<bool>(Feature) .Case("aes", HasAES) .Case("avx", SSELevel >= AVX) .Case("avx2", SSELevel >= AVX2) .Case("avx512f", SSELevel >= AVX512F) .Case("avx512cd", HasAVX512CD) .Case("avx512er", HasAVX512ER) .Case("avx512pf", HasAVX512PF) .Case("avx512dq", HasAVX512DQ) .Case("avx512bw", HasAVX512BW) .Case("avx512vl", HasAVX512VL) .Case("bmi", HasBMI) .Case("bmi2", HasBMI2) .Case("cx16", HasCX16) .Case("f16c", HasF16C) .Case("fma", HasFMA) .Case("fma4", XOPLevel >= FMA4) .Case("fsgsbase", HasFSGSBASE) .Case("lzcnt", HasLZCNT) .Case("mm3dnow", MMX3DNowLevel >= AMD3DNow) .Case("mm3dnowa", MMX3DNowLevel >= AMD3DNowAthlon) .Case("mmx", MMX3DNowLevel >= MMX) .Case("pclmul", HasPCLMUL) .Case("popcnt", HasPOPCNT) .Case("prfchw", HasPRFCHW) .Case("rdrnd", HasRDRND) .Case("rdseed", HasRDSEED) .Case("rtm", HasRTM) .Case("sha", HasSHA) .Case("sse", SSELevel >= SSE1) .Case("sse2", SSELevel >= SSE2) .Case("sse3", SSELevel >= SSE3) .Case("ssse3", SSELevel >= SSSE3) .Case("sse4.1", SSELevel >= SSE41) .Case("sse4.2", SSELevel >= SSE42) .Case("sse4a", XOPLevel >= SSE4A) .Case("tbm", HasTBM) .Case("x86", true) .Case("x86_32", getTriple().getArch() == llvm::Triple::x86) .Case("x86_64", getTriple().getArch() == llvm::Triple::x86_64) .Case("xop", XOPLevel >= XOP) .Default(false); } // We can't use a generic validation scheme for the features accepted here // versus subtarget features accepted in the target attribute because the // bitfield structure that's initialized in the runtime only supports the // below currently rather than the full range of subtarget features. (See // X86TargetInfo::hasFeature for a somewhat comprehensive list). bool X86TargetInfo::validateCpuSupports(StringRef FeatureStr) const { return llvm::StringSwitch<bool>(FeatureStr) .Case("cmov", true) .Case("mmx", true) .Case("popcnt", true) .Case("sse", true) .Case("sse2", true) .Case("sse3", true) .Case("sse4.1", true) .Case("sse4.2", true) .Case("avx", true) .Case("avx2", true) .Case("sse4a", true) .Case("fma4", true) .Case("xop", true) .Case("fma", true) .Case("avx512f", true) .Case("bmi", true) .Case("bmi2", true) .Default(false); } bool X86TargetInfo::validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const { switch (*Name) { default: return false; case 'I': Info.setRequiresImmediate(0, 31); return true; case 'J': Info.setRequiresImmediate(0, 63); return true; case 'K': Info.setRequiresImmediate(-128, 127); return true; case 'L': // FIXME: properly analyze this constraint: // must be one of 0xff, 0xffff, or 0xffffffff return true; case 'M': Info.setRequiresImmediate(0, 3); return true; case 'N': Info.setRequiresImmediate(0, 255); return true; case 'O': Info.setRequiresImmediate(0, 127); return true; case 'Y': // first letter of a pair: switch (*(Name+1)) { default: return false; case '0': // First SSE register. case 't': // Any SSE register, when SSE2 is enabled. case 'i': // Any SSE register, when SSE2 and inter-unit moves enabled. case 'm': // any MMX register, when inter-unit moves enabled. break; // falls through to setAllowsRegister. } case 'f': // any x87 floating point stack register. // Constraint 'f' cannot be used for output operands. if (Info.ConstraintStr[0] == '=') return false; Info.setAllowsRegister(); return true; case 'a': // eax. case 'b': // ebx. case 'c': // ecx. case 'd': // edx. case 'S': // esi. case 'D': // edi. case 'A': // edx:eax. case 't': // top of floating point stack. case 'u': // second from top of floating point stack. case 'q': // Any register accessible as [r]l: a, b, c, and d. case 'y': // Any MMX register. case 'x': // Any SSE register. case 'Q': // Any register accessible as [r]h: a, b, c, and d. case 'R': // "Legacy" registers: ax, bx, cx, dx, di, si, sp, bp. case 'l': // "Index" registers: any general register that can be used as an // index in a base+index memory access. Info.setAllowsRegister(); return true; case 'C': // SSE floating point constant. case 'G': // x87 floating point constant. case 'e': // 32-bit signed integer constant for use with zero-extending // x86_64 instructions. case 'Z': // 32-bit unsigned integer constant for use with zero-extending // x86_64 instructions. return true; } } bool X86TargetInfo::validateOutputSize(StringRef Constraint, unsigned Size) const { // Strip off constraint modifiers. while (Constraint[0] == '=' || Constraint[0] == '+' || Constraint[0] == '&') Constraint = Constraint.substr(1); return validateOperandSize(Constraint, Size); } bool X86TargetInfo::validateInputSize(StringRef Constraint, unsigned Size) const { return validateOperandSize(Constraint, Size); } bool X86TargetInfo::validateOperandSize(StringRef Constraint, unsigned Size) const { switch (Constraint[0]) { default: break; case 'y': return Size <= 64; case 'f': case 't': case 'u': return Size <= 128; case 'x': // 256-bit ymm registers can be used if target supports AVX. return Size <= (SSELevel >= AVX ? 256U : 128U); } return true; } std::string X86TargetInfo::convertConstraint(const char *&Constraint) const { switch (*Constraint) { case 'a': return std::string("{ax}"); case 'b': return std::string("{bx}"); case 'c': return std::string("{cx}"); case 'd': return std::string("{dx}"); case 'S': return std::string("{si}"); case 'D': return std::string("{di}"); case 'p': // address return std::string("im"); case 't': // top of floating point stack. return std::string("{st}"); case 'u': // second from top of floating point stack. return std::string("{st(1)}"); // second from top of floating point stack. default: return std::string(1, *Constraint); } } // X86-32 generic target class X86_32TargetInfo : public X86TargetInfo { public: X86_32TargetInfo(const llvm::Triple &Triple) : X86TargetInfo(Triple) { DoubleAlign = LongLongAlign = 32; LongDoubleWidth = 96; LongDoubleAlign = 32; SuitableAlign = 128; DescriptionString = "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128"; SizeType = UnsignedInt; PtrDiffType = SignedInt; IntPtrType = SignedInt; RegParmMax = 3; // Use fpret for all types. RealTypeUsesObjCFPRet = ((1 << TargetInfo::Float) | (1 << TargetInfo::Double) | (1 << TargetInfo::LongDouble)); // x86-32 has atomics up to 8 bytes // FIXME: Check that we actually have cmpxchg8b before setting // MaxAtomicInlineWidth. (cmpxchg8b is an i586 instruction.) MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::CharPtrBuiltinVaList; } int getEHDataRegisterNumber(unsigned RegNo) const override { if (RegNo == 0) return 0; if (RegNo == 1) return 2; return -1; } bool validateOperandSize(StringRef Constraint, unsigned Size) const override { switch (Constraint[0]) { default: break; case 'R': case 'q': case 'Q': case 'a': case 'b': case 'c': case 'd': case 'S': case 'D': return Size <= 32; case 'A': return Size <= 64; } return X86TargetInfo::validateOperandSize(Constraint, Size); } }; class NetBSDI386TargetInfo : public NetBSDTargetInfo<X86_32TargetInfo> { public: NetBSDI386TargetInfo(const llvm::Triple &Triple) : NetBSDTargetInfo<X86_32TargetInfo>(Triple) {} unsigned getFloatEvalMethod() const override { unsigned Major, Minor, Micro; getTriple().getOSVersion(Major, Minor, Micro); // New NetBSD uses the default rounding mode. if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 26) || Major == 0) return X86_32TargetInfo::getFloatEvalMethod(); // NetBSD before 6.99.26 defaults to "double" rounding. return 1; } }; class OpenBSDI386TargetInfo : public OpenBSDTargetInfo<X86_32TargetInfo> { public: OpenBSDI386TargetInfo(const llvm::Triple &Triple) : OpenBSDTargetInfo<X86_32TargetInfo>(Triple) { SizeType = UnsignedLong; IntPtrType = SignedLong; PtrDiffType = SignedLong; } }; class BitrigI386TargetInfo : public BitrigTargetInfo<X86_32TargetInfo> { public: BitrigI386TargetInfo(const llvm::Triple &Triple) : BitrigTargetInfo<X86_32TargetInfo>(Triple) { SizeType = UnsignedLong; IntPtrType = SignedLong; PtrDiffType = SignedLong; } }; class DarwinI386TargetInfo : public DarwinTargetInfo<X86_32TargetInfo> { public: DarwinI386TargetInfo(const llvm::Triple &Triple) : DarwinTargetInfo<X86_32TargetInfo>(Triple) { LongDoubleWidth = 128; LongDoubleAlign = 128; SuitableAlign = 128; MaxVectorAlign = 256; SizeType = UnsignedLong; IntPtrType = SignedLong; DescriptionString = "e-m:o-p:32:32-f64:32:64-f80:128-n8:16:32-S128"; HasAlignMac68kSupport = true; } }; // x86-32 Windows target class WindowsX86_32TargetInfo : public WindowsTargetInfo<X86_32TargetInfo> { public: WindowsX86_32TargetInfo(const llvm::Triple &Triple) : WindowsTargetInfo<X86_32TargetInfo>(Triple) { WCharType = UnsignedShort; DoubleAlign = LongLongAlign = 64; bool IsWinCOFF = getTriple().isOSWindows() && getTriple().isOSBinFormatCOFF(); DescriptionString = IsWinCOFF ? "e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32" : "e-m:e-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32"; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { WindowsTargetInfo<X86_32TargetInfo>::getTargetDefines(Opts, Builder); } }; // x86-32 Windows Visual Studio target class MicrosoftX86_32TargetInfo : public WindowsX86_32TargetInfo { public: MicrosoftX86_32TargetInfo(const llvm::Triple &Triple) : WindowsX86_32TargetInfo(Triple) { LongDoubleWidth = LongDoubleAlign = 64; LongDoubleFormat = &llvm::APFloat::IEEEdouble; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { WindowsX86_32TargetInfo::getTargetDefines(Opts, Builder); WindowsX86_32TargetInfo::getVisualStudioDefines(Opts, Builder); // The value of the following reflects processor type. // 300=386, 400=486, 500=Pentium, 600=Blend (default) // We lost the original triple, so we use the default. Builder.defineMacro("_M_IX86", "600"); } }; } // end anonymous namespace static void addCygMingDefines(const LangOptions &Opts, MacroBuilder &Builder) { // Mingw and cygwin define __declspec(a) to __attribute__((a)). Clang supports // __declspec natively under -fms-extensions, but we define a no-op __declspec // macro anyway for pre-processor compatibility. if (Opts.MicrosoftExt) Builder.defineMacro("__declspec", "__declspec"); else Builder.defineMacro("__declspec(a)", "__attribute__((a))"); if (!Opts.MicrosoftExt) { // Provide macros for all the calling convention keywords. Provide both // single and double underscore prefixed variants. These are available on // x64 as well as x86, even though they have no effect. const char *CCs[] = {"cdecl", "stdcall", "fastcall", "thiscall", "pascal"}; for (const char *CC : CCs) { std::string GCCSpelling = "__attribute__((__"; GCCSpelling += CC; GCCSpelling += "__))"; Builder.defineMacro(Twine("_") + CC, GCCSpelling); Builder.defineMacro(Twine("__") + CC, GCCSpelling); } } } static void addMinGWDefines(const LangOptions &Opts, MacroBuilder &Builder) { Builder.defineMacro("__MSVCRT__"); Builder.defineMacro("__MINGW32__"); addCygMingDefines(Opts, Builder); } namespace { // x86-32 MinGW target class MinGWX86_32TargetInfo : public WindowsX86_32TargetInfo { public: MinGWX86_32TargetInfo(const llvm::Triple &Triple) : WindowsX86_32TargetInfo(Triple) {} void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { WindowsX86_32TargetInfo::getTargetDefines(Opts, Builder); DefineStd(Builder, "WIN32", Opts); DefineStd(Builder, "WINNT", Opts); Builder.defineMacro("_X86_"); addMinGWDefines(Opts, Builder); } }; // x86-32 Cygwin target class CygwinX86_32TargetInfo : public X86_32TargetInfo { public: CygwinX86_32TargetInfo(const llvm::Triple &Triple) : X86_32TargetInfo(Triple) { TLSSupported = false; WCharType = UnsignedShort; DoubleAlign = LongLongAlign = 64; DescriptionString = "e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32"; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { X86_32TargetInfo::getTargetDefines(Opts, Builder); Builder.defineMacro("_X86_"); Builder.defineMacro("__CYGWIN__"); Builder.defineMacro("__CYGWIN32__"); addCygMingDefines(Opts, Builder); DefineStd(Builder, "unix", Opts); if (Opts.CPlusPlus) Builder.defineMacro("_GNU_SOURCE"); } }; // x86-32 Haiku target class HaikuX86_32TargetInfo : public X86_32TargetInfo { public: HaikuX86_32TargetInfo(const llvm::Triple &Triple) : X86_32TargetInfo(Triple) { SizeType = UnsignedLong; IntPtrType = SignedLong; PtrDiffType = SignedLong; ProcessIDType = SignedLong; this->UserLabelPrefix = ""; this->TLSSupported = false; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { X86_32TargetInfo::getTargetDefines(Opts, Builder); Builder.defineMacro("__INTEL__"); Builder.defineMacro("__HAIKU__"); } }; // RTEMS Target template<typename Target> class RTEMSTargetInfo : public OSTargetInfo<Target> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { // RTEMS defines; list based off of gcc output Builder.defineMacro("__rtems__"); Builder.defineMacro("__ELF__"); } public: RTEMSTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) { this->UserLabelPrefix = ""; switch (Triple.getArch()) { default: case llvm::Triple::x86: // this->MCountName = ".mcount"; break; case llvm::Triple::mips: case llvm::Triple::mipsel: case llvm::Triple::ppc: case llvm::Triple::ppc64: case llvm::Triple::ppc64le: // this->MCountName = "_mcount"; break; case llvm::Triple::arm: // this->MCountName = "__mcount"; break; } } }; // x86-32 RTEMS target class RTEMSX86_32TargetInfo : public X86_32TargetInfo { public: RTEMSX86_32TargetInfo(const llvm::Triple &Triple) : X86_32TargetInfo(Triple) { SizeType = UnsignedLong; IntPtrType = SignedLong; PtrDiffType = SignedLong; this->UserLabelPrefix = ""; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { X86_32TargetInfo::getTargetDefines(Opts, Builder); Builder.defineMacro("__INTEL__"); Builder.defineMacro("__rtems__"); } }; // x86-64 generic target class X86_64TargetInfo : public X86TargetInfo { public: X86_64TargetInfo(const llvm::Triple &Triple) : X86TargetInfo(Triple) { const bool IsX32 = getTriple().getEnvironment() == llvm::Triple::GNUX32; bool IsWinCOFF = getTriple().isOSWindows() && getTriple().isOSBinFormatCOFF(); LongWidth = LongAlign = PointerWidth = PointerAlign = IsX32 ? 32 : 64; LongDoubleWidth = 128; LongDoubleAlign = 128; LargeArrayMinWidth = 128; LargeArrayAlign = 128; SuitableAlign = 128; SizeType = IsX32 ? UnsignedInt : UnsignedLong; PtrDiffType = IsX32 ? SignedInt : SignedLong; IntPtrType = IsX32 ? SignedInt : SignedLong; IntMaxType = IsX32 ? SignedLongLong : SignedLong; Int64Type = IsX32 ? SignedLongLong : SignedLong; RegParmMax = 6; // Pointers are 32-bit in x32. DescriptionString = IsX32 ? "e-m:e-p:32:32-i64:64-f80:128-n8:16:32:64-S128" : IsWinCOFF ? "e-m:w-i64:64-f80:128-n8:16:32:64-S128" : "e-m:e-i64:64-f80:128-n8:16:32:64-S128"; // Use fpret only for long double. RealTypeUsesObjCFPRet = (1 << TargetInfo::LongDouble); // Use fp2ret for _Complex long double. ComplexLongDoubleUsesFP2Ret = true; // x86-64 has atomics up to 16 bytes. MaxAtomicPromoteWidth = 128; MaxAtomicInlineWidth = 128; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::X86_64ABIBuiltinVaList; } int getEHDataRegisterNumber(unsigned RegNo) const override { if (RegNo == 0) return 0; if (RegNo == 1) return 1; return -1; } CallingConvCheckResult checkCallingConvention(CallingConv CC) const override { return (CC == CC_C || CC == CC_X86VectorCall || CC == CC_IntelOclBicc || CC == CC_X86_64Win64) ? CCCR_OK : CCCR_Warning; } CallingConv getDefaultCallingConv(CallingConvMethodType MT) const override { return CC_C; } // for x32 we need it here explicitly bool hasInt128Type() const override { return true; } }; // x86-64 Windows target class WindowsX86_64TargetInfo : public WindowsTargetInfo<X86_64TargetInfo> { public: WindowsX86_64TargetInfo(const llvm::Triple &Triple) : WindowsTargetInfo<X86_64TargetInfo>(Triple) { WCharType = UnsignedShort; LongWidth = LongAlign = 32; DoubleAlign = LongLongAlign = 64; IntMaxType = SignedLongLong; Int64Type = SignedLongLong; SizeType = UnsignedLongLong; PtrDiffType = SignedLongLong; IntPtrType = SignedLongLong; this->UserLabelPrefix = ""; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { WindowsTargetInfo<X86_64TargetInfo>::getTargetDefines(Opts, Builder); Builder.defineMacro("_WIN64"); } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::CharPtrBuiltinVaList; } CallingConvCheckResult checkCallingConvention(CallingConv CC) const override { switch (CC) { case CC_X86StdCall: case CC_X86ThisCall: case CC_X86FastCall: return CCCR_Ignore; case CC_C: case CC_X86VectorCall: case CC_IntelOclBicc: case CC_X86_64SysV: return CCCR_OK; default: return CCCR_Warning; } } }; // x86-64 Windows Visual Studio target class MicrosoftX86_64TargetInfo : public WindowsX86_64TargetInfo { public: MicrosoftX86_64TargetInfo(const llvm::Triple &Triple) : WindowsX86_64TargetInfo(Triple) { LongDoubleWidth = LongDoubleAlign = 64; LongDoubleFormat = &llvm::APFloat::IEEEdouble; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { WindowsX86_64TargetInfo::getTargetDefines(Opts, Builder); WindowsX86_64TargetInfo::getVisualStudioDefines(Opts, Builder); Builder.defineMacro("_M_X64"); Builder.defineMacro("_M_AMD64"); } }; // x86-64 MinGW target class MinGWX86_64TargetInfo : public WindowsX86_64TargetInfo { public: MinGWX86_64TargetInfo(const llvm::Triple &Triple) : WindowsX86_64TargetInfo(Triple) {} void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { WindowsX86_64TargetInfo::getTargetDefines(Opts, Builder); DefineStd(Builder, "WIN64", Opts); Builder.defineMacro("__MINGW64__"); addMinGWDefines(Opts, Builder); // GCC defines this macro when it is using __gxx_personality_seh0. if (!Opts.SjLjExceptions) Builder.defineMacro("__SEH__"); } }; class DarwinX86_64TargetInfo : public DarwinTargetInfo<X86_64TargetInfo> { public: DarwinX86_64TargetInfo(const llvm::Triple &Triple) : DarwinTargetInfo<X86_64TargetInfo>(Triple) { Int64Type = SignedLongLong; MaxVectorAlign = 256; // The 64-bit iOS simulator uses the builtin bool type for Objective-C. llvm::Triple T = llvm::Triple(Triple); if (T.isiOS()) UseSignedCharForObjCBool = false; DescriptionString = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"; } }; class OpenBSDX86_64TargetInfo : public OpenBSDTargetInfo<X86_64TargetInfo> { public: OpenBSDX86_64TargetInfo(const llvm::Triple &Triple) : OpenBSDTargetInfo<X86_64TargetInfo>(Triple) { IntMaxType = SignedLongLong; Int64Type = SignedLongLong; } }; class BitrigX86_64TargetInfo : public BitrigTargetInfo<X86_64TargetInfo> { public: BitrigX86_64TargetInfo(const llvm::Triple &Triple) : BitrigTargetInfo<X86_64TargetInfo>(Triple) { IntMaxType = SignedLongLong; Int64Type = SignedLongLong; } }; class ARMTargetInfo : public TargetInfo { // Possible FPU choices. enum FPUMode { VFP2FPU = (1 << 0), VFP3FPU = (1 << 1), VFP4FPU = (1 << 2), NeonFPU = (1 << 3), FPARMV8 = (1 << 4) }; // Possible HWDiv features. enum HWDivMode { HWDivThumb = (1 << 0), HWDivARM = (1 << 1) }; static bool FPUModeIsVFP(FPUMode Mode) { return Mode & (VFP2FPU | VFP3FPU | VFP4FPU | NeonFPU | FPARMV8); } static const TargetInfo::GCCRegAlias GCCRegAliases[]; static const char * const GCCRegNames[]; std::string ABI, CPU; enum { FP_Default, FP_VFP, FP_Neon } FPMath; unsigned FPU : 5; unsigned IsAAPCS : 1; unsigned IsThumb : 1; unsigned HWDiv : 2; // Initialized via features. unsigned SoftFloat : 1; unsigned SoftFloatABI : 1; unsigned CRC : 1; unsigned Crypto : 1; // ACLE 6.5.1 Hardware floating point enum { HW_FP_HP = (1 << 1), /// half (16-bit) HW_FP_SP = (1 << 2), /// single (32-bit) HW_FP_DP = (1 << 3), /// double (64-bit) }; uint32_t HW_FP; static const Builtin::Info BuiltinInfo[]; static bool shouldUseInlineAtomic(const llvm::Triple &T) { StringRef ArchName = T.getArchName(); if (T.getArch() == llvm::Triple::arm || T.getArch() == llvm::Triple::armeb) { StringRef VersionStr; if (ArchName.startswith("armv")) VersionStr = ArchName.substr(4, 1); else if (ArchName.startswith("armebv")) VersionStr = ArchName.substr(6, 1); else return false; unsigned Version; if (VersionStr.getAsInteger(10, Version)) return false; return Version >= 6; } assert(T.getArch() == llvm::Triple::thumb || T.getArch() == llvm::Triple::thumbeb); StringRef VersionStr; if (ArchName.startswith("thumbv")) VersionStr = ArchName.substr(6, 1); else if (ArchName.startswith("thumbebv")) VersionStr = ArchName.substr(8, 1); else return false; unsigned Version; if (VersionStr.getAsInteger(10, Version)) return false; return Version >= 7; } void setABIAAPCS() { IsAAPCS = true; DoubleAlign = LongLongAlign = LongDoubleAlign = SuitableAlign = 64; const llvm::Triple &T = getTriple(); // size_t is unsigned long on MachO-derived environments, NetBSD and Bitrig. if (T.isOSBinFormatMachO() || T.getOS() == llvm::Triple::NetBSD || T.getOS() == llvm::Triple::Bitrig) SizeType = UnsignedLong; else SizeType = UnsignedInt; switch (T.getOS()) { case llvm::Triple::NetBSD: WCharType = SignedInt; break; case llvm::Triple::Win32: WCharType = UnsignedShort; break; case llvm::Triple::Linux: default: // AAPCS 7.1.1, ARM-Linux ABI 2.4: type of wchar_t is unsigned int. WCharType = UnsignedInt; break; } UseBitFieldTypeAlignment = true; ZeroLengthBitfieldBoundary = 0; // Thumb1 add sp, #imm requires the immediate value be multiple of 4, // so set preferred for small types to 32. if (T.isOSBinFormatMachO()) { DescriptionString = BigEndian ? "E-m:o-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64" : "e-m:o-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64"; } else if (T.isOSWindows()) { assert(!BigEndian && "Windows on ARM does not support big endian"); DescriptionString = "e" "-m:w" "-p:32:32" "-i64:64" "-v128:64:128" "-a:0:32" "-n32" "-S64"; } else if (T.isOSNaCl()) { assert(!BigEndian && "NaCl on ARM does not support big endian"); DescriptionString = "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S128"; } else { DescriptionString = BigEndian ? "E-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64" : "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64"; } // FIXME: Enumerated types are variable width in straight AAPCS. } void setABIAPCS() { const llvm::Triple &T = getTriple(); IsAAPCS = false; DoubleAlign = LongLongAlign = LongDoubleAlign = SuitableAlign = 32; // size_t is unsigned int on FreeBSD. if (T.getOS() == llvm::Triple::FreeBSD) SizeType = UnsignedInt; else SizeType = UnsignedLong; // Revert to using SignedInt on apcs-gnu to comply with existing behaviour. WCharType = SignedInt; // Do not respect the alignment of bit-field types when laying out // structures. This corresponds to PCC_BITFIELD_TYPE_MATTERS in gcc. UseBitFieldTypeAlignment = false; /// gcc forces the alignment to 4 bytes, regardless of the type of the /// zero length bitfield. This corresponds to EMPTY_FIELD_BOUNDARY in /// gcc. ZeroLengthBitfieldBoundary = 32; if (T.isOSBinFormatMachO()) DescriptionString = BigEndian ? "E-m:o-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32" : "e-m:o-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32"; else DescriptionString = BigEndian ? "E-m:e-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32" : "e-m:e-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32"; // FIXME: Override "preferred align" for double and long long. } public: ARMTargetInfo(const llvm::Triple &Triple, bool IsBigEndian) : TargetInfo(Triple), CPU("arm1136j-s"), FPMath(FP_Default), IsAAPCS(true), HW_FP(0) { BigEndian = IsBigEndian; switch (getTriple().getOS()) { case llvm::Triple::NetBSD: PtrDiffType = SignedLong; break; default: PtrDiffType = SignedInt; break; } // {} in inline assembly are neon specifiers, not assembly variant // specifiers. NoAsmVariants = true; // FIXME: Should we just treat this as a feature? IsThumb = getTriple().getArchName().startswith("thumb"); // FIXME: This duplicates code from the driver that sets the -target-abi // option - this code is used if -target-abi isn't passed and should // be unified in some way. if (Triple.isOSBinFormatMachO()) { // The backend is hardwired to assume AAPCS for M-class processors, ensure // the frontend matches that. if (Triple.getEnvironment() == llvm::Triple::EABI || Triple.getOS() == llvm::Triple::UnknownOS || StringRef(CPU).startswith("cortex-m")) { setABI("aapcs"); } else { setABI("apcs-gnu"); } } else if (Triple.isOSWindows()) { // FIXME: this is invalid for WindowsCE setABI("aapcs"); } else { // Select the default based on the platform. switch (Triple.getEnvironment()) { case llvm::Triple::Android: case llvm::Triple::GNUEABI: case llvm::Triple::GNUEABIHF: setABI("aapcs-linux"); break; case llvm::Triple::EABIHF: case llvm::Triple::EABI: setABI("aapcs"); break; case llvm::Triple::GNU: setABI("apcs-gnu"); break; default: if (Triple.getOS() == llvm::Triple::NetBSD) setABI("apcs-gnu"); else setABI("aapcs"); break; } } // ARM targets default to using the ARM C++ ABI. TheCXXABI.set(TargetCXXABI::GenericARM); // ARM has atomics up to 8 bytes MaxAtomicPromoteWidth = 64; if (shouldUseInlineAtomic(getTriple())) MaxAtomicInlineWidth = 64; // Do force alignment of members that follow zero length bitfields. If // the alignment of the zero-length bitfield is greater than the member // that follows it, `bar', `bar' will be aligned as the type of the // zero length bitfield. UseZeroLengthBitfieldAlignment = true; } StringRef getABI() const override { return ABI; } bool setABI(const std::string &Name) override { ABI = Name; // The defaults (above) are for AAPCS, check if we need to change them. // // FIXME: We need support for -meabi... we could just mangle it into the // name. if (Name == "apcs-gnu") { setABIAPCS(); return true; } if (Name == "aapcs" || Name == "aapcs-vfp" || Name == "aapcs-linux") { setABIAAPCS(); return true; } return false; } // FIXME: This should be based on Arch attributes, not CPU names. void getDefaultFeatures(llvm::StringMap<bool> &Features) const override { StringRef ArchName = getTriple().getArchName(); unsigned ArchKind = llvm::ARMTargetParser::parseArch(ArchName); bool IsV8 = (ArchKind == llvm::ARM::AK_ARMV8A || ArchKind == llvm::ARM::AK_ARMV8_1A); if (CPU == "arm1136jf-s" || CPU == "arm1176jzf-s" || CPU == "mpcore") Features["vfp2"] = true; else if (CPU == "cortex-a8" || CPU == "cortex-a9") { Features["vfp3"] = true; Features["neon"] = true; } else if (CPU == "cortex-a5") { Features["vfp4"] = true; Features["neon"] = true; } else if (CPU == "swift" || CPU == "cortex-a7" || CPU == "cortex-a12" || CPU == "cortex-a15" || CPU == "cortex-a17" || CPU == "krait") { Features["vfp4"] = true; Features["neon"] = true; Features["hwdiv"] = true; Features["hwdiv-arm"] = true; } else if (CPU == "cyclone" || CPU == "cortex-a53" || CPU == "cortex-a57" || CPU == "cortex-a72") { Features["fp-armv8"] = true; Features["neon"] = true; Features["hwdiv"] = true; Features["hwdiv-arm"] = true; Features["crc"] = true; Features["crypto"] = true; } else if (CPU == "cortex-r5" || CPU == "cortex-r7" || IsV8) { Features["hwdiv"] = true; Features["hwdiv-arm"] = true; } else if (CPU == "cortex-m3" || CPU == "cortex-m4" || CPU == "cortex-m7" || CPU == "sc300" || CPU == "cortex-r4" || CPU == "cortex-r4f") { Features["hwdiv"] = true; } } bool handleTargetFeatures(std::vector<std::string> &Features, DiagnosticsEngine &Diags) override { FPU = 0; CRC = 0; Crypto = 0; SoftFloat = SoftFloatABI = false; HWDiv = 0; // This does not diagnose illegal cases like having both // "+vfpv2" and "+vfpv3" or having "+neon" and "+fp-only-sp". uint32_t HW_FP_remove = 0; for (const auto &Feature : Features) { if (Feature == "+soft-float") { SoftFloat = true; } else if (Feature == "+soft-float-abi") { SoftFloatABI = true; } else if (Feature == "+vfp2") { FPU |= VFP2FPU; HW_FP |= HW_FP_SP | HW_FP_DP; } else if (Feature == "+vfp3") { FPU |= VFP3FPU; HW_FP |= HW_FP_SP | HW_FP_DP; } else if (Feature == "+vfp4") { FPU |= VFP4FPU; HW_FP |= HW_FP_SP | HW_FP_DP | HW_FP_HP; } else if (Feature == "+fp-armv8") { FPU |= FPARMV8; HW_FP |= HW_FP_SP | HW_FP_DP | HW_FP_HP; } else if (Feature == "+neon") { FPU |= NeonFPU; HW_FP |= HW_FP_SP | HW_FP_DP; } else if (Feature == "+hwdiv") { HWDiv |= HWDivThumb; } else if (Feature == "+hwdiv-arm") { HWDiv |= HWDivARM; } else if (Feature == "+crc") { CRC = 1; } else if (Feature == "+crypto") { Crypto = 1; } else if (Feature == "+fp-only-sp") { HW_FP_remove |= HW_FP_DP | HW_FP_HP; } } HW_FP &= ~HW_FP_remove; if (!(FPU & NeonFPU) && FPMath == FP_Neon) { Diags.Report(diag::err_target_unsupported_fpmath) << "neon"; return false; } if (FPMath == FP_Neon) Features.push_back("+neonfp"); else if (FPMath == FP_VFP) Features.push_back("-neonfp"); // Remove front-end specific options which the backend handles differently. auto Feature = std::find(Features.begin(), Features.end(), "+soft-float-abi"); if (Feature != Features.end()) Features.erase(Feature); return true; } bool hasFeature(StringRef Feature) const override { return llvm::StringSwitch<bool>(Feature) .Case("arm", true) .Case("softfloat", SoftFloat) .Case("thumb", IsThumb) .Case("neon", (FPU & NeonFPU) && !SoftFloat) .Case("hwdiv", HWDiv & HWDivThumb) .Case("hwdiv-arm", HWDiv & HWDivARM) .Default(false); } const char *getCPUDefineSuffix(StringRef Name) const { if(Name == "generic") { auto subarch = getTriple().getSubArch(); switch (subarch) { case llvm::Triple::SubArchType::ARMSubArch_v8_1a: return "8_1A"; default: break; } } unsigned ArchKind = llvm::ARMTargetParser::parseCPUArch(Name); if (ArchKind == llvm::ARM::AK_INVALID) return ""; // For most sub-arches, the build attribute CPU name is enough. // For Cortex variants, it's slightly different. switch(ArchKind) { default: return llvm::ARMTargetParser::getCPUAttr(ArchKind); case llvm::ARM::AK_ARMV6M: case llvm::ARM::AK_ARMV6SM: return "6M"; case llvm::ARM::AK_ARMV7: case llvm::ARM::AK_ARMV7A: case llvm::ARM::AK_ARMV7S: return "7A"; case llvm::ARM::AK_ARMV7R: return "7R"; case llvm::ARM::AK_ARMV7M: return "7M"; case llvm::ARM::AK_ARMV7EM: return "7EM"; case llvm::ARM::AK_ARMV8A: return "8A"; case llvm::ARM::AK_ARMV8_1A: return "8_1A"; } } const char *getCPUProfile(StringRef Name) const { if(Name == "generic") { auto subarch = getTriple().getSubArch(); switch (subarch) { case llvm::Triple::SubArchType::ARMSubArch_v8_1a: return "A"; default: break; } } unsigned CPUArch = llvm::ARMTargetParser::parseCPUArch(Name); if (CPUArch == llvm::ARM::AK_INVALID) return ""; StringRef ArchName = llvm::ARMTargetParser::getArchName(CPUArch); switch(llvm::ARMTargetParser::parseArchProfile(ArchName)) { case llvm::ARM::PK_A: return "A"; case llvm::ARM::PK_R: return "R"; case llvm::ARM::PK_M: return "M"; default: return ""; } } bool setCPU(const std::string &Name) override { if (!getCPUDefineSuffix(Name)) return false; // Cortex M does not support 8 byte atomics, while general Thumb2 does. StringRef Profile = getCPUProfile(Name); if (Profile == "M" && MaxAtomicInlineWidth) { MaxAtomicPromoteWidth = 32; MaxAtomicInlineWidth = 32; } CPU = Name; return true; } bool setFPMath(StringRef Name) override; bool supportsThumb(StringRef ArchName, StringRef CPUArch, unsigned CPUArchVer) const { return CPUArchVer >= 7 || (CPUArch.find('T') != StringRef::npos) || (CPUArch.find('M') != StringRef::npos); } bool supportsThumb2(StringRef ArchName, StringRef CPUArch, unsigned CPUArchVer) const { // We check both CPUArchVer and ArchName because when only triple is // specified, the default CPU is arm1136j-s. return ArchName.endswith("v6t2") || ArchName.endswith("v7") || ArchName.endswith("v8.1a") || ArchName.endswith("v8") || CPUArch == "6T2" || CPUArchVer >= 7; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { // Target identification. Builder.defineMacro("__arm"); Builder.defineMacro("__arm__"); // Target properties. Builder.defineMacro("__REGISTER_PREFIX__", ""); StringRef CPUArch = getCPUDefineSuffix(CPU); unsigned int CPUArchVer; if (CPUArch.substr(0, 1).getAsInteger<unsigned int>(10, CPUArchVer)) llvm_unreachable("Invalid char for architecture version number"); Builder.defineMacro("__ARM_ARCH_" + CPUArch + "__"); // ACLE 6.4.1 ARM/Thumb instruction set architecture StringRef CPUProfile = getCPUProfile(CPU); StringRef ArchName = getTriple().getArchName(); // __ARM_ARCH is defined as an integer value indicating the current ARM ISA Builder.defineMacro("__ARM_ARCH", CPUArch.substr(0, 1)); if (CPUArch[0] >= '8') { Builder.defineMacro("__ARM_FEATURE_NUMERIC_MAXMIN"); Builder.defineMacro("__ARM_FEATURE_DIRECTED_ROUNDING"); } // __ARM_ARCH_ISA_ARM is defined to 1 if the core supports the ARM ISA. It // is not defined for the M-profile. // NOTE that the deffault profile is assumed to be 'A' if (CPUProfile.empty() || CPUProfile != "M") Builder.defineMacro("__ARM_ARCH_ISA_ARM", "1"); // __ARM_ARCH_ISA_THUMB is defined to 1 if the core supporst the original // Thumb ISA (including v6-M). It is set to 2 if the core supports the // Thumb-2 ISA as found in the v6T2 architecture and all v7 architecture. if (supportsThumb2(ArchName, CPUArch, CPUArchVer)) Builder.defineMacro("__ARM_ARCH_ISA_THUMB", "2"); else if (supportsThumb(ArchName, CPUArch, CPUArchVer)) Builder.defineMacro("__ARM_ARCH_ISA_THUMB", "1"); // __ARM_32BIT_STATE is defined to 1 if code is being generated for a 32-bit // instruction set such as ARM or Thumb. Builder.defineMacro("__ARM_32BIT_STATE", "1"); // ACLE 6.4.2 Architectural Profile (A, R, M or pre-Cortex) // __ARM_ARCH_PROFILE is defined as 'A', 'R', 'M' or 'S', or unset. if (!CPUProfile.empty()) Builder.defineMacro("__ARM_ARCH_PROFILE", "'" + CPUProfile + "'"); // ACLE 6.5.1 Hardware Floating Point if (HW_FP) Builder.defineMacro("__ARM_FP", "0x" + llvm::utohexstr(HW_FP)); // ACLE predefines. Builder.defineMacro("__ARM_ACLE", "200"); // Subtarget options. // FIXME: It's more complicated than this and we don't really support // interworking. // Windows on ARM does not "support" interworking if (5 <= CPUArchVer && CPUArchVer <= 8 && !getTriple().isOSWindows()) Builder.defineMacro("__THUMB_INTERWORK__"); if (ABI == "aapcs" || ABI == "aapcs-linux" || ABI == "aapcs-vfp") { // Embedded targets on Darwin follow AAPCS, but not EABI. // Windows on ARM follows AAPCS VFP, but does not conform to EABI. if (!getTriple().isOSDarwin() && !getTriple().isOSWindows()) Builder.defineMacro("__ARM_EABI__"); Builder.defineMacro("__ARM_PCS", "1"); if ((!SoftFloat && !SoftFloatABI) || ABI == "aapcs-vfp") Builder.defineMacro("__ARM_PCS_VFP", "1"); } if (SoftFloat) Builder.defineMacro("__SOFTFP__"); if (CPU == "xscale") Builder.defineMacro("__XSCALE__"); if (IsThumb) { Builder.defineMacro("__THUMBEL__"); Builder.defineMacro("__thumb__"); if (supportsThumb2(ArchName, CPUArch, CPUArchVer)) Builder.defineMacro("__thumb2__"); } if (((HWDiv & HWDivThumb) && IsThumb) || ((HWDiv & HWDivARM) && !IsThumb)) Builder.defineMacro("__ARM_ARCH_EXT_IDIV__", "1"); // Note, this is always on in gcc, even though it doesn't make sense. Builder.defineMacro("__APCS_32__"); if (FPUModeIsVFP((FPUMode) FPU)) { Builder.defineMacro("__VFP_FP__"); if (FPU & VFP2FPU) Builder.defineMacro("__ARM_VFPV2__"); if (FPU & VFP3FPU) Builder.defineMacro("__ARM_VFPV3__"); if (FPU & VFP4FPU) Builder.defineMacro("__ARM_VFPV4__"); } // This only gets set when Neon instructions are actually available, unlike // the VFP define, hence the soft float and arch check. This is subtly // different from gcc, we follow the intent which was that it should be set // when Neon instructions are actually available. if ((FPU & NeonFPU) && !SoftFloat && CPUArchVer >= 7) { Builder.defineMacro("__ARM_NEON"); Builder.defineMacro("__ARM_NEON__"); } Builder.defineMacro("__ARM_SIZEOF_WCHAR_T", Opts.ShortWChar ? "2" : "4"); Builder.defineMacro("__ARM_SIZEOF_MINIMAL_ENUM", Opts.ShortEnums ? "1" : "4"); if (CRC) Builder.defineMacro("__ARM_FEATURE_CRC32"); if (Crypto) Builder.defineMacro("__ARM_FEATURE_CRYPTO"); if (CPUArchVer >= 6 && CPUArch != "6M") { Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8"); } bool is5EOrAbove = (CPUArchVer >= 6 || (CPUArchVer == 5 && CPUArch.find('E') != StringRef::npos)); bool is32Bit = (!IsThumb || supportsThumb2(ArchName, CPUArch, CPUArchVer)); if (is5EOrAbove && is32Bit && (CPUProfile != "M" || CPUArch == "7EM")) Builder.defineMacro("__ARM_FEATURE_DSP"); } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::ARM::LastTSBuiltin-Builtin::FirstTSBuiltin; } bool isCLZForZeroUndef() const override { return false; } BuiltinVaListKind getBuiltinVaListKind() const override { return IsAAPCS ? AAPCSABIBuiltinVaList : TargetInfo::VoidPtrBuiltinVaList; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override; void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override; bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const override { switch (*Name) { default: break; case 'l': // r0-r7 case 'h': // r8-r15 case 'w': // VFP Floating point register single precision case 'P': // VFP Floating point register double precision Info.setAllowsRegister(); return true; case 'I': case 'J': case 'K': case 'L': case 'M': // FIXME return true; case 'Q': // A memory address that is a single base register. Info.setAllowsMemory(); return true; case 'U': // a memory reference... switch (Name[1]) { case 'q': // ...ARMV4 ldrsb case 'v': // ...VFP load/store (reg+constant offset) case 'y': // ...iWMMXt load/store case 't': // address valid for load/store opaque types wider // than 128-bits case 'n': // valid address for Neon doubleword vector load/store case 'm': // valid address for Neon element and structure load/store case 's': // valid address for non-offset loads/stores of quad-word // values in four ARM registers Info.setAllowsMemory(); Name++; return true; } } return false; } std::string convertConstraint(const char *&Constraint) const override { std::string R; switch (*Constraint) { case 'U': // Two-character constraint; add "^" hint for later parsing. R = std::string("^") + std::string(Constraint, 2); Constraint++; break; case 'p': // 'p' should be translated to 'r' by default. R = std::string("r"); break; default: return std::string(1, *Constraint); } return R; } bool validateConstraintModifier(StringRef Constraint, char Modifier, unsigned Size, std::string &SuggestedModifier) const override { bool isOutput = (Constraint[0] == '='); bool isInOut = (Constraint[0] == '+'); // Strip off constraint modifiers. while (Constraint[0] == '=' || Constraint[0] == '+' || Constraint[0] == '&') Constraint = Constraint.substr(1); switch (Constraint[0]) { default: break; case 'r': { switch (Modifier) { default: return (isInOut || isOutput || Size <= 64); case 'q': // A register of size 32 cannot fit a vector type. return false; } } } return true; } const char *getClobbers() const override { // FIXME: Is this really right? return ""; } CallingConvCheckResult checkCallingConvention(CallingConv CC) const override { return (CC == CC_AAPCS || CC == CC_AAPCS_VFP) ? CCCR_OK : CCCR_Warning; } int getEHDataRegisterNumber(unsigned RegNo) const override { if (RegNo == 0) return 0; if (RegNo == 1) return 1; return -1; } }; bool ARMTargetInfo::setFPMath(StringRef Name) { if (Name == "neon") { FPMath = FP_Neon; return true; } else if (Name == "vfp" || Name == "vfp2" || Name == "vfp3" || Name == "vfp4") { FPMath = FP_VFP; return true; } return false; } const char * const ARMTargetInfo::GCCRegNames[] = { // Integer registers "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc", // Float registers "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31", // Double registers "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15", "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23", "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31", // Quad registers "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" }; void ARMTargetInfo::getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } const TargetInfo::GCCRegAlias ARMTargetInfo::GCCRegAliases[] = { { { "a1" }, "r0" }, { { "a2" }, "r1" }, { { "a3" }, "r2" }, { { "a4" }, "r3" }, { { "v1" }, "r4" }, { { "v2" }, "r5" }, { { "v3" }, "r6" }, { { "v4" }, "r7" }, { { "v5" }, "r8" }, { { "v6", "rfp" }, "r9" }, { { "sl" }, "r10" }, { { "fp" }, "r11" }, { { "ip" }, "r12" }, { { "r13" }, "sp" }, { { "r14" }, "lr" }, { { "r15" }, "pc" }, // The S, D and Q registers overlap, but aren't really aliases; we // don't want to substitute one of these for a different-sized one. }; void ARMTargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const { Aliases = GCCRegAliases; NumAliases = llvm::array_lengthof(GCCRegAliases); } const Builtin::Info ARMTargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER,\ ALL_LANGUAGES }, #include "clang/Basic/BuiltinsNEON.def" #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #define LANGBUILTIN(ID, TYPE, ATTRS, LANG) { #ID, TYPE, ATTRS, 0, LANG }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER,\ ALL_LANGUAGES }, #include "clang/Basic/BuiltinsARM.def" }; class ARMleTargetInfo : public ARMTargetInfo { public: ARMleTargetInfo(const llvm::Triple &Triple) : ARMTargetInfo(Triple, false) { } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { Builder.defineMacro("__ARMEL__"); ARMTargetInfo::getTargetDefines(Opts, Builder); } }; class ARMbeTargetInfo : public ARMTargetInfo { public: ARMbeTargetInfo(const llvm::Triple &Triple) : ARMTargetInfo(Triple, true) { } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { Builder.defineMacro("__ARMEB__"); Builder.defineMacro("__ARM_BIG_ENDIAN"); ARMTargetInfo::getTargetDefines(Opts, Builder); } }; class WindowsARMTargetInfo : public WindowsTargetInfo<ARMleTargetInfo> { const llvm::Triple Triple; public: WindowsARMTargetInfo(const llvm::Triple &Triple) : WindowsTargetInfo<ARMleTargetInfo>(Triple), Triple(Triple) { TLSSupported = false; WCharType = UnsignedShort; SizeType = UnsignedInt; UserLabelPrefix = ""; } void getVisualStudioDefines(const LangOptions &Opts, MacroBuilder &Builder) const { WindowsTargetInfo<ARMleTargetInfo>::getVisualStudioDefines(Opts, Builder); // FIXME: this is invalid for WindowsCE Builder.defineMacro("_M_ARM_NT", "1"); Builder.defineMacro("_M_ARMT", "_M_ARM"); Builder.defineMacro("_M_THUMB", "_M_ARM"); assert((Triple.getArch() == llvm::Triple::arm || Triple.getArch() == llvm::Triple::thumb) && "invalid architecture for Windows ARM target info"); unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6; Builder.defineMacro("_M_ARM", Triple.getArchName().substr(Offset)); // TODO map the complete set of values // 31: VFPv3 40: VFPv4 Builder.defineMacro("_M_ARM_FP", "31"); } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::CharPtrBuiltinVaList; } }; // Windows ARM + Itanium C++ ABI Target class ItaniumWindowsARMleTargetInfo : public WindowsARMTargetInfo { public: ItaniumWindowsARMleTargetInfo(const llvm::Triple &Triple) : WindowsARMTargetInfo(Triple) { TheCXXABI.set(TargetCXXABI::GenericARM); } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { WindowsARMTargetInfo::getTargetDefines(Opts, Builder); if (Opts.MSVCCompat) WindowsARMTargetInfo::getVisualStudioDefines(Opts, Builder); } }; // Windows ARM, MS (C++) ABI class MicrosoftARMleTargetInfo : public WindowsARMTargetInfo { public: MicrosoftARMleTargetInfo(const llvm::Triple &Triple) : WindowsARMTargetInfo(Triple) { TheCXXABI.set(TargetCXXABI::Microsoft); } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { WindowsARMTargetInfo::getTargetDefines(Opts, Builder); WindowsARMTargetInfo::getVisualStudioDefines(Opts, Builder); } }; class DarwinARMTargetInfo : public DarwinTargetInfo<ARMleTargetInfo> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { getDarwinDefines(Builder, Opts, Triple, PlatformName, PlatformMinVersion); } public: DarwinARMTargetInfo(const llvm::Triple &Triple) : DarwinTargetInfo<ARMleTargetInfo>(Triple) { HasAlignMac68kSupport = true; // iOS always has 64-bit atomic instructions. // FIXME: This should be based off of the target features in // ARMleTargetInfo. MaxAtomicInlineWidth = 64; // Darwin on iOS uses a variant of the ARM C++ ABI. TheCXXABI.set(TargetCXXABI::iOS); } }; class AArch64TargetInfo : public TargetInfo { virtual void setDescriptionString() = 0; static const TargetInfo::GCCRegAlias GCCRegAliases[]; static const char *const GCCRegNames[]; enum FPUModeEnum { FPUMode, NeonMode }; unsigned FPU; unsigned CRC; unsigned Crypto; static const Builtin::Info BuiltinInfo[]; std::string ABI; public: AArch64TargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple), ABI("aapcs") { if (getTriple().getOS() == llvm::Triple::NetBSD) { WCharType = SignedInt; // NetBSD apparently prefers consistency across ARM targets to consistency // across 64-bit targets. Int64Type = SignedLongLong; IntMaxType = SignedLongLong; } else { WCharType = UnsignedInt; Int64Type = SignedLong; IntMaxType = SignedLong; } LongWidth = LongAlign = PointerWidth = PointerAlign = 64; MaxVectorAlign = 128; MaxAtomicInlineWidth = 128; MaxAtomicPromoteWidth = 128; LongDoubleWidth = LongDoubleAlign = SuitableAlign = 128; LongDoubleFormat = &llvm::APFloat::IEEEquad; // {} in inline assembly are neon specifiers, not assembly variant // specifiers. NoAsmVariants = true; // AAPCS gives rules for bitfields. 7.1.7 says: "The container type // contributes to the alignment of the containing aggregate in the same way // a plain (non bit-field) member of that type would, without exception for // zero-sized or anonymous bit-fields." UseBitFieldTypeAlignment = true; UseZeroLengthBitfieldAlignment = true; // AArch64 targets default to using the ARM C++ ABI. TheCXXABI.set(TargetCXXABI::GenericAArch64); } StringRef getABI() const override { return ABI; } bool setABI(const std::string &Name) override { if (Name != "aapcs" && Name != "darwinpcs") return false; ABI = Name; return true; } bool setCPU(const std::string &Name) override { bool CPUKnown = llvm::StringSwitch<bool>(Name) .Case("generic", true) .Cases("cortex-a53", "cortex-a57", "cortex-a72", true) .Case("cyclone", true) .Default(false); return CPUKnown; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { // Target identification. Builder.defineMacro("__aarch64__"); // Target properties. Builder.defineMacro("_LP64"); Builder.defineMacro("__LP64__"); // ACLE predefines. Many can only have one possible value on v8 AArch64. Builder.defineMacro("__ARM_ACLE", "200"); Builder.defineMacro("__ARM_ARCH", "8"); Builder.defineMacro("__ARM_ARCH_PROFILE", "'A'"); Builder.defineMacro("__ARM_64BIT_STATE"); Builder.defineMacro("__ARM_PCS_AAPCS64"); Builder.defineMacro("__ARM_ARCH_ISA_A64"); Builder.defineMacro("__ARM_FEATURE_UNALIGNED"); Builder.defineMacro("__ARM_FEATURE_CLZ"); Builder.defineMacro("__ARM_FEATURE_FMA"); Builder.defineMacro("__ARM_FEATURE_DIV"); Builder.defineMacro("__ARM_FEATURE_IDIV"); // As specified in ACLE Builder.defineMacro("__ARM_FEATURE_DIV"); // For backwards compatibility Builder.defineMacro("__ARM_FEATURE_NUMERIC_MAXMIN"); Builder.defineMacro("__ARM_FEATURE_DIRECTED_ROUNDING"); Builder.defineMacro("__ARM_ALIGN_MAX_STACK_PWR", "4"); // 0xe implies support for half, single and double precision operations. Builder.defineMacro("__ARM_FP", "0xe"); // PCS specifies this for SysV variants, which is all we support. Other ABIs // may choose __ARM_FP16_FORMAT_ALTERNATIVE. Builder.defineMacro("__ARM_FP16_FORMAT_IEEE"); if (Opts.FastMath || Opts.FiniteMathOnly) Builder.defineMacro("__ARM_FP_FAST"); if (Opts.C99 && !Opts.Freestanding) Builder.defineMacro("__ARM_FP_FENV_ROUNDING"); Builder.defineMacro("__ARM_SIZEOF_WCHAR_T", Opts.ShortWChar ? "2" : "4"); Builder.defineMacro("__ARM_SIZEOF_MINIMAL_ENUM", Opts.ShortEnums ? "1" : "4"); if (FPU == NeonMode) { Builder.defineMacro("__ARM_NEON"); // 64-bit NEON supports half, single and double precision operations. Builder.defineMacro("__ARM_NEON_FP", "0xe"); } if (CRC) Builder.defineMacro("__ARM_FEATURE_CRC32"); if (Crypto) Builder.defineMacro("__ARM_FEATURE_CRYPTO"); // All of the __sync_(bool|val)_compare_and_swap_(1|2|4|8) builtins work. Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4"); Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8"); } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::AArch64::LastTSBuiltin - Builtin::FirstTSBuiltin; } bool hasFeature(StringRef Feature) const override { return Feature == "aarch64" || Feature == "arm64" || (Feature == "neon" && FPU == NeonMode); } bool handleTargetFeatures(std::vector<std::string> &Features, DiagnosticsEngine &Diags) override { FPU = FPUMode; CRC = 0; Crypto = 0; for (unsigned i = 0, e = Features.size(); i != e; ++i) { if (Features[i] == "+neon") FPU = NeonMode; if (Features[i] == "+crc") CRC = 1; if (Features[i] == "+crypto") Crypto = 1; } setDescriptionString(); return true; } bool isCLZForZeroUndef() const override { return false; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::AArch64ABIBuiltinVaList; } void getGCCRegNames(const char *const *&Names, unsigned &NumNames) const override; void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override; bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const override { switch (*Name) { default: return false; case 'w': // Floating point and SIMD registers (V0-V31) Info.setAllowsRegister(); return true; case 'I': // Constant that can be used with an ADD instruction case 'J': // Constant that can be used with a SUB instruction case 'K': // Constant that can be used with a 32-bit logical instruction case 'L': // Constant that can be used with a 64-bit logical instruction case 'M': // Constant that can be used as a 32-bit MOV immediate case 'N': // Constant that can be used as a 64-bit MOV immediate case 'Y': // Floating point constant zero case 'Z': // Integer constant zero return true; case 'Q': // A memory reference with base register and no offset Info.setAllowsMemory(); return true; case 'S': // A symbolic address Info.setAllowsRegister(); return true; case 'U': // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes. // Utf: A memory address suitable for ldp/stp in TF mode. // Usa: An absolute symbolic address. // Ush: The high part (bits 32:12) of a pc-relative symbolic address. llvm_unreachable("FIXME: Unimplemented support for U* constraints."); case 'z': // Zero register, wzr or xzr Info.setAllowsRegister(); return true; case 'x': // Floating point and SIMD registers (V0-V15) Info.setAllowsRegister(); return true; } return false; } bool validateConstraintModifier(StringRef Constraint, char Modifier, unsigned Size, std::string &SuggestedModifier) const override { // Strip off constraint modifiers. while (Constraint[0] == '=' || Constraint[0] == '+' || Constraint[0] == '&') Constraint = Constraint.substr(1); switch (Constraint[0]) { default: return true; case 'z': case 'r': { switch (Modifier) { case 'x': case 'w': // For now assume that the person knows what they're // doing with the modifier. return true; default: // By default an 'r' constraint will be in the 'x' // registers. if (Size == 64) return true; SuggestedModifier = "w"; return false; } } } } const char *getClobbers() const override { return ""; } int getEHDataRegisterNumber(unsigned RegNo) const override { if (RegNo == 0) return 0; if (RegNo == 1) return 1; return -1; } }; const char *const AArch64TargetInfo::GCCRegNames[] = { // 32-bit Integer registers "w0", "w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8", "w9", "w10", "w11", "w12", "w13", "w14", "w15", "w16", "w17", "w18", "w19", "w20", "w21", "w22", "w23", "w24", "w25", "w26", "w27", "w28", "w29", "w30", "wsp", // 64-bit Integer registers "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x18", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "fp", "lr", "sp", // 32-bit floating point regsisters "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31", // 64-bit floating point regsisters "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15", "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23", "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31", // Vector registers "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31" }; void AArch64TargetInfo::getGCCRegNames(const char *const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } const TargetInfo::GCCRegAlias AArch64TargetInfo::GCCRegAliases[] = { { { "w31" }, "wsp" }, { { "x29" }, "fp" }, { { "x30" }, "lr" }, { { "x31" }, "sp" }, // The S/D/Q and W/X registers overlap, but aren't really aliases; we // don't want to substitute one of these for a different-sized one. }; void AArch64TargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const { Aliases = GCCRegAliases; NumAliases = llvm::array_lengthof(GCCRegAliases); } const Builtin::Info AArch64TargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) \ { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #include "clang/Basic/BuiltinsNEON.def" #define BUILTIN(ID, TYPE, ATTRS) \ { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #include "clang/Basic/BuiltinsAArch64.def" }; class AArch64leTargetInfo : public AArch64TargetInfo { void setDescriptionString() override { if (getTriple().isOSBinFormatMachO()) DescriptionString = "e-m:o-i64:64-i128:128-n32:64-S128"; else DescriptionString = "e-m:e-i64:64-i128:128-n32:64-S128"; } public: AArch64leTargetInfo(const llvm::Triple &Triple) : AArch64TargetInfo(Triple) { BigEndian = false; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { Builder.defineMacro("__AARCH64EL__"); AArch64TargetInfo::getTargetDefines(Opts, Builder); } }; class AArch64beTargetInfo : public AArch64TargetInfo { void setDescriptionString() override { assert(!getTriple().isOSBinFormatMachO()); DescriptionString = "E-m:e-i64:64-i128:128-n32:64-S128"; } public: AArch64beTargetInfo(const llvm::Triple &Triple) : AArch64TargetInfo(Triple) { } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { Builder.defineMacro("__AARCH64EB__"); Builder.defineMacro("__AARCH_BIG_ENDIAN"); Builder.defineMacro("__ARM_BIG_ENDIAN"); AArch64TargetInfo::getTargetDefines(Opts, Builder); } }; class DarwinAArch64TargetInfo : public DarwinTargetInfo<AArch64leTargetInfo> { protected: void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple, MacroBuilder &Builder) const override { Builder.defineMacro("__AARCH64_SIMD__"); Builder.defineMacro("__ARM64_ARCH_8__"); Builder.defineMacro("__ARM_NEON__"); Builder.defineMacro("__LITTLE_ENDIAN__"); Builder.defineMacro("__REGISTER_PREFIX__", ""); Builder.defineMacro("__arm64", "1"); Builder.defineMacro("__arm64__", "1"); getDarwinDefines(Builder, Opts, Triple, PlatformName, PlatformMinVersion); } public: DarwinAArch64TargetInfo(const llvm::Triple &Triple) : DarwinTargetInfo<AArch64leTargetInfo>(Triple) { Int64Type = SignedLongLong; WCharType = SignedInt; UseSignedCharForObjCBool = false; LongDoubleWidth = LongDoubleAlign = SuitableAlign = 64; LongDoubleFormat = &llvm::APFloat::IEEEdouble; TheCXXABI.set(TargetCXXABI::iOS64); } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::CharPtrBuiltinVaList; } }; // Hexagon abstract base class class HexagonTargetInfo : public TargetInfo { static const Builtin::Info BuiltinInfo[]; static const char * const GCCRegNames[]; static const TargetInfo::GCCRegAlias GCCRegAliases[]; std::string CPU; public: HexagonTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { BigEndian = false; DescriptionString = "e-m:e-p:32:32-i1:32-i64:64-a:0-n32"; // {} in inline assembly are packet specifiers, not assembly variant // specifiers. NoAsmVariants = true; } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::Hexagon::LastTSBuiltin-Builtin::FirstTSBuiltin; } bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const override { return true; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override; bool hasFeature(StringRef Feature) const override { return Feature == "hexagon"; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::CharPtrBuiltinVaList; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override; void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override; const char *getClobbers() const override { return ""; } static const char *getHexagonCPUSuffix(StringRef Name) { return llvm::StringSwitch<const char*>(Name) .Case("hexagonv4", "4") .Case("hexagonv5", "5") .Default(nullptr); } bool setCPU(const std::string &Name) override { if (!getHexagonCPUSuffix(Name)) return false; CPU = Name; return true; } }; void HexagonTargetInfo::getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const { Builder.defineMacro("qdsp6"); Builder.defineMacro("__qdsp6", "1"); Builder.defineMacro("__qdsp6__", "1"); Builder.defineMacro("hexagon"); Builder.defineMacro("__hexagon", "1"); Builder.defineMacro("__hexagon__", "1"); if(CPU == "hexagonv1") { Builder.defineMacro("__HEXAGON_V1__"); Builder.defineMacro("__HEXAGON_ARCH__", "1"); if(Opts.HexagonQdsp6Compat) { Builder.defineMacro("__QDSP6_V1__"); Builder.defineMacro("__QDSP6_ARCH__", "1"); } } else if(CPU == "hexagonv2") { Builder.defineMacro("__HEXAGON_V2__"); Builder.defineMacro("__HEXAGON_ARCH__", "2"); if(Opts.HexagonQdsp6Compat) { Builder.defineMacro("__QDSP6_V2__"); Builder.defineMacro("__QDSP6_ARCH__", "2"); } } else if(CPU == "hexagonv3") { Builder.defineMacro("__HEXAGON_V3__"); Builder.defineMacro("__HEXAGON_ARCH__", "3"); if(Opts.HexagonQdsp6Compat) { Builder.defineMacro("__QDSP6_V3__"); Builder.defineMacro("__QDSP6_ARCH__", "3"); } } else if(CPU == "hexagonv4") { Builder.defineMacro("__HEXAGON_V4__"); Builder.defineMacro("__HEXAGON_ARCH__", "4"); if(Opts.HexagonQdsp6Compat) { Builder.defineMacro("__QDSP6_V4__"); Builder.defineMacro("__QDSP6_ARCH__", "4"); } } else if(CPU == "hexagonv5") { Builder.defineMacro("__HEXAGON_V5__"); Builder.defineMacro("__HEXAGON_ARCH__", "5"); if(Opts.HexagonQdsp6Compat) { Builder.defineMacro("__QDSP6_V5__"); Builder.defineMacro("__QDSP6_ARCH__", "5"); } } } const char * const HexagonTargetInfo::GCCRegNames[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31", "p0", "p1", "p2", "p3", "sa0", "lc0", "sa1", "lc1", "m0", "m1", "usr", "ugp" }; void HexagonTargetInfo::getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } const TargetInfo::GCCRegAlias HexagonTargetInfo::GCCRegAliases[] = { { { "sp" }, "r29" }, { { "fp" }, "r30" }, { { "lr" }, "r31" }, }; void HexagonTargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const { Aliases = GCCRegAliases; NumAliases = llvm::array_lengthof(GCCRegAliases); } const Builtin::Info HexagonTargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER,\ ALL_LANGUAGES }, #include "clang/Basic/BuiltinsHexagon.def" }; // Shared base class for SPARC v8 (32-bit) and SPARC v9 (64-bit). class SparcTargetInfo : public TargetInfo { static const TargetInfo::GCCRegAlias GCCRegAliases[]; static const char * const GCCRegNames[]; bool SoftFloat; public: SparcTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple), SoftFloat(false) {} bool handleTargetFeatures(std::vector<std::string> &Features, DiagnosticsEngine &Diags) override { // The backend doesn't actually handle soft float yet, but in case someone // is using the support for the front end continue to support it. auto Feature = std::find(Features.begin(), Features.end(), "+soft-float"); if (Feature != Features.end()) { SoftFloat = true; Features.erase(Feature); } return true; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "sparc", Opts); Builder.defineMacro("__REGISTER_PREFIX__", ""); if (SoftFloat) Builder.defineMacro("SOFT_FLOAT", "1"); } bool hasFeature(StringRef Feature) const override { return llvm::StringSwitch<bool>(Feature) .Case("softfloat", SoftFloat) .Case("sparc", true) .Default(false); } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { // FIXME: Implement! } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::VoidPtrBuiltinVaList; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override; void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override; bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override { // FIXME: Implement! switch (*Name) { case 'I': // Signed 13-bit constant case 'J': // Zero case 'K': // 32-bit constant with the low 12 bits clear case 'L': // A constant in the range supported by movcc (11-bit signed imm) case 'M': // A constant in the range supported by movrcc (19-bit signed imm) case 'N': // Same as 'K' but zext (required for SIMode) case 'O': // The constant 4096 return true; } return false; } const char *getClobbers() const override { // FIXME: Implement! return ""; } }; const char * const SparcTargetInfo::GCCRegNames[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31" }; void SparcTargetInfo::getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } const TargetInfo::GCCRegAlias SparcTargetInfo::GCCRegAliases[] = { { { "g0" }, "r0" }, { { "g1" }, "r1" }, { { "g2" }, "r2" }, { { "g3" }, "r3" }, { { "g4" }, "r4" }, { { "g5" }, "r5" }, { { "g6" }, "r6" }, { { "g7" }, "r7" }, { { "o0" }, "r8" }, { { "o1" }, "r9" }, { { "o2" }, "r10" }, { { "o3" }, "r11" }, { { "o4" }, "r12" }, { { "o5" }, "r13" }, { { "o6", "sp" }, "r14" }, { { "o7" }, "r15" }, { { "l0" }, "r16" }, { { "l1" }, "r17" }, { { "l2" }, "r18" }, { { "l3" }, "r19" }, { { "l4" }, "r20" }, { { "l5" }, "r21" }, { { "l6" }, "r22" }, { { "l7" }, "r23" }, { { "i0" }, "r24" }, { { "i1" }, "r25" }, { { "i2" }, "r26" }, { { "i3" }, "r27" }, { { "i4" }, "r28" }, { { "i5" }, "r29" }, { { "i6", "fp" }, "r30" }, { { "i7" }, "r31" }, }; void SparcTargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const { Aliases = GCCRegAliases; NumAliases = llvm::array_lengthof(GCCRegAliases); } // SPARC v8 is the 32-bit mode selected by Triple::sparc. class SparcV8TargetInfo : public SparcTargetInfo { public: SparcV8TargetInfo(const llvm::Triple &Triple) : SparcTargetInfo(Triple) { DescriptionString = "E-m:e-p:32:32-i64:64-f128:64-n32-S64"; // NetBSD uses long (same as llvm default); everyone else uses int. if (getTriple().getOS() == llvm::Triple::NetBSD) { SizeType = UnsignedLong; IntPtrType = SignedLong; PtrDiffType = SignedLong; } else { SizeType = UnsignedInt; IntPtrType = SignedInt; PtrDiffType = SignedInt; } } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { SparcTargetInfo::getTargetDefines(Opts, Builder); Builder.defineMacro("__sparcv8"); } }; // SPARCV8el is the 32-bit little-endian mode selected by Triple::sparcel. class SparcV8elTargetInfo : public SparcV8TargetInfo { public: SparcV8elTargetInfo(const llvm::Triple &Triple) : SparcV8TargetInfo(Triple) { DescriptionString = "e-m:e-p:32:32-i64:64-f128:64-n32-S64"; BigEndian = false; } }; // SPARC v9 is the 64-bit mode selected by Triple::sparcv9. class SparcV9TargetInfo : public SparcTargetInfo { public: SparcV9TargetInfo(const llvm::Triple &Triple) : SparcTargetInfo(Triple) { // FIXME: Support Sparc quad-precision long double? DescriptionString = "E-m:e-i64:64-n32:64-S128"; // This is an LP64 platform. LongWidth = LongAlign = PointerWidth = PointerAlign = 64; // OpenBSD uses long long for int64_t and intmax_t. if (getTriple().getOS() == llvm::Triple::OpenBSD) IntMaxType = SignedLongLong; else IntMaxType = SignedLong; Int64Type = IntMaxType; // The SPARCv8 System V ABI has long double 128-bits in size, but 64-bit // aligned. The SPARCv9 SCD 2.4.1 says 16-byte aligned. LongDoubleWidth = 128; LongDoubleAlign = 128; LongDoubleFormat = &llvm::APFloat::IEEEquad; MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { SparcTargetInfo::getTargetDefines(Opts, Builder); Builder.defineMacro("__sparcv9"); Builder.defineMacro("__arch64__"); // Solaris doesn't need these variants, but the BSDs do. if (getTriple().getOS() != llvm::Triple::Solaris) { Builder.defineMacro("__sparc64__"); Builder.defineMacro("__sparc_v9__"); Builder.defineMacro("__sparcv9__"); } } bool setCPU(const std::string &Name) override { bool CPUKnown = llvm::StringSwitch<bool>(Name) .Case("v9", true) .Case("ultrasparc", true) .Case("ultrasparc3", true) .Case("niagara", true) .Case("niagara2", true) .Case("niagara3", true) .Case("niagara4", true) .Default(false); // No need to store the CPU yet. There aren't any CPU-specific // macros to define. return CPUKnown; } }; class SystemZTargetInfo : public TargetInfo { static const Builtin::Info BuiltinInfo[]; static const char *const GCCRegNames[]; std::string CPU; bool HasTransactionalExecution; bool HasVector; public: SystemZTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple), CPU("z10"), HasTransactionalExecution(false), HasVector(false) { IntMaxType = SignedLong; Int64Type = SignedLong; TLSSupported = true; IntWidth = IntAlign = 32; LongWidth = LongLongWidth = LongAlign = LongLongAlign = 64; PointerWidth = PointerAlign = 64; LongDoubleWidth = 128; LongDoubleAlign = 64; LongDoubleFormat = &llvm::APFloat::IEEEquad; DefaultAlignForAttributeAligned = 64; MinGlobalAlign = 16; DescriptionString = "E-m:e-i1:8:16-i8:8:16-i64:64-f128:64-a:8:16-n32:64"; MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { Builder.defineMacro("__s390__"); Builder.defineMacro("__s390x__"); Builder.defineMacro("__zarch__"); Builder.defineMacro("__LONG_DOUBLE_128__"); if (HasTransactionalExecution) Builder.defineMacro("__HTM__"); if (Opts.ZVector) Builder.defineMacro("__VEC__", "10301"); } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::SystemZ::LastTSBuiltin-Builtin::FirstTSBuiltin; } void getGCCRegNames(const char *const *&Names, unsigned &NumNames) const override; void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override { // No aliases. Aliases = nullptr; NumAliases = 0; } bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override; const char *getClobbers() const override { // FIXME: Is this really right? return ""; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::SystemZBuiltinVaList; } bool setCPU(const std::string &Name) override { CPU = Name; bool CPUKnown = llvm::StringSwitch<bool>(Name) .Case("z10", true) .Case("z196", true) .Case("zEC12", true) .Case("z13", true) .Default(false); return CPUKnown; } void getDefaultFeatures(llvm::StringMap<bool> &Features) const override { if (CPU == "zEC12") Features["transactional-execution"] = true; if (CPU == "z13") { Features["transactional-execution"] = true; Features["vector"] = true; } } bool handleTargetFeatures(std::vector<std::string> &Features, DiagnosticsEngine &Diags) override { HasTransactionalExecution = false; for (unsigned i = 0, e = Features.size(); i != e; ++i) { if (Features[i] == "+transactional-execution") HasTransactionalExecution = true; if (Features[i] == "+vector") HasVector = true; } // If we use the vector ABI, vector types are 64-bit aligned. if (HasVector) { MaxVectorAlign = 64; DescriptionString = "E-m:e-i1:8:16-i8:8:16-i64:64-f128:64" "-v128:64-a:8:16-n32:64"; } return true; } bool hasFeature(StringRef Feature) const override { return llvm::StringSwitch<bool>(Feature) .Case("systemz", true) .Case("htm", HasTransactionalExecution) .Case("vx", HasVector) .Default(false); } StringRef getABI() const override { if (HasVector) return "vector"; return ""; } bool useFloat128ManglingForLongDouble() const override { return true; } }; const Builtin::Info SystemZTargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) \ { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #include "clang/Basic/BuiltinsSystemZ.def" }; const char *const SystemZTargetInfo::GCCRegNames[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "f0", "f2", "f4", "f6", "f1", "f3", "f5", "f7", "f8", "f10", "f12", "f14", "f9", "f11", "f13", "f15" }; void SystemZTargetInfo::getGCCRegNames(const char *const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } bool SystemZTargetInfo:: validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const { switch (*Name) { default: return false; case 'a': // Address register case 'd': // Data register (equivalent to 'r') case 'f': // Floating-point register Info.setAllowsRegister(); return true; case 'I': // Unsigned 8-bit constant case 'J': // Unsigned 12-bit constant case 'K': // Signed 16-bit constant case 'L': // Signed 20-bit displacement (on all targets we support) case 'M': // 0x7fffffff return true; case 'Q': // Memory with base and unsigned 12-bit displacement case 'R': // Likewise, plus an index case 'S': // Memory with base and signed 20-bit displacement case 'T': // Likewise, plus an index Info.setAllowsMemory(); return true; } } class MSP430TargetInfo : public TargetInfo { static const char * const GCCRegNames[]; public: MSP430TargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { BigEndian = false; TLSSupported = false; IntWidth = 16; IntAlign = 16; LongWidth = 32; LongLongWidth = 64; LongAlign = LongLongAlign = 16; PointerWidth = 16; PointerAlign = 16; SuitableAlign = 16; SizeType = UnsignedInt; IntMaxType = SignedLongLong; IntPtrType = SignedInt; PtrDiffType = SignedInt; SigAtomicType = SignedLong; DescriptionString = "e-m:e-p:16:16-i32:16:32-a:16-n8:16"; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { Builder.defineMacro("MSP430"); Builder.defineMacro("__MSP430__"); // FIXME: defines for different 'flavours' of MCU } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { // FIXME: Implement. Records = nullptr; NumRecords = 0; } bool hasFeature(StringRef Feature) const override { return Feature == "msp430"; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override; void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override { // No aliases. Aliases = nullptr; NumAliases = 0; } bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override { // FIXME: implement switch (*Name) { case 'K': // the constant 1 case 'L': // constant -1^20 .. 1^19 case 'M': // constant 1-4: return true; } // No target constraints for now. return false; } const char *getClobbers() const override { // FIXME: Is this really right? return ""; } BuiltinVaListKind getBuiltinVaListKind() const override { // FIXME: implement return TargetInfo::CharPtrBuiltinVaList; } }; const char * const MSP430TargetInfo::GCCRegNames[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }; void MSP430TargetInfo::getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } // LLVM and Clang cannot be used directly to output native binaries for // target, but is used to compile C code to llvm bitcode with correct // type and alignment information. // // TCE uses the llvm bitcode as input and uses it for generating customized // target processor and program binary. TCE co-design environment is // publicly available in http://tce.cs.tut.fi static const unsigned TCEOpenCLAddrSpaceMap[] = { 3, // opencl_global 4, // opencl_local 5, // opencl_constant // FIXME: generic has to be added to the target 0, // opencl_generic 0, // cuda_device 0, // cuda_constant 0 // cuda_shared }; class TCETargetInfo : public TargetInfo{ public: TCETargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { TLSSupported = false; IntWidth = 32; LongWidth = LongLongWidth = 32; PointerWidth = 32; IntAlign = 32; LongAlign = LongLongAlign = 32; PointerAlign = 32; SuitableAlign = 32; SizeType = UnsignedInt; IntMaxType = SignedLong; IntPtrType = SignedInt; PtrDiffType = SignedInt; FloatWidth = 32; FloatAlign = 32; DoubleWidth = 32; DoubleAlign = 32; LongDoubleWidth = 32; LongDoubleAlign = 32; FloatFormat = &llvm::APFloat::IEEEsingle; DoubleFormat = &llvm::APFloat::IEEEsingle; LongDoubleFormat = &llvm::APFloat::IEEEsingle; DescriptionString = "E-p:32:32-i8:8:32-i16:16:32-i64:32" "-f64:32-v64:32-v128:32-a:0:32-n32"; AddrSpaceMap = &TCEOpenCLAddrSpaceMap; UseAddrSpaceMapMangling = true; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "tce", Opts); Builder.defineMacro("__TCE__"); Builder.defineMacro("__TCE_V1__"); } bool hasFeature(StringRef Feature) const override { return Feature == "tce"; } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override {} const char *getClobbers() const override { return ""; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::VoidPtrBuiltinVaList; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override {} bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override{ return true; } void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override {} }; class BPFTargetInfo : public TargetInfo { public: BPFTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { LongWidth = LongAlign = PointerWidth = PointerAlign = 64; SizeType = UnsignedLong; PtrDiffType = SignedLong; IntPtrType = SignedLong; IntMaxType = SignedLong; Int64Type = SignedLong; RegParmMax = 5; if (Triple.getArch() == llvm::Triple::bpfeb) { BigEndian = true; DescriptionString = "E-m:e-p:64:64-i64:64-n32:64-S128"; } else { BigEndian = false; DescriptionString = "e-m:e-p:64:64-i64:64-n32:64-S128"; } MaxAtomicPromoteWidth = 64; MaxAtomicInlineWidth = 64; TLSSupported = false; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "bpf", Opts); Builder.defineMacro("__BPF__"); } bool hasFeature(StringRef Feature) const override { return Feature == "bpf"; } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override {} const char *getClobbers() const override { return ""; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::VoidPtrBuiltinVaList; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override { Names = nullptr; NumNames = 0; } bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override { return true; } void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override { Aliases = nullptr; NumAliases = 0; } }; class MipsTargetInfoBase : public TargetInfo { virtual void setDescriptionString() = 0; static const Builtin::Info BuiltinInfo[]; std::string CPU; bool IsMips16; bool IsMicromips; bool IsNan2008; bool IsSingleFloat; enum MipsFloatABI { HardFloat, SoftFloat } FloatABI; enum DspRevEnum { NoDSP, DSP1, DSP2 } DspRev; bool HasMSA; protected: bool HasFP64; std::string ABI; public: MipsTargetInfoBase(const llvm::Triple &Triple, const std::string &ABIStr, const std::string &CPUStr) : TargetInfo(Triple), CPU(CPUStr), IsMips16(false), IsMicromips(false), IsNan2008(false), IsSingleFloat(false), FloatABI(HardFloat), DspRev(NoDSP), HasMSA(false), HasFP64(false), ABI(ABIStr) { TheCXXABI.set(TargetCXXABI::GenericMIPS); } bool isNaN2008Default() const { return CPU == "mips32r6" || CPU == "mips64r6"; } bool isFP64Default() const { return CPU == "mips32r6" || ABI == "n32" || ABI == "n64" || ABI == "64"; } bool isNan2008() const override { return IsNan2008; } StringRef getABI() const override { return ABI; } bool setCPU(const std::string &Name) override { bool IsMips32 = getTriple().getArch() == llvm::Triple::mips || getTriple().getArch() == llvm::Triple::mipsel; CPU = Name; return llvm::StringSwitch<bool>(Name) .Case("mips1", IsMips32) .Case("mips2", IsMips32) .Case("mips3", true) .Case("mips4", true) .Case("mips5", true) .Case("mips32", IsMips32) .Case("mips32r2", IsMips32) .Case("mips32r3", IsMips32) .Case("mips32r5", IsMips32) .Case("mips32r6", IsMips32) .Case("mips64", true) .Case("mips64r2", true) .Case("mips64r3", true) .Case("mips64r5", true) .Case("mips64r6", true) .Case("octeon", true) .Default(false); } const std::string& getCPU() const { return CPU; } void getDefaultFeatures(llvm::StringMap<bool> &Features) const override { if (CPU == "octeon") Features["mips64r2"] = Features["cnmips"] = true; else Features[CPU] = true; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { Builder.defineMacro("__mips__"); Builder.defineMacro("_mips"); if (Opts.GNUMode) Builder.defineMacro("mips"); Builder.defineMacro("__REGISTER_PREFIX__", ""); switch (FloatABI) { case HardFloat: Builder.defineMacro("__mips_hard_float", Twine(1)); break; case SoftFloat: Builder.defineMacro("__mips_soft_float", Twine(1)); break; } if (IsSingleFloat) Builder.defineMacro("__mips_single_float", Twine(1)); Builder.defineMacro("__mips_fpr", HasFP64 ? Twine(64) : Twine(32)); Builder.defineMacro("_MIPS_FPSET", Twine(32 / (HasFP64 || IsSingleFloat ? 1 : 2))); if (IsMips16) Builder.defineMacro("__mips16", Twine(1)); if (IsMicromips) Builder.defineMacro("__mips_micromips", Twine(1)); if (IsNan2008) Builder.defineMacro("__mips_nan2008", Twine(1)); switch (DspRev) { default: break; case DSP1: Builder.defineMacro("__mips_dsp_rev", Twine(1)); Builder.defineMacro("__mips_dsp", Twine(1)); break; case DSP2: Builder.defineMacro("__mips_dsp_rev", Twine(2)); Builder.defineMacro("__mips_dspr2", Twine(1)); Builder.defineMacro("__mips_dsp", Twine(1)); break; } if (HasMSA) Builder.defineMacro("__mips_msa", Twine(1)); Builder.defineMacro("_MIPS_SZPTR", Twine(getPointerWidth(0))); Builder.defineMacro("_MIPS_SZINT", Twine(getIntWidth())); Builder.defineMacro("_MIPS_SZLONG", Twine(getLongWidth())); Builder.defineMacro("_MIPS_ARCH", "\"" + CPU + "\""); Builder.defineMacro("_MIPS_ARCH_" + StringRef(CPU).upper()); } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::Mips::LastTSBuiltin - Builtin::FirstTSBuiltin; } bool hasFeature(StringRef Feature) const override { return llvm::StringSwitch<bool>(Feature) .Case("mips", true) .Case("fp64", HasFP64) .Default(false); } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::VoidPtrBuiltinVaList; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override { static const char *const GCCRegNames[] = { // CPU register names // Must match second column of GCCRegAliases "$0", "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9", "$10", "$11", "$12", "$13", "$14", "$15", "$16", "$17", "$18", "$19", "$20", "$21", "$22", "$23", "$24", "$25", "$26", "$27", "$28", "$29", "$30", "$31", // Floating point register names "$f0", "$f1", "$f2", "$f3", "$f4", "$f5", "$f6", "$f7", "$f8", "$f9", "$f10", "$f11", "$f12", "$f13", "$f14", "$f15", "$f16", "$f17", "$f18", "$f19", "$f20", "$f21", "$f22", "$f23", "$f24", "$f25", "$f26", "$f27", "$f28", "$f29", "$f30", "$f31", // Hi/lo and condition register names "hi", "lo", "", "$fcc0","$fcc1","$fcc2","$fcc3","$fcc4", "$fcc5","$fcc6","$fcc7", // MSA register names "$w0", "$w1", "$w2", "$w3", "$w4", "$w5", "$w6", "$w7", "$w8", "$w9", "$w10", "$w11", "$w12", "$w13", "$w14", "$w15", "$w16", "$w17", "$w18", "$w19", "$w20", "$w21", "$w22", "$w23", "$w24", "$w25", "$w26", "$w27", "$w28", "$w29", "$w30", "$w31", // MSA control register names "$msair", "$msacsr", "$msaaccess", "$msasave", "$msamodify", "$msarequest", "$msamap", "$msaunmap" }; Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override = 0; bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const override { switch (*Name) { default: return false; case 'r': // CPU registers. case 'd': // Equivalent to "r" unless generating MIPS16 code. case 'y': // Equivalent to "r", backward compatibility only. case 'f': // floating-point registers. case 'c': // $25 for indirect jumps case 'l': // lo register case 'x': // hilo register pair Info.setAllowsRegister(); return true; case 'I': // Signed 16-bit constant case 'J': // Integer 0 case 'K': // Unsigned 16-bit constant case 'L': // Signed 32-bit constant, lower 16-bit zeros (for lui) case 'M': // Constants not loadable via lui, addiu, or ori case 'N': // Constant -1 to -65535 case 'O': // A signed 15-bit constant case 'P': // A constant between 1 go 65535 return true; case 'R': // An address that can be used in a non-macro load or store Info.setAllowsMemory(); return true; case 'Z': if (Name[1] == 'C') { // An address usable by ll, and sc. Info.setAllowsMemory(); Name++; // Skip over 'Z'. return true; } return false; } } std::string convertConstraint(const char *&Constraint) const override { std::string R; switch (*Constraint) { case 'Z': // Two-character constraint; add "^" hint for later parsing. if (Constraint[1] == 'C') { R = std::string("^") + std::string(Constraint, 2); Constraint++; return R; } break; } return TargetInfo::convertConstraint(Constraint); } const char *getClobbers() const override { // In GCC, $1 is not widely used in generated code (it's used only in a few // specific situations), so there is no real need for users to add it to // the clobbers list if they want to use it in their inline assembly code. // // In LLVM, $1 is treated as a normal GPR and is always allocatable during // code generation, so using it in inline assembly without adding it to the // clobbers list can cause conflicts between the inline assembly code and // the surrounding generated code. // // Another problem is that LLVM is allowed to choose $1 for inline assembly // operands, which will conflict with the ".set at" assembler option (which // we use only for inline assembly, in order to maintain compatibility with // GCC) and will also conflict with the user's usage of $1. // // The easiest way to avoid these conflicts and keep $1 as an allocatable // register for generated code is to automatically clobber $1 for all inline // assembly code. // // FIXME: We should automatically clobber $1 only for inline assembly code // which actually uses it. This would allow LLVM to use $1 for inline // assembly operands if the user's assembly code doesn't use it. return "~{$1}"; } bool handleTargetFeatures(std::vector<std::string> &Features, DiagnosticsEngine &Diags) override { IsMips16 = false; IsMicromips = false; IsNan2008 = isNaN2008Default(); IsSingleFloat = false; FloatABI = HardFloat; DspRev = NoDSP; HasFP64 = isFP64Default(); for (std::vector<std::string>::iterator it = Features.begin(), ie = Features.end(); it != ie; ++it) { if (*it == "+single-float") IsSingleFloat = true; else if (*it == "+soft-float") FloatABI = SoftFloat; else if (*it == "+mips16") IsMips16 = true; else if (*it == "+micromips") IsMicromips = true; else if (*it == "+dsp") DspRev = std::max(DspRev, DSP1); else if (*it == "+dspr2") DspRev = std::max(DspRev, DSP2); else if (*it == "+msa") HasMSA = true; else if (*it == "+fp64") HasFP64 = true; else if (*it == "-fp64") HasFP64 = false; else if (*it == "+nan2008") IsNan2008 = true; else if (*it == "-nan2008") IsNan2008 = false; } setDescriptionString(); return true; } int getEHDataRegisterNumber(unsigned RegNo) const override { if (RegNo == 0) return 4; if (RegNo == 1) return 5; return -1; } bool isCLZForZeroUndef() const override { return false; } }; const Builtin::Info MipsTargetInfoBase::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER,\ ALL_LANGUAGES }, #include "clang/Basic/BuiltinsMips.def" }; class Mips32TargetInfoBase : public MipsTargetInfoBase { public: Mips32TargetInfoBase(const llvm::Triple &Triple) : MipsTargetInfoBase(Triple, "o32", "mips32r2") { SizeType = UnsignedInt; PtrDiffType = SignedInt; Int64Type = SignedLongLong; IntMaxType = Int64Type; MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32; } bool setABI(const std::string &Name) override { if (Name == "o32" || Name == "eabi") { ABI = Name; return true; } return false; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { MipsTargetInfoBase::getTargetDefines(Opts, Builder); Builder.defineMacro("__mips", "32"); Builder.defineMacro("_MIPS_ISA", "_MIPS_ISA_MIPS32"); const std::string& CPUStr = getCPU(); if (CPUStr == "mips32") Builder.defineMacro("__mips_isa_rev", "1"); else if (CPUStr == "mips32r2") Builder.defineMacro("__mips_isa_rev", "2"); else if (CPUStr == "mips32r3") Builder.defineMacro("__mips_isa_rev", "3"); else if (CPUStr == "mips32r5") Builder.defineMacro("__mips_isa_rev", "5"); else if (CPUStr == "mips32r6") Builder.defineMacro("__mips_isa_rev", "6"); if (ABI == "o32") { Builder.defineMacro("__mips_o32"); Builder.defineMacro("_ABIO32", "1"); Builder.defineMacro("_MIPS_SIM", "_ABIO32"); } else if (ABI == "eabi") Builder.defineMacro("__mips_eabi"); else llvm_unreachable("Invalid ABI for Mips32."); } void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override { static const TargetInfo::GCCRegAlias GCCRegAliases[] = { { { "at" }, "$1" }, { { "v0" }, "$2" }, { { "v1" }, "$3" }, { { "a0" }, "$4" }, { { "a1" }, "$5" }, { { "a2" }, "$6" }, { { "a3" }, "$7" }, { { "t0" }, "$8" }, { { "t1" }, "$9" }, { { "t2" }, "$10" }, { { "t3" }, "$11" }, { { "t4" }, "$12" }, { { "t5" }, "$13" }, { { "t6" }, "$14" }, { { "t7" }, "$15" }, { { "s0" }, "$16" }, { { "s1" }, "$17" }, { { "s2" }, "$18" }, { { "s3" }, "$19" }, { { "s4" }, "$20" }, { { "s5" }, "$21" }, { { "s6" }, "$22" }, { { "s7" }, "$23" }, { { "t8" }, "$24" }, { { "t9" }, "$25" }, { { "k0" }, "$26" }, { { "k1" }, "$27" }, { { "gp" }, "$28" }, { { "sp","$sp" }, "$29" }, { { "fp","$fp" }, "$30" }, { { "ra" }, "$31" } }; Aliases = GCCRegAliases; NumAliases = llvm::array_lengthof(GCCRegAliases); } }; class Mips32EBTargetInfo : public Mips32TargetInfoBase { void setDescriptionString() override { DescriptionString = "E-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64"; } public: Mips32EBTargetInfo(const llvm::Triple &Triple) : Mips32TargetInfoBase(Triple) { } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "MIPSEB", Opts); Builder.defineMacro("_MIPSEB"); Mips32TargetInfoBase::getTargetDefines(Opts, Builder); } }; class Mips32ELTargetInfo : public Mips32TargetInfoBase { void setDescriptionString() override { DescriptionString = "e-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64"; } public: Mips32ELTargetInfo(const llvm::Triple &Triple) : Mips32TargetInfoBase(Triple) { BigEndian = false; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "MIPSEL", Opts); Builder.defineMacro("_MIPSEL"); Mips32TargetInfoBase::getTargetDefines(Opts, Builder); } }; class Mips64TargetInfoBase : public MipsTargetInfoBase { public: Mips64TargetInfoBase(const llvm::Triple &Triple) : MipsTargetInfoBase(Triple, "n64", "mips64r2") { LongDoubleWidth = LongDoubleAlign = 128; LongDoubleFormat = &llvm::APFloat::IEEEquad; if (getTriple().getOS() == llvm::Triple::FreeBSD) { LongDoubleWidth = LongDoubleAlign = 64; LongDoubleFormat = &llvm::APFloat::IEEEdouble; } setN64ABITypes(); SuitableAlign = 128; MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64; } void setN64ABITypes() { LongWidth = LongAlign = 64; PointerWidth = PointerAlign = 64; SizeType = UnsignedLong; PtrDiffType = SignedLong; Int64Type = SignedLong; IntMaxType = Int64Type; } void setN32ABITypes() { LongWidth = LongAlign = 32; PointerWidth = PointerAlign = 32; SizeType = UnsignedInt; PtrDiffType = SignedInt; Int64Type = SignedLongLong; IntMaxType = Int64Type; } bool setABI(const std::string &Name) override { if (Name == "n32") { setN32ABITypes(); ABI = Name; return true; } if (Name == "n64") { setN64ABITypes(); ABI = Name; return true; } return false; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { MipsTargetInfoBase::getTargetDefines(Opts, Builder); Builder.defineMacro("__mips", "64"); Builder.defineMacro("__mips64"); Builder.defineMacro("__mips64__"); Builder.defineMacro("_MIPS_ISA", "_MIPS_ISA_MIPS64"); const std::string& CPUStr = getCPU(); if (CPUStr == "mips64") Builder.defineMacro("__mips_isa_rev", "1"); else if (CPUStr == "mips64r2") Builder.defineMacro("__mips_isa_rev", "2"); else if (CPUStr == "mips64r3") Builder.defineMacro("__mips_isa_rev", "3"); else if (CPUStr == "mips64r5") Builder.defineMacro("__mips_isa_rev", "5"); else if (CPUStr == "mips64r6") Builder.defineMacro("__mips_isa_rev", "6"); if (ABI == "n32") { Builder.defineMacro("__mips_n32"); Builder.defineMacro("_ABIN32", "2"); Builder.defineMacro("_MIPS_SIM", "_ABIN32"); } else if (ABI == "n64") { Builder.defineMacro("__mips_n64"); Builder.defineMacro("_ABI64", "3"); Builder.defineMacro("_MIPS_SIM", "_ABI64"); } else llvm_unreachable("Invalid ABI for Mips64."); } void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override { static const TargetInfo::GCCRegAlias GCCRegAliases[] = { { { "at" }, "$1" }, { { "v0" }, "$2" }, { { "v1" }, "$3" }, { { "a0" }, "$4" }, { { "a1" }, "$5" }, { { "a2" }, "$6" }, { { "a3" }, "$7" }, { { "a4" }, "$8" }, { { "a5" }, "$9" }, { { "a6" }, "$10" }, { { "a7" }, "$11" }, { { "t0" }, "$12" }, { { "t1" }, "$13" }, { { "t2" }, "$14" }, { { "t3" }, "$15" }, { { "s0" }, "$16" }, { { "s1" }, "$17" }, { { "s2" }, "$18" }, { { "s3" }, "$19" }, { { "s4" }, "$20" }, { { "s5" }, "$21" }, { { "s6" }, "$22" }, { { "s7" }, "$23" }, { { "t8" }, "$24" }, { { "t9" }, "$25" }, { { "k0" }, "$26" }, { { "k1" }, "$27" }, { { "gp" }, "$28" }, { { "sp","$sp" }, "$29" }, { { "fp","$fp" }, "$30" }, { { "ra" }, "$31" } }; Aliases = GCCRegAliases; NumAliases = llvm::array_lengthof(GCCRegAliases); } bool hasInt128Type() const override { return true; } }; class Mips64EBTargetInfo : public Mips64TargetInfoBase { void setDescriptionString() override { if (ABI == "n32") DescriptionString = "E-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32:64-S128"; else DescriptionString = "E-m:m-i8:8:32-i16:16:32-i64:64-n32:64-S128"; } public: Mips64EBTargetInfo(const llvm::Triple &Triple) : Mips64TargetInfoBase(Triple) {} void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "MIPSEB", Opts); Builder.defineMacro("_MIPSEB"); Mips64TargetInfoBase::getTargetDefines(Opts, Builder); } }; class Mips64ELTargetInfo : public Mips64TargetInfoBase { void setDescriptionString() override { if (ABI == "n32") DescriptionString = "e-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32:64-S128"; else DescriptionString = "e-m:m-i8:8:32-i16:16:32-i64:64-n32:64-S128"; } public: Mips64ELTargetInfo(const llvm::Triple &Triple) : Mips64TargetInfoBase(Triple) { // Default ABI is n64. BigEndian = false; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "MIPSEL", Opts); Builder.defineMacro("_MIPSEL"); Mips64TargetInfoBase::getTargetDefines(Opts, Builder); } }; class PNaClTargetInfo : public TargetInfo { public: PNaClTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { BigEndian = false; this->UserLabelPrefix = ""; this->LongAlign = 32; this->LongWidth = 32; this->PointerAlign = 32; this->PointerWidth = 32; this->IntMaxType = TargetInfo::SignedLongLong; this->Int64Type = TargetInfo::SignedLongLong; this->DoubleAlign = 64; this->LongDoubleWidth = 64; this->LongDoubleAlign = 64; this->SizeType = TargetInfo::UnsignedInt; this->PtrDiffType = TargetInfo::SignedInt; this->IntPtrType = TargetInfo::SignedInt; this->RegParmMax = 0; // Disallow regparm } void getDefaultFeatures(llvm::StringMap<bool> &Features) const override { } void getArchDefines(const LangOptions &Opts, MacroBuilder &Builder) const { Builder.defineMacro("__le32__"); Builder.defineMacro("__pnacl__"); } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { getArchDefines(Opts, Builder); } bool hasFeature(StringRef Feature) const override { return Feature == "pnacl"; } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::PNaClABIBuiltinVaList; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override; void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override; bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const override { return false; } const char *getClobbers() const override { return ""; } }; void PNaClTargetInfo::getGCCRegNames(const char * const *&Names, unsigned &NumNames) const { Names = nullptr; NumNames = 0; } void PNaClTargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const { Aliases = nullptr; NumAliases = 0; } // We attempt to use PNaCl (le32) frontend and Mips32EL backend. class NaClMips32ELTargetInfo : public Mips32ELTargetInfo { public: NaClMips32ELTargetInfo(const llvm::Triple &Triple) : Mips32ELTargetInfo(Triple) { MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 0; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::PNaClABIBuiltinVaList; } }; class Le64TargetInfo : public TargetInfo { static const Builtin::Info BuiltinInfo[]; public: Le64TargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { BigEndian = false; NoAsmVariants = true; LongWidth = LongAlign = PointerWidth = PointerAlign = 64; MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64; DescriptionString = "e-m:e-v128:32-v16:16-v32:32-v96:32-n8:16:32:64-S128"; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "unix", Opts); defineCPUMacros(Builder, "le64", /*Tuning=*/false); Builder.defineMacro("__ELF__"); } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::Le64::LastTSBuiltin - Builtin::FirstTSBuiltin; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::PNaClABIBuiltinVaList; } const char *getClobbers() const override { return ""; } void getGCCRegNames(const char *const *&Names, unsigned &NumNames) const override { Names = nullptr; NumNames = 0; } void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override { Aliases = nullptr; NumAliases = 0; } bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const override { return false; } bool hasProtectedVisibility() const override { return false; } }; } // end anonymous namespace. const Builtin::Info Le64TargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) \ { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #include "clang/Basic/BuiltinsLe64.def" }; namespace { static const unsigned SPIRAddrSpaceMap[] = { 1, // opencl_global 3, // opencl_local 2, // opencl_constant 4, // opencl_generic 0, // cuda_device 0, // cuda_constant 0 // cuda_shared }; class SPIRTargetInfo : public TargetInfo { public: SPIRTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { assert(getTriple().getOS() == llvm::Triple::UnknownOS && "SPIR target must use unknown OS"); assert(getTriple().getEnvironment() == llvm::Triple::UnknownEnvironment && "SPIR target must use unknown environment type"); BigEndian = false; TLSSupported = false; LongWidth = LongAlign = 64; AddrSpaceMap = &SPIRAddrSpaceMap; UseAddrSpaceMapMangling = true; // Define available target features // These must be defined in sorted order! NoAsmVariants = true; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "SPIR", Opts); } bool hasFeature(StringRef Feature) const override { return Feature == "spir"; } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override {} const char *getClobbers() const override { return ""; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override {} bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override { return true; } void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override {} BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::VoidPtrBuiltinVaList; } CallingConvCheckResult checkCallingConvention(CallingConv CC) const override { return (CC == CC_SpirFunction || CC == CC_SpirKernel) ? CCCR_OK : CCCR_Warning; } CallingConv getDefaultCallingConv(CallingConvMethodType MT) const override { return CC_SpirFunction; } }; class SPIR32TargetInfo : public SPIRTargetInfo { public: SPIR32TargetInfo(const llvm::Triple &Triple) : SPIRTargetInfo(Triple) { PointerWidth = PointerAlign = 32; SizeType = TargetInfo::UnsignedInt; PtrDiffType = IntPtrType = TargetInfo::SignedInt; DescriptionString = "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-" "v96:128-v192:256-v256:256-v512:512-v1024:1024"; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "SPIR32", Opts); } }; class SPIR64TargetInfo : public SPIRTargetInfo { public: SPIR64TargetInfo(const llvm::Triple &Triple) : SPIRTargetInfo(Triple) { PointerWidth = PointerAlign = 64; SizeType = TargetInfo::UnsignedLong; PtrDiffType = IntPtrType = TargetInfo::SignedLong; DescriptionString = "e-i64:64-v16:16-v24:32-v32:32-v48:64-" "v96:128-v192:256-v256:256-v512:512-v1024:1024"; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { DefineStd(Builder, "SPIR64", Opts); } }; class XCoreTargetInfo : public TargetInfo { static const Builtin::Info BuiltinInfo[]; public: XCoreTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { BigEndian = false; NoAsmVariants = true; LongLongAlign = 32; SuitableAlign = 32; DoubleAlign = LongDoubleAlign = 32; SizeType = UnsignedInt; PtrDiffType = SignedInt; IntPtrType = SignedInt; WCharType = UnsignedChar; WIntType = UnsignedInt; UseZeroLengthBitfieldAlignment = true; DescriptionString = "e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i64:32" "-f64:32-a:0:32-n32"; } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { Builder.defineMacro("__XS1B__"); } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::XCore::LastTSBuiltin-Builtin::FirstTSBuiltin; } BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::VoidPtrBuiltinVaList; } const char *getClobbers() const override { return ""; } void getGCCRegNames(const char * const *&Names, unsigned &NumNames) const override { static const char * const GCCRegNames[] = { "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "cp", "dp", "sp", "lr" }; Names = GCCRegNames; NumNames = llvm::array_lengthof(GCCRegNames); } void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override { Aliases = nullptr; NumAliases = 0; } bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &Info) const override { return false; } int getEHDataRegisterNumber(unsigned RegNo) const override { // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister return (RegNo < 2)? RegNo : -1; } }; const Builtin::Info XCoreTargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER,\ ALL_LANGUAGES }, #include "clang/Basic/BuiltinsXCore.def" }; } // end anonymous namespace. namespace { // x86_32 Android target class AndroidX86_32TargetInfo : public LinuxTargetInfo<X86_32TargetInfo> { public: AndroidX86_32TargetInfo(const llvm::Triple &Triple) : LinuxTargetInfo<X86_32TargetInfo>(Triple) { SuitableAlign = 32; LongDoubleWidth = 64; LongDoubleFormat = &llvm::APFloat::IEEEdouble; } }; } // end anonymous namespace namespace { // x86_64 Android target class AndroidX86_64TargetInfo : public LinuxTargetInfo<X86_64TargetInfo> { public: AndroidX86_64TargetInfo(const llvm::Triple &Triple) : LinuxTargetInfo<X86_64TargetInfo>(Triple) { LongDoubleFormat = &llvm::APFloat::IEEEquad; } bool useFloat128ManglingForLongDouble() const override { return true; } }; } // end anonymous namespace #endif // HLSL Change - remove unsupported targets namespace { class DXILTargetInfo : public TargetInfo { static const Builtin::Info BuiltinInfo[]; public: DXILTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) { BigEndian = false; TLSSupported = false; LongWidth = LongAlign = 32; LongDoubleWidth = LongDoubleAlign = 64; LongDoubleFormat = &llvm::APFloat::IEEEdouble; BoolWidth = BoolAlign = 32; // using the Microsoft ABI. TheCXXABI.set(TargetCXXABI::Microsoft); } void getTargetDefines(const LangOptions &Opts, MacroBuilder &Builder) const override { // add target defines } void getTargetBuiltins(const Builtin::Info *&Records, unsigned &NumRecords) const override { Records = BuiltinInfo; NumRecords = clang::DXIL::LastTSBuiltin - Builtin::FirstTSBuiltin; } bool hasFeature(StringRef Feature) const override { return Feature == "dxil"; } const char *getClobbers() const override { return ""; } void getGCCRegNames(const char *const *&Names, unsigned &NumNames) const override {} bool validateAsmConstraint(const char *&Name, TargetInfo::ConstraintInfo &info) const override { return true; } void getGCCRegAliases(const GCCRegAlias *&Aliases, unsigned &NumAliases) const override {} BuiltinVaListKind getBuiltinVaListKind() const override { return TargetInfo::CharPtrBuiltinVaList; } }; const Builtin::Info DXILTargetInfo::BuiltinInfo[] = { #define BUILTIN(ID, TYPE, ATTRS) {#ID, TYPE, ATTRS, 0, ALL_LANGUAGES}, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \ {#ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES}, #include "clang/Basic/BuiltinsDXIL.def" }; // DXIL 32 target class DXIL_32TargetInfo : public DXILTargetInfo { public: DXIL_32TargetInfo(const llvm::Triple &Triple, const char *descriptionString) : DXILTargetInfo(Triple) { // TODO: Update Description for DXIL DescriptionString = descriptionString; } }; } // HLSL Change Ends //===----------------------------------------------------------------------===// // Driver code //===----------------------------------------------------------------------===// static TargetInfo *AllocateTarget(const llvm::Triple &Triple, const char* descrptionString) { #if 1 // HLSL Change return new DXIL_32TargetInfo(Triple, descrptionString); #else // HLSL Change llvm::Triple::OSType os = Triple.getOS(); switch (Triple.getArch()) { default: return nullptr; case llvm::Triple::xcore: return new XCoreTargetInfo(Triple); case llvm::Triple::hexagon: return new HexagonTargetInfo(Triple); case llvm::Triple::aarch64: if (Triple.isOSDarwin()) return new DarwinAArch64TargetInfo(Triple); switch (os) { case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<AArch64leTargetInfo>(Triple); case llvm::Triple::Linux: return new LinuxTargetInfo<AArch64leTargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<AArch64leTargetInfo>(Triple); default: return new AArch64leTargetInfo(Triple); } case llvm::Triple::aarch64_be: switch (os) { case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<AArch64beTargetInfo>(Triple); case llvm::Triple::Linux: return new LinuxTargetInfo<AArch64beTargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<AArch64beTargetInfo>(Triple); default: return new AArch64beTargetInfo(Triple); } case llvm::Triple::arm: case llvm::Triple::thumb: if (Triple.isOSBinFormatMachO()) return new DarwinARMTargetInfo(Triple); switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<ARMleTargetInfo>(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<ARMleTargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<ARMleTargetInfo>(Triple); case llvm::Triple::OpenBSD: return new OpenBSDTargetInfo<ARMleTargetInfo>(Triple); case llvm::Triple::Bitrig: return new BitrigTargetInfo<ARMleTargetInfo>(Triple); case llvm::Triple::RTEMS: return new RTEMSTargetInfo<ARMleTargetInfo>(Triple); case llvm::Triple::NaCl: return new NaClTargetInfo<ARMleTargetInfo>(Triple); case llvm::Triple::Win32: switch (Triple.getEnvironment()) { case llvm::Triple::Itanium: return new ItaniumWindowsARMleTargetInfo(Triple); case llvm::Triple::MSVC: default: // Assume MSVC for unknown environments return new MicrosoftARMleTargetInfo(Triple); } default: return new ARMleTargetInfo(Triple); } case llvm::Triple::armeb: case llvm::Triple::thumbeb: if (Triple.isOSDarwin()) return new DarwinARMTargetInfo(Triple); switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<ARMbeTargetInfo>(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<ARMbeTargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<ARMbeTargetInfo>(Triple); case llvm::Triple::OpenBSD: return new OpenBSDTargetInfo<ARMbeTargetInfo>(Triple); case llvm::Triple::Bitrig: return new BitrigTargetInfo<ARMbeTargetInfo>(Triple); case llvm::Triple::RTEMS: return new RTEMSTargetInfo<ARMbeTargetInfo>(Triple); case llvm::Triple::NaCl: return new NaClTargetInfo<ARMbeTargetInfo>(Triple); default: return new ARMbeTargetInfo(Triple); } case llvm::Triple::bpfeb: case llvm::Triple::bpfel: return new BPFTargetInfo(Triple); case llvm::Triple::msp430: return new MSP430TargetInfo(Triple); case llvm::Triple::mips: switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<Mips32EBTargetInfo>(Triple); case llvm::Triple::RTEMS: return new RTEMSTargetInfo<Mips32EBTargetInfo>(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<Mips32EBTargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<Mips32EBTargetInfo>(Triple); default: return new Mips32EBTargetInfo(Triple); } case llvm::Triple::mipsel: switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<Mips32ELTargetInfo>(Triple); case llvm::Triple::RTEMS: return new RTEMSTargetInfo<Mips32ELTargetInfo>(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<Mips32ELTargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<Mips32ELTargetInfo>(Triple); case llvm::Triple::NaCl: return new NaClTargetInfo<NaClMips32ELTargetInfo>(Triple); default: return new Mips32ELTargetInfo(Triple); } case llvm::Triple::mips64: switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<Mips64EBTargetInfo>(Triple); case llvm::Triple::RTEMS: return new RTEMSTargetInfo<Mips64EBTargetInfo>(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<Mips64EBTargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<Mips64EBTargetInfo>(Triple); case llvm::Triple::OpenBSD: return new OpenBSDTargetInfo<Mips64EBTargetInfo>(Triple); default: return new Mips64EBTargetInfo(Triple); } case llvm::Triple::mips64el: switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<Mips64ELTargetInfo>(Triple); case llvm::Triple::RTEMS: return new RTEMSTargetInfo<Mips64ELTargetInfo>(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<Mips64ELTargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<Mips64ELTargetInfo>(Triple); case llvm::Triple::OpenBSD: return new OpenBSDTargetInfo<Mips64ELTargetInfo>(Triple); default: return new Mips64ELTargetInfo(Triple); } case llvm::Triple::le32: switch (os) { case llvm::Triple::NaCl: return new NaClTargetInfo<PNaClTargetInfo>(Triple); default: return nullptr; } case llvm::Triple::le64: return new Le64TargetInfo(Triple); case llvm::Triple::ppc: if (Triple.isOSDarwin()) return new DarwinPPC32TargetInfo(Triple); switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<PPC32TargetInfo>(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<PPC32TargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<PPC32TargetInfo>(Triple); case llvm::Triple::OpenBSD: return new OpenBSDTargetInfo<PPC32TargetInfo>(Triple); case llvm::Triple::RTEMS: return new RTEMSTargetInfo<PPC32TargetInfo>(Triple); default: return new PPC32TargetInfo(Triple); } case llvm::Triple::ppc64: if (Triple.isOSDarwin()) return new DarwinPPC64TargetInfo(Triple); switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<PPC64TargetInfo>(Triple); case llvm::Triple::Lv2: return new PS3PPUTargetInfo<PPC64TargetInfo>(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<PPC64TargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<PPC64TargetInfo>(Triple); default: return new PPC64TargetInfo(Triple); } case llvm::Triple::ppc64le: switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<PPC64TargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<PPC64TargetInfo>(Triple); default: return new PPC64TargetInfo(Triple); } case llvm::Triple::nvptx: return new NVPTX32TargetInfo(Triple); case llvm::Triple::nvptx64: return new NVPTX64TargetInfo(Triple); case llvm::Triple::amdgcn: case llvm::Triple::r600: return new AMDGPUTargetInfo(Triple); case llvm::Triple::sparc: switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<SparcV8TargetInfo>(Triple); case llvm::Triple::Solaris: return new SolarisTargetInfo<SparcV8TargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<SparcV8TargetInfo>(Triple); case llvm::Triple::OpenBSD: return new OpenBSDTargetInfo<SparcV8TargetInfo>(Triple); case llvm::Triple::RTEMS: return new RTEMSTargetInfo<SparcV8TargetInfo>(Triple); default: return new SparcV8TargetInfo(Triple); } // The 'sparcel' architecture copies all the above cases except for Solaris. case llvm::Triple::sparcel: switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<SparcV8elTargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<SparcV8elTargetInfo>(Triple); case llvm::Triple::OpenBSD: return new OpenBSDTargetInfo<SparcV8elTargetInfo>(Triple); case llvm::Triple::RTEMS: return new RTEMSTargetInfo<SparcV8elTargetInfo>(Triple); default: return new SparcV8elTargetInfo(Triple); } case llvm::Triple::sparcv9: switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<SparcV9TargetInfo>(Triple); case llvm::Triple::Solaris: return new SolarisTargetInfo<SparcV9TargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<SparcV9TargetInfo>(Triple); case llvm::Triple::OpenBSD: return new OpenBSDTargetInfo<SparcV9TargetInfo>(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<SparcV9TargetInfo>(Triple); default: return new SparcV9TargetInfo(Triple); } case llvm::Triple::systemz: switch (os) { case llvm::Triple::Linux: return new LinuxTargetInfo<SystemZTargetInfo>(Triple); default: return new SystemZTargetInfo(Triple); } case llvm::Triple::tce: return new TCETargetInfo(Triple); case llvm::Triple::x86: if (Triple.isOSDarwin()) return new DarwinI386TargetInfo(Triple); switch (os) { case llvm::Triple::CloudABI: return new CloudABITargetInfo<X86_32TargetInfo>(Triple); case llvm::Triple::Linux: { switch (Triple.getEnvironment()) { default: return new LinuxTargetInfo<X86_32TargetInfo>(Triple); case llvm::Triple::Android: return new AndroidX86_32TargetInfo(Triple); } } case llvm::Triple::DragonFly: return new DragonFlyBSDTargetInfo<X86_32TargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDI386TargetInfo(Triple); case llvm::Triple::OpenBSD: return new OpenBSDI386TargetInfo(Triple); case llvm::Triple::Bitrig: return new BitrigI386TargetInfo(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<X86_32TargetInfo>(Triple); case llvm::Triple::KFreeBSD: return new KFreeBSDTargetInfo<X86_32TargetInfo>(Triple); case llvm::Triple::Minix: return new MinixTargetInfo<X86_32TargetInfo>(Triple); case llvm::Triple::Solaris: return new SolarisTargetInfo<X86_32TargetInfo>(Triple); case llvm::Triple::Win32: { switch (Triple.getEnvironment()) { case llvm::Triple::Cygnus: return new CygwinX86_32TargetInfo(Triple); case llvm::Triple::GNU: return new MinGWX86_32TargetInfo(Triple); case llvm::Triple::Itanium: case llvm::Triple::MSVC: default: // Assume MSVC for unknown environments return new MicrosoftX86_32TargetInfo(Triple); } } case llvm::Triple::Haiku: return new HaikuX86_32TargetInfo(Triple); case llvm::Triple::RTEMS: return new RTEMSX86_32TargetInfo(Triple); case llvm::Triple::NaCl: return new NaClTargetInfo<X86_32TargetInfo>(Triple); default: return new X86_32TargetInfo(Triple); } case llvm::Triple::x86_64: if (Triple.isOSDarwin() || Triple.isOSBinFormatMachO()) return new DarwinX86_64TargetInfo(Triple); switch (os) { case llvm::Triple::CloudABI: return new CloudABITargetInfo<X86_64TargetInfo>(Triple); case llvm::Triple::Linux: { switch (Triple.getEnvironment()) { default: return new LinuxTargetInfo<X86_64TargetInfo>(Triple); case llvm::Triple::Android: return new AndroidX86_64TargetInfo(Triple); } } case llvm::Triple::DragonFly: return new DragonFlyBSDTargetInfo<X86_64TargetInfo>(Triple); case llvm::Triple::NetBSD: return new NetBSDTargetInfo<X86_64TargetInfo>(Triple); case llvm::Triple::OpenBSD: return new OpenBSDX86_64TargetInfo(Triple); case llvm::Triple::Bitrig: return new BitrigX86_64TargetInfo(Triple); case llvm::Triple::FreeBSD: return new FreeBSDTargetInfo<X86_64TargetInfo>(Triple); case llvm::Triple::KFreeBSD: return new KFreeBSDTargetInfo<X86_64TargetInfo>(Triple); case llvm::Triple::Solaris: return new SolarisTargetInfo<X86_64TargetInfo>(Triple); case llvm::Triple::Win32: { switch (Triple.getEnvironment()) { case llvm::Triple::GNU: return new MinGWX86_64TargetInfo(Triple); case llvm::Triple::MSVC: default: // Assume MSVC for unknown environments return new MicrosoftX86_64TargetInfo(Triple); } } case llvm::Triple::NaCl: return new NaClTargetInfo<X86_64TargetInfo>(Triple); case llvm::Triple::PS4: return new PS4OSTargetInfo<X86_64TargetInfo>(Triple); default: return new X86_64TargetInfo(Triple); } case llvm::Triple::spir: { if (Triple.getOS() != llvm::Triple::UnknownOS || Triple.getEnvironment() != llvm::Triple::UnknownEnvironment) return nullptr; return new SPIR32TargetInfo(Triple); } case llvm::Triple::spir64: { if (Triple.getOS() != llvm::Triple::UnknownOS || Triple.getEnvironment() != llvm::Triple::UnknownEnvironment) return nullptr; return new SPIR64TargetInfo(Triple); } } #endif // HLSL Change } /// CreateTargetInfo - Return the target info object for the specified target /// triple. TargetInfo * TargetInfo::CreateTargetInfo(DiagnosticsEngine &Diags, const std::shared_ptr<TargetOptions> &Opts) { llvm::Triple Triple(Opts->Triple); // Construct the target std::unique_ptr<TargetInfo> Target(AllocateTarget(Triple, Opts.get()->DescriptionString)); if (!Target) { Diags.Report(diag::err_target_unknown_triple) << Triple.str(); return nullptr; } Target->TargetOpts = Opts; // Set the target CPU if specified. if (!Opts->CPU.empty() && !Target->setCPU(Opts->CPU)) { Diags.Report(diag::err_target_unknown_cpu) << Opts->CPU; return nullptr; } // Set the target ABI if specified. if (!Opts->ABI.empty() && !Target->setABI(Opts->ABI)) { Diags.Report(diag::err_target_unknown_abi) << Opts->ABI; return nullptr; } // Set the fp math unit. if (!Opts->FPMath.empty() && !Target->setFPMath(Opts->FPMath)) { Diags.Report(diag::err_target_unknown_fpmath) << Opts->FPMath; return nullptr; } // Compute the default target features, we need the target to handle this // because features may have dependencies on one another. llvm::StringMap<bool> Features; Target->getDefaultFeatures(Features); // Apply the user specified deltas. for (unsigned I = 0, N = Opts->FeaturesAsWritten.size(); I < N; ++I) { const char *Name = Opts->FeaturesAsWritten[I].c_str(); // Apply the feature via the target. bool Enabled = Name[0] == '+'; Target->setFeatureEnabled(Features, Name + 1, Enabled); } // Add the features to the compile options. // // FIXME: If we are completely confident that we have the right set, we only // need to pass the minuses. Opts->Features.clear(); for (llvm::StringMap<bool>::const_iterator it = Features.begin(), ie = Features.end(); it != ie; ++it) Opts->Features.push_back((it->second ? "+" : "-") + it->first().str()); if (!Target->handleTargetFeatures(Opts->Features, Diags)) return nullptr; return Target.release(); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/VirtualFileSystem.cpp
//===- VirtualFileSystem.cpp - Virtual File System Layer --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // This file implements the VirtualFileSystem interface. //===----------------------------------------------------------------------===// #include "clang/Basic/VirtualFileSystem.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSet.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Errc.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/YAMLParser.h" #include <atomic> #include <memory> using namespace clang; using namespace clang::vfs; using namespace llvm; using llvm::sys::fs::file_status; using llvm::sys::fs::file_type; using llvm::sys::fs::perms; using llvm::sys::fs::UniqueID; Status::Status(const file_status &Status) : UID(Status.getUniqueID()), MTime(Status.getLastModificationTime()), User(Status.getUser()), Group(Status.getGroup()), Size(Status.getSize()), Type(Status.type()), Perms(Status.permissions()), IsVFSMapped(false) {} Status::Status(StringRef Name, StringRef ExternalName, UniqueID UID, sys::TimeValue MTime, uint32_t User, uint32_t Group, uint64_t Size, file_type Type, perms Perms) : Name(Name), UID(UID), MTime(MTime), User(User), Group(Group), Size(Size), Type(Type), Perms(Perms), IsVFSMapped(false) {} bool Status::equivalent(const Status &Other) const { return getUniqueID() == Other.getUniqueID(); } bool Status::isDirectory() const { return Type == file_type::directory_file; } bool Status::isRegularFile() const { return Type == file_type::regular_file; } bool Status::isOther() const { return exists() && !isRegularFile() && !isDirectory() && !isSymlink(); } bool Status::isSymlink() const { return Type == file_type::symlink_file; } bool Status::isStatusKnown() const { return Type != file_type::status_error; } bool Status::exists() const { return isStatusKnown() && Type != file_type::file_not_found; } File::~File() {} FileSystem::~FileSystem() {} ErrorOr<std::unique_ptr<MemoryBuffer>> FileSystem::getBufferForFile(const llvm::Twine &Name, int64_t FileSize, bool RequiresNullTerminator, bool IsVolatile) { auto F = openFileForRead(Name); if (!F) return F.getError(); return (*F)->getBuffer(Name, FileSize, RequiresNullTerminator, IsVolatile); } //===-----------------------------------------------------------------------===/ // RealFileSystem implementation //===-----------------------------------------------------------------------===/ namespace { /// \brief Wrapper around a raw file descriptor. class RealFile : public File { int FD; Status S; friend class RealFileSystem; RealFile(int FD) : FD(FD) { assert(FD >= 0 && "Invalid or inactive file descriptor"); } public: ~RealFile() override; ErrorOr<Status> status() override; ErrorOr<std::unique_ptr<MemoryBuffer>> getBuffer(const Twine &Name, int64_t FileSize = -1, bool RequiresNullTerminator = true, bool IsVolatile = false) override; std::error_code close() override; void setName(StringRef Name) override; }; } // end anonymous namespace RealFile::~RealFile() { close(); } ErrorOr<Status> RealFile::status() { assert(FD != -1 && "cannot stat closed file"); if (!S.isStatusKnown()) { file_status RealStatus; if (std::error_code EC = sys::fs::status(FD, RealStatus)) return EC; Status NewS(RealStatus); NewS.setName(S.getName()); S = std::move(NewS); } return S; } ErrorOr<std::unique_ptr<MemoryBuffer>> RealFile::getBuffer(const Twine &Name, int64_t FileSize, bool RequiresNullTerminator, bool IsVolatile) { assert(FD != -1 && "cannot get buffer for closed file"); return MemoryBuffer::getOpenFile(FD, Name, FileSize, RequiresNullTerminator, IsVolatile); } // FIXME: This is terrible, we need this for ::close. #if !defined(_MSC_VER) && !defined(__MINGW32__) #include <unistd.h> #include <sys/uio.h> #else #include <io.h> #ifndef S_ISFIFO #define S_ISFIFO(x) (0) #endif #endif #include "llvm/Support/FileSystem.h" // HLSL Change std::error_code RealFile::close() { if (llvm::sys::fs::msf_close(FD)) // HLSL Change return std::error_code(errno, std::generic_category()); FD = -1; return std::error_code(); } void RealFile::setName(StringRef Name) { S.setName(Name); } namespace { /// \brief The file system according to your operating system. class RealFileSystem : public FileSystem { public: ErrorOr<Status> status(const Twine &Path) override; ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override; directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override; }; } // end anonymous namespace ErrorOr<Status> RealFileSystem::status(const Twine &Path) { sys::fs::file_status RealStatus; if (std::error_code EC = sys::fs::status(Path, RealStatus)) return EC; Status Result(RealStatus); Result.setName(Path.str()); return Result; } ErrorOr<std::unique_ptr<File>> RealFileSystem::openFileForRead(const Twine &Name) { int FD; if (std::error_code EC = sys::fs::openFileForRead(Name, FD)) return EC; std::unique_ptr<File> Result(new RealFile(FD)); Result->setName(Name.str()); return std::move(Result); } #if 0 // HLSL Change Starts IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() { static IntrusiveRefCntPtr<FileSystem> FS = new RealFileSystem(); return FS; } #else static RealFileSystem g_RealFileSystem; IntrusiveRefCntPtr<FileSystem> vfs::getRealFileSystem() { g_RealFileSystem.Retain(); // never let go - TODO: guard against refcount wraparound IntrusiveRefCntPtr<FileSystem> Result(&g_RealFileSystem); return Result; } #endif // HLSL Change Ends namespace { class RealFSDirIter : public clang::vfs::detail::DirIterImpl { std::string Path; llvm::sys::fs::directory_iterator Iter; public: RealFSDirIter(const Twine &_Path, std::error_code &EC) : Path(_Path.str()), Iter(Path, EC) { if (!EC && Iter != llvm::sys::fs::directory_iterator()) { llvm::sys::fs::file_status S; EC = Iter->status(S); if (!EC) { CurrentEntry = Status(S); CurrentEntry.setName(Iter->path()); } } } std::error_code increment() override { std::error_code EC; Iter.increment(EC); if (EC) { return EC; } else if (Iter == llvm::sys::fs::directory_iterator()) { CurrentEntry = Status(); } else { llvm::sys::fs::file_status S; EC = Iter->status(S); CurrentEntry = Status(S); CurrentEntry.setName(Iter->path()); } return EC; } }; } directory_iterator RealFileSystem::dir_begin(const Twine &Dir, std::error_code &EC) { return directory_iterator(std::make_shared<RealFSDirIter>(Dir, EC)); } //===-----------------------------------------------------------------------===/ // OverlayFileSystem implementation //===-----------------------------------------------------------------------===/ OverlayFileSystem::OverlayFileSystem(IntrusiveRefCntPtr<FileSystem> BaseFS) { pushOverlay(BaseFS); } void OverlayFileSystem::pushOverlay(IntrusiveRefCntPtr<FileSystem> FS) { FSList.push_back(FS); } ErrorOr<Status> OverlayFileSystem::status(const Twine &Path) { // FIXME: handle symlinks that cross file systems for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) { ErrorOr<Status> Status = (*I)->status(Path); if (Status || Status.getError() != llvm::errc::no_such_file_or_directory) return Status; } return make_error_code(llvm::errc::no_such_file_or_directory); } ErrorOr<std::unique_ptr<File>> OverlayFileSystem::openFileForRead(const llvm::Twine &Path) { // FIXME: handle symlinks that cross file systems for (iterator I = overlays_begin(), E = overlays_end(); I != E; ++I) { auto Result = (*I)->openFileForRead(Path); if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) return Result; } return make_error_code(llvm::errc::no_such_file_or_directory); } clang::vfs::detail::DirIterImpl::~DirIterImpl() { } namespace { class OverlayFSDirIterImpl : public clang::vfs::detail::DirIterImpl { OverlayFileSystem &Overlays; std::string Path; OverlayFileSystem::iterator CurrentFS; directory_iterator CurrentDirIter; llvm::StringSet<> SeenNames; std::error_code incrementFS() { assert(CurrentFS != Overlays.overlays_end() && "incrementing past end"); ++CurrentFS; for (auto E = Overlays.overlays_end(); CurrentFS != E; ++CurrentFS) { std::error_code EC; CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC); if (EC && EC != errc::no_such_file_or_directory) return EC; if (CurrentDirIter != directory_iterator()) break; // found } return std::error_code(); } std::error_code incrementDirIter(bool IsFirstTime) { assert((IsFirstTime || CurrentDirIter != directory_iterator()) && "incrementing past end"); std::error_code EC; if (!IsFirstTime) CurrentDirIter.increment(EC); if (!EC && CurrentDirIter == directory_iterator()) EC = incrementFS(); return EC; } std::error_code incrementImpl(bool IsFirstTime) { while (true) { std::error_code EC = incrementDirIter(IsFirstTime); if (EC || CurrentDirIter == directory_iterator()) { CurrentEntry = Status(); return EC; } CurrentEntry = *CurrentDirIter; StringRef Name = llvm::sys::path::filename(CurrentEntry.getName()); if (SeenNames.insert(Name).second) return EC; // name not seen before } llvm_unreachable("returned above"); } public: OverlayFSDirIterImpl(const Twine &Path, OverlayFileSystem &FS, std::error_code &EC) : Overlays(FS), Path(Path.str()), CurrentFS(Overlays.overlays_begin()) { CurrentDirIter = (*CurrentFS)->dir_begin(Path, EC); EC = incrementImpl(true); } std::error_code increment() override { return incrementImpl(false); } }; } // end anonymous namespace directory_iterator OverlayFileSystem::dir_begin(const Twine &Dir, std::error_code &EC) { return directory_iterator( std::make_shared<OverlayFSDirIterImpl>(Dir, *this, EC)); } //===-----------------------------------------------------------------------===/ // VFSFromYAML implementation //===-----------------------------------------------------------------------===/ namespace { enum EntryKind { EK_Directory, EK_File }; /// \brief A single file or directory in the VFS. class Entry { EntryKind Kind; std::string Name; public: virtual ~Entry(); Entry(EntryKind K, StringRef Name) : Kind(K), Name(Name) {} StringRef getName() const { return Name; } EntryKind getKind() const { return Kind; } }; class DirectoryEntry : public Entry { std::vector<Entry *> Contents; Status S; public: ~DirectoryEntry() override; DirectoryEntry(StringRef Name, std::vector<Entry *> Contents, Status S) : Entry(EK_Directory, Name), Contents(std::move(Contents)), S(std::move(S)) {} Status getStatus() { return S; } typedef std::vector<Entry *>::iterator iterator; iterator contents_begin() { return Contents.begin(); } iterator contents_end() { return Contents.end(); } static bool classof(const Entry *E) { return E->getKind() == EK_Directory; } }; class FileEntry : public Entry { public: enum NameKind { NK_NotSet, NK_External, NK_Virtual }; private: std::string ExternalContentsPath; NameKind UseName; public: FileEntry(StringRef Name, StringRef ExternalContentsPath, NameKind UseName) : Entry(EK_File, Name), ExternalContentsPath(ExternalContentsPath), UseName(UseName) {} StringRef getExternalContentsPath() const { return ExternalContentsPath; } /// \brief whether to use the external path as the name for this file. bool useExternalName(bool GlobalUseExternalName) const { return UseName == NK_NotSet ? GlobalUseExternalName : (UseName == NK_External); } static bool classof(const Entry *E) { return E->getKind() == EK_File; } }; class VFSFromYAML; class VFSFromYamlDirIterImpl : public clang::vfs::detail::DirIterImpl { std::string Dir; VFSFromYAML &FS; DirectoryEntry::iterator Current, End; public: VFSFromYamlDirIterImpl(const Twine &Path, VFSFromYAML &FS, DirectoryEntry::iterator Begin, DirectoryEntry::iterator End, std::error_code &EC); std::error_code increment() override; }; /// \brief A virtual file system parsed from a YAML file. /// /// Currently, this class allows creating virtual directories and mapping /// virtual file paths to existing external files, available in \c ExternalFS. /// /// The basic structure of the parsed file is: /// \verbatim /// { /// 'version': <version number>, /// <optional configuration> /// 'roots': [ /// <directory entries> /// ] /// } /// \endverbatim /// /// All configuration options are optional. /// 'case-sensitive': <boolean, default=true> /// 'use-external-names': <boolean, default=true> /// /// Virtual directories are represented as /// \verbatim /// { /// 'type': 'directory', /// 'name': <string>, /// 'contents': [ <file or directory entries> ] /// } /// \endverbatim /// /// The default attributes for virtual directories are: /// \verbatim /// MTime = now() when created /// Perms = 0777 /// User = Group = 0 /// Size = 0 /// UniqueID = unspecified unique value /// \endverbatim /// /// Re-mapped files are represented as /// \verbatim /// { /// 'type': 'file', /// 'name': <string>, /// 'use-external-name': <boolean> # Optional /// 'external-contents': <path to external file>) /// } /// \endverbatim /// /// and inherit their attributes from the external contents. /// /// In both cases, the 'name' field may contain multiple path components (e.g. /// /path/to/file). However, any directory that contains more than one child /// must be uniquely represented by a directory entry. class VFSFromYAML : public vfs::FileSystem { std::vector<Entry *> Roots; ///< The root(s) of the virtual file system. /// \brief The file system to use for external references. IntrusiveRefCntPtr<FileSystem> ExternalFS; /// @name Configuration /// @{ /// \brief Whether to perform case-sensitive comparisons. /// /// Currently, case-insensitive matching only works correctly with ASCII. bool CaseSensitive; /// \brief Whether to use to use the value of 'external-contents' for the /// names of files. This global value is overridable on a per-file basis. bool UseExternalNames; /// @} friend class VFSFromYAMLParser; private: VFSFromYAML(IntrusiveRefCntPtr<FileSystem> ExternalFS) : ExternalFS(ExternalFS), CaseSensitive(true), UseExternalNames(true) {} /// \brief Looks up \p Path in \c Roots. ErrorOr<Entry *> lookupPath(const Twine &Path); /// \brief Looks up the path <tt>[Start, End)</tt> in \p From, possibly /// recursing into the contents of \p From if it is a directory. ErrorOr<Entry *> lookupPath(sys::path::const_iterator Start, sys::path::const_iterator End, Entry *From); /// \brief Get the status of a given an \c Entry. ErrorOr<Status> status(const Twine &Path, Entry *E); public: ~VFSFromYAML() override; /// \brief Parses \p Buffer, which is expected to be in YAML format and /// returns a virtual file system representing its contents. static VFSFromYAML *create(std::unique_ptr<MemoryBuffer> Buffer, SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS); ErrorOr<Status> status(const Twine &Path) override; ErrorOr<std::unique_ptr<File>> openFileForRead(const Twine &Path) override; directory_iterator dir_begin(const Twine &Dir, std::error_code &EC) override{ ErrorOr<Entry *> E = lookupPath(Dir); if (!E) { EC = E.getError(); return directory_iterator(); } ErrorOr<Status> S = status(Dir, *E); if (!S) { EC = S.getError(); return directory_iterator(); } if (!S->isDirectory()) { EC = std::error_code(static_cast<int>(errc::not_a_directory), std::system_category()); return directory_iterator(); } DirectoryEntry *D = cast<DirectoryEntry>(*E); return directory_iterator(std::make_shared<VFSFromYamlDirIterImpl>(Dir, *this, D->contents_begin(), D->contents_end(), EC)); } }; /// \brief A helper class to hold the common YAML parsing state. class VFSFromYAMLParser { yaml::Stream &Stream; void error(yaml::Node *N, const Twine &Msg) { Stream.printError(N, Msg); } // false on error bool parseScalarString(yaml::Node *N, StringRef &Result, SmallVectorImpl<char> &Storage) { yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N); if (!S) { error(N, "expected string"); return false; } Result = S->getValue(Storage); return true; } // false on error bool parseScalarBool(yaml::Node *N, bool &Result) { SmallString<5> Storage; StringRef Value; if (!parseScalarString(N, Value, Storage)) return false; if (Value.equals_lower("true") || Value.equals_lower("on") || Value.equals_lower("yes") || Value == "1") { Result = true; return true; } else if (Value.equals_lower("false") || Value.equals_lower("off") || Value.equals_lower("no") || Value == "0") { Result = false; return true; } error(N, "expected boolean value"); return false; } struct KeyStatus { KeyStatus(bool Required=false) : Required(Required), Seen(false) {} bool Required; bool Seen; }; typedef std::pair<StringRef, KeyStatus> KeyStatusPair; // false on error bool checkDuplicateOrUnknownKey(yaml::Node *KeyNode, StringRef Key, DenseMap<StringRef, KeyStatus> &Keys) { if (!Keys.count(Key)) { error(KeyNode, "unknown key"); return false; } KeyStatus &S = Keys[Key]; if (S.Seen) { error(KeyNode, Twine("duplicate key '") + Key + "'"); return false; } S.Seen = true; return true; } // false on error bool checkMissingKeys(yaml::Node *Obj, DenseMap<StringRef, KeyStatus> &Keys) { for (DenseMap<StringRef, KeyStatus>::iterator I = Keys.begin(), E = Keys.end(); I != E; ++I) { if (I->second.Required && !I->second.Seen) { error(Obj, Twine("missing key '") + I->first + "'"); return false; } } return true; } Entry *parseEntry(yaml::Node *N) { yaml::MappingNode *M = dyn_cast<yaml::MappingNode>(N); if (!M) { error(N, "expected mapping node for file or directory entry"); return nullptr; } KeyStatusPair Fields[] = { KeyStatusPair("name", true), KeyStatusPair("type", true), KeyStatusPair("contents", false), KeyStatusPair("external-contents", false), KeyStatusPair("use-external-name", false), }; DenseMap<StringRef, KeyStatus> Keys( &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0])); bool HasContents = false; // external or otherwise std::vector<Entry *> EntryArrayContents; std::string ExternalContentsPath; std::string Name; FileEntry::NameKind UseExternalName = FileEntry::NK_NotSet; EntryKind Kind; for (yaml::MappingNode::iterator I = M->begin(), E = M->end(); I != E; ++I) { StringRef Key; // Reuse the buffer for key and value, since we don't look at key after // parsing value. SmallString<256> Buffer; if (!parseScalarString(I->getKey(), Key, Buffer)) return nullptr; if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys)) return nullptr; StringRef Value; if (Key == "name") { if (!parseScalarString(I->getValue(), Value, Buffer)) return nullptr; Name = Value; } else if (Key == "type") { if (!parseScalarString(I->getValue(), Value, Buffer)) return nullptr; if (Value == "file") Kind = EK_File; else if (Value == "directory") Kind = EK_Directory; else { error(I->getValue(), "unknown value for 'type'"); return nullptr; } } else if (Key == "contents") { if (HasContents) { error(I->getKey(), "entry already has 'contents' or 'external-contents'"); return nullptr; } HasContents = true; yaml::SequenceNode *Contents = dyn_cast<yaml::SequenceNode>(I->getValue()); if (!Contents) { // FIXME: this is only for directories, what about files? error(I->getValue(), "expected array"); return nullptr; } for (yaml::SequenceNode::iterator I = Contents->begin(), E = Contents->end(); I != E; ++I) { if (Entry *E = parseEntry(&*I)) EntryArrayContents.push_back(E); else return nullptr; } } else if (Key == "external-contents") { if (HasContents) { error(I->getKey(), "entry already has 'contents' or 'external-contents'"); return nullptr; } HasContents = true; if (!parseScalarString(I->getValue(), Value, Buffer)) return nullptr; ExternalContentsPath = Value; } else if (Key == "use-external-name") { bool Val; if (!parseScalarBool(I->getValue(), Val)) return nullptr; UseExternalName = Val ? FileEntry::NK_External : FileEntry::NK_Virtual; } else { llvm_unreachable("key missing from Keys"); } } if (Stream.failed()) return nullptr; // check for missing keys if (!HasContents) { error(N, "missing key 'contents' or 'external-contents'"); return nullptr; } if (!checkMissingKeys(N, Keys)) return nullptr; // check invalid configuration if (Kind == EK_Directory && UseExternalName != FileEntry::NK_NotSet) { error(N, "'use-external-name' is not supported for directories"); return nullptr; } // Remove trailing slash(es), being careful not to remove the root path StringRef Trimmed(Name); size_t RootPathLen = sys::path::root_path(Trimmed).size(); while (Trimmed.size() > RootPathLen && sys::path::is_separator(Trimmed.back())) Trimmed = Trimmed.slice(0, Trimmed.size()-1); // Get the last component StringRef LastComponent = sys::path::filename(Trimmed); Entry *Result = nullptr; switch (Kind) { case EK_File: Result = new FileEntry(LastComponent, std::move(ExternalContentsPath), UseExternalName); break; case EK_Directory: Result = new DirectoryEntry(LastComponent, std::move(EntryArrayContents), Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0, file_type::directory_file, sys::fs::all_all)); break; } StringRef Parent = sys::path::parent_path(Trimmed); if (Parent.empty()) return Result; // if 'name' contains multiple components, create implicit directory entries for (sys::path::reverse_iterator I = sys::path::rbegin(Parent), E = sys::path::rend(Parent); I != E; ++I) { Result = new DirectoryEntry(*I, llvm::makeArrayRef(Result), Status("", "", getNextVirtualUniqueID(), sys::TimeValue::now(), 0, 0, 0, file_type::directory_file, sys::fs::all_all)); } return Result; } public: VFSFromYAMLParser(yaml::Stream &S) : Stream(S) {} // false on error bool parse(yaml::Node *Root, VFSFromYAML *FS) { yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root); if (!Top) { error(Root, "expected mapping node"); return false; } KeyStatusPair Fields[] = { KeyStatusPair("version", true), KeyStatusPair("case-sensitive", false), KeyStatusPair("use-external-names", false), KeyStatusPair("roots", true), }; DenseMap<StringRef, KeyStatus> Keys( &Fields[0], Fields + sizeof(Fields)/sizeof(Fields[0])); // Parse configuration and 'roots' for (yaml::MappingNode::iterator I = Top->begin(), E = Top->end(); I != E; ++I) { SmallString<10> KeyBuffer; StringRef Key; if (!parseScalarString(I->getKey(), Key, KeyBuffer)) return false; if (!checkDuplicateOrUnknownKey(I->getKey(), Key, Keys)) return false; if (Key == "roots") { yaml::SequenceNode *Roots = dyn_cast<yaml::SequenceNode>(I->getValue()); if (!Roots) { error(I->getValue(), "expected array"); return false; } for (yaml::SequenceNode::iterator I = Roots->begin(), E = Roots->end(); I != E; ++I) { if (Entry *E = parseEntry(&*I)) FS->Roots.push_back(E); else return false; } } else if (Key == "version") { StringRef VersionString; SmallString<4> Storage; if (!parseScalarString(I->getValue(), VersionString, Storage)) return false; int Version; if (VersionString.getAsInteger<int>(10, Version)) { error(I->getValue(), "expected integer"); return false; } if (Version < 0) { error(I->getValue(), "invalid version number"); return false; } if (Version != 0) { error(I->getValue(), "version mismatch, expected 0"); return false; } } else if (Key == "case-sensitive") { if (!parseScalarBool(I->getValue(), FS->CaseSensitive)) return false; } else if (Key == "use-external-names") { if (!parseScalarBool(I->getValue(), FS->UseExternalNames)) return false; } else { llvm_unreachable("key missing from Keys"); } } if (Stream.failed()) return false; if (!checkMissingKeys(Top, Keys)) return false; return true; } }; } // end of anonymous namespace Entry::~Entry() {} DirectoryEntry::~DirectoryEntry() { llvm::DeleteContainerPointers(Contents); } VFSFromYAML::~VFSFromYAML() { llvm::DeleteContainerPointers(Roots); } VFSFromYAML *VFSFromYAML::create(std::unique_ptr<MemoryBuffer> Buffer, SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS) { SourceMgr SM; yaml::Stream Stream(Buffer->getMemBufferRef(), SM); SM.setDiagHandler(DiagHandler, DiagContext); yaml::document_iterator DI = Stream.begin(); yaml::Node *Root = DI->getRoot(); if (DI == Stream.end() || !Root) { SM.PrintMessage(SMLoc(), SourceMgr::DK_Error, "expected root node"); return nullptr; } VFSFromYAMLParser P(Stream); std::unique_ptr<VFSFromYAML> FS(new VFSFromYAML(ExternalFS)); if (!P.parse(Root, FS.get())) return nullptr; return FS.release(); } ErrorOr<Entry *> VFSFromYAML::lookupPath(const Twine &Path_) { SmallString<256> Path; Path_.toVector(Path); // Handle relative paths if (std::error_code EC = sys::fs::make_absolute(Path)) return EC; if (Path.empty()) return make_error_code(llvm::errc::invalid_argument); sys::path::const_iterator Start = sys::path::begin(Path); sys::path::const_iterator End = sys::path::end(Path); for (std::vector<Entry *>::iterator I = Roots.begin(), E = Roots.end(); I != E; ++I) { ErrorOr<Entry *> Result = lookupPath(Start, End, *I); if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) return Result; } return make_error_code(llvm::errc::no_such_file_or_directory); } ErrorOr<Entry *> VFSFromYAML::lookupPath(sys::path::const_iterator Start, sys::path::const_iterator End, Entry *From) { if (Start->equals(".")) ++Start; // FIXME: handle .. if (CaseSensitive ? !Start->equals(From->getName()) : !Start->equals_lower(From->getName())) // failure to match return make_error_code(llvm::errc::no_such_file_or_directory); ++Start; if (Start == End) { // Match! return From; } DirectoryEntry *DE = dyn_cast<DirectoryEntry>(From); if (!DE) return make_error_code(llvm::errc::not_a_directory); for (DirectoryEntry::iterator I = DE->contents_begin(), E = DE->contents_end(); I != E; ++I) { ErrorOr<Entry *> Result = lookupPath(Start, End, *I); if (Result || Result.getError() != llvm::errc::no_such_file_or_directory) return Result; } return make_error_code(llvm::errc::no_such_file_or_directory); } ErrorOr<Status> VFSFromYAML::status(const Twine &Path, Entry *E) { assert(E != nullptr); std::string PathStr(Path.str()); if (FileEntry *F = dyn_cast<FileEntry>(E)) { ErrorOr<Status> S = ExternalFS->status(F->getExternalContentsPath()); assert(!S || S->getName() == F->getExternalContentsPath()); if (S && !F->useExternalName(UseExternalNames)) S->setName(PathStr); if (S) S->IsVFSMapped = true; return S; } else { // directory DirectoryEntry *DE = cast<DirectoryEntry>(E); Status S = DE->getStatus(); S.setName(PathStr); return S; } } ErrorOr<Status> VFSFromYAML::status(const Twine &Path) { ErrorOr<Entry *> Result = lookupPath(Path); if (!Result) return Result.getError(); return status(Path, *Result); } ErrorOr<std::unique_ptr<File>> VFSFromYAML::openFileForRead(const Twine &Path) { ErrorOr<Entry *> E = lookupPath(Path); if (!E) return E.getError(); FileEntry *F = dyn_cast<FileEntry>(*E); if (!F) // FIXME: errc::not_a_file? return make_error_code(llvm::errc::invalid_argument); auto Result = ExternalFS->openFileForRead(F->getExternalContentsPath()); if (!Result) return Result; if (!F->useExternalName(UseExternalNames)) (*Result)->setName(Path.str()); return Result; } IntrusiveRefCntPtr<FileSystem> vfs::getVFSFromYAML(std::unique_ptr<MemoryBuffer> Buffer, SourceMgr::DiagHandlerTy DiagHandler, void *DiagContext, IntrusiveRefCntPtr<FileSystem> ExternalFS) { return VFSFromYAML::create(std::move(Buffer), DiagHandler, DiagContext, ExternalFS); } UniqueID vfs::getNextVirtualUniqueID() { static std::atomic<unsigned> UID; unsigned ID = ++UID; // The following assumes that uint64_t max will never collide with a real // dev_t value from the OS. return UniqueID(std::numeric_limits<uint64_t>::max(), ID); } #ifndef NDEBUG static bool pathHasTraversal(StringRef Path) { using namespace llvm::sys; for (StringRef Comp : llvm::make_range(path::begin(Path), path::end(Path))) if (Comp == "." || Comp == "..") return true; return false; } #endif void YAMLVFSWriter::addFileMapping(StringRef VirtualPath, StringRef RealPath) { assert(sys::path::is_absolute(VirtualPath) && "virtual path not absolute"); assert(sys::path::is_absolute(RealPath) && "real path not absolute"); assert(!pathHasTraversal(VirtualPath) && "path traversal is not supported"); Mappings.emplace_back(VirtualPath, RealPath); } namespace { class JSONWriter { llvm::raw_ostream &OS; SmallVector<StringRef, 16> DirStack; inline unsigned getDirIndent() { return 4 * DirStack.size(); } inline unsigned getFileIndent() { return 4 * (DirStack.size() + 1); } bool containedIn(StringRef Parent, StringRef Path); StringRef containedPart(StringRef Parent, StringRef Path); void startDirectory(StringRef Path); void endDirectory(); void writeEntry(StringRef VPath, StringRef RPath); public: JSONWriter(llvm::raw_ostream &OS) : OS(OS) {} void write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive); }; } bool JSONWriter::containedIn(StringRef Parent, StringRef Path) { using namespace llvm::sys; // Compare each path component. auto IParent = path::begin(Parent), EParent = path::end(Parent); for (auto IChild = path::begin(Path), EChild = path::end(Path); IParent != EParent && IChild != EChild; ++IParent, ++IChild) { if (*IParent != *IChild) return false; } // Have we exhausted the parent path? return IParent == EParent; } StringRef JSONWriter::containedPart(StringRef Parent, StringRef Path) { assert(!Parent.empty()); assert(containedIn(Parent, Path)); return Path.slice(Parent.size() + 1, StringRef::npos); } void JSONWriter::startDirectory(StringRef Path) { StringRef Name = DirStack.empty() ? Path : containedPart(DirStack.back(), Path); DirStack.push_back(Path); unsigned Indent = getDirIndent(); OS.indent(Indent) << "{\n"; OS.indent(Indent + 2) << "'type': 'directory',\n"; OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(Name) << "\",\n"; OS.indent(Indent + 2) << "'contents': [\n"; } void JSONWriter::endDirectory() { unsigned Indent = getDirIndent(); OS.indent(Indent + 2) << "]\n"; OS.indent(Indent) << "}"; DirStack.pop_back(); } void JSONWriter::writeEntry(StringRef VPath, StringRef RPath) { unsigned Indent = getFileIndent(); OS.indent(Indent) << "{\n"; OS.indent(Indent + 2) << "'type': 'file',\n"; OS.indent(Indent + 2) << "'name': \"" << llvm::yaml::escape(VPath) << "\",\n"; OS.indent(Indent + 2) << "'external-contents': \"" << llvm::yaml::escape(RPath) << "\"\n"; OS.indent(Indent) << "}"; } void JSONWriter::write(ArrayRef<YAMLVFSEntry> Entries, Optional<bool> IsCaseSensitive) { using namespace llvm::sys; OS << "{\n" " 'version': 0,\n"; if (IsCaseSensitive.hasValue()) OS << " 'case-sensitive': '" << (IsCaseSensitive.getValue() ? "true" : "false") << "',\n"; OS << " 'roots': [\n"; if (!Entries.empty()) { const YAMLVFSEntry &Entry = Entries.front(); startDirectory(path::parent_path(Entry.VPath)); writeEntry(path::filename(Entry.VPath), Entry.RPath); for (const auto &Entry : Entries.slice(1)) { StringRef Dir = path::parent_path(Entry.VPath); if (Dir == DirStack.back()) OS << ",\n"; else { while (!DirStack.empty() && !containedIn(DirStack.back(), Dir)) { OS << "\n"; endDirectory(); } OS << ",\n"; startDirectory(Dir); } writeEntry(path::filename(Entry.VPath), Entry.RPath); } while (!DirStack.empty()) { OS << "\n"; endDirectory(); } OS << "\n"; } OS << " ]\n" << "}\n"; } void YAMLVFSWriter::write(llvm::raw_ostream &OS) { std::sort(Mappings.begin(), Mappings.end(), [](const YAMLVFSEntry &LHS, const YAMLVFSEntry &RHS) { return LHS.VPath < RHS.VPath; }); JSONWriter(OS).write(Mappings, IsCaseSensitive); } VFSFromYamlDirIterImpl::VFSFromYamlDirIterImpl(const Twine &_Path, VFSFromYAML &FS, DirectoryEntry::iterator Begin, DirectoryEntry::iterator End, std::error_code &EC) : Dir(_Path.str()), FS(FS), Current(Begin), End(End) { if (Current != End) { SmallString<128> PathStr(Dir); llvm::sys::path::append(PathStr, (*Current)->getName()); llvm::ErrorOr<vfs::Status> S = FS.status(PathStr); if (S) CurrentEntry = *S; else EC = S.getError(); } } std::error_code VFSFromYamlDirIterImpl::increment() { assert(Current != End && "cannot iterate past end"); if (++Current != End) { SmallString<128> PathStr(Dir); llvm::sys::path::append(PathStr, (*Current)->getName()); llvm::ErrorOr<vfs::Status> S = FS.status(PathStr); if (!S) return S.getError(); CurrentEntry = *S; } else { CurrentEntry = Status(); } return std::error_code(); } vfs::recursive_directory_iterator::recursive_directory_iterator(FileSystem &FS_, const Twine &Path, std::error_code &EC) : FS(&FS_) { directory_iterator I = FS->dir_begin(Path, EC); if (!EC && I != directory_iterator()) { State = std::make_shared<IterState>(); State->push(I); } } vfs::recursive_directory_iterator & recursive_directory_iterator::increment(std::error_code &EC) { assert(FS && State && !State->empty() && "incrementing past end"); assert(State->top()->isStatusKnown() && "non-canonical end iterator"); vfs::directory_iterator End; if (State->top()->isDirectory()) { vfs::directory_iterator I = FS->dir_begin(State->top()->getName(), EC); if (EC) return *this; if (I != End) { State->push(I); return *this; } } while (!State->empty() && State->top().increment(EC) == End) State->pop(); if (State->empty()) State.reset(); // end iterator return *this; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/Version.cpp
//===- Version.cpp - Clang Version Number -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines several version-related utility functions for Clang. // //===----------------------------------------------------------------------===// #include "clang/Basic/Version.h" #include "clang/Basic/LLVM.h" #include "clang/Config/config.h" #include "llvm/Support/raw_ostream.h" #include <cstdlib> #include <cstring> #ifdef HAVE_SVN_VERSION_INC # include "SVNVersion.inc" #endif // HLSL Change Starts #include "dxcversion.inc" // Here are some defaults, but these should be defined in dxcversion.inc #ifndef HLSL_TOOL_NAME #define HLSL_TOOL_NAME "dxc(private)" #endif #ifndef HLSL_LLVM_IDENT #ifdef RC_FILE_VERSION #define HLSL_LLVM_IDENT HLSL_TOOL_NAME " " RC_FILE_VERSION #else #define HLSL_LLVM_IDENT HLSL_TOOL_NAME " version unknown" #endif #endif #ifndef HLSL_VERSION_MACRO #ifdef RC_PRODUCT_VERSION #define HLSL_VERSION_MACRO HLSL_TOOL_NAME " " RC_PRODUCT_VERSION #else #define HLSL_VERSION_MACRO HLSL_TOOL_NAME " version unknown" #endif #endif // HLSL Change Ends namespace clang { std::string getClangRepositoryPath() { #ifdef HLSL_FIXED_VER // HLSL Change Starts return std::string(); #else #if defined(CLANG_REPOSITORY_STRING) return CLANG_REPOSITORY_STRING; #else #ifdef SVN_REPOSITORY StringRef URL(SVN_REPOSITORY); #else StringRef URL(""); #endif // If the SVN_REPOSITORY is empty, try to use the SVN keyword. This helps us // pick up a tag in an SVN export, for example. StringRef SVNRepository("$URL: https://llvm.org/svn/llvm-project/cfe/tags/RELEASE_370/final/lib/Basic/Version.cpp $"); if (URL.empty()) { URL = SVNRepository.slice(SVNRepository.find(':'), SVNRepository.find("/lib/Basic")); } // Strip off version from a build from an integration branch. URL = URL.slice(0, URL.find("/src/tools/clang")); // Trim path prefix off, assuming path came from standard cfe path. size_t Start = URL.find("cfe/"); if (Start != StringRef::npos) URL = URL.substr(Start + 4); return URL; #endif #endif // HLSL Change Ends } std::string getLLVMRepositoryPath() { #ifdef HLSL_FIXED_VER // HLSL Change Starts return std::string(); #else #ifdef LLVM_REPOSITORY StringRef URL(LLVM_REPOSITORY); #else StringRef URL(""); #endif // Trim path prefix off, assuming path came from standard llvm path. // Leave "llvm/" prefix to distinguish the following llvm revision from the // clang revision. size_t Start = URL.find("llvm/"); if (Start != StringRef::npos) URL = URL.substr(Start); return URL; #endif // HLSL Change Ends } std::string getClangRevision() { #ifdef HLSL_FIXED_VER // HLSL Change Starts return std::string(); #else #ifdef SVN_REVISION return SVN_REVISION; #else return ""; #endif #endif // HLSL Change Ends } std::string getLLVMRevision() { #ifdef HLSL_FIXED_VER // HLSL Change Starts return std::string(); #else #ifdef LLVM_REVISION return LLVM_REVISION; #else return ""; #endif #endif // HLSL Change Ends } std::string getClangFullRepositoryVersion() { #ifdef HLSL_FIXED_VER // HLSL Change Starts return std::string(); #else std::string buf; llvm::raw_string_ostream OS(buf); std::string Path = getClangRepositoryPath(); std::string Revision = getClangRevision(); if (!Path.empty() || !Revision.empty()) { OS << '('; if (!Path.empty()) OS << Path; if (!Revision.empty()) { if (!Path.empty()) OS << ' '; OS << Revision; } OS << ')'; } // Support LLVM in a separate repository. std::string LLVMRev = getLLVMRevision(); if (!LLVMRev.empty() && LLVMRev != Revision) { OS << " ("; std::string LLVMRepo = getLLVMRepositoryPath(); if (!LLVMRepo.empty()) OS << LLVMRepo << ' '; OS << LLVMRev << ')'; } return OS.str(); #endif } std::string getClangFullVersion() { return getClangToolFullVersion(HLSL_TOOL_NAME); // HLSL Change } std::string getClangToolFullVersion(StringRef ToolName) { #ifdef HLSL_LLVM_IDENT // HLSL Change Starts return std::string(HLSL_LLVM_IDENT); #else // HLSL Change Ends std::string buf; llvm::raw_string_ostream OS(buf); #ifdef CLANG_VENDOR OS << CLANG_VENDOR; #endif OS << ToolName << " version " CLANG_VERSION_STRING " " << getClangFullRepositoryVersion(); // If vendor supplied, include the base LLVM version as well. #ifdef CLANG_VENDOR OS << " (based on " << BACKEND_PACKAGE_STRING << ")"; #endif return OS.str(); #endif // HLSL Change } std::string getClangFullCPPVersion() { #ifdef HLSL_VERSION_MACRO // HLSL Change Starts return std::string(HLSL_VERSION_MACRO); #else // HLSL Change Ends // The version string we report in __VERSION__ is just a compacted version of // the one we report on the command line. std::string buf; llvm::raw_string_ostream OS(buf); #ifdef CLANG_VENDOR OS << CLANG_VENDOR; #endif OS << "unofficial"; return OS.str(); #endif // HLSL Change } // HLSL Change Starts #ifdef SUPPORT_QUERY_GIT_COMMIT_INFO #include "GitCommitInfo.inc" uint32_t getGitCommitCount() { return kGitCommitCount; } const char *getGitCommitHash() { return kGitCommitHash; } #endif // SUPPORT_QUERY_GIT_COMMIT_INFO // HLSL Change Ends } // end namespace clang
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/DiagnosticOptions.cpp
//===--- DiagnosticOptions.cpp - C Language Family Diagnostic Handling ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the DiagnosticOptions related interfaces. // //===----------------------------------------------------------------------===// #include "clang/Basic/DiagnosticOptions.h" #include "llvm/Support/raw_ostream.h" namespace clang { raw_ostream& operator<<(raw_ostream& Out, DiagnosticLevelMask M) { using UT = std::underlying_type<DiagnosticLevelMask>::type; return Out << static_cast<UT>(M); } } // end namespace clang
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/FileManager.cpp
//===--- FileManager.cpp - File System Probing and Caching ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the FileManager interface. // //===----------------------------------------------------------------------===// // // TODO: This should index all interesting directories with dirent calls. // getdirentries ? // opendir/readdir_r/closedir ? // //===----------------------------------------------------------------------===// #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemStatCache.h" #include "clang/Frontend/PCHContainerOperations.h" #include "llvm/ADT/SmallString.h" #include "llvm/Config/llvm-config.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <map> #include <set> #include <string> #include <system_error> using namespace clang; /// NON_EXISTENT_DIR - A special value distinct from null that is used to /// represent a dir name that doesn't exist on the disk. #define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1) /// NON_EXISTENT_FILE - A special value distinct from null that is used to /// represent a filename that doesn't exist on the disk. #define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1) //===----------------------------------------------------------------------===// // Common logic. //===----------------------------------------------------------------------===// FileManager::FileManager(const FileSystemOptions &FSO, IntrusiveRefCntPtr<vfs::FileSystem> FS) : FS(FS), FileSystemOpts(FSO), SeenDirEntries(64), SeenFileEntries(64), NextFileUID(0) { NumDirLookups = NumFileLookups = 0; NumDirCacheMisses = NumFileCacheMisses = 0; // If the caller doesn't provide a virtual file system, just grab the real // file system. if (!FS) this->FS = vfs::getRealFileSystem(); } FileManager::~FileManager() { for (unsigned i = 0, e = VirtualFileEntries.size(); i != e; ++i) delete VirtualFileEntries[i]; for (unsigned i = 0, e = VirtualDirectoryEntries.size(); i != e; ++i) delete VirtualDirectoryEntries[i]; } void FileManager::addStatCache(std::unique_ptr<FileSystemStatCache> statCache, bool AtBeginning) { assert(statCache && "No stat cache provided?"); if (AtBeginning || !StatCache.get()) { statCache->setNextStatCache(std::move(StatCache)); StatCache = std::move(statCache); return; } FileSystemStatCache *LastCache = StatCache.get(); while (LastCache->getNextStatCache()) LastCache = LastCache->getNextStatCache(); LastCache->setNextStatCache(std::move(statCache)); } void FileManager::removeStatCache(FileSystemStatCache *statCache) { if (!statCache) return; if (StatCache.get() == statCache) { // This is the first stat cache. StatCache = StatCache->takeNextStatCache(); return; } // Find the stat cache in the list. FileSystemStatCache *PrevCache = StatCache.get(); while (PrevCache && PrevCache->getNextStatCache() != statCache) PrevCache = PrevCache->getNextStatCache(); assert(PrevCache && "Stat cache not found for removal"); PrevCache->setNextStatCache(statCache->takeNextStatCache()); } void FileManager::clearStatCaches() { StatCache.reset(); } /// \brief Retrieve the directory that the given file name resides in. /// Filename can point to either a real file or a virtual file. static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr, StringRef Filename, bool CacheFailure) { if (Filename.empty()) return nullptr; if (llvm::sys::path::is_separator(Filename[Filename.size() - 1])) return nullptr; // If Filename is a directory. StringRef DirName = llvm::sys::path::parent_path(Filename); // Use the current directory if file has no path component. if (DirName.empty()) DirName = "."; return FileMgr.getDirectory(DirName, CacheFailure); } /// Add all ancestors of the given path (pointing to either a file or /// a directory) as virtual directories. void FileManager::addAncestorsAsVirtualDirs(StringRef Path) { StringRef DirName = llvm::sys::path::parent_path(Path); if (DirName.empty()) return; auto &NamedDirEnt = *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; // When caching a virtual directory, we always cache its ancestors // at the same time. Therefore, if DirName is already in the cache, // we don't need to recurse as its ancestors must also already be in // the cache. if (NamedDirEnt.second) return; // Add the virtual directory to the cache. DirectoryEntry *UDE = new DirectoryEntry; UDE->Name = NamedDirEnt.first().data(); NamedDirEnt.second = UDE; VirtualDirectoryEntries.push_back(UDE); // Recursively add the other ancestors. addAncestorsAsVirtualDirs(DirName); } const DirectoryEntry *FileManager::getDirectory(StringRef DirName, bool CacheFailure) { // stat doesn't like trailing separators except for root directory. // At least, on Win32 MSVCRT, stat() cannot strip trailing '/'. // (though it can strip '\\') if (DirName.size() > 1 && DirName != llvm::sys::path::root_path(DirName) && llvm::sys::path::is_separator(DirName.back())) DirName = DirName.substr(0, DirName.size()-1); #ifdef LLVM_ON_WIN32 // Fixing a problem with "clang C:test.c" on Windows. // Stat("C:") does not recognize "C:" as a valid directory std::string DirNameStr; if (DirName.size() > 1 && DirName.back() == ':' && DirName.equals_lower(llvm::sys::path::root_name(DirName))) { DirNameStr = DirName.str() + '.'; DirName = DirNameStr; } #endif ++NumDirLookups; auto &NamedDirEnt = *SeenDirEntries.insert(std::make_pair(DirName, nullptr)).first; // See if there was already an entry in the map. Note that the map // contains both virtual and real directories. if (NamedDirEnt.second) return NamedDirEnt.second == NON_EXISTENT_DIR ? nullptr : NamedDirEnt.second; ++NumDirCacheMisses; // By default, initialize it to invalid. NamedDirEnt.second = NON_EXISTENT_DIR; // Get the null-terminated directory name as stored as the key of the // SeenDirEntries map. const char *InterndDirName = NamedDirEnt.first().data(); // Check to see if the directory exists. FileData Data; if (getStatValue(InterndDirName, Data, false, nullptr /*directory lookup*/)) { // There's no real directory at the given path. if (!CacheFailure) SeenDirEntries.erase(DirName); return nullptr; } // It exists. See if we have already opened a directory with the // same inode (this occurs on Unix-like systems when one dir is // symlinked to another, for example) or the same path (on // Windows). DirectoryEntry &UDE = UniqueRealDirs[Data.UniqueID]; NamedDirEnt.second = &UDE; if (!UDE.getName()) { // We don't have this directory yet, add it. We use the string // key from the SeenDirEntries map as the string. UDE.Name = InterndDirName; } return &UDE; } const FileEntry *FileManager::getFile(StringRef Filename, bool openFile, bool CacheFailure) { ++NumFileLookups; // See if there is already an entry in the map. auto &NamedFileEnt = *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; // See if there is already an entry in the map. if (NamedFileEnt.second) return NamedFileEnt.second == NON_EXISTENT_FILE ? nullptr : NamedFileEnt.second; ++NumFileCacheMisses; // By default, initialize it to invalid. NamedFileEnt.second = NON_EXISTENT_FILE; // Get the null-terminated file name as stored as the key of the // SeenFileEntries map. const char *InterndFileName = NamedFileEnt.first().data(); // Look up the directory for the file. When looking up something like // sys/foo.h we'll discover all of the search directories that have a 'sys' // subdirectory. This will let us avoid having to waste time on known-to-fail // searches when we go to find sys/bar.h, because all the search directories // without a 'sys' subdir will get a cached failure result. #if 0 // HLSL Change Starts - do not probe for directories const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, CacheFailure); if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist. if (!CacheFailure) SeenFileEntries.erase(Filename); return nullptr; } #else const DirectoryEntry *DirInfo = nullptr; #endif // HLSL Change Ends - do not probe for directories // FIXME: Use the directory info to prune this, before doing the stat syscall. // FIXME: This will reduce the # syscalls. // Nope, there isn't. Check to see if the file exists. std::unique_ptr<vfs::File> F; FileData Data; if (getStatValue(InterndFileName, Data, true, openFile ? &F : nullptr)) { // There's no real file at the given path. if (!CacheFailure) SeenFileEntries.erase(Filename); return nullptr; } assert((openFile || !F) && "undesired open file"); // It exists. See if we have already opened a file with the same inode. // This occurs when one dir is symlinked to another, for example. FileEntry &UFE = UniqueRealFiles[Data.UniqueID]; NamedFileEnt.second = &UFE; // If the name returned by getStatValue is different than Filename, re-intern // the name. if (Data.Name != Filename) { auto &NamedFileEnt = *SeenFileEntries.insert(std::make_pair(Data.Name, nullptr)).first; if (!NamedFileEnt.second) NamedFileEnt.second = &UFE; else assert(NamedFileEnt.second == &UFE && "filename from getStatValue() refers to wrong file"); InterndFileName = NamedFileEnt.first().data(); } // HLSL Change Starts - do not probe for directories before looking for file // This way the include handler can report all the included files paths as existing. DirInfo = getDirectoryFromFile(*this, Filename, CacheFailure); if (DirInfo == nullptr) { // Directory doesn't exist, file can't exist. if (!CacheFailure) SeenFileEntries.erase(Filename); return nullptr; } // HLSL Change Ends - do not probe for directories if (UFE.isValid()) { // Already have an entry with this inode, return it. // FIXME: this hack ensures that if we look up a file by a virtual path in // the VFS that the getDir() will have the virtual path, even if we found // the file by a 'real' path first. This is required in order to find a // module's structure when its headers/module map are mapped in the VFS. // We should remove this as soon as we can properly support a file having // multiple names. if (DirInfo != UFE.Dir && Data.IsVFSMapped) UFE.Dir = DirInfo; // Always update the name to use the last name by which a file was accessed. // FIXME: Neither this nor always using the first name is correct; we want // to switch towards a design where we return a FileName object that // encapsulates both the name by which the file was accessed and the // corresponding FileEntry. UFE.Name = InterndFileName; return &UFE; } // Otherwise, we don't have this file yet, add it. UFE.Name = InterndFileName; UFE.Size = Data.Size; UFE.ModTime = Data.ModTime; UFE.Dir = DirInfo; UFE.UID = NextFileUID++; UFE.UniqueID = Data.UniqueID; UFE.IsNamedPipe = Data.IsNamedPipe; UFE.InPCH = Data.InPCH; UFE.File = std::move(F); UFE.IsValid = true; return &UFE; } const FileEntry * FileManager::getVirtualFile(StringRef Filename, off_t Size, time_t ModificationTime) { ++NumFileLookups; // See if there is already an entry in the map. auto &NamedFileEnt = *SeenFileEntries.insert(std::make_pair(Filename, nullptr)).first; // See if there is already an entry in the map. if (NamedFileEnt.second && NamedFileEnt.second != NON_EXISTENT_FILE) return NamedFileEnt.second; ++NumFileCacheMisses; // By default, initialize it to invalid. NamedFileEnt.second = NON_EXISTENT_FILE; addAncestorsAsVirtualDirs(Filename); FileEntry *UFE = nullptr; // Now that all ancestors of Filename are in the cache, the // following call is guaranteed to find the DirectoryEntry from the // cache. const DirectoryEntry *DirInfo = getDirectoryFromFile(*this, Filename, /*CacheFailure=*/true); assert(DirInfo && "The directory of a virtual file should already be in the cache."); // Check to see if the file exists. If so, drop the virtual file FileData Data; const char *InterndFileName = NamedFileEnt.first().data(); if (getStatValue(InterndFileName, Data, true, nullptr) == 0) { Data.Size = Size; Data.ModTime = ModificationTime; UFE = &UniqueRealFiles[Data.UniqueID]; NamedFileEnt.second = UFE; // If we had already opened this file, close it now so we don't // leak the descriptor. We're not going to use the file // descriptor anyway, since this is a virtual file. if (UFE->File) UFE->closeFile(); // If we already have an entry with this inode, return it. if (UFE->isValid()) return UFE; UFE->UniqueID = Data.UniqueID; UFE->IsNamedPipe = Data.IsNamedPipe; UFE->InPCH = Data.InPCH; } if (!UFE) { UFE = new FileEntry(); VirtualFileEntries.push_back(UFE); NamedFileEnt.second = UFE; } UFE->Name = InterndFileName; UFE->Size = Size; UFE->ModTime = ModificationTime; UFE->Dir = DirInfo; UFE->UID = NextFileUID++; UFE->File.reset(); return UFE; } void FileManager::FixupRelativePath(SmallVectorImpl<char> &path) const { StringRef pathRef(path.data(), path.size()); if (FileSystemOpts.WorkingDir.empty() || llvm::sys::path::is_absolute(pathRef)) return; SmallString<128> NewPath(FileSystemOpts.WorkingDir); llvm::sys::path::append(NewPath, pathRef); path = NewPath; } llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileManager::getBufferForFile(const FileEntry *Entry, bool isVolatile, bool ShouldCloseOpenFile) { uint64_t FileSize = Entry->getSize(); // If there's a high enough chance that the file have changed since we // got its size, force a stat before opening it. if (isVolatile) FileSize = -1; const char *Filename = Entry->getName(); // If the file is already open, use the open file descriptor. if (Entry->File) { auto Result = Entry->File->getBuffer(Filename, FileSize, /*RequiresNullTerminator=*/true, isVolatile); // FIXME: we need a set of APIs that can make guarantees about whether a // FileEntry is open or not. if (ShouldCloseOpenFile) Entry->closeFile(); return Result; } // Otherwise, open the file. if (FileSystemOpts.WorkingDir.empty()) return FS->getBufferForFile(Filename, FileSize, /*RequiresNullTerminator=*/true, isVolatile); SmallString<128> FilePath(Entry->getName()); FixupRelativePath(FilePath); return FS->getBufferForFile(FilePath, FileSize, /*RequiresNullTerminator=*/true, isVolatile); } llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileManager::getBufferForFile(StringRef Filename) { if (FileSystemOpts.WorkingDir.empty()) return FS->getBufferForFile(Filename); SmallString<128> FilePath(Filename); FixupRelativePath(FilePath); return FS->getBufferForFile(FilePath.c_str()); } /// getStatValue - Get the 'stat' information for the specified path, /// using the cache to accelerate it if possible. This returns true /// if the path points to a virtual file or does not exist, or returns /// false if it's an existent real file. If FileDescriptor is NULL, /// do directory look-up instead of file look-up. bool FileManager::getStatValue(const char *Path, FileData &Data, bool isFile, std::unique_ptr<vfs::File> *F) { // FIXME: FileSystemOpts shouldn't be passed in here, all paths should be // absolute! if (FileSystemOpts.WorkingDir.empty()) return FileSystemStatCache::get(Path, Data, isFile, F,StatCache.get(), *FS); SmallString<128> FilePath(Path); FixupRelativePath(FilePath); return FileSystemStatCache::get(FilePath.c_str(), Data, isFile, F, StatCache.get(), *FS); } bool FileManager::getNoncachedStatValue(StringRef Path, vfs::Status &Result) { SmallString<128> FilePath(Path); FixupRelativePath(FilePath); llvm::ErrorOr<vfs::Status> S = FS->status(FilePath.c_str()); if (!S) return true; Result = *S; return false; } void FileManager::invalidateCache(const FileEntry *Entry) { assert(Entry && "Cannot invalidate a NULL FileEntry"); SeenFileEntries.erase(Entry->getName()); // FileEntry invalidation should not block future optimizations in the file // caches. Possible alternatives are cache truncation (invalidate last N) or // invalidation of the whole cache. UniqueRealFiles.erase(Entry->getUniqueID()); } void FileManager::GetUniqueIDMapping( SmallVectorImpl<const FileEntry *> &UIDToFiles) const { UIDToFiles.clear(); UIDToFiles.resize(NextFileUID); // Map file entries for (llvm::StringMap<FileEntry*, llvm::BumpPtrAllocator>::const_iterator FE = SeenFileEntries.begin(), FEEnd = SeenFileEntries.end(); FE != FEEnd; ++FE) if (FE->getValue() && FE->getValue() != NON_EXISTENT_FILE) UIDToFiles[FE->getValue()->getUID()] = FE->getValue(); // Map virtual file entries for (SmallVectorImpl<FileEntry *>::const_iterator VFE = VirtualFileEntries.begin(), VFEEnd = VirtualFileEntries.end(); VFE != VFEEnd; ++VFE) if (*VFE && *VFE != NON_EXISTENT_FILE) UIDToFiles[(*VFE)->getUID()] = *VFE; } void FileManager::modifyFileEntry(FileEntry *File, off_t Size, time_t ModificationTime) { File->Size = Size; File->ModTime = ModificationTime; } /// Remove '.' path components from the given absolute path. /// \return \c true if any changes were made. // FIXME: Move this to llvm::sys::path. bool FileManager::removeDotPaths(SmallVectorImpl<char> &Path) { using namespace llvm::sys; SmallVector<StringRef, 16> ComponentStack; StringRef P(Path.data(), Path.size()); // Skip the root path, then look for traversal in the components. StringRef Rel = path::relative_path(P); bool AnyDots = false; for (StringRef C : llvm::make_range(path::begin(Rel), path::end(Rel))) { if (C == ".") { AnyDots = true; continue; } ComponentStack.push_back(C); } if (!AnyDots) return false; SmallString<256> Buffer = path::root_path(P); for (StringRef C : ComponentStack) path::append(Buffer, C); Path.swap(Buffer); return true; } StringRef FileManager::getCanonicalName(const DirectoryEntry *Dir) { // FIXME: use llvm::sys::fs::canonical() when it gets implemented llvm::DenseMap<const DirectoryEntry *, llvm::StringRef>::iterator Known = CanonicalDirNames.find(Dir); if (Known != CanonicalDirNames.end()) return Known->second; StringRef CanonicalName(Dir->getName()); #ifdef LLVM_ON_UNIX char CanonicalNameBuf[PATH_MAX]; if (realpath(Dir->getName(), CanonicalNameBuf)) { unsigned Len = strlen(CanonicalNameBuf); char *Mem = static_cast<char *>(CanonicalNameStorage.Allocate(Len, 1)); memcpy(Mem, CanonicalNameBuf, Len); CanonicalName = StringRef(Mem, Len); } #else SmallString<256> CanonicalNameBuf(CanonicalName); llvm::sys::fs::make_absolute(CanonicalNameBuf); llvm::sys::path::native(CanonicalNameBuf); removeDotPaths(CanonicalNameBuf); #endif CanonicalDirNames.insert(std::make_pair(Dir, CanonicalName)); return CanonicalName; } void FileManager::PrintStats() const { llvm::errs() << "\n*** File Manager Stats:\n"; llvm::errs() << UniqueRealFiles.size() << " real files found, " << UniqueRealDirs.size() << " real dirs found.\n"; llvm::errs() << VirtualFileEntries.size() << " virtual files found, " << VirtualDirectoryEntries.size() << " virtual dirs found.\n"; llvm::errs() << NumDirLookups << " dir lookups, " << NumDirCacheMisses << " dir cache misses.\n"; llvm::errs() << NumFileLookups << " file lookups, " << NumFileCacheMisses << " file cache misses.\n"; //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups; } // Virtual destructors for abstract base classes that need live in Basic. PCHContainerWriter::~PCHContainerWriter() {} PCHContainerReader::~PCHContainerReader() {}
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/LangOptions.cpp
//===--- LangOptions.cpp - C Language Family Language Options ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the LangOptions class. // //===----------------------------------------------------------------------===// #include "clang/Basic/LangOptions.h" // // /////////////////////////////////////////////////////////////////////////////// using namespace clang; #ifdef LLVM_ON_UNIX #ifndef MS_SUPPORT_VARIABLE_LANGOPTS #define LANGOPT(Name, Bits, Default, Description) const unsigned LangOptionsBase::Name; #define LANGOPT_BOOL(Name, Default, Description) const bool LangOptionsBase::Name; #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) #include "clang/Basic/LangOptions.fixed.def" #endif // MS_SUPPORT_VARIABLE_LANGOPTS #endif // LLVM_ON_UNIX LangOptions::LangOptions() : HLSLVersion(hlsl::LangStd::vLatest) { #ifdef MS_SUPPORT_VARIABLE_LANGOPTS #define LANGOPT(Name, Bits, Default, Description) Name = Default; #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) set##Name(Default); #include "clang/Basic/LangOptions.def" #endif } void LangOptions::resetNonModularOptions() { #ifdef MS_SUPPORT_VARIABLE_LANGOPTS #define LANGOPT(Name, Bits, Default, Description) #define BENIGN_LANGOPT(Name, Bits, Default, Description) Name = Default; #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ Name = Default; #include "clang/Basic/LangOptions.def" #endif // FIXME: This should not be reset; modules can be different with different // sanitizer options (this affects __has_feature(address_sanitizer) etc). Sanitize.clear(); SanitizerBlacklistFiles.clear(); CurrentModule.clear(); ImplementationOfModule.clear(); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/TargetInfo.cpp
//===--- TargetInfo.cpp - Information about Target machine ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TargetInfo and TargetInfoImpl interfaces. // //===----------------------------------------------------------------------===// #include "clang/Basic/TargetInfo.h" #include "clang/Basic/AddressSpaces.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/LangOptions.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/ErrorHandling.h" #include <cstdlib> using namespace clang; static const LangAS::Map DefaultAddrSpaceMap = { 0 }; // TargetInfo Constructor. TargetInfo::TargetInfo(const llvm::Triple &T) : TargetOpts(), Triple(T) { // Set defaults. Defaults are set for a 32-bit RISC platform, like PPC or // SPARC. These should be overridden by concrete targets as needed. BigEndian = true; TLSSupported = true; NoAsmVariants = false; PointerWidth = PointerAlign = 32; BoolWidth = BoolAlign = 8; IntWidth = IntAlign = 32; LongWidth = LongAlign = 32; LongLongWidth = LongLongAlign = 64; SuitableAlign = 64; DefaultAlignForAttributeAligned = 128; MinGlobalAlign = 0; HalfWidth = 16; HalfAlign = 16; FloatWidth = 32; FloatAlign = 32; DoubleWidth = 64; DoubleAlign = 64; LongDoubleWidth = 64; LongDoubleAlign = 64; LargeArrayMinWidth = 0; LargeArrayAlign = 0; MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 0; MaxVectorAlign = 0; MaxTLSAlign = 0; SimdDefaultAlign = 0; SizeType = UnsignedLong; PtrDiffType = SignedLong; IntMaxType = SignedLongLong; IntPtrType = SignedLong; WCharType = SignedInt; WIntType = SignedInt; Char16Type = UnsignedShort; Char32Type = UnsignedInt; Int64Type = SignedLongLong; SigAtomicType = SignedInt; ProcessIDType = SignedInt; UseSignedCharForObjCBool = true; UseBitFieldTypeAlignment = true; UseZeroLengthBitfieldAlignment = false; ZeroLengthBitfieldBoundary = 0; HalfFormat = &llvm::APFloat::IEEEhalf; FloatFormat = &llvm::APFloat::IEEEsingle; DoubleFormat = &llvm::APFloat::IEEEdouble; LongDoubleFormat = &llvm::APFloat::IEEEdouble; DescriptionString = nullptr; UserLabelPrefix = "_"; MCountName = "mcount"; RegParmMax = 0; SSERegParmMax = 0; HasAlignMac68kSupport = false; // Default to no types using fpret. RealTypeUsesObjCFPRet = 0; // Default to not using fp2ret for __Complex long double ComplexLongDoubleUsesFP2Ret = false; // Set the C++ ABI based on the triple. TheCXXABI.set(Triple.isKnownWindowsMSVCEnvironment() ? TargetCXXABI::Microsoft : TargetCXXABI::GenericItanium); // Default to an empty address space map. AddrSpaceMap = &DefaultAddrSpaceMap; UseAddrSpaceMapMangling = false; // Default to an unknown platform name. PlatformName = "unknown"; PlatformMinVersion = VersionTuple(); } // Out of line virtual dtor for TargetInfo. TargetInfo::~TargetInfo() {} /// getTypeName - Return the user string for the specified integer type enum. /// For example, SignedShort -> "short". const char *TargetInfo::getTypeName(IntType T) { switch (T) { default: llvm_unreachable("not an integer!"); case SignedChar: return "signed char"; case UnsignedChar: return "unsigned char"; case SignedShort: return "short"; case UnsignedShort: return "unsigned short"; case SignedInt: return "int"; case UnsignedInt: return "unsigned int"; case SignedLong: return "long int"; case UnsignedLong: return "long unsigned int"; case SignedLongLong: return "long long int"; case UnsignedLongLong: return "long long unsigned int"; } } /// getTypeConstantSuffix - Return the constant suffix for the specified /// integer type enum. For example, SignedLong -> "L". const char *TargetInfo::getTypeConstantSuffix(IntType T) const { switch (T) { default: llvm_unreachable("not an integer!"); case SignedChar: case SignedShort: case SignedInt: return ""; case SignedLong: return "L"; case SignedLongLong: return "LL"; case UnsignedChar: if (getCharWidth() < getIntWidth()) return ""; LLVM_FALLTHROUGH; // HLSL Change case UnsignedShort: if (getShortWidth() < getIntWidth()) return ""; LLVM_FALLTHROUGH; // HLSL Change case UnsignedInt: return "U"; case UnsignedLong: return "UL"; case UnsignedLongLong: return "ULL"; } } /// getTypeFormatModifier - Return the printf format modifier for the /// specified integer type enum. For example, SignedLong -> "l". const char *TargetInfo::getTypeFormatModifier(IntType T) { switch (T) { default: llvm_unreachable("not an integer!"); case SignedChar: case UnsignedChar: return "hh"; case SignedShort: case UnsignedShort: return "h"; case SignedInt: case UnsignedInt: return ""; case SignedLong: case UnsignedLong: return "l"; case SignedLongLong: case UnsignedLongLong: return "ll"; } } /// getTypeWidth - Return the width (in bits) of the specified integer type /// enum. For example, SignedInt -> getIntWidth(). unsigned TargetInfo::getTypeWidth(IntType T) const { switch (T) { default: llvm_unreachable("not an integer!"); case SignedChar: case UnsignedChar: return getCharWidth(); case SignedShort: case UnsignedShort: return getShortWidth(); case SignedInt: case UnsignedInt: return getIntWidth(); case SignedLong: case UnsignedLong: return getLongWidth(); case SignedLongLong: case UnsignedLongLong: return getLongLongWidth(); }; } TargetInfo::IntType TargetInfo::getIntTypeByWidth( unsigned BitWidth, bool IsSigned) const { if (getCharWidth() == BitWidth) return IsSigned ? SignedChar : UnsignedChar; if (getShortWidth() == BitWidth) return IsSigned ? SignedShort : UnsignedShort; if (getIntWidth() == BitWidth) return IsSigned ? SignedInt : UnsignedInt; if (getLongWidth() == BitWidth) return IsSigned ? SignedLong : UnsignedLong; if (getLongLongWidth() == BitWidth) return IsSigned ? SignedLongLong : UnsignedLongLong; return NoInt; } TargetInfo::IntType TargetInfo::getLeastIntTypeByWidth(unsigned BitWidth, bool IsSigned) const { if (getCharWidth() >= BitWidth) return IsSigned ? SignedChar : UnsignedChar; if (getShortWidth() >= BitWidth) return IsSigned ? SignedShort : UnsignedShort; if (getIntWidth() >= BitWidth) return IsSigned ? SignedInt : UnsignedInt; if (getLongWidth() >= BitWidth) return IsSigned ? SignedLong : UnsignedLong; if (getLongLongWidth() >= BitWidth) return IsSigned ? SignedLongLong : UnsignedLongLong; return NoInt; } TargetInfo::RealType TargetInfo::getRealTypeByWidth(unsigned BitWidth) const { if (getFloatWidth() == BitWidth) return Float; if (getDoubleWidth() == BitWidth) return Double; switch (BitWidth) { case 96: if (&getLongDoubleFormat() == &llvm::APFloat::x87DoubleExtended) return LongDouble; break; case 128: if (&getLongDoubleFormat() == &llvm::APFloat::PPCDoubleDouble || &getLongDoubleFormat() == &llvm::APFloat::IEEEquad) return LongDouble; break; } return NoFloat; } /// getTypeAlign - Return the alignment (in bits) of the specified integer type /// enum. For example, SignedInt -> getIntAlign(). unsigned TargetInfo::getTypeAlign(IntType T) const { switch (T) { default: llvm_unreachable("not an integer!"); case SignedChar: case UnsignedChar: return getCharAlign(); case SignedShort: case UnsignedShort: return getShortAlign(); case SignedInt: case UnsignedInt: return getIntAlign(); case SignedLong: case UnsignedLong: return getLongAlign(); case SignedLongLong: case UnsignedLongLong: return getLongLongAlign(); }; } /// isTypeSigned - Return whether an integer types is signed. Returns true if /// the type is signed; false otherwise. bool TargetInfo::isTypeSigned(IntType T) { switch (T) { default: llvm_unreachable("not an integer!"); case SignedChar: case SignedShort: case SignedInt: case SignedLong: case SignedLongLong: return true; case UnsignedChar: case UnsignedShort: case UnsignedInt: case UnsignedLong: case UnsignedLongLong: return false; }; } /// adjust - Set forced language options. /// Apply changes to the target information with respect to certain /// language options which change the target configuration. void TargetInfo::adjust(const LangOptions &Opts) { if (Opts.NoBitFieldTypeAlign) UseBitFieldTypeAlignment = false; if (Opts.ShortWChar) WCharType = UnsignedShort; // HLSL Change Begin // We should have always set these values for HLSL, but instead we hacked // ASTContext::getTypeInfoImpl to override some of the uses (but not all). // With 202x relying more on Clang's C/C++ support we need to correctly set // the TargetInfo at least for this subset of types. This change probably // shouldn't be dependent on the language version, but I made it this way to // reduce any unforseen risk. if (Opts.HLSL) { // DXILTargetInfo in Tergets.cpp sets base values that aren't dependent on // language options. The values here adjust the base values once the // language options are initialized. if (Opts.HLSLVersion >= hlsl::LangStd::v202x) { IntWidth = IntAlign = 32; LongLongWidth = LongLongAlign = 64; if (!Opts.UseMinPrecision) HalfWidth = HalfAlign = 16; else HalfWidth = HalfAlign = 32; FloatWidth = FloatAlign = 32; } } // HLSL Change End if (Opts.OpenCL) { // OpenCL C requires specific widths for types, irrespective of // what these normally are for the target. // We also define long long and long double here, although the // OpenCL standard only mentions these as "reserved". IntWidth = IntAlign = 32; LongWidth = LongAlign = 64; LongLongWidth = LongLongAlign = 128; HalfWidth = HalfAlign = 16; FloatWidth = FloatAlign = 32; // Embedded 32-bit targets (OpenCL EP) might have double C type // defined as float. Let's not override this as it might lead // to generating illegal code that uses 64bit doubles. if (DoubleWidth != FloatWidth) { DoubleWidth = DoubleAlign = 64; DoubleFormat = &llvm::APFloat::IEEEdouble; } LongDoubleWidth = LongDoubleAlign = 128; assert(PointerWidth == 32 || PointerWidth == 64); bool Is32BitArch = PointerWidth == 32; SizeType = Is32BitArch ? UnsignedInt : UnsignedLong; PtrDiffType = Is32BitArch ? SignedInt : SignedLong; IntPtrType = Is32BitArch ? SignedInt : SignedLong; IntMaxType = SignedLongLong; Int64Type = SignedLong; HalfFormat = &llvm::APFloat::IEEEhalf; FloatFormat = &llvm::APFloat::IEEEsingle; LongDoubleFormat = &llvm::APFloat::IEEEquad; } } //===----------------------------------------------------------------------===// static StringRef removeGCCRegisterPrefix(StringRef Name) { if (Name[0] == '%' || Name[0] == '#') Name = Name.substr(1); return Name; } /// isValidClobber - Returns whether the passed in string is /// a valid clobber in an inline asm statement. This is used by /// Sema. bool TargetInfo::isValidClobber(StringRef Name) const { return (isValidGCCRegisterName(Name) || Name == "memory" || Name == "cc"); } /// isValidGCCRegisterName - Returns whether the passed in string /// is a valid register name according to GCC. This is used by Sema for /// inline asm statements. bool TargetInfo::isValidGCCRegisterName(StringRef Name) const { if (Name.empty()) return false; const char * const *Names; unsigned NumNames; // Get rid of any register prefix. Name = removeGCCRegisterPrefix(Name); if (Name.empty()) return false; getGCCRegNames(Names, NumNames); // If we have a number it maps to an entry in the register name array. if (isDigit(Name[0])) { int n; if (!Name.getAsInteger(0, n)) return n >= 0 && (unsigned)n < NumNames; } // Check register names. for (unsigned i = 0; i < NumNames; i++) { if (Name == Names[i]) return true; } // Check any additional names that we have. const AddlRegName *AddlNames; unsigned NumAddlNames; getGCCAddlRegNames(AddlNames, NumAddlNames); for (unsigned i = 0; i < NumAddlNames; i++) for (unsigned j = 0; j < llvm::array_lengthof(AddlNames[i].Names); j++) { if (!AddlNames[i].Names[j]) break; // Make sure the register that the additional name is for is within // the bounds of the register names from above. if (AddlNames[i].Names[j] == Name && AddlNames[i].RegNum < NumNames) return true; } // Now check aliases. const GCCRegAlias *Aliases; unsigned NumAliases; getGCCRegAliases(Aliases, NumAliases); for (unsigned i = 0; i < NumAliases; i++) { for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) { if (!Aliases[i].Aliases[j]) break; if (Aliases[i].Aliases[j] == Name) return true; } } return false; } StringRef TargetInfo::getNormalizedGCCRegisterName(StringRef Name) const { assert(isValidGCCRegisterName(Name) && "Invalid register passed in"); // Get rid of any register prefix. Name = removeGCCRegisterPrefix(Name); const char * const *Names; unsigned NumNames; getGCCRegNames(Names, NumNames); // First, check if we have a number. if (isDigit(Name[0])) { int n; if (!Name.getAsInteger(0, n)) { assert(n >= 0 && (unsigned)n < NumNames && "Out of bounds register number!"); return Names[n]; } } // Check any additional names that we have. const AddlRegName *AddlNames; unsigned NumAddlNames; getGCCAddlRegNames(AddlNames, NumAddlNames); for (unsigned i = 0; i < NumAddlNames; i++) for (unsigned j = 0; j < llvm::array_lengthof(AddlNames[i].Names); j++) { if (!AddlNames[i].Names[j]) break; // Make sure the register that the additional name is for is within // the bounds of the register names from above. if (AddlNames[i].Names[j] == Name && AddlNames[i].RegNum < NumNames) return Name; } // Now check aliases. const GCCRegAlias *Aliases; unsigned NumAliases; getGCCRegAliases(Aliases, NumAliases); for (unsigned i = 0; i < NumAliases; i++) { for (unsigned j = 0 ; j < llvm::array_lengthof(Aliases[i].Aliases); j++) { if (!Aliases[i].Aliases[j]) break; if (Aliases[i].Aliases[j] == Name) return Aliases[i].Register; } } return Name; } bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const { const char *Name = Info.getConstraintStr().c_str(); // An output constraint must start with '=' or '+' if (*Name != '=' && *Name != '+') return false; if (*Name == '+') Info.setIsReadWrite(); Name++; while (*Name) { switch (*Name) { default: if (!validateAsmConstraint(Name, Info)) { // FIXME: We temporarily return false // so we can add more constraints as we hit it. // Eventually, an unknown constraint should just be treated as 'g'. return false; } break; case '&': // early clobber. Info.setEarlyClobber(); break; case '%': // commutative. // FIXME: Check that there is a another register after this one. break; case 'r': // general register. Info.setAllowsRegister(); break; case 'm': // memory operand. case 'o': // offsetable memory operand. case 'V': // non-offsetable memory operand. case '<': // autodecrement memory operand. case '>': // autoincrement memory operand. Info.setAllowsMemory(); break; case 'g': // general register, memory operand or immediate integer. case 'X': // any operand. Info.setAllowsRegister(); Info.setAllowsMemory(); break; case ',': // multiple alternative constraint. Pass it. // Handle additional optional '=' or '+' modifiers. if (Name[1] == '=' || Name[1] == '+') Name++; break; case '#': // Ignore as constraint. while (Name[1] && Name[1] != ',') Name++; break; case '?': // Disparage slightly code. case '!': // Disparage severely. case '*': // Ignore for choosing register preferences. break; // Pass them. } Name++; } // Early clobber with a read-write constraint which doesn't permit registers // is invalid. if (Info.earlyClobber() && Info.isReadWrite() && !Info.allowsRegister()) return false; // If a constraint allows neither memory nor register operands it contains // only modifiers. Reject it. return Info.allowsMemory() || Info.allowsRegister(); } bool TargetInfo::resolveSymbolicName(const char *&Name, ConstraintInfo *OutputConstraints, unsigned NumOutputs, unsigned &Index) const { assert(*Name == '[' && "Symbolic name did not start with '['"); Name++; const char *Start = Name; while (*Name && *Name != ']') Name++; if (!*Name) { // Missing ']' return false; } std::string SymbolicName(Start, Name - Start); for (Index = 0; Index != NumOutputs; ++Index) if (SymbolicName == OutputConstraints[Index].getName()) return true; return false; } bool TargetInfo::validateInputConstraint(ConstraintInfo *OutputConstraints, unsigned NumOutputs, ConstraintInfo &Info) const { const char *Name = Info.ConstraintStr.c_str(); if (!*Name) return false; while (*Name) { switch (*Name) { default: // Check if we have a matching constraint if (*Name >= '0' && *Name <= '9') { const char *DigitStart = Name; while (Name[1] >= '0' && Name[1] <= '9') Name++; const char *DigitEnd = Name; unsigned i; if (StringRef(DigitStart, DigitEnd - DigitStart + 1) .getAsInteger(10, i)) return false; // Check if matching constraint is out of bounds. if (i >= NumOutputs) return false; // A number must refer to an output only operand. if (OutputConstraints[i].isReadWrite()) return false; // If the constraint is already tied, it must be tied to the // same operand referenced to by the number. if (Info.hasTiedOperand() && Info.getTiedOperand() != i) return false; // The constraint should have the same info as the respective // output constraint. Info.setTiedOperand(i, OutputConstraints[i]); } else if (!validateAsmConstraint(Name, Info)) { // FIXME: This error return is in place temporarily so we can // add more constraints as we hit it. Eventually, an unknown // constraint should just be treated as 'g'. return false; } break; case '[': { unsigned Index = 0; if (!resolveSymbolicName(Name, OutputConstraints, NumOutputs, Index)) return false; // If the constraint is already tied, it must be tied to the // same operand referenced to by the number. if (Info.hasTiedOperand() && Info.getTiedOperand() != Index) return false; // A number must refer to an output only operand. if (OutputConstraints[Index].isReadWrite()) return false; Info.setTiedOperand(Index, OutputConstraints[Index]); break; } case '%': // commutative // FIXME: Fail if % is used with the last operand. break; case 'i': // immediate integer. case 'n': // immediate integer with a known value. break; case 'I': // Various constant constraints with target-specific meanings. case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': if (!validateAsmConstraint(Name, Info)) return false; break; case 'r': // general register. Info.setAllowsRegister(); break; case 'm': // memory operand. case 'o': // offsettable memory operand. case 'V': // non-offsettable memory operand. case '<': // autodecrement memory operand. case '>': // autoincrement memory operand. Info.setAllowsMemory(); break; case 'g': // general register, memory operand or immediate integer. case 'X': // any operand. Info.setAllowsRegister(); Info.setAllowsMemory(); break; case 'E': // immediate floating point. case 'F': // immediate floating point. case 'p': // address operand. break; case ',': // multiple alternative constraint. Ignore comma. break; case '#': // Ignore as constraint. while (Name[1] && Name[1] != ',') Name++; break; case '?': // Disparage slightly code. case '!': // Disparage severely. case '*': // Ignore for choosing register preferences. break; // Pass them. } Name++; } return true; } bool TargetCXXABI::tryParse(llvm::StringRef name) { const Kind unknown = static_cast<Kind>(-1); Kind kind = llvm::StringSwitch<Kind>(name) .Case("arm", GenericARM) .Case("ios", iOS) .Case("itanium", GenericItanium) .Case("microsoft", Microsoft) .Case("mips", GenericMIPS) .Default(unknown); if (kind == unknown) return false; set(kind); return true; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/Module.cpp
//===--- Module.cpp - Describe a module -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Module class, which describes a module in the source // code. // //===----------------------------------------------------------------------===// #include "clang/Basic/Module.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace clang; Module::Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent, bool IsFramework, bool IsExplicit, unsigned VisibilityID) : Name(Name), DefinitionLoc(DefinitionLoc), Parent(Parent), Directory(), Umbrella(), Signature(0), ASTFile(nullptr), VisibilityID(VisibilityID), IsMissingRequirement(false), IsAvailable(true), IsFromModuleFile(false), IsFramework(IsFramework), IsExplicit(IsExplicit), IsSystem(false), IsExternC(false), IsInferred(false), InferSubmodules(false), InferExplicitSubmodules(false), InferExportWildcard(false), ConfigMacrosExhaustive(false), NameVisibility(Hidden) { if (Parent) { if (!Parent->isAvailable()) IsAvailable = false; if (Parent->IsSystem) IsSystem = true; if (Parent->IsExternC) IsExternC = true; IsMissingRequirement = Parent->IsMissingRequirement; Parent->SubModuleIndex[Name] = Parent->SubModules.size(); Parent->SubModules.push_back(this); } } Module::~Module() { for (submodule_iterator I = submodule_begin(), IEnd = submodule_end(); I != IEnd; ++I) { delete *I; } } /// \brief Determine whether a translation unit built using the current /// language options has the given feature. static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target) { bool HasFeature = llvm::StringSwitch<bool>(Feature) .Case("altivec", LangOpts.AltiVec) .Case("blocks", LangOpts.Blocks) .Case("cplusplus", LangOpts.CPlusPlus) .Case("cplusplus11", LangOpts.CPlusPlus11) .Case("objc", LangOpts.ObjC1) .Case("objc_arc", LangOpts.ObjCAutoRefCount) .Case("opencl", LangOpts.OpenCL) .Case("tls", Target.isTLSSupported()) .Case("zvector", LangOpts.ZVector) .Default(Target.hasFeature(Feature)); if (!HasFeature) HasFeature = std::find(LangOpts.ModuleFeatures.begin(), LangOpts.ModuleFeatures.end(), Feature) != LangOpts.ModuleFeatures.end(); return HasFeature; } bool Module::isAvailable(const LangOptions &LangOpts, const TargetInfo &Target, Requirement &Req, UnresolvedHeaderDirective &MissingHeader) const { if (IsAvailable) return true; for (const Module *Current = this; Current; Current = Current->Parent) { for (unsigned I = 0, N = Current->Requirements.size(); I != N; ++I) { if (hasFeature(Current->Requirements[I].first, LangOpts, Target) != Current->Requirements[I].second) { Req = Current->Requirements[I]; return false; } } if (!Current->MissingHeaders.empty()) { MissingHeader = Current->MissingHeaders.front(); return false; } } llvm_unreachable("could not find a reason why module is unavailable"); } bool Module::isSubModuleOf(const Module *Other) const { const Module *This = this; do { if (This == Other) return true; This = This->Parent; } while (This); return false; } const Module *Module::getTopLevelModule() const { const Module *Result = this; while (Result->Parent) Result = Result->Parent; return Result; } std::string Module::getFullModuleName() const { SmallVector<StringRef, 2> Names; // Build up the set of module names (from innermost to outermost). for (const Module *M = this; M; M = M->Parent) Names.push_back(M->Name); std::string Result; for (SmallVectorImpl<StringRef>::reverse_iterator I = Names.rbegin(), IEnd = Names.rend(); I != IEnd; ++I) { if (!Result.empty()) Result += '.'; Result += *I; } return Result; } Module::DirectoryName Module::getUmbrellaDir() const { if (Header U = getUmbrellaHeader()) return {"", U.Entry->getDir()}; return {UmbrellaAsWritten, Umbrella.dyn_cast<const DirectoryEntry *>()}; } ArrayRef<const FileEntry *> Module::getTopHeaders(FileManager &FileMgr) { if (!TopHeaderNames.empty()) { for (std::vector<std::string>::iterator I = TopHeaderNames.begin(), E = TopHeaderNames.end(); I != E; ++I) { if (const FileEntry *FE = FileMgr.getFile(*I)) TopHeaders.insert(FE); } TopHeaderNames.clear(); } return llvm::makeArrayRef(TopHeaders.begin(), TopHeaders.end()); } bool Module::directlyUses(const Module *Requested) const { auto *Top = getTopLevelModule(); // A top-level module implicitly uses itself. if (Requested->isSubModuleOf(Top)) return true; for (auto *Use : Top->DirectUses) if (Requested->isSubModuleOf(Use)) return true; return false; } void Module::addRequirement(StringRef Feature, bool RequiredState, const LangOptions &LangOpts, const TargetInfo &Target) { Requirements.push_back(Requirement(Feature, RequiredState)); // If this feature is currently available, we're done. if (hasFeature(Feature, LangOpts, Target) == RequiredState) return; markUnavailable(/*MissingRequirement*/true); } void Module::markUnavailable(bool MissingRequirement) { auto needUpdate = [MissingRequirement](Module *M) { return M->IsAvailable || (!M->IsMissingRequirement && MissingRequirement); }; if (!needUpdate(this)) return; SmallVector<Module *, 2> Stack; Stack.push_back(this); while (!Stack.empty()) { Module *Current = Stack.back(); Stack.pop_back(); if (!needUpdate(Current)) continue; Current->IsAvailable = false; Current->IsMissingRequirement |= MissingRequirement; for (submodule_iterator Sub = Current->submodule_begin(), SubEnd = Current->submodule_end(); Sub != SubEnd; ++Sub) { if (needUpdate(*Sub)) Stack.push_back(*Sub); } } } Module *Module::findSubmodule(StringRef Name) const { llvm::StringMap<unsigned>::const_iterator Pos = SubModuleIndex.find(Name); if (Pos == SubModuleIndex.end()) return nullptr; return SubModules[Pos->getValue()]; } static void printModuleId(raw_ostream &OS, const ModuleId &Id) { for (unsigned I = 0, N = Id.size(); I != N; ++I) { if (I) OS << "."; OS << Id[I].first; } } void Module::getExportedModules(SmallVectorImpl<Module *> &Exported) const { // All non-explicit submodules are exported. for (std::vector<Module *>::const_iterator I = SubModules.begin(), E = SubModules.end(); I != E; ++I) { Module *Mod = *I; if (!Mod->IsExplicit) Exported.push_back(Mod); } // Find re-exported modules by filtering the list of imported modules. bool AnyWildcard = false; bool UnrestrictedWildcard = false; SmallVector<Module *, 4> WildcardRestrictions; for (unsigned I = 0, N = Exports.size(); I != N; ++I) { Module *Mod = Exports[I].getPointer(); if (!Exports[I].getInt()) { // Export a named module directly; no wildcards involved. Exported.push_back(Mod); continue; } // Wildcard export: export all of the imported modules that match // the given pattern. AnyWildcard = true; if (UnrestrictedWildcard) continue; if (Module *Restriction = Exports[I].getPointer()) WildcardRestrictions.push_back(Restriction); else { WildcardRestrictions.clear(); UnrestrictedWildcard = true; } } // If there were any wildcards, push any imported modules that were // re-exported by the wildcard restriction. if (!AnyWildcard) return; for (unsigned I = 0, N = Imports.size(); I != N; ++I) { Module *Mod = Imports[I]; bool Acceptable = UnrestrictedWildcard; if (!Acceptable) { // Check whether this module meets one of the restrictions. for (unsigned R = 0, NR = WildcardRestrictions.size(); R != NR; ++R) { Module *Restriction = WildcardRestrictions[R]; if (Mod == Restriction || Mod->isSubModuleOf(Restriction)) { Acceptable = true; break; } } } if (!Acceptable) continue; Exported.push_back(Mod); } } void Module::buildVisibleModulesCache() const { assert(VisibleModulesCache.empty() && "cache does not need building"); // This module is visible to itself. VisibleModulesCache.insert(this); // Every imported module is visible. SmallVector<Module *, 16> Stack(Imports.begin(), Imports.end()); while (!Stack.empty()) { Module *CurrModule = Stack.pop_back_val(); // Every module transitively exported by an imported module is visible. if (VisibleModulesCache.insert(CurrModule).second) CurrModule->getExportedModules(Stack); } } void Module::print(raw_ostream &OS, unsigned Indent) const { OS.indent(Indent); if (IsFramework) OS << "framework "; if (IsExplicit) OS << "explicit "; OS << "module " << Name; if (IsSystem || IsExternC) { OS.indent(Indent + 2); if (IsSystem) OS << " [system]"; if (IsExternC) OS << " [extern_c]"; } OS << " {\n"; if (!Requirements.empty()) { OS.indent(Indent + 2); OS << "requires "; for (unsigned I = 0, N = Requirements.size(); I != N; ++I) { if (I) OS << ", "; if (!Requirements[I].second) OS << "!"; OS << Requirements[I].first; } OS << "\n"; } if (Header H = getUmbrellaHeader()) { OS.indent(Indent + 2); OS << "umbrella header \""; OS.write_escaped(H.NameAsWritten); OS << "\"\n"; } else if (DirectoryName D = getUmbrellaDir()) { OS.indent(Indent + 2); OS << "umbrella \""; OS.write_escaped(D.NameAsWritten); OS << "\"\n"; } if (!ConfigMacros.empty() || ConfigMacrosExhaustive) { OS.indent(Indent + 2); OS << "config_macros "; if (ConfigMacrosExhaustive) OS << "[exhaustive]"; for (unsigned I = 0, N = ConfigMacros.size(); I != N; ++I) { if (I) OS << ", "; OS << ConfigMacros[I]; } OS << "\n"; } struct { StringRef Prefix; HeaderKind Kind; } Kinds[] = {{"", HK_Normal}, {"textual ", HK_Textual}, {"private ", HK_Private}, {"private textual ", HK_PrivateTextual}, {"exclude ", HK_Excluded}}; for (auto &K : Kinds) { for (auto &H : Headers[K.Kind]) { OS.indent(Indent + 2); OS << K.Prefix << "header \""; OS.write_escaped(H.NameAsWritten); OS << "\"\n"; } } for (submodule_const_iterator MI = submodule_begin(), MIEnd = submodule_end(); MI != MIEnd; ++MI) // Print inferred subframework modules so that we don't need to re-infer // them (requires expensive directory iteration + stat calls) when we build // the module. Regular inferred submodules are OK, as we need to look at all // those header files anyway. if (!(*MI)->IsInferred || (*MI)->IsFramework) (*MI)->print(OS, Indent + 2); for (unsigned I = 0, N = Exports.size(); I != N; ++I) { OS.indent(Indent + 2); OS << "export "; if (Module *Restriction = Exports[I].getPointer()) { OS << Restriction->getFullModuleName(); if (Exports[I].getInt()) OS << ".*"; } else { OS << "*"; } OS << "\n"; } for (unsigned I = 0, N = UnresolvedExports.size(); I != N; ++I) { OS.indent(Indent + 2); OS << "export "; printModuleId(OS, UnresolvedExports[I].Id); if (UnresolvedExports[I].Wildcard) { if (UnresolvedExports[I].Id.empty()) OS << "*"; else OS << ".*"; } OS << "\n"; } for (unsigned I = 0, N = DirectUses.size(); I != N; ++I) { OS.indent(Indent + 2); OS << "use "; OS << DirectUses[I]->getFullModuleName(); OS << "\n"; } for (unsigned I = 0, N = UnresolvedDirectUses.size(); I != N; ++I) { OS.indent(Indent + 2); OS << "use "; printModuleId(OS, UnresolvedDirectUses[I]); OS << "\n"; } for (unsigned I = 0, N = LinkLibraries.size(); I != N; ++I) { OS.indent(Indent + 2); OS << "link "; if (LinkLibraries[I].IsFramework) OS << "framework "; OS << "\""; OS.write_escaped(LinkLibraries[I].Library); OS << "\""; } for (unsigned I = 0, N = UnresolvedConflicts.size(); I != N; ++I) { OS.indent(Indent + 2); OS << "conflict "; printModuleId(OS, UnresolvedConflicts[I].Id); OS << ", \""; OS.write_escaped(UnresolvedConflicts[I].Message); OS << "\"\n"; } for (unsigned I = 0, N = Conflicts.size(); I != N; ++I) { OS.indent(Indent + 2); OS << "conflict "; OS << Conflicts[I].Other->getFullModuleName(); OS << ", \""; OS.write_escaped(Conflicts[I].Message); OS << "\"\n"; } if (InferSubmodules) { OS.indent(Indent + 2); if (InferExplicitSubmodules) OS << "explicit "; OS << "module * {\n"; if (InferExportWildcard) { OS.indent(Indent + 4); OS << "export *\n"; } OS.indent(Indent + 2); OS << "}\n"; } OS.indent(Indent); OS << "}\n"; } void Module::dump() const { print(llvm::errs()); } void VisibleModuleSet::setVisible(Module *M, SourceLocation Loc, VisibleCallback Vis, ConflictCallback Cb) { if (isVisible(M)) return; ++Generation; struct Visiting { Module *M; Visiting *ExportedBy; }; std::function<void(Visiting)> VisitModule = [&](Visiting V) { // Modules that aren't available cannot be made visible. if (!V.M->isAvailable()) return; // Nothing to do for a module that's already visible. unsigned ID = V.M->getVisibilityID(); if (ImportLocs.size() <= ID) ImportLocs.resize(ID + 1); else if (ImportLocs[ID].isValid()) return; ImportLocs[ID] = Loc; Vis(M); // Make any exported modules visible. SmallVector<Module *, 16> Exports; V.M->getExportedModules(Exports); for (Module *E : Exports) VisitModule({E, &V}); for (auto &C : V.M->Conflicts) { if (isVisible(C.Other)) { llvm::SmallVector<Module*, 8> Path; for (Visiting *I = &V; I; I = I->ExportedBy) Path.push_back(I->M); Cb(Path, C.Other, C.Message); } } }; VisitModule({M, nullptr}); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/OperatorPrecedence.cpp
//===--- OperatorPrecedence.cpp ---------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines and computes precedence levels for binary/ternary operators. /// //===----------------------------------------------------------------------===// #include "clang/Basic/OperatorPrecedence.h" // // /////////////////////////////////////////////////////////////////////////////// namespace clang { prec::Level getBinOpPrecedence(tok::TokenKind Kind, bool GreaterThanIsOperator, bool CPlusPlus11) { switch (Kind) { case tok::greater: // C++ [temp.names]p3: // [...] When parsing a template-argument-list, the first // non-nested > is taken as the ending delimiter rather than a // greater-than operator. [...] if (GreaterThanIsOperator) return prec::Relational; return prec::Unknown; case tok::greatergreater: // C++11 [temp.names]p3: // // [...] Similarly, the first non-nested >> is treated as two // consecutive but distinct > tokens, the first of which is // taken as the end of the template-argument-list and completes // the template-id. [...] if (GreaterThanIsOperator || !CPlusPlus11) return prec::Shift; return prec::Unknown; default: return prec::Unknown; case tok::comma: return prec::Comma; case tok::equal: case tok::starequal: case tok::slashequal: case tok::percentequal: case tok::plusequal: case tok::minusequal: case tok::lesslessequal: case tok::greatergreaterequal: case tok::ampequal: case tok::caretequal: case tok::pipeequal: return prec::Assignment; case tok::question: return prec::Conditional; case tok::pipepipe: return prec::LogicalOr; case tok::ampamp: return prec::LogicalAnd; case tok::pipe: return prec::InclusiveOr; case tok::caret: return prec::ExclusiveOr; case tok::amp: return prec::And; case tok::exclaimequal: case tok::equalequal: return prec::Equality; case tok::lessequal: case tok::less: case tok::greaterequal: return prec::Relational; case tok::lessless: return prec::Shift; case tok::plus: case tok::minus: return prec::Additive; case tok::percent: case tok::slash: case tok::star: return prec::Multiplicative; case tok::periodstar: case tok::arrowstar: return prec::PointerToMember; } } } // namespace clang
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/ObjCRuntime.cpp
//===- ObjCRuntime.cpp - Objective-C Runtime Handling -----------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the ObjCRuntime class, which represents the // target Objective-C runtime. // //===----------------------------------------------------------------------===// #include "clang/Basic/ObjCRuntime.h" #include "llvm/Support/raw_ostream.h" // // /////////////////////////////////////////////////////////////////////////////// using namespace clang; std::string ObjCRuntime::getAsString() const { std::string Result; { llvm::raw_string_ostream Out(Result); Out << *this; } return Result; } raw_ostream &clang::operator<<(raw_ostream &out, const ObjCRuntime &value) { switch (value.getKind()) { case ObjCRuntime::MacOSX: out << "macosx"; break; case ObjCRuntime::FragileMacOSX: out << "macosx-fragile"; break; case ObjCRuntime::iOS: out << "ios"; break; case ObjCRuntime::GNUstep: out << "gnustep"; break; case ObjCRuntime::GCC: out << "gcc"; break; case ObjCRuntime::ObjFW: out << "objfw"; break; } if (value.getVersion() > VersionTuple(0)) { out << '-' << value.getVersion(); } return out; } bool ObjCRuntime::tryParse(StringRef input) { // Look for the last dash. std::size_t dash = input.rfind('-'); // We permit dashes in the runtime name, and we also permit the // version to be omitted, so if we see a dash not followed by a // digit then we need to ignore it. if (dash != StringRef::npos && dash + 1 != input.size() && (input[dash+1] < '0' || input[dash+1] > '9')) { dash = StringRef::npos; } // Everything prior to that must be a valid string name. Kind kind; StringRef runtimeName = input.substr(0, dash); Version = VersionTuple(0); if (runtimeName == "macosx") { kind = ObjCRuntime::MacOSX; } else if (runtimeName == "macosx-fragile") { kind = ObjCRuntime::FragileMacOSX; } else if (runtimeName == "ios") { kind = ObjCRuntime::iOS; } else if (runtimeName == "gnustep") { // If no version is specified then default to the most recent one that we // know about. Version = VersionTuple(1, 6); kind = ObjCRuntime::GNUstep; } else if (runtimeName == "gcc") { kind = ObjCRuntime::GCC; } else if (runtimeName == "objfw") { kind = ObjCRuntime::ObjFW; Version = VersionTuple(0, 8); } else { return true; } TheKind = kind; if (dash != StringRef::npos) { StringRef verString = input.substr(dash + 1); if (Version.tryParse(verString)) return true; } if (kind == ObjCRuntime::ObjFW && Version > VersionTuple(0, 8)) Version = VersionTuple(0, 8); return false; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/DiagnosticIDs.cpp
//===--- DiagnosticIDs.cpp - Diagnostic IDs Handling ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Diagnostic IDs-related interfaces. // //===----------------------------------------------------------------------===// #include "clang/Basic/DiagnosticIDs.h" #include "clang/Basic/AllDiagnostics.h" #include "clang/Basic/DiagnosticCategories.h" #include "clang/Basic/SourceManager.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/ErrorHandling.h" #include <map> using namespace clang; //===----------------------------------------------------------------------===// // Builtin Diagnostic information //===----------------------------------------------------------------------===// namespace { // Diagnostic classes. enum { CLASS_NOTE = 0x01, CLASS_REMARK = 0x02, CLASS_WARNING = 0x03, CLASS_EXTENSION = 0x04, CLASS_ERROR = 0x05 }; struct StaticDiagInfoRec { uint16_t DiagID; unsigned DefaultSeverity : 3; unsigned Class : 3; unsigned SFINAE : 2; unsigned WarnNoWerror : 1; unsigned WarnShowInSystemHeader : 1; unsigned Category : 5; uint16_t OptionGroupIndex; uint16_t DescriptionLen; const char *DescriptionStr; unsigned getOptionGroupIndex() const { return OptionGroupIndex; } StringRef getDescription() const { return StringRef(DescriptionStr, DescriptionLen); } diag::Flavor getFlavor() const { return Class == CLASS_REMARK ? diag::Flavor::Remark : diag::Flavor::WarningOrError; } bool operator<(const StaticDiagInfoRec &RHS) const { return DiagID < RHS.DiagID; } }; } // namespace anonymous static const StaticDiagInfoRec StaticDiagInfo[] = { #define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, \ SHOWINSYSHEADER, CATEGORY) \ { \ diag::ENUM, DEFAULT_SEVERITY, CLASS, DiagnosticIDs::SFINAE, NOWERROR, \ SHOWINSYSHEADER, CATEGORY, GROUP, STR_SIZE(DESC, uint16_t), DESC \ } \ , #include "clang/Basic/DiagnosticCommonKinds.inc" #include "clang/Basic/DiagnosticDriverKinds.inc" #include "clang/Basic/DiagnosticFrontendKinds.inc" #include "clang/Basic/DiagnosticSerializationKinds.inc" #include "clang/Basic/DiagnosticLexKinds.inc" #include "clang/Basic/DiagnosticParseKinds.inc" #include "clang/Basic/DiagnosticASTKinds.inc" #include "clang/Basic/DiagnosticCommentKinds.inc" #include "clang/Basic/DiagnosticSemaKinds.inc" #include "clang/Basic/DiagnosticAnalysisKinds.inc" #undef DIAG }; static const unsigned StaticDiagInfoSize = _countof(StaticDiagInfo); // HLSL Change - SAL doesn't understand llvm::array_lengthof(StaticDiagInfo); /// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID, /// or null if the ID is invalid. static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) { // If assertions are enabled, verify that the StaticDiagInfo array is sorted. #ifndef NDEBUG static bool IsFirst = true; // So the check is only performed on first call. if (IsFirst) { for (unsigned i = 1; i != StaticDiagInfoSize; ++i) { assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID && "Diag ID conflict, the enums at the start of clang::diag (in " "DiagnosticIDs.h) probably need to be increased"); assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] && "Improperly sorted diag info"); } IsFirst = false; } #endif // Out of bounds diag. Can't be in the table. using namespace diag; if (DiagID >= DIAG_UPPER_LIMIT || DiagID <= DIAG_START_COMMON) return nullptr; // Compute the index of the requested diagnostic in the static table. // 1. Add the number of diagnostics in each category preceding the // diagnostic and of the category the diagnostic is in. This gives us // the offset of the category in the table. // 2. Subtract the number of IDs in each category from our ID. This gives us // the offset of the diagnostic in the category. // This is cheaper than a binary search on the table as it doesn't touch // memory at all. unsigned Offset = 0; unsigned ID = DiagID - DIAG_START_COMMON - 1; // HLSL Change: Added static_asserts to prevent overflow in each category. #define CATEGORY(NAME, PREV) \ static_assert(NUM_BUILTIN_##PREV##_DIAGNOSTICS < DIAG_START_##NAME, \ "otherwise, " #PREV " diagnostic group overflows"); \ if (DiagID > DIAG_START_##NAME) { \ Offset += NUM_BUILTIN_##PREV##_DIAGNOSTICS - DIAG_START_##PREV - 1; \ ID -= DIAG_START_##NAME - DIAG_START_##PREV; \ } CATEGORY(DRIVER, COMMON) CATEGORY(FRONTEND, DRIVER) CATEGORY(SERIALIZATION, FRONTEND) CATEGORY(LEX, SERIALIZATION) CATEGORY(PARSE, LEX) CATEGORY(AST, PARSE) CATEGORY(COMMENT, AST) CATEGORY(SEMA, COMMENT) CATEGORY(ANALYSIS, SEMA) #undef CATEGORY static_assert(NUM_BUILTIN_ANALYSIS_DIAGNOSTICS < DIAG_UPPER_LIMIT, "otherwise, ANALYSIS diagnostic group overflows"); // Avoid out of bounds reads. if (ID + Offset >= StaticDiagInfoSize) return nullptr; assert(ID < StaticDiagInfoSize && Offset < StaticDiagInfoSize); const StaticDiagInfoRec *Found = &StaticDiagInfo[ID + Offset]; // If the diag id doesn't match we found a different diag, abort. This can // happen when this function is called with an ID that points into a hole in // the diagID space. if (Found->DiagID != DiagID) return nullptr; return Found; } static DiagnosticMapping GetDefaultDiagMapping(unsigned DiagID) { DiagnosticMapping Info = DiagnosticMapping::Make( diag::Severity::Fatal, /*IsUser=*/false, /*IsPragma=*/false); if (const StaticDiagInfoRec *StaticInfo = GetDiagInfo(DiagID)) { Info.setSeverity((diag::Severity)StaticInfo->DefaultSeverity); if (StaticInfo->WarnNoWerror) { assert(Info.getSeverity() == diag::Severity::Warning && "Unexpected mapping with no-Werror bit!"); Info.setNoWarningAsError(true); } } return Info; } /// getCategoryNumberForDiag - Return the category number that a specified /// DiagID belongs to, or 0 if no category. unsigned DiagnosticIDs::getCategoryNumberForDiag(unsigned DiagID) { if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) return Info->Category; return 0; } namespace { // The diagnostic category names. struct StaticDiagCategoryRec { const char *NameStr; uint8_t NameLen; StringRef getName() const { return StringRef(NameStr, NameLen); } }; } // Unfortunately, the split between DiagnosticIDs and Diagnostic is not // particularly clean, but for now we just implement this method here so we can // access GetDefaultDiagMapping. DiagnosticMapping & DiagnosticsEngine::DiagState::getOrAddMapping(diag::kind Diag) { std::pair<iterator, bool> Result = DiagMap.insert(std::make_pair(Diag, DiagnosticMapping())); // Initialize the entry if we added it. if (Result.second) Result.first->second = GetDefaultDiagMapping(Diag); return Result.first->second; } static const StaticDiagCategoryRec CategoryNameTable[] = { #define GET_CATEGORY_TABLE #define CATEGORY(X, ENUM) { X, STR_SIZE(X, uint8_t) }, #include "clang/Basic/DiagnosticGroups.inc" #undef GET_CATEGORY_TABLE { nullptr, 0 } }; /// getNumberOfCategories - Return the number of categories unsigned DiagnosticIDs::getNumberOfCategories() { return llvm::array_lengthof(CategoryNameTable) - 1; } /// getCategoryNameFromID - Given a category ID, return the name of the /// category, an empty string if CategoryID is zero, or null if CategoryID is /// invalid. StringRef DiagnosticIDs::getCategoryNameFromID(unsigned CategoryID) { if (CategoryID >= getNumberOfCategories()) return StringRef(); return CategoryNameTable[CategoryID].getName(); } DiagnosticIDs::SFINAEResponse DiagnosticIDs::getDiagnosticSFINAEResponse(unsigned DiagID) { if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) return static_cast<DiagnosticIDs::SFINAEResponse>(Info->SFINAE); return SFINAE_Report; } /// getBuiltinDiagClass - Return the class field of the diagnostic. /// static unsigned getBuiltinDiagClass(unsigned DiagID) { if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) return Info->Class; return ~0U; } //===----------------------------------------------------------------------===// // Custom Diagnostic information //===----------------------------------------------------------------------===// namespace clang { namespace diag { class CustomDiagInfo { typedef std::pair<DiagnosticIDs::Level, std::string> DiagDesc; std::vector<DiagDesc> DiagInfo; std::map<DiagDesc, unsigned> DiagIDs; public: /// getDescription - Return the description of the specified custom /// diagnostic. StringRef getDescription(unsigned DiagID) const { assert(DiagID - DIAG_UPPER_LIMIT < DiagInfo.size() && "Invalid diagnostic ID"); return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second; } /// getLevel - Return the level of the specified custom diagnostic. DiagnosticIDs::Level getLevel(unsigned DiagID) const { assert(DiagID - DIAG_UPPER_LIMIT < DiagInfo.size() && "Invalid diagnostic ID"); return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first; } unsigned getOrCreateDiagID(DiagnosticIDs::Level L, StringRef Message, DiagnosticIDs &Diags) { // HLSL Change Starts // ".str()" is a workaround for a bug in VC++'s STL where std::pair<T,U>::pair<T2,U2>(T2&&,U2&&) // may cause a conversion operator from U2 to U to be invoked within a noexcept function. // This would cause a call std::terminate if we ran out of memory and throw std::bad_alloc DiagDesc D(L, Message.str()); // HLSL Change Ends // Check to see if it already exists. std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D); if (I != DiagIDs.end() && I->first == D) return I->second; // If not, assign a new ID. unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT; DiagIDs.insert(std::make_pair(D, ID)); DiagInfo.push_back(D); return ID; } }; } // end diag namespace } // end clang namespace //===----------------------------------------------------------------------===// // Common Diagnostic implementation //===----------------------------------------------------------------------===// DiagnosticIDs::DiagnosticIDs() { CustomDiagInfo = nullptr; } DiagnosticIDs::~DiagnosticIDs() { delete CustomDiagInfo; } /// getCustomDiagID - Return an ID for a diagnostic with the specified message /// and level. If this is the first request for this diagnostic, it is /// registered and created, otherwise the existing ID is returned. /// /// \param FormatString A fixed diagnostic format string that will be hashed and /// mapped to a unique DiagID. unsigned DiagnosticIDs::getCustomDiagID(Level L, StringRef FormatString) { if (!CustomDiagInfo) CustomDiagInfo = new diag::CustomDiagInfo(); return CustomDiagInfo->getOrCreateDiagID(L, FormatString, *this); } /// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic /// level of the specified diagnostic ID is a Warning or Extension. /// This only works on builtin diagnostics, not custom ones, and is not legal to /// call on NOTEs. bool DiagnosticIDs::isBuiltinWarningOrExtension(unsigned DiagID) { return DiagID < diag::DIAG_UPPER_LIMIT && getBuiltinDiagClass(DiagID) != CLASS_ERROR; } /// \brief Determine whether the given built-in diagnostic ID is a /// Note. bool DiagnosticIDs::isBuiltinNote(unsigned DiagID) { return DiagID < diag::DIAG_UPPER_LIMIT && getBuiltinDiagClass(DiagID) == CLASS_NOTE; } /// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic /// ID is for an extension of some sort. This also returns EnabledByDefault, /// which is set to indicate whether the diagnostic is ignored by default (in /// which case -pedantic enables it) or treated as a warning/error by default. /// bool DiagnosticIDs::isBuiltinExtensionDiag(unsigned DiagID, bool &EnabledByDefault) { if (DiagID >= diag::DIAG_UPPER_LIMIT || getBuiltinDiagClass(DiagID) != CLASS_EXTENSION) return false; EnabledByDefault = GetDefaultDiagMapping(DiagID).getSeverity() != diag::Severity::Ignored; return true; } bool DiagnosticIDs::isDefaultMappingAsError(unsigned DiagID) { if (DiagID >= diag::DIAG_UPPER_LIMIT) return false; return GetDefaultDiagMapping(DiagID).getSeverity() == diag::Severity::Error; } /// getDescription - Given a diagnostic ID, return a description of the /// issue. StringRef DiagnosticIDs::getDescription(unsigned DiagID) const { if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) return Info->getDescription(); assert(CustomDiagInfo && "Invalid CustomDiagInfo"); return CustomDiagInfo->getDescription(DiagID); } static DiagnosticIDs::Level toLevel(diag::Severity SV) { switch (SV) { case diag::Severity::Ignored: return DiagnosticIDs::Ignored; case diag::Severity::Remark: return DiagnosticIDs::Remark; case diag::Severity::Warning: return DiagnosticIDs::Warning; case diag::Severity::Error: return DiagnosticIDs::Error; case diag::Severity::Fatal: return DiagnosticIDs::Fatal; } llvm_unreachable("unexpected severity"); } /// getDiagnosticLevel - Based on the way the client configured the /// DiagnosticsEngine object, classify the specified diagnostic ID into a Level, /// by consumable the DiagnosticClient. DiagnosticIDs::Level DiagnosticIDs::getDiagnosticLevel(unsigned DiagID, SourceLocation Loc, const DiagnosticsEngine &Diag) const { // Handle custom diagnostics, which cannot be mapped. if (DiagID >= diag::DIAG_UPPER_LIMIT) { assert(CustomDiagInfo && "Invalid CustomDiagInfo"); return CustomDiagInfo->getLevel(DiagID); } unsigned DiagClass = getBuiltinDiagClass(DiagID); if (DiagClass == CLASS_NOTE) return DiagnosticIDs::Note; return toLevel(getDiagnosticSeverity(DiagID, Loc, Diag)); } /// \brief Based on the way the client configured the Diagnostic /// object, classify the specified diagnostic ID into a Level, consumable by /// the DiagnosticClient. /// /// \param Loc The source location we are interested in finding out the /// diagnostic state. Can be null in order to query the latest state. diag::Severity DiagnosticIDs::getDiagnosticSeverity(unsigned DiagID, SourceLocation Loc, const DiagnosticsEngine &Diag) const { assert(getBuiltinDiagClass(DiagID) != CLASS_NOTE); // Specific non-error diagnostics may be mapped to various levels from ignored // to error. Errors can only be mapped to fatal. diag::Severity Result = diag::Severity::Fatal; DiagnosticsEngine::DiagStatePointsTy::iterator Pos = Diag.GetDiagStatePointForLoc(Loc); DiagnosticsEngine::DiagState *State = Pos->State; // Get the mapping information, or compute it lazily. DiagnosticMapping &Mapping = State->getOrAddMapping((diag::kind)DiagID); // TODO: Can a null severity really get here? if (Mapping.getSeverity() != diag::Severity()) Result = Mapping.getSeverity(); // Upgrade ignored diagnostics if -Weverything is enabled. if (Diag.EnableAllWarnings && Result == diag::Severity::Ignored && !Mapping.isUser() && getBuiltinDiagClass(DiagID) != CLASS_REMARK) Result = diag::Severity::Warning; // Ignore -pedantic diagnostics inside __extension__ blocks. // (The diagnostics controlled by -pedantic are the extension diagnostics // that are not enabled by default.) bool EnabledByDefault = false; bool IsExtensionDiag = isBuiltinExtensionDiag(DiagID, EnabledByDefault); if (Diag.AllExtensionsSilenced && IsExtensionDiag && !EnabledByDefault) return diag::Severity::Ignored; // For extension diagnostics that haven't been explicitly mapped, check if we // should upgrade the diagnostic. if (IsExtensionDiag && !Mapping.isUser()) Result = std::max(Result, Diag.ExtBehavior); // At this point, ignored errors can no longer be upgraded. if (Result == diag::Severity::Ignored) return Result; // Honor -w, which is lower in priority than pedantic-errors, but higher than // -Werror. if (Result == diag::Severity::Warning && Diag.IgnoreAllWarnings) return diag::Severity::Ignored; // If -Werror is enabled, map warnings to errors unless explicitly disabled. if (Result == diag::Severity::Warning) { if (Diag.WarningsAsErrors && !Mapping.hasNoWarningAsError()) Result = diag::Severity::Error; } // If -Wfatal-errors is enabled, map errors to fatal unless explicity // disabled. if (Result == diag::Severity::Error) { if (Diag.ErrorsAsFatal && !Mapping.hasNoErrorAsFatal()) Result = diag::Severity::Fatal; } // Custom diagnostics always are emitted in system headers. bool ShowInSystemHeader = !GetDiagInfo(DiagID) || GetDiagInfo(DiagID)->WarnShowInSystemHeader; // If we are in a system header, we ignore it. We look at the diagnostic class // because we also want to ignore extensions and warnings in -Werror and // -pedantic-errors modes, which *map* warnings/extensions to errors. if (Diag.SuppressSystemWarnings && !ShowInSystemHeader && Loc.isValid() && Diag.getSourceManager().isInSystemHeader( Diag.getSourceManager().getExpansionLoc(Loc))) return diag::Severity::Ignored; return Result; } #define GET_DIAG_ARRAYS #include "clang/Basic/DiagnosticGroups.inc" #undef GET_DIAG_ARRAYS namespace { struct WarningOption { uint16_t NameOffset; uint16_t Members; uint16_t SubGroups; // String is stored with a pascal-style length byte. StringRef getName() const { return StringRef(DiagGroupNames + NameOffset + 1, DiagGroupNames[NameOffset]); } }; } // Second the table of options, sorted by name for fast binary lookup. static const WarningOption OptionTable[] = { #define GET_DIAG_TABLE #include "clang/Basic/DiagnosticGroups.inc" #undef GET_DIAG_TABLE }; static const size_t OptionTableSize = llvm::array_lengthof(OptionTable); static bool WarningOptionCompare(const WarningOption &LHS, StringRef RHS) { return LHS.getName() < RHS; } /// getWarningOptionForDiag - Return the lowest-level warning option that /// enables the specified diagnostic. If there is no -Wfoo flag that controls /// the diagnostic, this returns null. StringRef DiagnosticIDs::getWarningOptionForDiag(unsigned DiagID) { if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) return OptionTable[Info->getOptionGroupIndex()].getName(); return StringRef(); } /// Return \c true if any diagnostics were found in this group, even if they /// were filtered out due to having the wrong flavor. static bool getDiagnosticsInGroup(diag::Flavor Flavor, const WarningOption *Group, SmallVectorImpl<diag::kind> &Diags) { // An empty group is considered to be a warning group: we have empty groups // for GCC compatibility, and GCC does not have remarks. if (!Group->Members && !Group->SubGroups) return Flavor == diag::Flavor::Remark; bool NotFound = true; // Add the members of the option diagnostic set. const int16_t *Member = DiagArrays + Group->Members; for (; *Member != -1; ++Member) { // HLSL Change: Check result of GetDiagInfo const StaticDiagInfoRec *Info = GetDiagInfo(*Member); assert(Info && "otherwise, group contains invalid diag ID"); if (Info->getFlavor() == Flavor) { NotFound = false; Diags.push_back(*Member); } } // Add the members of the subgroups. const int16_t *SubGroups = DiagSubGroups + Group->SubGroups; for (; *SubGroups != (int16_t)-1; ++SubGroups) NotFound &= getDiagnosticsInGroup(Flavor, &OptionTable[(short)*SubGroups], Diags); return NotFound; } bool DiagnosticIDs::getDiagnosticsInGroup(diag::Flavor Flavor, StringRef Group, SmallVectorImpl<diag::kind> &Diags) const { const WarningOption *Found = std::lower_bound( OptionTable, OptionTable + OptionTableSize, Group, WarningOptionCompare); if (Found == OptionTable + OptionTableSize || Found->getName() != Group) return true; // Option not found. return ::getDiagnosticsInGroup(Flavor, Found, Diags); } void DiagnosticIDs::getAllDiagnostics(diag::Flavor Flavor, SmallVectorImpl<diag::kind> &Diags) const { for (unsigned i = 0; i != StaticDiagInfoSize; ++i) if (StaticDiagInfo[i].getFlavor() == Flavor) Diags.push_back(StaticDiagInfo[i].DiagID); } StringRef DiagnosticIDs::getNearestOption(diag::Flavor Flavor, StringRef Group) { StringRef Best; unsigned BestDistance = Group.size() + 1; // Sanity threshold. for (const WarningOption *i = OptionTable, *e = OptionTable + OptionTableSize; i != e; ++i) { // Don't suggest ignored warning flags. if (!i->Members && !i->SubGroups) continue; unsigned Distance = i->getName().edit_distance(Group, true, BestDistance); if (Distance > BestDistance) continue; // Don't suggest groups that are not of this kind. llvm::SmallVector<diag::kind, 8> Diags; if (::getDiagnosticsInGroup(Flavor, i, Diags) || Diags.empty()) continue; if (Distance == BestDistance) { // Two matches with the same distance, don't prefer one over the other. Best = ""; } else if (Distance < BestDistance) { // This is a better match. Best = i->getName(); BestDistance = Distance; } } return Best; } /// ProcessDiag - This is the method used to report a diagnostic that is /// finally fully formed. bool DiagnosticIDs::ProcessDiag(DiagnosticsEngine &Diag) const { Diagnostic Info(&Diag); assert(Diag.getClient() && "DiagnosticClient not set!"); // Figure out the diagnostic level of this message. unsigned DiagID = Info.getID(); DiagnosticIDs::Level DiagLevel = getDiagnosticLevel(DiagID, Info.getLocation(), Diag); // Update counts for DiagnosticErrorTrap even if a fatal error occurred // or diagnostics are suppressed. if (DiagLevel >= DiagnosticIDs::Error) { ++Diag.TrapNumErrorsOccurred; if (isUnrecoverable(DiagID)) ++Diag.TrapNumUnrecoverableErrorsOccurred; } if (Diag.SuppressAllDiagnostics) return false; if (DiagLevel != DiagnosticIDs::Note) { // Record that a fatal error occurred only when we see a second // non-note diagnostic. This allows notes to be attached to the // fatal error, but suppresses any diagnostics that follow those // notes. if (Diag.LastDiagLevel == DiagnosticIDs::Fatal) Diag.FatalErrorOccurred = true; Diag.LastDiagLevel = DiagLevel; } // If a fatal error has already been emitted, silence all subsequent // diagnostics. if (Diag.FatalErrorOccurred) { if (DiagLevel >= DiagnosticIDs::Error && Diag.Client->IncludeInDiagnosticCounts()) { ++Diag.NumErrors; } return false; } // If the client doesn't care about this message, don't issue it. If this is // a note and the last real diagnostic was ignored, ignore it too. if (DiagLevel == DiagnosticIDs::Ignored || (DiagLevel == DiagnosticIDs::Note && Diag.LastDiagLevel == DiagnosticIDs::Ignored)) return false; if (DiagLevel >= DiagnosticIDs::Error) { if (isUnrecoverable(DiagID)) Diag.UnrecoverableErrorOccurred = true; // Warnings which have been upgraded to errors do not prevent compilation. if (isDefaultMappingAsError(DiagID)) Diag.UncompilableErrorOccurred = true; Diag.ErrorOccurred = true; if (Diag.Client->IncludeInDiagnosticCounts()) { ++Diag.NumErrors; } // If we've emitted a lot of errors, emit a fatal error instead of it to // stop a flood of bogus errors. if (Diag.ErrorLimit && Diag.NumErrors > Diag.ErrorLimit && DiagLevel == DiagnosticIDs::Error) { Diag.SetDelayedDiagnostic(diag::fatal_too_many_errors); return false; } } // Finally, report it. // HLSL Change - guard bad_alloc with a fatal error report. try { EmitDiag(Diag, DiagLevel); } catch (const std::bad_alloc &) { Diag.FatalErrorOccurred = true; Diag.ErrorOccurred = true; Diag.UnrecoverableErrorOccurred = true; } return true; } void DiagnosticIDs::EmitDiag(DiagnosticsEngine &Diag, Level DiagLevel) const { Diagnostic Info(&Diag); assert(DiagLevel != DiagnosticIDs::Ignored && "Cannot emit ignored diagnostics!"); Diag.Client->HandleDiagnostic((DiagnosticsEngine::Level)DiagLevel, Info); if (Diag.Client->IncludeInDiagnosticCounts()) { if (DiagLevel == DiagnosticIDs::Warning) ++Diag.NumWarnings; } Diag.CurDiagID = ~0U; } bool DiagnosticIDs::isUnrecoverable(unsigned DiagID) const { if (DiagID >= diag::DIAG_UPPER_LIMIT) { assert(CustomDiagInfo && "Invalid CustomDiagInfo"); // Custom diagnostics. return CustomDiagInfo->getLevel(DiagID) >= DiagnosticIDs::Error; } // Only errors may be unrecoverable. if (getBuiltinDiagClass(DiagID) < CLASS_ERROR) return false; if (DiagID == diag::err_unavailable || DiagID == diag::err_unavailable_message) return false; // Currently we consider all ARC errors as recoverable. if (isARCDiagnostic(DiagID)) return false; return true; } bool DiagnosticIDs::isARCDiagnostic(unsigned DiagID) { unsigned cat = getCategoryNumberForDiag(DiagID); return DiagnosticIDs::getCategoryNameFromID(cat).startswith("ARC "); } // HLSL Change Starts static_assert(std::is_nothrow_constructible<clang::DiagnosticIDs::Level>::value == 1, "enum cannot nothrow"); static_assert(std::is_nothrow_constructible<std::string, llvm::StringRef>::value == 0, "string from StringRef can throw"); static_assert(std::is_nothrow_constructible<std::string, llvm::StringRef &>::value == 0, "string from StringRef & can throw"); static_assert(std::is_nothrow_constructible<std::pair<clang::DiagnosticIDs::Level, std::string>, std::pair<clang::DiagnosticIDs::Level, std::string>&>::value == 0, "pair can throw"); // HLSL Change Starts Ends
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/TokenKinds.cpp
//===--- TokenKinds.cpp - Token Kinds Support -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the TokenKind enum and support functions. // //===----------------------------------------------------------------------===// #include "clang/Basic/TokenKinds.h" #include "llvm/Support/ErrorHandling.h" using namespace clang; static const char * const TokNames[] = { #define TOK(X) #X, #define KEYWORD(X,Y) #X, #include "clang/Basic/TokenKinds.def" nullptr }; const char *tok::getTokenName(TokenKind Kind) { if (Kind < tok::NUM_TOKENS) return TokNames[Kind]; llvm_unreachable("unknown TokenKind"); return nullptr; } const char *tok::getPunctuatorSpelling(TokenKind Kind) { switch (Kind) { #define PUNCTUATOR(X,Y) case X: return Y; #include "clang/Basic/TokenKinds.def" default: break; } return nullptr; } const char *tok::getKeywordSpelling(TokenKind Kind) { switch (Kind) { #define KEYWORD(X,Y) case kw_ ## X: return #X; #include "clang/Basic/TokenKinds.def" default: break; } return nullptr; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/SourceManager.cpp
//===--- SourceManager.cpp - Track and cache source files -----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the SourceManager interface. // //===----------------------------------------------------------------------===// #include "clang/Basic/SourceManager.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManagerInternals.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Capacity.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cstring> #include <string> using namespace clang; using namespace SrcMgr; using llvm::MemoryBuffer; //===----------------------------------------------------------------------===// // SourceManager Helper Classes //===----------------------------------------------------------------------===// ContentCache::~ContentCache() { if (shouldFreeBuffer()) delete Buffer.getPointer(); } /// getSizeBytesMapped - Returns the number of bytes actually mapped for this /// ContentCache. This can be 0 if the MemBuffer was not actually expanded. unsigned ContentCache::getSizeBytesMapped() const { return Buffer.getPointer() ? Buffer.getPointer()->getBufferSize() : 0; } /// Returns the kind of memory used to back the memory buffer for /// this content cache. This is used for performance analysis. llvm::MemoryBuffer::BufferKind ContentCache::getMemoryBufferKind() const { assert(Buffer.getPointer()); // Should be unreachable, but keep for sanity. if (!Buffer.getPointer()) return llvm::MemoryBuffer::MemoryBuffer_Malloc; llvm::MemoryBuffer *buf = Buffer.getPointer(); return buf->getBufferKind(); } /// getSize - Returns the size of the content encapsulated by this ContentCache. /// This can be the size of the source file or the size of an arbitrary /// scratch buffer. If the ContentCache encapsulates a source file, that /// file is not lazily brought in from disk to satisfy this query. unsigned ContentCache::getSize() const { return Buffer.getPointer() ? (unsigned) Buffer.getPointer()->getBufferSize() : (unsigned) ContentsEntry->getSize(); } void ContentCache::replaceBuffer(llvm::MemoryBuffer *B, bool DoNotFree) { if (B && B == Buffer.getPointer()) { assert(0 && "Replacing with the same buffer"); Buffer.setInt(DoNotFree? DoNotFreeFlag : 0); return; } if (shouldFreeBuffer()) delete Buffer.getPointer(); Buffer.setPointer(B); Buffer.setInt(DoNotFree? DoNotFreeFlag : 0); } llvm::MemoryBuffer *ContentCache::getBuffer(DiagnosticsEngine &Diag, const SourceManager &SM, SourceLocation Loc, bool *Invalid) const { // Lazily create the Buffer for ContentCaches that wrap files. If we already // computed it, just return what we have. if (Buffer.getPointer() || !ContentsEntry) { if (Invalid) *Invalid = isBufferInvalid(); return Buffer.getPointer(); } bool isVolatile = SM.userFilesAreVolatile() && !IsSystemFile; auto BufferOrError = SM.getFileManager().getBufferForFile(ContentsEntry, isVolatile); // If we were unable to open the file, then we are in an inconsistent // situation where the content cache referenced a file which no longer // exists. Most likely, we were using a stat cache with an invalid entry but // the file could also have been removed during processing. Since we can't // really deal with this situation, just create an empty buffer. // // FIXME: This is definitely not ideal, but our immediate clients can't // currently handle returning a null entry here. Ideally we should detect // that we are in an inconsistent situation and error out as quickly as // possible. if (!BufferOrError) { StringRef FillStr("<<<MISSING SOURCE FILE>>>\n"); Buffer.setPointer(MemoryBuffer::getNewUninitMemBuffer( ContentsEntry->getSize(), "<invalid>").release()); if (Buffer.getPointer() == nullptr) throw std::bad_alloc(); // HLSL Change char *Ptr = const_cast<char*>(Buffer.getPointer()->getBufferStart()); for (unsigned i = 0, e = ContentsEntry->getSize(); i != e; ++i) Ptr[i] = FillStr[i % FillStr.size()]; if (Diag.isDiagnosticInFlight()) Diag.SetDelayedDiagnostic(diag::err_cannot_open_file, ContentsEntry->getName(), BufferOrError.getError().message()); else Diag.Report(Loc, diag::err_cannot_open_file) << ContentsEntry->getName() << BufferOrError.getError().message(); Buffer.setInt(Buffer.getInt() | InvalidFlag); if (Invalid) *Invalid = true; return Buffer.getPointer(); } Buffer.setPointer(BufferOrError->release()); // Check that the file's size is the same as in the file entry (which may // have come from a stat cache). if (getRawBuffer()->getBufferSize() != (size_t)ContentsEntry->getSize()) { if (Diag.isDiagnosticInFlight()) Diag.SetDelayedDiagnostic(diag::err_file_modified, ContentsEntry->getName()); else Diag.Report(Loc, diag::err_file_modified) << ContentsEntry->getName(); Buffer.setInt(Buffer.getInt() | InvalidFlag); if (Invalid) *Invalid = true; return Buffer.getPointer(); } // If the buffer is valid, check to see if it has a UTF Byte Order Mark // (BOM). We only support UTF-8 with and without a BOM right now. See // http://en.wikipedia.org/wiki/Byte_order_mark for more information. StringRef BufStr = Buffer.getPointer()->getBuffer(); const char *InvalidBOM = llvm::StringSwitch<const char *>(BufStr) .StartsWith("\xFE\xFF", "UTF-16 (BE)") .StartsWith("\xFF\xFE", "UTF-16 (LE)") .StartsWith("\x00\x00\xFE\xFF", "UTF-32 (BE)") .StartsWith("\xFF\xFE\x00\x00", "UTF-32 (LE)") .StartsWith("\x2B\x2F\x76", "UTF-7") .StartsWith("\xF7\x64\x4C", "UTF-1") .StartsWith("\xDD\x73\x66\x73", "UTF-EBCDIC") .StartsWith("\x0E\xFE\xFF", "SDSU") .StartsWith("\xFB\xEE\x28", "BOCU-1") .StartsWith("\x84\x31\x95\x33", "GB-18030") .Default(nullptr); if (InvalidBOM) { Diag.Report(Loc, diag::err_unsupported_bom) << InvalidBOM << ContentsEntry->getName(); Buffer.setInt(Buffer.getInt() | InvalidFlag); } if (Invalid) *Invalid = isBufferInvalid(); return Buffer.getPointer(); } unsigned LineTableInfo::getLineTableFilenameID(StringRef Name) { auto IterBool = FilenameIDs.insert(std::make_pair(Name, FilenamesByID.size())); if (IterBool.second) FilenamesByID.push_back(&*IterBool.first); return IterBool.first->second; } /// AddLineNote - Add a line note to the line table that indicates that there /// is a \#line at the specified FID/Offset location which changes the presumed /// location to LineNo/FilenameID. void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo, int FilenameID) { std::vector<LineEntry> &Entries = LineEntries[FID]; assert((Entries.empty() || Entries.back().FileOffset < Offset) && "Adding line entries out of order!"); SrcMgr::CharacteristicKind Kind = SrcMgr::C_User; unsigned IncludeOffset = 0; if (!Entries.empty()) { // If this is a '#line 4' after '#line 42 "foo.h"', make sure to remember // that we are still in "foo.h". if (FilenameID == -1) FilenameID = Entries.back().FilenameID; // If we are after a line marker that switched us to system header mode, or // that set #include information, preserve it. Kind = Entries.back().FileKind; IncludeOffset = Entries.back().IncludeOffset; } Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, Kind, IncludeOffset)); } /// AddLineNote This is the same as the previous version of AddLineNote, but is /// used for GNU line markers. If EntryExit is 0, then this doesn't change the /// presumed \#include stack. If it is 1, this is a file entry, if it is 2 then /// this is a file exit. FileKind specifies whether this is a system header or /// extern C system header. void LineTableInfo::AddLineNote(FileID FID, unsigned Offset, unsigned LineNo, int FilenameID, unsigned EntryExit, SrcMgr::CharacteristicKind FileKind) { assert(FilenameID != -1 && "Unspecified filename should use other accessor"); std::vector<LineEntry> &Entries = LineEntries[FID]; assert((Entries.empty() || Entries.back().FileOffset < Offset) && "Adding line entries out of order!"); unsigned IncludeOffset = 0; if (EntryExit == 0) { // No #include stack change. IncludeOffset = Entries.empty() ? 0 : Entries.back().IncludeOffset; } else if (EntryExit == 1) { IncludeOffset = Offset-1; } else if (EntryExit == 2) { assert(!Entries.empty() && Entries.back().IncludeOffset && "PPDirectives should have caught case when popping empty include stack"); // Get the include loc of the last entries' include loc as our include loc. IncludeOffset = 0; if (const LineEntry *PrevEntry = FindNearestLineEntry(FID, Entries.back().IncludeOffset)) IncludeOffset = PrevEntry->IncludeOffset; } Entries.push_back(LineEntry::get(Offset, LineNo, FilenameID, FileKind, IncludeOffset)); } /// FindNearestLineEntry - Find the line entry nearest to FID that is before /// it. If there is no line entry before Offset in FID, return null. const LineEntry *LineTableInfo::FindNearestLineEntry(FileID FID, unsigned Offset) { const std::vector<LineEntry> &Entries = LineEntries[FID]; assert(!Entries.empty() && "No #line entries for this FID after all!"); // It is very common for the query to be after the last #line, check this // first. if (Entries.back().FileOffset <= Offset) return &Entries.back(); // Do a binary search to find the maximal element that is still before Offset. std::vector<LineEntry>::const_iterator I = std::upper_bound(Entries.begin(), Entries.end(), Offset); if (I == Entries.begin()) return nullptr; return &*--I; } /// \brief Add a new line entry that has already been encoded into /// the internal representation of the line table. void LineTableInfo::AddEntry(FileID FID, const std::vector<LineEntry> &Entries) { LineEntries[FID] = Entries; } /// getLineTableFilenameID - Return the uniqued ID for the specified filename. /// unsigned SourceManager::getLineTableFilenameID(StringRef Name) { if (!LineTable) LineTable = new LineTableInfo(); return LineTable->getLineTableFilenameID(Name); } /// AddLineNote - Add a line note to the line table for the FileID and offset /// specified by Loc. If FilenameID is -1, it is considered to be /// unspecified. void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID) { std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); bool Invalid = false; const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); if (!Entry.isFile() || Invalid) return; const SrcMgr::FileInfo &FileInfo = Entry.getFile(); // Remember that this file has #line directives now if it doesn't already. const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives(); if (!LineTable) LineTable = new LineTableInfo(); LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID); } /// AddLineNote - Add a GNU line marker to the line table. void SourceManager::AddLineNote(SourceLocation Loc, unsigned LineNo, int FilenameID, bool IsFileEntry, bool IsFileExit, bool IsSystemHeader, bool IsExternCHeader) { // If there is no filename and no flags, this is treated just like a #line, // which does not change the flags of the previous line marker. if (FilenameID == -1) { assert(!IsFileEntry && !IsFileExit && !IsSystemHeader && !IsExternCHeader && "Can't set flags without setting the filename!"); return AddLineNote(Loc, LineNo, FilenameID); } std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); bool Invalid = false; const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); if (!Entry.isFile() || Invalid) return; const SrcMgr::FileInfo &FileInfo = Entry.getFile(); // Remember that this file has #line directives now if it doesn't already. const_cast<SrcMgr::FileInfo&>(FileInfo).setHasLineDirectives(); if (!LineTable) LineTable = new LineTableInfo(); SrcMgr::CharacteristicKind FileKind; if (IsExternCHeader) FileKind = SrcMgr::C_ExternCSystem; else if (IsSystemHeader) FileKind = SrcMgr::C_System; else FileKind = SrcMgr::C_User; unsigned EntryExit = 0; if (IsFileEntry) EntryExit = 1; else if (IsFileExit) EntryExit = 2; LineTable->AddLineNote(LocInfo.first, LocInfo.second, LineNo, FilenameID, EntryExit, FileKind); } LineTableInfo &SourceManager::getLineTable() { if (!LineTable) LineTable = new LineTableInfo(); return *LineTable; } //===----------------------------------------------------------------------===// // Private 'Create' methods. //===----------------------------------------------------------------------===// SourceManager::SourceManager(DiagnosticsEngine &Diag, FileManager &FileMgr, bool UserFilesAreVolatile) : Diag(Diag), FileMgr(FileMgr), OverridenFilesKeepOriginalName(true), UserFilesAreVolatile(UserFilesAreVolatile), ExternalSLocEntries(nullptr), LineTable(nullptr), NumLinearScans(0), NumBinaryProbes(0) { clearIDTables(); Diag.setSourceManager(this); } SourceManager::~SourceManager() { delete LineTable; // Delete FileEntry objects corresponding to content caches. Since the actual // content cache objects are bump pointer allocated, we just have to run the // dtors, but we call the deallocate method for completeness. for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) { if (MemBufferInfos[i]) { MemBufferInfos[i]->~ContentCache(); ContentCacheAlloc.Deallocate(MemBufferInfos[i]); } } for (llvm::DenseMap<const FileEntry*, SrcMgr::ContentCache*>::iterator I = FileInfos.begin(), E = FileInfos.end(); I != E; ++I) { if (I->second) { I->second->~ContentCache(); ContentCacheAlloc.Deallocate(I->second); } } llvm::DeleteContainerSeconds(MacroArgsCacheMap); } void SourceManager::clearIDTables() { MainFileID = FileID(); LocalSLocEntryTable.clear(); LoadedSLocEntryTable.clear(); SLocEntryLoaded.clear(); LastLineNoFileIDQuery = FileID(); LastLineNoContentCache = nullptr; LastFileIDLookup = FileID(); if (LineTable) LineTable->clear(); // Use up FileID #0 as an invalid expansion. NextLocalOffset = 0; CurrentLoadedOffset = MaxLoadedOffset; createExpansionLoc(SourceLocation(),SourceLocation(),SourceLocation(), 1); } /// getOrCreateContentCache - Create or return a cached ContentCache for the /// specified file. const ContentCache * SourceManager::getOrCreateContentCache(const FileEntry *FileEnt, bool isSystemFile) { assert(FileEnt && "Didn't specify a file entry to use?"); // Do we already have information about this file? ContentCache *&Entry = FileInfos[FileEnt]; if (Entry) return Entry; // Nope, create a new Cache entry. Entry = ContentCacheAlloc.Allocate<ContentCache>(); if (OverriddenFilesInfo) { // If the file contents are overridden with contents from another file, // pass that file to ContentCache. llvm::DenseMap<const FileEntry *, const FileEntry *>::iterator overI = OverriddenFilesInfo->OverriddenFiles.find(FileEnt); if (overI == OverriddenFilesInfo->OverriddenFiles.end()) new (Entry) ContentCache(FileEnt); else new (Entry) ContentCache(OverridenFilesKeepOriginalName ? FileEnt : overI->second, overI->second); } else { new (Entry) ContentCache(FileEnt); } Entry->IsSystemFile = isSystemFile; return Entry; } /// createMemBufferContentCache - Create a new ContentCache for the specified /// memory buffer. This does no caching. const ContentCache *SourceManager::createMemBufferContentCache( std::unique_ptr<llvm::MemoryBuffer> Buffer) { // Add a new ContentCache to the MemBufferInfos list and return it. ContentCache *Entry = ContentCacheAlloc.Allocate<ContentCache>(); new (Entry) ContentCache(); MemBufferInfos.push_back(Entry); Entry->setBuffer(std::move(Buffer)); return Entry; } const SrcMgr::SLocEntry &SourceManager::loadSLocEntry(unsigned Index, bool *Invalid) const { assert(!SLocEntryLoaded[Index]); if (ExternalSLocEntries->ReadSLocEntry(-(static_cast<int>(Index) + 2))) { if (Invalid) *Invalid = true; // If the file of the SLocEntry changed we could still have loaded it. if (!SLocEntryLoaded[Index]) { // Try to recover; create a SLocEntry so the rest of clang can handle it. LoadedSLocEntryTable[Index] = SLocEntry::get(0, FileInfo::get(SourceLocation(), getFakeContentCacheForRecovery(), SrcMgr::C_User)); } } return LoadedSLocEntryTable[Index]; } std::pair<int, unsigned> SourceManager::AllocateLoadedSLocEntries(unsigned NumSLocEntries, unsigned TotalSize) { assert(ExternalSLocEntries && "Don't have an external sloc source"); LoadedSLocEntryTable.resize(LoadedSLocEntryTable.size() + NumSLocEntries); SLocEntryLoaded.resize(LoadedSLocEntryTable.size()); CurrentLoadedOffset -= TotalSize; assert(CurrentLoadedOffset >= NextLocalOffset && "Out of source locations"); int ID = LoadedSLocEntryTable.size(); return std::make_pair(-ID - 1, CurrentLoadedOffset); } /// \brief As part of recovering from missing or changed content, produce a /// fake, non-empty buffer. llvm::MemoryBuffer *SourceManager::getFakeBufferForRecovery() const { if (!FakeBufferForRecovery) FakeBufferForRecovery = llvm::MemoryBuffer::getMemBuffer("<<<INVALID BUFFER>>"); return FakeBufferForRecovery.get(); } /// \brief As part of recovering from missing or changed content, produce a /// fake content cache. const SrcMgr::ContentCache * SourceManager::getFakeContentCacheForRecovery() const { if (!FakeContentCacheForRecovery) { FakeContentCacheForRecovery = llvm::make_unique<SrcMgr::ContentCache>(); FakeContentCacheForRecovery->replaceBuffer(getFakeBufferForRecovery(), /*DoNotFree=*/true); } return FakeContentCacheForRecovery.get(); } /// \brief Returns the previous in-order FileID or an invalid FileID if there /// is no previous one. FileID SourceManager::getPreviousFileID(FileID FID) const { if (FID.isInvalid()) return FileID(); int ID = FID.ID; if (ID == -1) return FileID(); if (ID > 0) { if (ID-1 == 0) return FileID(); } else if (unsigned(-(ID-1) - 2) >= LoadedSLocEntryTable.size()) { return FileID(); } return FileID::get(ID-1); } /// \brief Returns the next in-order FileID or an invalid FileID if there is /// no next one. FileID SourceManager::getNextFileID(FileID FID) const { if (FID.isInvalid()) return FileID(); int ID = FID.ID; if (ID > 0) { if (unsigned(ID+1) >= local_sloc_entry_size()) return FileID(); } else if (ID+1 >= -1) { return FileID(); } return FileID::get(ID+1); } //===----------------------------------------------------------------------===// // Methods to create new FileID's and macro expansions. //===----------------------------------------------------------------------===// /// createFileID - Create a new FileID for the specified ContentCache and /// include position. This works regardless of whether the ContentCache /// corresponds to a file or some other input source. FileID SourceManager::createFileID(const ContentCache *File, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID, unsigned LoadedOffset) { if (LoadedID < 0) { assert(LoadedID != -1 && "Loading sentinel FileID"); unsigned Index = unsigned(-LoadedID) - 2; assert(Index < LoadedSLocEntryTable.size() && "FileID out of range"); assert(!SLocEntryLoaded[Index] && "FileID already loaded"); LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, FileInfo::get(IncludePos, File, FileCharacter)); SLocEntryLoaded[Index] = true; return FileID::get(LoadedID); } LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, FileInfo::get(IncludePos, File, FileCharacter))); unsigned FileSize = File->getSize(); assert(NextLocalOffset + FileSize + 1 > NextLocalOffset && NextLocalOffset + FileSize + 1 <= CurrentLoadedOffset && "Ran out of source locations!"); // We do a +1 here because we want a SourceLocation that means "the end of the // file", e.g. for the "no newline at the end of the file" diagnostic. NextLocalOffset += FileSize + 1; // Set LastFileIDLookup to the newly created file. The next getFileID call is // almost guaranteed to be from that file. FileID FID = FileID::get(LocalSLocEntryTable.size()-1); return LastFileIDLookup = FID; } SourceLocation SourceManager::createMacroArgExpansionLoc(SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned TokLength) { ExpansionInfo Info = ExpansionInfo::createForMacroArg(SpellingLoc, ExpansionLoc); return createExpansionLocImpl(Info, TokLength); } SourceLocation SourceManager::createExpansionLoc(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned TokLength, int LoadedID, unsigned LoadedOffset) { ExpansionInfo Info = ExpansionInfo::create(SpellingLoc, ExpansionLocStart, ExpansionLocEnd); return createExpansionLocImpl(Info, TokLength, LoadedID, LoadedOffset); } SourceLocation SourceManager::createExpansionLocImpl(const ExpansionInfo &Info, unsigned TokLength, int LoadedID, unsigned LoadedOffset) { if (LoadedID < 0) { assert(LoadedID != -1 && "Loading sentinel FileID"); unsigned Index = unsigned(-LoadedID) - 2; assert(Index < LoadedSLocEntryTable.size() && "FileID out of range"); assert(!SLocEntryLoaded[Index] && "FileID already loaded"); LoadedSLocEntryTable[Index] = SLocEntry::get(LoadedOffset, Info); SLocEntryLoaded[Index] = true; return SourceLocation::getMacroLoc(LoadedOffset); } LocalSLocEntryTable.push_back(SLocEntry::get(NextLocalOffset, Info)); assert(NextLocalOffset + TokLength + 1 > NextLocalOffset && NextLocalOffset + TokLength + 1 <= CurrentLoadedOffset && "Ran out of source locations!"); // See createFileID for that +1. NextLocalOffset += TokLength + 1; return SourceLocation::getMacroLoc(NextLocalOffset - (TokLength + 1)); } llvm::MemoryBuffer *SourceManager::getMemoryBufferForFile(const FileEntry *File, bool *Invalid) { const SrcMgr::ContentCache *IR = getOrCreateContentCache(File); assert(IR && "getOrCreateContentCache() cannot return NULL"); return IR->getBuffer(Diag, *this, SourceLocation(), Invalid); } void SourceManager::overrideFileContents(const FileEntry *SourceFile, llvm::MemoryBuffer *Buffer, bool DoNotFree) { const SrcMgr::ContentCache *IR = getOrCreateContentCache(SourceFile); assert(IR && "getOrCreateContentCache() cannot return NULL"); const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(Buffer, DoNotFree); const_cast<SrcMgr::ContentCache *>(IR)->BufferOverridden = true; getOverriddenFilesInfo().OverriddenFilesWithBuffer.insert(SourceFile); } void SourceManager::overrideFileContents(const FileEntry *SourceFile, const FileEntry *NewFile) { assert(SourceFile->getSize() == NewFile->getSize() && "Different sizes, use the FileManager to create a virtual file with " "the correct size"); assert(FileInfos.count(SourceFile) == 0 && "This function should be called at the initialization stage, before " "any parsing occurs."); getOverriddenFilesInfo().OverriddenFiles[SourceFile] = NewFile; } void SourceManager::disableFileContentsOverride(const FileEntry *File) { if (!isFileOverridden(File)) return; const SrcMgr::ContentCache *IR = getOrCreateContentCache(File); const_cast<SrcMgr::ContentCache *>(IR)->replaceBuffer(nullptr); const_cast<SrcMgr::ContentCache *>(IR)->ContentsEntry = IR->OrigEntry; assert(OverriddenFilesInfo); OverriddenFilesInfo->OverriddenFiles.erase(File); OverriddenFilesInfo->OverriddenFilesWithBuffer.erase(File); } StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { bool MyInvalid = false; const SLocEntry &SLoc = getSLocEntry(FID, &MyInvalid); if (!SLoc.isFile() || MyInvalid) { if (Invalid) *Invalid = true; return "<<<<<INVALID SOURCE LOCATION>>>>>"; } llvm::MemoryBuffer *Buf = SLoc.getFile().getContentCache()->getBuffer( Diag, *this, SourceLocation(), &MyInvalid); if (Invalid) *Invalid = MyInvalid; if (MyInvalid) return "<<<<<INVALID SOURCE LOCATION>>>>>"; return Buf->getBuffer(); } //===----------------------------------------------------------------------===// // SourceLocation manipulation methods. //===----------------------------------------------------------------------===// /// \brief Return the FileID for a SourceLocation. /// /// This is the cache-miss path of getFileID. Not as hot as that function, but /// still very important. It is responsible for finding the entry in the /// SLocEntry tables that contains the specified location. FileID SourceManager::getFileIDSlow(unsigned SLocOffset) const { if (!SLocOffset) return FileID::get(0); // Now it is time to search for the correct file. See where the SLocOffset // sits in the global view and consult local or loaded buffers for it. if (SLocOffset < NextLocalOffset) return getFileIDLocal(SLocOffset); return getFileIDLoaded(SLocOffset); } /// \brief Return the FileID for a SourceLocation with a low offset. /// /// This function knows that the SourceLocation is in a local buffer, not a /// loaded one. FileID SourceManager::getFileIDLocal(unsigned SLocOffset) const { assert(SLocOffset < NextLocalOffset && "Bad function choice"); // After the first and second level caches, I see two common sorts of // behavior: 1) a lot of searched FileID's are "near" the cached file // location or are "near" the cached expansion location. 2) others are just // completely random and may be a very long way away. // // To handle this, we do a linear search for up to 8 steps to catch #1 quickly // then we fall back to a less cache efficient, but more scalable, binary // search to find the location. // See if this is near the file point - worst case we start scanning from the // most newly created FileID. const SrcMgr::SLocEntry *I; if (LastFileIDLookup.ID < 0 || LocalSLocEntryTable[LastFileIDLookup.ID].getOffset() < SLocOffset) { // Neither loc prunes our search. I = LocalSLocEntryTable.end(); } else { // Perhaps it is near the file point. I = LocalSLocEntryTable.begin()+LastFileIDLookup.ID; } // Find the FileID that contains this. "I" is an iterator that points to a // FileID whose offset is known to be larger than SLocOffset. unsigned NumProbes = 0; while (1) { --I; if (I->getOffset() <= SLocOffset) { FileID Res = FileID::get(int(I - LocalSLocEntryTable.begin())); // If this isn't an expansion, remember it. We have good locality across // FileID lookups. if (!I->isExpansion()) LastFileIDLookup = Res; NumLinearScans += NumProbes+1; return Res; } if (++NumProbes == 8) break; } // Convert "I" back into an index. We know that it is an entry whose index is // larger than the offset we are looking for. unsigned GreaterIndex = I - LocalSLocEntryTable.begin(); // LessIndex - This is the lower bound of the range that we're searching. // We know that the offset corresponding to the FileID is is less than // SLocOffset. unsigned LessIndex = 0; NumProbes = 0; while (1) { bool Invalid = false; unsigned MiddleIndex = (GreaterIndex-LessIndex)/2+LessIndex; unsigned MidOffset = getLocalSLocEntry(MiddleIndex, &Invalid).getOffset(); if (Invalid) return FileID::get(0); ++NumProbes; // If the offset of the midpoint is too large, chop the high side of the // range to the midpoint. if (MidOffset > SLocOffset) { GreaterIndex = MiddleIndex; continue; } // If the middle index contains the value, succeed and return. // FIXME: This could be made faster by using a function that's aware of // being in the local area. if (isOffsetInFileID(FileID::get(MiddleIndex), SLocOffset)) { FileID Res = FileID::get(MiddleIndex); // If this isn't a macro expansion, remember it. We have good locality // across FileID lookups. if (!LocalSLocEntryTable[MiddleIndex].isExpansion()) LastFileIDLookup = Res; NumBinaryProbes += NumProbes; return Res; } // Otherwise, move the low-side up to the middle index. LessIndex = MiddleIndex; } } /// \brief Return the FileID for a SourceLocation with a high offset. /// /// This function knows that the SourceLocation is in a loaded buffer, not a /// local one. FileID SourceManager::getFileIDLoaded(unsigned SLocOffset) const { // Sanity checking, otherwise a bug may lead to hanging in release build. if (SLocOffset < CurrentLoadedOffset) { assert(0 && "Invalid SLocOffset or bad function choice"); return FileID(); } // Essentially the same as the local case, but the loaded array is sorted // in the other direction. // First do a linear scan from the last lookup position, if possible. unsigned I; int LastID = LastFileIDLookup.ID; if (LastID >= 0 || getLoadedSLocEntryByID(LastID).getOffset() < SLocOffset) I = 0; else I = (-LastID - 2) + 1; unsigned NumProbes; for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++I) { // Make sure the entry is loaded! const SrcMgr::SLocEntry &E = getLoadedSLocEntry(I); if (E.getOffset() <= SLocOffset) { FileID Res = FileID::get(-int(I) - 2); if (!E.isExpansion()) LastFileIDLookup = Res; NumLinearScans += NumProbes + 1; return Res; } } // Linear scan failed. Do the binary search. Note the reverse sorting of the // table: GreaterIndex is the one where the offset is greater, which is // actually a lower index! unsigned GreaterIndex = I; unsigned LessIndex = LoadedSLocEntryTable.size(); NumProbes = 0; while (1) { ++NumProbes; unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex; const SrcMgr::SLocEntry &E = getLoadedSLocEntry(MiddleIndex); if (E.getOffset() == 0) return FileID(); // invalid entry. ++NumProbes; if (E.getOffset() > SLocOffset) { // Sanity checking, otherwise a bug may lead to hanging in release build. if (GreaterIndex == MiddleIndex) { assert(0 && "binary search missed the entry"); return FileID(); } GreaterIndex = MiddleIndex; continue; } if (isOffsetInFileID(FileID::get(-int(MiddleIndex) - 2), SLocOffset)) { FileID Res = FileID::get(-int(MiddleIndex) - 2); if (!E.isExpansion()) LastFileIDLookup = Res; NumBinaryProbes += NumProbes; return Res; } // Sanity checking, otherwise a bug may lead to hanging in release build. if (LessIndex == MiddleIndex) { assert(0 && "binary search missed the entry"); return FileID(); } LessIndex = MiddleIndex; } } SourceLocation SourceManager:: getExpansionLocSlowCase(SourceLocation Loc) const { do { // Note: If Loc indicates an offset into a token that came from a macro // expansion (e.g. the 5th character of the token) we do not want to add // this offset when going to the expansion location. The expansion // location is the macro invocation, which the offset has nothing to do // with. This is unlike when we get the spelling loc, because the offset // directly correspond to the token whose spelling we're inspecting. Loc = getSLocEntry(getFileID(Loc)).getExpansion().getExpansionLocStart(); } while (!Loc.isFileID()); return Loc; } SourceLocation SourceManager::getSpellingLocSlowCase(SourceLocation Loc) const { do { std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc(); Loc = Loc.getLocWithOffset(LocInfo.second); } while (!Loc.isFileID()); return Loc; } SourceLocation SourceManager::getFileLocSlowCase(SourceLocation Loc) const { do { if (isMacroArgExpansion(Loc)) Loc = getImmediateSpellingLoc(Loc); else Loc = getImmediateExpansionRange(Loc).first; } while (!Loc.isFileID()); return Loc; } std::pair<FileID, unsigned> SourceManager::getDecomposedExpansionLocSlowCase( const SrcMgr::SLocEntry *E) const { // If this is an expansion record, walk through all the expansion points. FileID FID; SourceLocation Loc; unsigned Offset; do { Loc = E->getExpansion().getExpansionLocStart(); FID = getFileID(Loc); E = &getSLocEntry(FID); Offset = Loc.getOffset()-E->getOffset(); } while (!Loc.isFileID()); return std::make_pair(FID, Offset); } std::pair<FileID, unsigned> SourceManager::getDecomposedSpellingLocSlowCase(const SrcMgr::SLocEntry *E, unsigned Offset) const { // If this is an expansion record, walk through all the expansion points. FileID FID; SourceLocation Loc; do { Loc = E->getExpansion().getSpellingLoc(); Loc = Loc.getLocWithOffset(Offset); FID = getFileID(Loc); E = &getSLocEntry(FID); Offset = Loc.getOffset()-E->getOffset(); } while (!Loc.isFileID()); return std::make_pair(FID, Offset); } /// getImmediateSpellingLoc - Given a SourceLocation object, return the /// spelling location referenced by the ID. This is the first level down /// towards the place where the characters that make up the lexed token can be /// found. This should not generally be used by clients. SourceLocation SourceManager::getImmediateSpellingLoc(SourceLocation Loc) const{ if (Loc.isFileID()) return Loc; std::pair<FileID, unsigned> LocInfo = getDecomposedLoc(Loc); Loc = getSLocEntry(LocInfo.first).getExpansion().getSpellingLoc(); return Loc.getLocWithOffset(LocInfo.second); } /// getImmediateExpansionRange - Loc is required to be an expansion location. /// Return the start/end of the expansion information. std::pair<SourceLocation,SourceLocation> SourceManager::getImmediateExpansionRange(SourceLocation Loc) const { assert(Loc.isMacroID() && "Not a macro expansion loc!"); const ExpansionInfo &Expansion = getSLocEntry(getFileID(Loc)).getExpansion(); return Expansion.getExpansionLocRange(); } /// getExpansionRange - Given a SourceLocation object, return the range of /// tokens covered by the expansion in the ultimate file. std::pair<SourceLocation,SourceLocation> SourceManager::getExpansionRange(SourceLocation Loc) const { if (Loc.isFileID()) return std::make_pair(Loc, Loc); std::pair<SourceLocation,SourceLocation> Res = getImmediateExpansionRange(Loc); // Fully resolve the start and end locations to their ultimate expansion // points. while (!Res.first.isFileID()) Res.first = getImmediateExpansionRange(Res.first).first; while (!Res.second.isFileID()) Res.second = getImmediateExpansionRange(Res.second).second; return Res; } bool SourceManager::isMacroArgExpansion(SourceLocation Loc) const { if (!Loc.isMacroID()) return false; FileID FID = getFileID(Loc); const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion(); return Expansion.isMacroArgExpansion(); } bool SourceManager::isMacroBodyExpansion(SourceLocation Loc) const { if (!Loc.isMacroID()) return false; FileID FID = getFileID(Loc); const SrcMgr::ExpansionInfo &Expansion = getSLocEntry(FID).getExpansion(); return Expansion.isMacroBodyExpansion(); } bool SourceManager::isAtStartOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroBegin) const { assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc"); std::pair<FileID, unsigned> DecompLoc = getDecomposedLoc(Loc); if (DecompLoc.second > 0) return false; // Does not point at the start of expansion range. bool Invalid = false; const SrcMgr::ExpansionInfo &ExpInfo = getSLocEntry(DecompLoc.first, &Invalid).getExpansion(); if (Invalid) return false; SourceLocation ExpLoc = ExpInfo.getExpansionLocStart(); if (ExpInfo.isMacroArgExpansion()) { // For macro argument expansions, check if the previous FileID is part of // the same argument expansion, in which case this Loc is not at the // beginning of the expansion. FileID PrevFID = getPreviousFileID(DecompLoc.first); if (!PrevFID.isInvalid()) { const SrcMgr::SLocEntry &PrevEntry = getSLocEntry(PrevFID, &Invalid); if (Invalid) return false; if (PrevEntry.isExpansion() && PrevEntry.getExpansion().getExpansionLocStart() == ExpLoc) return false; } } if (MacroBegin) *MacroBegin = ExpLoc; return true; } bool SourceManager::isAtEndOfImmediateMacroExpansion(SourceLocation Loc, SourceLocation *MacroEnd) const { assert(Loc.isValid() && Loc.isMacroID() && "Expected a valid macro loc"); FileID FID = getFileID(Loc); SourceLocation NextLoc = Loc.getLocWithOffset(1); if (isInFileID(NextLoc, FID)) return false; // Does not point at the end of expansion range. bool Invalid = false; const SrcMgr::ExpansionInfo &ExpInfo = getSLocEntry(FID, &Invalid).getExpansion(); if (Invalid) return false; if (ExpInfo.isMacroArgExpansion()) { // For macro argument expansions, check if the next FileID is part of the // same argument expansion, in which case this Loc is not at the end of the // expansion. FileID NextFID = getNextFileID(FID); if (!NextFID.isInvalid()) { const SrcMgr::SLocEntry &NextEntry = getSLocEntry(NextFID, &Invalid); if (Invalid) return false; if (NextEntry.isExpansion() && NextEntry.getExpansion().getExpansionLocStart() == ExpInfo.getExpansionLocStart()) return false; } } if (MacroEnd) *MacroEnd = ExpInfo.getExpansionLocEnd(); return true; } //===----------------------------------------------------------------------===// // Queries about the code at a SourceLocation. //===----------------------------------------------------------------------===// /// getCharacterData - Return a pointer to the start of the specified location /// in the appropriate MemoryBuffer. const char *SourceManager::getCharacterData(SourceLocation SL, bool *Invalid) const { // Note that this is a hot function in the getSpelling() path, which is // heavily used by -E mode. std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(SL); // Note that calling 'getBuffer()' may lazily page in a source file. bool CharDataInvalid = false; const SLocEntry &Entry = getSLocEntry(LocInfo.first, &CharDataInvalid); if (CharDataInvalid || !Entry.isFile()) { if (Invalid) *Invalid = true; return "<<<<INVALID BUFFER>>>>"; } llvm::MemoryBuffer *Buffer = Entry.getFile().getContentCache()->getBuffer( Diag, *this, SourceLocation(), &CharDataInvalid); if (Invalid) *Invalid = CharDataInvalid; return Buffer->getBufferStart() + (CharDataInvalid? 0 : LocInfo.second); } /// getColumnNumber - Return the column # for the specified file position. /// this is significantly cheaper to compute than the line number. unsigned SourceManager::getColumnNumber(FileID FID, unsigned FilePos, bool *Invalid) const { bool MyInvalid = false; llvm::MemoryBuffer *MemBuf = getBuffer(FID, &MyInvalid); if (Invalid) *Invalid = MyInvalid; if (MyInvalid) return 1; // It is okay to request a position just past the end of the buffer. if (FilePos > MemBuf->getBufferSize()) { if (Invalid) *Invalid = true; return 1; } // See if we just calculated the line number for this FilePos and can use // that to lookup the start of the line instead of searching for it. if (LastLineNoFileIDQuery == FID && LastLineNoContentCache->SourceLineCache != nullptr && LastLineNoResult < LastLineNoContentCache->NumLines) { unsigned *SourceLineCache = LastLineNoContentCache->SourceLineCache; unsigned LineStart = SourceLineCache[LastLineNoResult - 1]; unsigned LineEnd = SourceLineCache[LastLineNoResult]; if (FilePos >= LineStart && FilePos < LineEnd) return FilePos - LineStart + 1; } const char *Buf = MemBuf->getBufferStart(); unsigned LineStart = FilePos; while (LineStart && Buf[LineStart-1] != '\n' && Buf[LineStart-1] != '\r') --LineStart; return FilePos-LineStart+1; } // isInvalid - Return the result of calling loc.isInvalid(), and // if Invalid is not null, set its value to same. static bool isInvalid(SourceLocation Loc, bool *Invalid) { bool MyInvalid = Loc.isInvalid(); if (Invalid) *Invalid = MyInvalid; return MyInvalid; } unsigned SourceManager::getSpellingColumnNumber(SourceLocation Loc, bool *Invalid) const { if (isInvalid(Loc, Invalid)) return 0; std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); } unsigned SourceManager::getExpansionColumnNumber(SourceLocation Loc, bool *Invalid) const { if (isInvalid(Loc, Invalid)) return 0; std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); return getColumnNumber(LocInfo.first, LocInfo.second, Invalid); } unsigned SourceManager::getPresumedColumnNumber(SourceLocation Loc, bool *Invalid) const { if (isInvalid(Loc, Invalid)) return 0; return getPresumedLoc(Loc).getColumn(); } #ifdef __SSE2__ #include <emmintrin.h> #endif static LLVM_ATTRIBUTE_NOINLINE void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI, llvm::BumpPtrAllocator &Alloc, const SourceManager &SM, bool &Invalid); static void ComputeLineNumbers(DiagnosticsEngine &Diag, ContentCache *FI, llvm::BumpPtrAllocator &Alloc, const SourceManager &SM, bool &Invalid) { // Note that calling 'getBuffer()' may lazily page in the file. MemoryBuffer *Buffer = FI->getBuffer(Diag, SM, SourceLocation(), &Invalid); if (Invalid) return; // Find the file offsets of all of the *physical* source lines. This does // not look at trigraphs, escaped newlines, or anything else tricky. SmallVector<unsigned, 256> LineOffsets; // Line #1 starts at char 0. LineOffsets.push_back(0); const unsigned char *Buf = (const unsigned char *)Buffer->getBufferStart(); const unsigned char *End = (const unsigned char *)Buffer->getBufferEnd(); unsigned Offs = 0; while (1) { // Skip over the contents of the line. const unsigned char *NextBuf = (const unsigned char *)Buf; #ifdef __SSE2__ // Try to skip to the next newline using SSE instructions. This is very // performance sensitive for programs with lots of diagnostics and in -E // mode. __m128i CRs = _mm_set1_epi8('\r'); __m128i LFs = _mm_set1_epi8('\n'); // First fix up the alignment to 16 bytes. while (((uintptr_t)NextBuf & 0xF) != 0) { if (*NextBuf == '\n' || *NextBuf == '\r' || *NextBuf == '\0') goto FoundSpecialChar; ++NextBuf; } // Scan 16 byte chunks for '\r' and '\n'. Ignore '\0'. while (NextBuf+16 <= End) { const __m128i Chunk = *(const __m128i*)NextBuf; __m128i Cmp = _mm_or_si128(_mm_cmpeq_epi8(Chunk, CRs), _mm_cmpeq_epi8(Chunk, LFs)); unsigned Mask = _mm_movemask_epi8(Cmp); // If we found a newline, adjust the pointer and jump to the handling code. if (Mask != 0) { NextBuf += llvm::countTrailingZeros(Mask); goto FoundSpecialChar; } NextBuf += 16; } #endif while (*NextBuf != '\n' && *NextBuf != '\r' && *NextBuf != '\0') ++NextBuf; #ifdef __SSE2__ FoundSpecialChar: #endif Offs += NextBuf-Buf; Buf = NextBuf; if (Buf[0] == '\n' || Buf[0] == '\r') { // If this is \n\r or \r\n, skip both characters. if ((Buf[1] == '\n' || Buf[1] == '\r') && Buf[0] != Buf[1]) ++Offs, ++Buf; ++Offs, ++Buf; LineOffsets.push_back(Offs); } else { // Otherwise, this is a null. If end of file, exit. if (Buf == End) break; // Otherwise, skip the null. ++Offs, ++Buf; } } // Copy the offsets into the FileInfo structure. FI->NumLines = LineOffsets.size(); FI->SourceLineCache = Alloc.Allocate<unsigned>(LineOffsets.size()); std::copy(LineOffsets.begin(), LineOffsets.end(), FI->SourceLineCache); } /// getLineNumber - Given a SourceLocation, return the spelling line number /// for the position indicated. This requires building and caching a table of /// line offsets for the MemoryBuffer, so this is not cheap: use only when /// about to emit a diagnostic. unsigned SourceManager::getLineNumber(FileID FID, unsigned FilePos, bool *Invalid) const { if (FID.isInvalid()) { if (Invalid) *Invalid = true; return 1; } ContentCache *Content; if (LastLineNoFileIDQuery == FID) Content = LastLineNoContentCache; else { bool MyInvalid = false; const SLocEntry &Entry = getSLocEntry(FID, &MyInvalid); if (MyInvalid || !Entry.isFile()) { if (Invalid) *Invalid = true; return 1; } Content = const_cast<ContentCache*>(Entry.getFile().getContentCache()); } // If this is the first use of line information for this buffer, compute the /// SourceLineCache for it on demand. if (!Content->SourceLineCache) { bool MyInvalid = false; ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid); if (Invalid) *Invalid = MyInvalid; if (MyInvalid) return 1; } else if (Invalid) *Invalid = false; // Okay, we know we have a line number table. Do a binary search to find the // line number that this character position lands on. unsigned *SourceLineCache = Content->SourceLineCache; unsigned *SourceLineCacheStart = SourceLineCache; unsigned *SourceLineCacheEnd = SourceLineCache + Content->NumLines; unsigned QueriedFilePos = FilePos+1; // FIXME: I would like to be convinced that this code is worth being as // complicated as it is, binary search isn't that slow. // // If it is worth being optimized, then in my opinion it could be more // performant, simpler, and more obviously correct by just "galloping" outward // from the queried file position. In fact, this could be incorporated into a // generic algorithm such as lower_bound_with_hint. // // If someone gives me a test case where this matters, and I will do it! - DWD // If the previous query was to the same file, we know both the file pos from // that query and the line number returned. This allows us to narrow the // search space from the entire file to something near the match. if (LastLineNoFileIDQuery == FID) { if (QueriedFilePos >= LastLineNoFilePos) { // FIXME: Potential overflow? SourceLineCache = SourceLineCache+LastLineNoResult-1; // The query is likely to be nearby the previous one. Here we check to // see if it is within 5, 10 or 20 lines. It can be far away in cases // where big comment blocks and vertical whitespace eat up lines but // contribute no tokens. if (SourceLineCache+5 < SourceLineCacheEnd) { if (SourceLineCache[5] > QueriedFilePos) SourceLineCacheEnd = SourceLineCache+5; else if (SourceLineCache+10 < SourceLineCacheEnd) { if (SourceLineCache[10] > QueriedFilePos) SourceLineCacheEnd = SourceLineCache+10; else if (SourceLineCache+20 < SourceLineCacheEnd) { if (SourceLineCache[20] > QueriedFilePos) SourceLineCacheEnd = SourceLineCache+20; } } } } else { if (LastLineNoResult < Content->NumLines) SourceLineCacheEnd = SourceLineCache+LastLineNoResult+1; } } unsigned *Pos = std::lower_bound(SourceLineCache, SourceLineCacheEnd, QueriedFilePos); unsigned LineNo = Pos-SourceLineCacheStart; LastLineNoFileIDQuery = FID; LastLineNoContentCache = Content; LastLineNoFilePos = QueriedFilePos; LastLineNoResult = LineNo; return LineNo; } unsigned SourceManager::getSpellingLineNumber(SourceLocation Loc, bool *Invalid) const { if (isInvalid(Loc, Invalid)) return 0; std::pair<FileID, unsigned> LocInfo = getDecomposedSpellingLoc(Loc); return getLineNumber(LocInfo.first, LocInfo.second); } unsigned SourceManager::getExpansionLineNumber(SourceLocation Loc, bool *Invalid) const { if (isInvalid(Loc, Invalid)) return 0; std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); return getLineNumber(LocInfo.first, LocInfo.second); } unsigned SourceManager::getPresumedLineNumber(SourceLocation Loc, bool *Invalid) const { if (isInvalid(Loc, Invalid)) return 0; return getPresumedLoc(Loc).getLine(); } /// getFileCharacteristic - return the file characteristic of the specified /// source location, indicating whether this is a normal file, a system /// header, or an "implicit extern C" system header. /// /// This state can be modified with flags on GNU linemarker directives like: /// # 4 "foo.h" 3 /// which changes all source locations in the current file after that to be /// considered to be from a system header. SrcMgr::CharacteristicKind SourceManager::getFileCharacteristic(SourceLocation Loc) const { assert(!Loc.isInvalid() && "Can't get file characteristic of invalid loc!"); std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); bool Invalid = false; const SLocEntry &SEntry = getSLocEntry(LocInfo.first, &Invalid); if (Invalid || !SEntry.isFile()) return C_User; const SrcMgr::FileInfo &FI = SEntry.getFile(); // If there are no #line directives in this file, just return the whole-file // state. if (!FI.hasLineDirectives()) return FI.getFileCharacteristic(); assert(LineTable && "Can't have linetable entries without a LineTable!"); // See if there is a #line directive before the location. const LineEntry *Entry = LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second); // If this is before the first line marker, use the file characteristic. if (!Entry) return FI.getFileCharacteristic(); return Entry->FileKind; } /// Return the filename or buffer identifier of the buffer the location is in. /// Note that this name does not respect \#line directives. Use getPresumedLoc /// for normal clients. const char *SourceManager::getBufferName(SourceLocation Loc, bool *Invalid) const { if (isInvalid(Loc, Invalid)) return "<invalid loc>"; return getBuffer(getFileID(Loc), Invalid)->getBufferIdentifier(); } /// getPresumedLoc - This method returns the "presumed" location of a /// SourceLocation specifies. A "presumed location" can be modified by \#line /// or GNU line marker directives. This provides a view on the data that a /// user should see in diagnostics, for example. /// /// Note that a presumed location is always given as the expansion point of an /// expansion location, not at the spelling location. PresumedLoc SourceManager::getPresumedLoc(SourceLocation Loc, bool UseLineDirectives) const { if (Loc.isInvalid()) return PresumedLoc(); // Presumed locations are always for expansion points. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); bool Invalid = false; const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); if (Invalid || !Entry.isFile()) return PresumedLoc(); const SrcMgr::FileInfo &FI = Entry.getFile(); const SrcMgr::ContentCache *C = FI.getContentCache(); // To get the source name, first consult the FileEntry (if one exists) // before the MemBuffer as this will avoid unnecessarily paging in the // MemBuffer. const char *Filename; if (C->OrigEntry) Filename = C->OrigEntry->getName(); else Filename = C->getBuffer(Diag, *this)->getBufferIdentifier(); unsigned LineNo = getLineNumber(LocInfo.first, LocInfo.second, &Invalid); if (Invalid) return PresumedLoc(); unsigned ColNo = getColumnNumber(LocInfo.first, LocInfo.second, &Invalid); if (Invalid) return PresumedLoc(); SourceLocation IncludeLoc = FI.getIncludeLoc(); // If we have #line directives in this file, update and overwrite the physical // location info if appropriate. if (UseLineDirectives && FI.hasLineDirectives()) { assert(LineTable && "Can't have linetable entries without a LineTable!"); // See if there is a #line directive before this. If so, get it. if (const LineEntry *Entry = LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) { // If the LineEntry indicates a filename, use it. if (Entry->FilenameID != -1) Filename = LineTable->getFilename(Entry->FilenameID); // Use the line number specified by the LineEntry. This line number may // be multiple lines down from the line entry. Add the difference in // physical line numbers from the query point and the line marker to the // total. unsigned MarkerLineNo = getLineNumber(LocInfo.first, Entry->FileOffset); LineNo = Entry->LineNo + (LineNo-MarkerLineNo-1); // Note that column numbers are not molested by line markers. // Handle virtual #include manipulation. if (Entry->IncludeOffset) { IncludeLoc = getLocForStartOfFile(LocInfo.first); IncludeLoc = IncludeLoc.getLocWithOffset(Entry->IncludeOffset); } } } return PresumedLoc(Filename, LineNo, ColNo, IncludeLoc); } /// \brief Returns whether the PresumedLoc for a given SourceLocation is /// in the main file. /// /// This computes the "presumed" location for a SourceLocation, then checks /// whether it came from a file other than the main file. This is different /// from isWrittenInMainFile() because it takes line marker directives into /// account. bool SourceManager::isInMainFile(SourceLocation Loc) const { if (Loc.isInvalid()) return false; // Presumed locations are always for expansion points. std::pair<FileID, unsigned> LocInfo = getDecomposedExpansionLoc(Loc); bool Invalid = false; const SLocEntry &Entry = getSLocEntry(LocInfo.first, &Invalid); if (Invalid || !Entry.isFile()) return false; const SrcMgr::FileInfo &FI = Entry.getFile(); // Check if there is a line directive for this location. if (FI.hasLineDirectives()) if (const LineEntry *Entry = LineTable->FindNearestLineEntry(LocInfo.first, LocInfo.second)) if (Entry->IncludeOffset) return false; return FI.getIncludeLoc().isInvalid(); } /// \brief The size of the SLocEntry that \p FID represents. unsigned SourceManager::getFileIDSize(FileID FID) const { bool Invalid = false; const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid); if (Invalid) return 0; int ID = FID.ID; unsigned NextOffset; if ((ID > 0 && unsigned(ID+1) == local_sloc_entry_size())) NextOffset = getNextLocalOffset(); else if (ID+1 == -1) NextOffset = MaxLoadedOffset; else NextOffset = getSLocEntry(FileID::get(ID+1)).getOffset(); return NextOffset - Entry.getOffset() - 1; } //===----------------------------------------------------------------------===// // Other miscellaneous methods. //===----------------------------------------------------------------------===// /// \brief Retrieve the inode for the given file entry, if possible. /// /// This routine involves a system call, and therefore should only be used /// in non-performance-critical code. static Optional<llvm::sys::fs::UniqueID> getActualFileUID(const FileEntry *File) { if (!File) return None; llvm::sys::fs::UniqueID ID; if (llvm::sys::fs::getUniqueID(File->getName(), ID)) return None; return ID; } /// \brief Get the source location for the given file:line:col triplet. /// /// If the source file is included multiple times, the source location will /// be based upon an arbitrary inclusion. SourceLocation SourceManager::translateFileLineCol(const FileEntry *SourceFile, unsigned Line, unsigned Col) const { assert(SourceFile && "Null source file!"); assert(Line && Col && "Line and column should start from 1!"); FileID FirstFID = translateFile(SourceFile); return translateLineCol(FirstFID, Line, Col); } /// \brief Get the FileID for the given file. /// /// If the source file is included multiple times, the FileID will be the /// first inclusion. FileID SourceManager::translateFile(const FileEntry *SourceFile) const { assert(SourceFile && "Null source file!"); // Find the first file ID that corresponds to the given file. FileID FirstFID; // First, check the main file ID, since it is common to look for a // location in the main file. Optional<llvm::sys::fs::UniqueID> SourceFileUID; Optional<StringRef> SourceFileName; if (!MainFileID.isInvalid()) { bool Invalid = false; const SLocEntry &MainSLoc = getSLocEntry(MainFileID, &Invalid); if (Invalid) return FileID(); if (MainSLoc.isFile()) { const ContentCache *MainContentCache = MainSLoc.getFile().getContentCache(); if (!MainContentCache) { // Can't do anything } else if (MainContentCache->OrigEntry == SourceFile) { FirstFID = MainFileID; } else { // Fall back: check whether we have the same base name and inode // as the main file. const FileEntry *MainFile = MainContentCache->OrigEntry; SourceFileName = llvm::sys::path::filename(SourceFile->getName()); if (*SourceFileName == llvm::sys::path::filename(MainFile->getName())) { SourceFileUID = getActualFileUID(SourceFile); if (SourceFileUID) { if (Optional<llvm::sys::fs::UniqueID> MainFileUID = getActualFileUID(MainFile)) { if (*SourceFileUID == *MainFileUID) { FirstFID = MainFileID; SourceFile = MainFile; } } } } } } } if (FirstFID.isInvalid()) { // The location we're looking for isn't in the main file; look // through all of the local source locations. for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) { bool Invalid = false; const SLocEntry &SLoc = getLocalSLocEntry(I, &Invalid); if (Invalid) return FileID(); if (SLoc.isFile() && SLoc.getFile().getContentCache() && SLoc.getFile().getContentCache()->OrigEntry == SourceFile) { FirstFID = FileID::get(I); break; } } // If that still didn't help, try the modules. if (FirstFID.isInvalid()) { for (unsigned I = 0, N = loaded_sloc_entry_size(); I != N; ++I) { const SLocEntry &SLoc = getLoadedSLocEntry(I); if (SLoc.isFile() && SLoc.getFile().getContentCache() && SLoc.getFile().getContentCache()->OrigEntry == SourceFile) { FirstFID = FileID::get(-int(I) - 2); break; } } } } // If we haven't found what we want yet, try again, but this time stat() // each of the files in case the files have changed since we originally // parsed the file. if (FirstFID.isInvalid() && (SourceFileName || (SourceFileName = llvm::sys::path::filename(SourceFile->getName()))) && (SourceFileUID || (SourceFileUID = getActualFileUID(SourceFile)))) { bool Invalid = false; for (unsigned I = 0, N = local_sloc_entry_size(); I != N; ++I) { FileID IFileID; IFileID.ID = I; const SLocEntry &SLoc = getSLocEntry(IFileID, &Invalid); if (Invalid) return FileID(); if (SLoc.isFile()) { const ContentCache *FileContentCache = SLoc.getFile().getContentCache(); const FileEntry *Entry = FileContentCache ? FileContentCache->OrigEntry : nullptr; if (Entry && *SourceFileName == llvm::sys::path::filename(Entry->getName())) { if (Optional<llvm::sys::fs::UniqueID> EntryUID = getActualFileUID(Entry)) { if (*SourceFileUID == *EntryUID) { FirstFID = FileID::get(I); SourceFile = Entry; break; } } } } } } (void) SourceFile; return FirstFID; } /// \brief Get the source location in \arg FID for the given line:col. /// Returns null location if \arg FID is not a file SLocEntry. SourceLocation SourceManager::translateLineCol(FileID FID, unsigned Line, unsigned Col) const { // Lines are used as a one-based index into a zero-based array. This assert // checks for possible buffer underruns. assert(Line != 0 && "Passed a zero-based line"); if (FID.isInvalid()) return SourceLocation(); bool Invalid = false; const SLocEntry &Entry = getSLocEntry(FID, &Invalid); if (Invalid) return SourceLocation(); if (!Entry.isFile()) return SourceLocation(); SourceLocation FileLoc = SourceLocation::getFileLoc(Entry.getOffset()); if (Line == 1 && Col == 1) return FileLoc; ContentCache *Content = const_cast<ContentCache *>(Entry.getFile().getContentCache()); if (!Content) return SourceLocation(); // If this is the first use of line information for this buffer, compute the // SourceLineCache for it on demand. if (!Content->SourceLineCache) { bool MyInvalid = false; ComputeLineNumbers(Diag, Content, ContentCacheAlloc, *this, MyInvalid); if (MyInvalid) return SourceLocation(); } if (Line > Content->NumLines) { unsigned Size = Content->getBuffer(Diag, *this)->getBufferSize(); if (Size > 0) --Size; return FileLoc.getLocWithOffset(Size); } llvm::MemoryBuffer *Buffer = Content->getBuffer(Diag, *this); unsigned FilePos = Content->SourceLineCache[Line - 1]; const char *Buf = Buffer->getBufferStart() + FilePos; unsigned BufLength = Buffer->getBufferSize() - FilePos; if (BufLength == 0) return FileLoc.getLocWithOffset(FilePos); unsigned i = 0; // Check that the given column is valid. while (i < BufLength-1 && i < Col-1 && Buf[i] != '\n' && Buf[i] != '\r') ++i; return FileLoc.getLocWithOffset(FilePos + i); } /// \brief Compute a map of macro argument chunks to their expanded source /// location. Chunks that are not part of a macro argument will map to an /// invalid source location. e.g. if a file contains one macro argument at /// offset 100 with length 10, this is how the map will be formed: /// 0 -> SourceLocation() /// 100 -> Expanded macro arg location /// 110 -> SourceLocation() void SourceManager::computeMacroArgsCache(MacroArgsMap *&CachePtr, FileID FID) const { assert(!FID.isInvalid()); assert(!CachePtr); CachePtr = new MacroArgsMap(); MacroArgsMap &MacroArgsCache = *CachePtr; // Initially no macro argument chunk is present. MacroArgsCache.insert(std::make_pair(0, SourceLocation())); int ID = FID.ID; while (1) { ++ID; // Stop if there are no more FileIDs to check. if (ID > 0) { if (unsigned(ID) >= local_sloc_entry_size()) return; } else if (ID == -1) { return; } bool Invalid = false; const SrcMgr::SLocEntry &Entry = getSLocEntryByID(ID, &Invalid); if (Invalid) return; if (Entry.isFile()) { SourceLocation IncludeLoc = Entry.getFile().getIncludeLoc(); if (IncludeLoc.isInvalid()) continue; if (!isInFileID(IncludeLoc, FID)) return; // No more files/macros that may be "contained" in this file. // Skip the files/macros of the #include'd file, we only care about macros // that lexed macro arguments from our file. if (Entry.getFile().NumCreatedFIDs) ID += Entry.getFile().NumCreatedFIDs - 1/*because of next ++ID*/; continue; } const ExpansionInfo &ExpInfo = Entry.getExpansion(); if (ExpInfo.getExpansionLocStart().isFileID()) { if (!isInFileID(ExpInfo.getExpansionLocStart(), FID)) return; // No more files/macros that may be "contained" in this file. } if (!ExpInfo.isMacroArgExpansion()) continue; associateFileChunkWithMacroArgExp(MacroArgsCache, FID, ExpInfo.getSpellingLoc(), SourceLocation::getMacroLoc(Entry.getOffset()), getFileIDSize(FileID::get(ID))); } } void SourceManager::associateFileChunkWithMacroArgExp( MacroArgsMap &MacroArgsCache, FileID FID, SourceLocation SpellLoc, SourceLocation ExpansionLoc, unsigned ExpansionLength) const { if (!SpellLoc.isFileID()) { unsigned SpellBeginOffs = SpellLoc.getOffset(); unsigned SpellEndOffs = SpellBeginOffs + ExpansionLength; // The spelling range for this macro argument expansion can span multiple // consecutive FileID entries. Go through each entry contained in the // spelling range and if one is itself a macro argument expansion, recurse // and associate the file chunk that it represents. FileID SpellFID; // Current FileID in the spelling range. unsigned SpellRelativeOffs; std::tie(SpellFID, SpellRelativeOffs) = getDecomposedLoc(SpellLoc); while (1) { const SLocEntry &Entry = getSLocEntry(SpellFID); unsigned SpellFIDBeginOffs = Entry.getOffset(); unsigned SpellFIDSize = getFileIDSize(SpellFID); unsigned SpellFIDEndOffs = SpellFIDBeginOffs + SpellFIDSize; const ExpansionInfo &Info = Entry.getExpansion(); if (Info.isMacroArgExpansion()) { unsigned CurrSpellLength; if (SpellFIDEndOffs < SpellEndOffs) CurrSpellLength = SpellFIDSize - SpellRelativeOffs; else CurrSpellLength = ExpansionLength; associateFileChunkWithMacroArgExp(MacroArgsCache, FID, Info.getSpellingLoc().getLocWithOffset(SpellRelativeOffs), ExpansionLoc, CurrSpellLength); } if (SpellFIDEndOffs >= SpellEndOffs) return; // we covered all FileID entries in the spelling range. // Move to the next FileID entry in the spelling range. unsigned advance = SpellFIDSize - SpellRelativeOffs + 1; ExpansionLoc = ExpansionLoc.getLocWithOffset(advance); ExpansionLength -= advance; ++SpellFID.ID; SpellRelativeOffs = 0; } } assert(SpellLoc.isFileID()); unsigned BeginOffs; if (!isInFileID(SpellLoc, FID, &BeginOffs)) return; unsigned EndOffs = BeginOffs + ExpansionLength; // Add a new chunk for this macro argument. A previous macro argument chunk // may have been lexed again, so e.g. if the map is // 0 -> SourceLocation() // 100 -> Expanded loc #1 // 110 -> SourceLocation() // and we found a new macro FileID that lexed from offet 105 with length 3, // the new map will be: // 0 -> SourceLocation() // 100 -> Expanded loc #1 // 105 -> Expanded loc #2 // 108 -> Expanded loc #1 // 110 -> SourceLocation() // // Since re-lexed macro chunks will always be the same size or less of // previous chunks, we only need to find where the ending of the new macro // chunk is mapped to and update the map with new begin/end mappings. MacroArgsMap::iterator I = MacroArgsCache.upper_bound(EndOffs); --I; SourceLocation EndOffsMappedLoc = I->second; MacroArgsCache[BeginOffs] = ExpansionLoc; MacroArgsCache[EndOffs] = EndOffsMappedLoc; } /// \brief If \arg Loc points inside a function macro argument, the returned /// location will be the macro location in which the argument was expanded. /// If a macro argument is used multiple times, the expanded location will /// be at the first expansion of the argument. /// e.g. /// MY_MACRO(foo); /// ^ /// Passing a file location pointing at 'foo', will yield a macro location /// where 'foo' was expanded into. SourceLocation SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const { if (Loc.isInvalid() || !Loc.isFileID()) return Loc; FileID FID; unsigned Offset; std::tie(FID, Offset) = getDecomposedLoc(Loc); if (FID.isInvalid()) return Loc; MacroArgsMap *&MacroArgsCache = MacroArgsCacheMap[FID]; if (!MacroArgsCache) computeMacroArgsCache(MacroArgsCache, FID); assert(!MacroArgsCache->empty()); MacroArgsMap::iterator I = MacroArgsCache->upper_bound(Offset); --I; unsigned MacroArgBeginOffs = I->first; SourceLocation MacroArgExpandedLoc = I->second; if (MacroArgExpandedLoc.isValid()) return MacroArgExpandedLoc.getLocWithOffset(Offset - MacroArgBeginOffs); return Loc; } std::pair<FileID, unsigned> SourceManager::getDecomposedIncludedLoc(FileID FID) const { if (FID.isInvalid()) return std::make_pair(FileID(), 0); // Uses IncludedLocMap to retrieve/cache the decomposed loc. typedef std::pair<FileID, unsigned> DecompTy; typedef llvm::DenseMap<FileID, DecompTy> MapTy; std::pair<MapTy::iterator, bool> InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy())); DecompTy &DecompLoc = InsertOp.first->second; if (!InsertOp.second) return DecompLoc; // already in map. SourceLocation UpperLoc; bool Invalid = false; const SrcMgr::SLocEntry &Entry = getSLocEntry(FID, &Invalid); if (!Invalid) { if (Entry.isExpansion()) UpperLoc = Entry.getExpansion().getExpansionLocStart(); else UpperLoc = Entry.getFile().getIncludeLoc(); } if (UpperLoc.isValid()) DecompLoc = getDecomposedLoc(UpperLoc); return DecompLoc; } /// Given a decomposed source location, move it up the include/expansion stack /// to the parent source location. If this is possible, return the decomposed /// version of the parent in Loc and return false. If Loc is the top-level /// entry, return true and don't modify it. static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc, const SourceManager &SM) { std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first); if (UpperLoc.first.isInvalid()) return true; // We reached the top. Loc = UpperLoc; return false; } /// Return the cache entry for comparing the given file IDs /// for isBeforeInTranslationUnit. InBeforeInTUCacheEntry &SourceManager::getInBeforeInTUCache(FileID LFID, FileID RFID) const { // This is a magic number for limiting the cache size. It was experimentally // derived from a small Objective-C project (where the cache filled // out to ~250 items). We can make it larger if necessary. enum { MagicCacheSize = 300 }; IsBeforeInTUCacheKey Key(LFID, RFID); // If the cache size isn't too large, do a lookup and if necessary default // construct an entry. We can then return it to the caller for direct // use. When they update the value, the cache will get automatically // updated as well. if (IBTUCache.size() < MagicCacheSize) return IBTUCache[Key]; // Otherwise, do a lookup that will not construct a new value. InBeforeInTUCache::iterator I = IBTUCache.find(Key); if (I != IBTUCache.end()) return I->second; // Fall back to the overflow value. return IBTUCacheOverflow; } /// \brief Determines the order of 2 source locations in the translation unit. /// /// \returns true if LHS source location comes before RHS, false otherwise. bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const { assert(LHS.isValid() && RHS.isValid() && "Passed invalid source location!"); if (LHS == RHS) return false; std::pair<FileID, unsigned> LOffs = getDecomposedLoc(LHS); std::pair<FileID, unsigned> ROffs = getDecomposedLoc(RHS); // getDecomposedLoc may have failed to return a valid FileID because, e.g. it // is a serialized one referring to a file that was removed after we loaded // the PCH. if (LOffs.first.isInvalid() || ROffs.first.isInvalid()) return LOffs.first.isInvalid() && !ROffs.first.isInvalid(); // If the source locations are in the same file, just compare offsets. if (LOffs.first == ROffs.first) return LOffs.second < ROffs.second; // If we are comparing a source location with multiple locations in the same // file, we get a big win by caching the result. InBeforeInTUCacheEntry &IsBeforeInTUCache = getInBeforeInTUCache(LOffs.first, ROffs.first); // If we are comparing a source location with multiple locations in the same // file, we get a big win by caching the result. if (IsBeforeInTUCache.isCacheValid(LOffs.first, ROffs.first)) return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second); // Okay, we missed in the cache, start updating the cache for this query. IsBeforeInTUCache.setQueryFIDs(LOffs.first, ROffs.first, /*isLFIDBeforeRFID=*/LOffs.first.ID < ROffs.first.ID); // We need to find the common ancestor. The only way of doing this is to // build the complete include chain for one and then walking up the chain // of the other looking for a match. // We use a map from FileID to Offset to store the chain. Easier than writing // a custom set hash info that only depends on the first part of a pair. typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet; LocSet LChain; do { LChain.insert(LOffs); // We catch the case where LOffs is in a file included by ROffs and // quit early. The other way round unfortunately remains suboptimal. } while (LOffs.first != ROffs.first && !MoveUpIncludeHierarchy(LOffs, *this)); LocSet::iterator I; while((I = LChain.find(ROffs.first)) == LChain.end()) { if (MoveUpIncludeHierarchy(ROffs, *this)) break; // Met at topmost file. } if (I != LChain.end()) LOffs = *I; // If we exited because we found a nearest common ancestor, compare the // locations within the common file and cache them. if (LOffs.first == ROffs.first) { IsBeforeInTUCache.setCommonLoc(LOffs.first, LOffs.second, ROffs.second); return IsBeforeInTUCache.getCachedResult(LOffs.second, ROffs.second); } // If we arrived here, the location is either in a built-ins buffer or // associated with global inline asm. PR5662 and PR22576 are examples. // Clear the lookup cache, it depends on a common location. IsBeforeInTUCache.clear(); llvm::MemoryBuffer *LBuf = getBuffer(LOffs.first); llvm::MemoryBuffer *RBuf = getBuffer(ROffs.first); bool LIsBuiltins = strcmp("<built-in>", LBuf->getBufferIdentifier()) == 0; bool RIsBuiltins = strcmp("<built-in>", RBuf->getBufferIdentifier()) == 0; // Sort built-in before non-built-in. if (LIsBuiltins || RIsBuiltins) { if (LIsBuiltins != RIsBuiltins) return LIsBuiltins; // Both are in built-in buffers, but from different files. We just claim that // lower IDs come first. return LOffs.first < ROffs.first; } bool LIsAsm = strcmp("<inline asm>", LBuf->getBufferIdentifier()) == 0; bool RIsAsm = strcmp("<inline asm>", RBuf->getBufferIdentifier()) == 0; // Sort assembler after built-ins, but before the rest. if (LIsAsm || RIsAsm) { if (LIsAsm != RIsAsm) return RIsAsm; assert(LOffs.first == ROffs.first); return false; } llvm_unreachable("Unsortable locations found"); } void SourceManager::PrintStats() const { llvm::errs() << "\n*** Source Manager Stats:\n"; llvm::errs() << FileInfos.size() << " files mapped, " << MemBufferInfos.size() << " mem buffers mapped.\n"; llvm::errs() << LocalSLocEntryTable.size() << " local SLocEntry's allocated (" << llvm::capacity_in_bytes(LocalSLocEntryTable) << " bytes of capacity), " << NextLocalOffset << "B of Sloc address space used.\n"; llvm::errs() << LoadedSLocEntryTable.size() << " loaded SLocEntries allocated, " << MaxLoadedOffset - CurrentLoadedOffset << "B of Sloc address space used.\n"; unsigned NumLineNumsComputed = 0; unsigned NumFileBytesMapped = 0; for (fileinfo_iterator I = fileinfo_begin(), E = fileinfo_end(); I != E; ++I){ NumLineNumsComputed += I->second->SourceLineCache != nullptr; NumFileBytesMapped += I->second->getSizeBytesMapped(); } unsigned NumMacroArgsComputed = MacroArgsCacheMap.size(); llvm::errs() << NumFileBytesMapped << " bytes of files mapped, " << NumLineNumsComputed << " files with line #'s computed, " << NumMacroArgsComputed << " files with macro args computed.\n"; llvm::errs() << "FileID scans: " << NumLinearScans << " linear, " << NumBinaryProbes << " binary.\n"; } ExternalSLocEntrySource::~ExternalSLocEntrySource() { } /// Return the amount of memory used by memory buffers, breaking down /// by heap-backed versus mmap'ed memory. SourceManager::MemoryBufferSizes SourceManager::getMemoryBufferSizes() const { size_t malloc_bytes = 0; size_t mmap_bytes = 0; for (unsigned i = 0, e = MemBufferInfos.size(); i != e; ++i) if (size_t sized_mapped = MemBufferInfos[i]->getSizeBytesMapped()) switch (MemBufferInfos[i]->getMemoryBufferKind()) { case llvm::MemoryBuffer::MemoryBuffer_MMap: mmap_bytes += sized_mapped; break; case llvm::MemoryBuffer::MemoryBuffer_Malloc: malloc_bytes += sized_mapped; break; } return MemoryBufferSizes(malloc_bytes, mmap_bytes); } size_t SourceManager::getDataStructureSizes() const { size_t size = llvm::capacity_in_bytes(MemBufferInfos) + llvm::capacity_in_bytes(LocalSLocEntryTable) + llvm::capacity_in_bytes(LoadedSLocEntryTable) + llvm::capacity_in_bytes(SLocEntryLoaded) + llvm::capacity_in_bytes(FileInfos); if (OverriddenFilesInfo) size += llvm::capacity_in_bytes(OverriddenFilesInfo->OverriddenFiles); return size; } unsigned SourceManager::getNumLineTableFilenames() const { assert(LineTable); return LineTable->getNumFilenames(); } const char * SourceManager::getLineTableFilename(unsigned ID) const { assert(LineTable); return LineTable->getFilename(ID); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/CMakeLists.txt
set(LLVM_LINK_COMPONENTS Core # MC # HLSL Change DxcSupport # HLSL Change Support ) # Figure out if we can track VC revisions. function(find_first_existing_file out_var) foreach(file ${ARGN}) if(EXISTS "${file}") set(${out_var} "${file}" PARENT_SCOPE) return() endif() endforeach() endfunction() macro(find_first_existing_vc_file out_var path) find_first_existing_file(${out_var} "${path}/.git/logs/HEAD" # Git "${path}/.svn/wc.db" # SVN 1.7 "${path}/.svn/entries" # SVN 1.6 ) endmacro() find_first_existing_vc_file(llvm_vc "${LLVM_MAIN_SRC_DIR}") find_first_existing_vc_file(clang_vc "${CLANG_SOURCE_DIR}") # The VC revision include that we want to generate. set(version_inc "${CMAKE_CURRENT_BINARY_DIR}/SVNVersion.inc") set(get_svn_script "${LLVM_MAIN_SRC_DIR}/cmake/modules/GetSVN.cmake") # HLSL Change Starts if (HLSL_ENABLE_FIXED_VER) # Actual version string is no longer specified here, but instead derived from # the defines in the generated or copied dxcversion.inc add_definitions(-DHLSL_FIXED_VER) endif (HLSL_ENABLE_FIXED_VER) # HLSL Change Ends if(DEFINED llvm_vc AND DEFINED clang_vc) # Create custom target to generate the VC revision include. add_custom_command(OUTPUT "${version_inc}" DEPENDS "${llvm_vc}" "${clang_vc}" "${get_svn_script}" COMMAND ${CMAKE_COMMAND} "-DFIRST_SOURCE_DIR=${LLVM_MAIN_SRC_DIR}" "-DFIRST_NAME=LLVM" "-DSECOND_SOURCE_DIR=${CLANG_SOURCE_DIR}" "-DSECOND_NAME=SVN" "-DHEADER_FILE=${version_inc}" -P "${get_svn_script}") # Mark the generated header as being generated. set_source_files_properties("${version_inc}" PROPERTIES GENERATED TRUE HEADER_FILE_ONLY TRUE) # Tell Version.cpp that it needs to build with -DHAVE_SVN_VERSION_INC. set_source_files_properties(Version.cpp PROPERTIES COMPILE_DEFINITIONS "HAVE_SVN_VERSION_INC") else() # Not producing a VC revision include. set(version_inc) endif() add_clang_library(clangBasic Attributes.cpp Builtins.cpp CharInfo.cpp Diagnostic.cpp DiagnosticIDs.cpp DiagnosticOptions.cpp FileManager.cpp FileSystemStatCache.cpp IdentifierTable.cpp LangOptions.cpp Module.cpp ObjCRuntime.cpp OpenMPKinds.cpp OperatorPrecedence.cpp SanitizerBlacklist.cpp Sanitizers.cpp SourceLocation.cpp SourceManager.cpp TargetInfo.cpp Targets.cpp TokenKinds.cpp Version.cpp VersionTuple.cpp VirtualFileSystem.cpp Warnings.cpp ${version_inc} DEPENDS hlsl_dxcversion_autogen # HLSL Change ) # HLSL Change Starts if ( HLSL_SUPPORT_QUERY_GIT_COMMIT_INFO ) set(GIT_COMMIT_INFO_FILE ${CMAKE_CURRENT_BINARY_DIR}/GitCommitInfo.inc) set(GET_GIT_COMMIT_SCRIPT ${PROJECT_SOURCE_DIR}/utils/GetCommitInfo.py) add_custom_command( OUTPUT ${GIT_COMMIT_INFO_FILE} COMMAND ${Python3_EXECUTABLE} ${GET_GIT_COMMIT_SCRIPT} ${PROJECT_SOURCE_DIR} ${GIT_COMMIT_INFO_FILE} DEPENDS ${GET_GIT_COMMIT_SCRIPT} GIT_COMMIT_INFO_ALWAYS_REBUILD COMMENT "Collect Git commit info for versioning" ) add_custom_target( GIT_COMMIT_INFO_ALWAYS_REBUILD ${CMAKE_COMMAND} -E touch ${GET_GIT_COMMIT_SCRIPT} COMMENT "Touch GetCommitInfo.py to trigger rebuild" ) set_property(TARGET GIT_COMMIT_INFO_ALWAYS_REBUILD PROPERTY FOLDER "Utils") set_source_files_properties(${CMAKE_CURRENT_SOURCE_DIR}/Version.cpp PROPERTIES OBJECT_DEPENDS "${GIT_COMMIT_INFO_FILE}") endif() target_include_directories(clangBasic PUBLIC ${HLSL_VERSION_LOCATION}) # HLSL Change # HLSL Change Ends
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/Sanitizers.cpp
//===--- Sanitizers.cpp - C Language Family Language Options ----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the classes from Sanitizers.h // //===----------------------------------------------------------------------===// #include "clang/Basic/Sanitizers.h" #include "clang/Basic/LLVM.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" // // /////////////////////////////////////////////////////////////////////////////// using namespace clang; SanitizerMask clang::parseSanitizerValue(StringRef Value, bool AllowGroups) { SanitizerMask ParsedKind = llvm::StringSwitch<SanitizerMask>(Value) #define SANITIZER(NAME, ID) .Case(NAME, SanitizerKind::ID) #define SANITIZER_GROUP(NAME, ID, ALIAS) \ .Case(NAME, AllowGroups ? SanitizerKind::ID##Group : 0) #include "clang/Basic/Sanitizers.def" .Default(0); return ParsedKind; } SanitizerMask clang::expandSanitizerGroups(SanitizerMask Kinds) { #define SANITIZER(NAME, ID) #define SANITIZER_GROUP(NAME, ID, ALIAS) \ if (Kinds & SanitizerKind::ID##Group) \ Kinds |= SanitizerKind::ID; #include "clang/Basic/Sanitizers.def" return Kinds; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/SourceLocation.cpp
//==--- SourceLocation.cpp - Compact identifier for Source Files -*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines accessor methods for the FullSourceLoc class. // //===----------------------------------------------------------------------===// #include "clang/Basic/SourceLocation.h" #include "clang/Basic/PrettyStackTrace.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include <cstdio> using namespace clang; //===----------------------------------------------------------------------===// // PrettyStackTraceLoc //===----------------------------------------------------------------------===// void PrettyStackTraceLoc::print(raw_ostream &OS) const { if (Loc.isValid()) { Loc.print(OS, SM); OS << ": "; } OS << Message << '\n'; } //===----------------------------------------------------------------------===// // SourceLocation //===----------------------------------------------------------------------===// void SourceLocation::print(raw_ostream &OS, const SourceManager &SM)const{ if (!isValid()) { OS << "<invalid loc>"; return; } if (isFileID()) { PresumedLoc PLoc = SM.getPresumedLoc(*this); if (PLoc.isInvalid()) { OS << "<invalid>"; return; } // The macro expansion and spelling pos is identical for file locs. OS << PLoc.getFilename() << ':' << PLoc.getLine() << ':' << PLoc.getColumn(); return; } SM.getExpansionLoc(*this).print(OS, SM); OS << " <Spelling="; SM.getSpellingLoc(*this).print(OS, SM); OS << '>'; } LLVM_DUMP_METHOD std::string SourceLocation::printToString(const SourceManager &SM) const { std::string S; llvm::raw_string_ostream OS(S); print(OS, SM); return OS.str(); } LLVM_DUMP_METHOD void SourceLocation::dump(const SourceManager &SM) const { print(llvm::errs(), SM); } //===----------------------------------------------------------------------===// // FullSourceLoc //===----------------------------------------------------------------------===// FileID FullSourceLoc::getFileID() const { assert(isValid()); return SrcMgr->getFileID(*this); } FullSourceLoc FullSourceLoc::getExpansionLoc() const { assert(isValid()); return FullSourceLoc(SrcMgr->getExpansionLoc(*this), *SrcMgr); } FullSourceLoc FullSourceLoc::getSpellingLoc() const { assert(isValid()); return FullSourceLoc(SrcMgr->getSpellingLoc(*this), *SrcMgr); } unsigned FullSourceLoc::getExpansionLineNumber(bool *Invalid) const { assert(isValid()); return SrcMgr->getExpansionLineNumber(*this, Invalid); } unsigned FullSourceLoc::getExpansionColumnNumber(bool *Invalid) const { assert(isValid()); return SrcMgr->getExpansionColumnNumber(*this, Invalid); } unsigned FullSourceLoc::getSpellingLineNumber(bool *Invalid) const { assert(isValid()); return SrcMgr->getSpellingLineNumber(*this, Invalid); } unsigned FullSourceLoc::getSpellingColumnNumber(bool *Invalid) const { assert(isValid()); return SrcMgr->getSpellingColumnNumber(*this, Invalid); } bool FullSourceLoc::isInSystemHeader() const { assert(isValid()); return SrcMgr->isInSystemHeader(*this); } bool FullSourceLoc::isBeforeInTranslationUnitThan(SourceLocation Loc) const { assert(isValid()); return SrcMgr->isBeforeInTranslationUnit(*this, Loc); } LLVM_DUMP_METHOD void FullSourceLoc::dump() const { SourceLocation::dump(*SrcMgr); } const char *FullSourceLoc::getCharacterData(bool *Invalid) const { assert(isValid()); return SrcMgr->getCharacterData(*this, Invalid); } StringRef FullSourceLoc::getBufferData(bool *Invalid) const { assert(isValid()); return SrcMgr->getBuffer(SrcMgr->getFileID(*this), Invalid)->getBuffer(); } std::pair<FileID, unsigned> FullSourceLoc::getDecomposedLoc() const { return SrcMgr->getDecomposedLoc(*this); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/IdentifierTable.cpp
//===--- IdentifierTable.cpp - Hash table for identifier lookup -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the IdentifierInfo, IdentifierVisitor, and // IdentifierTable interfaces. // //===----------------------------------------------------------------------===// #include "clang/Basic/CharInfo.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/OperatorKinds.h" #include "clang/Basic/Specifiers.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include <cstdio> using namespace clang; //===----------------------------------------------------------------------===// // IdentifierInfo Implementation //===----------------------------------------------------------------------===// IdentifierInfo::IdentifierInfo() { TokenID = tok::identifier; ObjCOrBuiltinID = 0; HasMacro = false; HadMacro = false; IsExtension = false; IsFutureCompatKeyword = false; IsPoisoned = false; IsCPPOperatorKeyword = false; NeedsHandleIdentifier = false; IsFromAST = false; ChangedAfterLoad = false; RevertedTokenID = false; OutOfDate = false; IsModulesImport = false; FETokenInfo = nullptr; Entry = nullptr; } //===----------------------------------------------------------------------===// // IdentifierTable Implementation //===----------------------------------------------------------------------===// IdentifierIterator::~IdentifierIterator() { } IdentifierInfoLookup::~IdentifierInfoLookup() {} namespace { /// \brief A simple identifier lookup iterator that represents an /// empty sequence of identifiers. class EmptyLookupIterator : public IdentifierIterator { public: StringRef Next() override { return StringRef(); } }; } IdentifierIterator *IdentifierInfoLookup::getIdentifiers() { return new EmptyLookupIterator(); } IdentifierTable::IdentifierTable(const LangOptions &LangOpts, IdentifierInfoLookup* externalLookup) : HashTable(8192), // Start with space for 8K identifiers. ExternalLookup(externalLookup) { // Populate the identifier table with info about keywords for the current // language. AddKeywords(LangOpts); // Add the '_experimental_modules_import' contextual keyword. get("import").setModulesImport(true); } //===----------------------------------------------------------------------===// // Language Keyword Implementation //===----------------------------------------------------------------------===// // Constants for TokenKinds.def namespace { enum { KEYC99 = 0x1, KEYCXX = 0x2, KEYCXX11 = 0x4, KEYGNU = 0x8, KEYMS = 0x10, BOOLSUPPORT = 0x20, KEYALTIVEC = 0x40, KEYNOCXX = 0x80, KEYBORLAND = 0x100, KEYOPENCL = 0x200, KEYC11 = 0x400, KEYARC = 0x800, KEYNOMS18 = 0x01000, KEYNOOPENCL = 0x02000, WCHARSUPPORT = 0x04000, HALFSUPPORT = 0x08000, KEYCONCEPTS = 0x10000, KEYOBJC2 = 0x20000, KEYZVECTOR = 0x40000, KEYHLSL = 0x80000, // MS Change: Flag for hlsl keywords KEYALL = (0x7ffff & ~KEYNOMS18 & ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude. }; /// \brief How a keyword is treated in the selected standard. enum KeywordStatus { KS_Disabled, // Disabled KS_Extension, // Is an extension KS_Enabled, // Enabled KS_Future // Is a keyword in future standard }; } /// \brief Translates flags as specified in TokenKinds.def into keyword status /// in the given language standard. static KeywordStatus getKeywordStatus(const LangOptions &LangOpts, unsigned Flags) { if (Flags == KEYALL) return KS_Enabled; if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled; if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled; if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled; if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension; if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension; if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension; if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled; if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled; if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled; if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled; if (LangOpts.OpenCL && (Flags & KEYOPENCL)) return KS_Enabled; if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled; if (LangOpts.HLSL && (Flags & KEYHLSL)) return KS_Enabled; // HLSL Change: Support for HLSL Keywords if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled; // We treat bridge casts as objective-C keywords so we can warn on them // in non-arc mode. if (LangOpts.ObjC2 && (Flags & KEYARC)) return KS_Enabled; if (LangOpts.ConceptsTS && (Flags & KEYCONCEPTS)) return KS_Enabled; if (LangOpts.ObjC2 && (Flags & KEYOBJC2)) return KS_Enabled; if (LangOpts.CPlusPlus && (Flags & KEYCXX11)) return KS_Future; return KS_Disabled; } /// AddKeyword - This method is used to associate a token ID with specific /// identifiers because they are language keywords. This causes the lexer to /// automatically map matching identifiers to specialized token codes. static void AddKeyword(StringRef Keyword, tok::TokenKind TokenCode, unsigned Flags, const LangOptions &LangOpts, IdentifierTable &Table) { KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags); // Don't add this keyword under MSVCCompat. if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) && !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015)) return; // Don't add this keyword under OpenCL. if (LangOpts.OpenCL && (Flags & KEYNOOPENCL)) return; // Don't add this keyword if disabled in this language. if (AddResult == KS_Disabled) return; IdentifierInfo &Info = Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode); Info.setIsExtensionToken(AddResult == KS_Extension); Info.setIsFutureCompatKeyword(AddResult == KS_Future); } /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative /// representations. static void AddCXXOperatorKeyword(StringRef Keyword, tok::TokenKind TokenCode, IdentifierTable &Table) { IdentifierInfo &Info = Table.get(Keyword, TokenCode); Info.setIsCPlusPlusOperatorKeyword(); } /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector" /// or "property". static void AddObjCKeyword(StringRef Name, tok::ObjCKeywordKind ObjCID, IdentifierTable &Table) { Table.get(Name).setObjCKeywordID(ObjCID); } /// AddKeywords - Add all keywords to the symbol table. /// void IdentifierTable::AddKeywords(const LangOptions &LangOpts) { // Add keywords and tokens for the current language. #define KEYWORD(NAME, FLAGS) \ AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \ FLAGS, LangOpts, *this); #define ALIAS(NAME, TOK, FLAGS) \ AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \ FLAGS, LangOpts, *this); #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \ if (LangOpts.CXXOperatorNames) \ AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this); #define OBJC1_AT_KEYWORD(NAME) \ if (LangOpts.ObjC1) \ AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this); #define OBJC2_AT_KEYWORD(NAME) \ if (LangOpts.ObjC2) \ AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this); #define TESTING_KEYWORD(NAME, FLAGS) #include "clang/Basic/TokenKinds.def" if (LangOpts.ParseUnknownAnytype) AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL, LangOpts, *this); // FIXME: __declspec isn't really a CUDA extension, however it is required for // supporting cuda_builtin_vars.h, which uses __declspec(property). Once that // has been rewritten in terms of something more generic, remove this code. if (LangOpts.CUDA) AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this); } /// \brief Checks if the specified token kind represents a keyword in the /// specified language. /// \returns Status of the keyword in the language. static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts, tok::TokenKind K) { switch (K) { #define KEYWORD(NAME, FLAGS) \ case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS); #include "clang/Basic/TokenKinds.def" default: return KS_Disabled; } } /// \brief Returns true if the identifier represents a keyword in the /// specified language. bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) { switch (getTokenKwStatus(LangOpts, getTokenID())) { case KS_Enabled: case KS_Extension: return true; default: return false; } } tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const { // We use a perfect hash function here involving the length of the keyword, // the first and third character. For preprocessor ID's there are no // collisions (if there were, the switch below would complain about duplicate // case values). Note that this depends on 'if' being null terminated. #define HASH(LEN, FIRST, THIRD) \ (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31) #define CASE(LEN, FIRST, THIRD, NAME) \ case HASH(LEN, FIRST, THIRD): \ return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME unsigned Len = getLength(); if (Len < 2) return tok::pp_not_keyword; const char *Name = getNameStart(); switch (HASH(Len, Name[0], Name[2])) { default: return tok::pp_not_keyword; CASE( 2, 'i', '\0', if); CASE( 4, 'e', 'i', elif); CASE( 4, 'e', 's', else); CASE( 4, 'l', 'n', line); CASE( 4, 's', 'c', sccs); CASE( 5, 'e', 'd', endif); CASE( 5, 'e', 'r', error); CASE( 5, 'i', 'e', ident); CASE( 5, 'i', 'd', ifdef); CASE( 5, 'u', 'd', undef); CASE( 6, 'a', 's', assert); CASE( 6, 'd', 'f', define); CASE( 6, 'i', 'n', ifndef); CASE( 6, 'i', 'p', import); CASE( 6, 'p', 'a', pragma); CASE( 7, 'd', 'f', defined); CASE( 7, 'i', 'c', include); CASE( 7, 'w', 'r', warning); CASE( 8, 'u', 'a', unassert); CASE(12, 'i', 'c', include_next); CASE(14, '_', 'p', __public_macro); CASE(15, '_', 'p', __private_macro); CASE(16, '_', 'i', __include_macros); #undef CASE #undef HASH } } //===----------------------------------------------------------------------===// // Stats Implementation //===----------------------------------------------------------------------===// /// PrintStats - Print statistics about how well the identifier table is doing /// at hashing identifiers. void IdentifierTable::PrintStats() const { unsigned NumBuckets = HashTable.getNumBuckets(); unsigned NumIdentifiers = HashTable.getNumItems(); unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers; unsigned AverageIdentifierSize = 0; unsigned MaxIdentifierLength = 0; // TODO: Figure out maximum times an identifier had to probe for -stats. for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator I = HashTable.begin(), E = HashTable.end(); I != E; ++I) { unsigned IdLen = I->getKeyLength(); AverageIdentifierSize += IdLen; if (MaxIdentifierLength < IdLen) MaxIdentifierLength = IdLen; } fprintf(stderr, "\n*** Identifier Table Stats:\n"); fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers); fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets); fprintf(stderr, "Hash density (#identifiers per bucket): %f\n", NumIdentifiers/(double)NumBuckets); fprintf(stderr, "Ave identifier length: %f\n", (AverageIdentifierSize/(double)NumIdentifiers)); fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength); // Compute statistics about the memory allocated for identifiers. HashTable.getAllocator().PrintStats(); } //===----------------------------------------------------------------------===// // SelectorTable Implementation //===----------------------------------------------------------------------===// unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) { return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr()); } namespace clang { /// MultiKeywordSelector - One of these variable length records is kept for each /// selector containing more than one keyword. We use a folding set /// to unique aggregate names (keyword selectors in ObjC parlance). Access to /// this class is provided strictly through Selector. class MultiKeywordSelector : public DeclarationNameExtra, public llvm::FoldingSetNode { MultiKeywordSelector(unsigned nKeys) { ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; } public: // Constructor for keyword selectors. MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) { assert((nKeys > 1) && "not a multi-keyword selector"); ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys; // Fill in the trailing keyword array. IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1); for (unsigned i = 0; i != nKeys; ++i) KeyInfo[i] = IIV[i]; } // getName - Derive the full selector name and return it. std::string getName() const; unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; } typedef IdentifierInfo *const *keyword_iterator; keyword_iterator keyword_begin() const { return reinterpret_cast<keyword_iterator>(this+1); } keyword_iterator keyword_end() const { return keyword_begin()+getNumArgs(); } IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const { assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index"); return keyword_begin()[i]; } static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys, unsigned NumArgs) { ID.AddInteger(NumArgs); for (unsigned i = 0; i != NumArgs; ++i) ID.AddPointer(ArgTys[i]); } void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, keyword_begin(), getNumArgs()); } }; } // end namespace clang. unsigned Selector::getNumArgs() const { unsigned IIF = getIdentifierInfoFlag(); if (IIF <= ZeroArg) return 0; if (IIF == OneArg) return 1; // We point to a MultiKeywordSelector. MultiKeywordSelector *SI = getMultiKeywordSelector(); return SI->getNumArgs(); } IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const { if (getIdentifierInfoFlag() < MultiArg) { assert(argIndex == 0 && "illegal keyword index"); return getAsIdentifierInfo(); } // We point to a MultiKeywordSelector. MultiKeywordSelector *SI = getMultiKeywordSelector(); return SI->getIdentifierInfoForSlot(argIndex); } StringRef Selector::getNameForSlot(unsigned int argIndex) const { IdentifierInfo *II = getIdentifierInfoForSlot(argIndex); return II? II->getName() : StringRef(); } std::string MultiKeywordSelector::getName() const { SmallString<256> Str; llvm::raw_svector_ostream OS(Str); for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) { if (*I) OS << (*I)->getName(); OS << ':'; } return OS.str(); } std::string Selector::getAsString() const { if (InfoPtr == 0) return "<null selector>"; if (getIdentifierInfoFlag() < MultiArg) { IdentifierInfo *II = getAsIdentifierInfo(); // If the number of arguments is 0 then II is guaranteed to not be null. if (getNumArgs() == 0) return II->getName(); if (!II) return ":"; return II->getName().str() + ":"; } // We have a multiple keyword selector. return getMultiKeywordSelector()->getName(); } void Selector::print(llvm::raw_ostream &OS) const { OS << getAsString(); } /// Interpreting the given string using the normal CamelCase /// conventions, determine whether the given string starts with the /// given "word", which is assumed to end in a lowercase letter. static bool startsWithWord(StringRef name, StringRef word) { if (name.size() < word.size()) return false; return ((name.size() == word.size() || !isLowercase(name[word.size()])) && name.startswith(word)); } ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return OMF_None; StringRef name = first->getName(); if (sel.isUnarySelector()) { if (name == "autorelease") return OMF_autorelease; if (name == "dealloc") return OMF_dealloc; if (name == "finalize") return OMF_finalize; if (name == "release") return OMF_release; if (name == "retain") return OMF_retain; if (name == "retainCount") return OMF_retainCount; if (name == "self") return OMF_self; if (name == "initialize") return OMF_initialize; } if (name == "performSelector") return OMF_performSelector; // The other method families may begin with a prefix of underscores. while (!name.empty() && name.front() == '_') name = name.substr(1); if (name.empty()) return OMF_None; switch (name.front()) { case 'a': if (startsWithWord(name, "alloc")) return OMF_alloc; break; case 'c': if (startsWithWord(name, "copy")) return OMF_copy; break; case 'i': if (startsWithWord(name, "init")) return OMF_init; break; case 'm': if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy; break; case 'n': if (startsWithWord(name, "new")) return OMF_new; break; default: break; } return OMF_None; } ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return OIT_None; StringRef name = first->getName(); if (name.empty()) return OIT_None; switch (name.front()) { case 'a': if (startsWithWord(name, "array")) return OIT_Array; break; case 'd': if (startsWithWord(name, "default")) return OIT_ReturnsSelf; if (startsWithWord(name, "dictionary")) return OIT_Dictionary; break; case 's': if (startsWithWord(name, "shared")) return OIT_ReturnsSelf; if (startsWithWord(name, "standard")) return OIT_Singleton; break; case 'i': if (startsWithWord(name, "init")) return OIT_Init; break; // HLSL Change default: break; } return OIT_None; } ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) { IdentifierInfo *first = sel.getIdentifierInfoForSlot(0); if (!first) return SFF_None; StringRef name = first->getName(); switch (name.front()) { case 'a': if (name == "appendFormat") return SFF_NSString; break; case 'i': if (name == "initWithFormat") return SFF_NSString; break; case 'l': if (name == "localizedStringWithFormat") return SFF_NSString; break; case 's': if (name == "stringByAppendingFormat" || name == "stringWithFormat") return SFF_NSString; break; } return SFF_None; } namespace { struct SelectorTableImpl { llvm::FoldingSet<MultiKeywordSelector> Table; llvm::BumpPtrAllocator Allocator; }; } // end anonymous namespace. static SelectorTableImpl &getSelectorTableImpl(void *P) { return *static_cast<SelectorTableImpl*>(P); } SmallString<64> SelectorTable::constructSetterName(StringRef Name) { SmallString<64> SetterName("set"); SetterName += Name; SetterName[3] = toUppercase(SetterName[3]); return SetterName; } Selector SelectorTable::constructSetterSelector(IdentifierTable &Idents, SelectorTable &SelTable, const IdentifierInfo *Name) { IdentifierInfo *SetterName = &Idents.get(constructSetterName(Name->getName())); return SelTable.getUnarySelector(SetterName); } size_t SelectorTable::getTotalMemory() const { SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); return SelTabImpl.Allocator.getTotalMemory(); } Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) { if (nKeys < 2) return Selector(IIV[0], nKeys); SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl); // Unique selector, to guarantee there is one per name. llvm::FoldingSetNodeID ID; MultiKeywordSelector::Profile(ID, IIV, nKeys); void *InsertPos = nullptr; if (MultiKeywordSelector *SI = SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos)) return Selector(SI); // MultiKeywordSelector objects are not allocated with new because they have a // variable size array (for parameter types) at the end of them. unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *); MultiKeywordSelector *SI = (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size, llvm::alignOf<MultiKeywordSelector>()); new (SI) MultiKeywordSelector(nKeys, IIV); SelTabImpl.Table.InsertNode(SI, InsertPos); return Selector(SI); } SelectorTable::SelectorTable() { Impl = new SelectorTableImpl(); } SelectorTable::~SelectorTable() { delete &getSelectorTableImpl(Impl); } const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) { switch (Operator) { case OO_None: case NUM_OVERLOADED_OPERATORS: return nullptr; #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ case OO_##Name: return Spelling; #include "clang/Basic/OperatorKinds.def" } llvm_unreachable("Invalid OverloadedOperatorKind!"); } StringRef clang::getNullabilitySpelling(NullabilityKind kind, bool isContextSensitive) { switch (kind) { case NullabilityKind::NonNull: return isContextSensitive ? "nonnull" : "_Nonnull"; case NullabilityKind::Nullable: return isContextSensitive ? "nullable" : "_Nullable"; case NullabilityKind::Unspecified: return isContextSensitive ? "null_unspecified" : "_Null_unspecified"; } llvm_unreachable("Unknown nullability kind."); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/VersionTuple.cpp
//===- VersionTuple.cpp - Version Number Handling ---------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the VersionTuple class, which represents a version in // the form major[.minor[.subminor]]. // //===----------------------------------------------------------------------===// #include "clang/Basic/VersionTuple.h" #include "llvm/Support/raw_ostream.h" // // /////////////////////////////////////////////////////////////////////////////// using namespace clang; std::string VersionTuple::getAsString() const { std::string Result; { llvm::raw_string_ostream Out(Result); Out << *this; } return Result; } raw_ostream& clang::operator<<(raw_ostream &Out, const VersionTuple &V) { Out << V.getMajor(); if (Optional<unsigned> Minor = V.getMinor()) Out << (V.usesUnderscores() ? '_' : '.') << *Minor; if (Optional<unsigned> Subminor = V.getSubminor()) Out << (V.usesUnderscores() ? '_' : '.') << *Subminor; if (Optional<unsigned> Build = V.getBuild()) Out << (V.usesUnderscores() ? '_' : '.') << *Build; return Out; } static bool parseInt(StringRef &input, unsigned &value) { assert(value == 0); if (input.empty()) return true; char next = input[0]; input = input.substr(1); if (next < '0' || next > '9') return true; value = (unsigned) (next - '0'); while (!input.empty()) { next = input[0]; if (next < '0' || next > '9') return false; input = input.substr(1); value = value * 10 + (unsigned) (next - '0'); } return false; } bool VersionTuple::tryParse(StringRef input) { unsigned major = 0, minor = 0, micro = 0, build = 0; // Parse the major version, [0-9]+ if (parseInt(input, major)) return true; if (input.empty()) { *this = VersionTuple(major); return false; } // If we're not done, parse the minor version, \.[0-9]+ if (input[0] != '.') return true; input = input.substr(1); if (parseInt(input, minor)) return true; if (input.empty()) { *this = VersionTuple(major, minor); return false; } // If we're not done, parse the micro version, \.[0-9]+ if (input[0] != '.') return true; input = input.substr(1); if (parseInt(input, micro)) return true; if (input.empty()) { *this = VersionTuple(major, minor, micro); return false; } // If we're not done, parse the micro version, \.[0-9]+ if (input[0] != '.') return true; input = input.substr(1); if (parseInt(input, build)) return true; // If we have characters left over, it's an error. if (!input.empty()) return true; *this = VersionTuple(major, minor, micro, build); return false; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/Warnings.cpp
//===--- Warnings.cpp - C-Language Front-end ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Command line warning options handler. // //===----------------------------------------------------------------------===// // // This file is responsible for handling all warning options. This includes // a number of -Wfoo options and their variants, which are driven by TableGen- // generated data, and the special cases -pedantic, -pedantic-errors, -w, // -Werror and -Wfatal-errors. // // Each warning option controls any number of actual warnings. // Given a warning option 'foo', the following are valid: // -Wfoo, -Wno-foo, -Werror=foo, -Wfatal-errors=foo // // Remark options are also handled here, analogously, except that they are much // simpler because a remark can't be promoted to an error. #include "clang/Basic/AllDiagnostics.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include <algorithm> #include <cstring> #include <utility> using namespace clang; // // /////////////////////////////////////////////////////////////////////////////// // EmitUnknownDiagWarning - Emit a warning and typo hint for unknown warning // opts static void EmitUnknownDiagWarning(DiagnosticsEngine &Diags, diag::Flavor Flavor, StringRef Prefix, StringRef Opt) { StringRef Suggestion = DiagnosticIDs::getNearestOption(Flavor, Opt); Diags.Report(diag::warn_unknown_diag_option) << (Flavor == diag::Flavor::WarningOrError ? 0 : 1) << (Prefix.str() += Opt) << !Suggestion.empty() << (Prefix.str() += Suggestion); } void clang::ProcessWarningOptions(DiagnosticsEngine &Diags, const DiagnosticOptions &Opts, bool ReportDiags) { Diags.setSuppressSystemWarnings(true); // Default to -Wno-system-headers Diags.setIgnoreAllWarnings(Opts.IgnoreWarnings); Diags.setShowOverloads(Opts.getShowOverloads()); Diags.setElideType(Opts.ElideType); Diags.setPrintTemplateTree(Opts.ShowTemplateTree); Diags.setShowColors(Opts.ShowColors); // Handle -ferror-limit if (Opts.ErrorLimit) Diags.setErrorLimit(Opts.ErrorLimit); if (Opts.TemplateBacktraceLimit) Diags.setTemplateBacktraceLimit(Opts.TemplateBacktraceLimit); if (Opts.ConstexprBacktraceLimit) Diags.setConstexprBacktraceLimit(Opts.ConstexprBacktraceLimit); // If -pedantic or -pedantic-errors was specified, then we want to map all // extension diagnostics onto WARNING or ERROR unless the user has futz'd // around with them explicitly. if (Opts.PedanticErrors) Diags.setExtensionHandlingBehavior(diag::Severity::Error); else if (Opts.Pedantic) Diags.setExtensionHandlingBehavior(diag::Severity::Warning); else Diags.setExtensionHandlingBehavior(diag::Severity::Ignored); SmallVector<diag::kind, 10> _Diags; const IntrusiveRefCntPtr< DiagnosticIDs > DiagIDs = Diags.getDiagnosticIDs(); // We parse the warning options twice. The first pass sets diagnostic state, // while the second pass reports warnings/errors. This has the effect that // we follow the more canonical "last option wins" paradigm when there are // conflicting options. for (unsigned Report = 0, ReportEnd = 2; Report != ReportEnd; ++Report) { bool SetDiagnostic = (Report == 0); // If we've set the diagnostic state and are not reporting diagnostics then // we're done. if (!SetDiagnostic && !ReportDiags) break; for (unsigned i = 0, e = Opts.Warnings.size(); i != e; ++i) { const auto Flavor = diag::Flavor::WarningOrError; StringRef Opt = Opts.Warnings[i]; StringRef OrigOpt = Opts.Warnings[i]; // Treat -Wformat=0 as an alias for -Wno-format. if (Opt == "format=0") Opt = "no-format"; // Check to see if this warning starts with "no-", if so, this is a // negative form of the option. bool isPositive = true; if (Opt.startswith("no-")) { isPositive = false; Opt = Opt.substr(3); } // Figure out how this option affects the warning. If -Wfoo, map the // diagnostic to a warning, if -Wno-foo, map it to ignore. diag::Severity Mapping = isPositive ? diag::Severity::Warning : diag::Severity::Ignored; // -Wsystem-headers is a special case, not driven by the option table. It // cannot be controlled with -Werror. if (Opt == "system-headers") { if (SetDiagnostic) Diags.setSuppressSystemWarnings(!isPositive); continue; } // -Weverything is a special case as well. It implicitly enables all // warnings, including ones not explicitly in a warning group. if (Opt == "everything") { if (SetDiagnostic) { if (isPositive) { Diags.setEnableAllWarnings(true); } else { Diags.setEnableAllWarnings(false); Diags.setSeverityForAll(Flavor, diag::Severity::Ignored); } } continue; } // -Werror/-Wno-error is a special case, not controlled by the option // table. It also has the "specifier" form of -Werror=foo and -Werror-foo. if (Opt.startswith("error")) { StringRef Specifier; if (Opt.size() > 5) { // Specifier must be present. if ((Opt[5] != '=' && Opt[5] != '-') || Opt.size() == 6) { if (Report) Diags.Report(diag::warn_unknown_warning_specifier) << "-Werror" << ("-W" + OrigOpt.str()); continue; } Specifier = Opt.substr(6); } if (Specifier.empty()) { if (SetDiagnostic) Diags.setWarningsAsErrors(isPositive); continue; } if (SetDiagnostic) { // Set the warning as error flag for this specifier. Diags.setDiagnosticGroupWarningAsError(Specifier, isPositive); } else if (DiagIDs->getDiagnosticsInGroup(Flavor, Specifier, _Diags)) { EmitUnknownDiagWarning(Diags, Flavor, "-Werror=", Specifier); } continue; } // -Wfatal-errors is yet another special case. if (Opt.startswith("fatal-errors")) { StringRef Specifier; if (Opt.size() != 12) { if ((Opt[12] != '=' && Opt[12] != '-') || Opt.size() == 13) { if (Report) Diags.Report(diag::warn_unknown_warning_specifier) << "-Wfatal-errors" << ("-W" + OrigOpt.str()); continue; } Specifier = Opt.substr(13); } if (Specifier.empty()) { if (SetDiagnostic) Diags.setErrorsAsFatal(isPositive); continue; } if (SetDiagnostic) { // Set the error as fatal flag for this specifier. Diags.setDiagnosticGroupErrorAsFatal(Specifier, isPositive); } else if (DiagIDs->getDiagnosticsInGroup(Flavor, Specifier, _Diags)) { EmitUnknownDiagWarning(Diags, Flavor, "-Wfatal-errors=", Specifier); } continue; } if (Report) { if (DiagIDs->getDiagnosticsInGroup(Flavor, Opt, _Diags)) EmitUnknownDiagWarning(Diags, Flavor, isPositive ? "-W" : "-Wno-", Opt); } else { Diags.setSeverityForGroup(Flavor, Opt, Mapping); } } for (unsigned i = 0, e = Opts.Remarks.size(); i != e; ++i) { StringRef Opt = Opts.Remarks[i]; const auto Flavor = diag::Flavor::Remark; // Check to see if this warning starts with "no-", if so, this is a // negative form of the option. bool IsPositive = !Opt.startswith("no-"); if (!IsPositive) Opt = Opt.substr(3); auto Severity = IsPositive ? diag::Severity::Remark : diag::Severity::Ignored; // -Reverything sets the state of all remarks. Note that all remarks are // in remark groups, so we don't need a separate 'all remarks enabled' // flag. if (Opt == "everything") { if (SetDiagnostic) Diags.setSeverityForAll(Flavor, Severity); continue; } if (Report) { if (DiagIDs->getDiagnosticsInGroup(Flavor, Opt, _Diags)) EmitUnknownDiagWarning(Diags, Flavor, IsPositive ? "-R" : "-Rno-", Opt); } else { Diags.setSeverityForGroup(Flavor, Opt, IsPositive ? diag::Severity::Remark : diag::Severity::Ignored); } } } }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/Builtins.cpp
//===--- Builtins.cpp - Builtin function implementation -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements various things for builtin functions. // //===----------------------------------------------------------------------===// #include "clang/Basic/Builtins.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" using namespace clang; static const Builtin::Info BuiltinInfo[] = { { "not a builtin function", nullptr, nullptr, nullptr, ALL_LANGUAGES}, #define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES }, #define LANGBUILTIN(ID, TYPE, ATTRS, BUILTIN_LANG) { #ID, TYPE, ATTRS, 0, BUILTIN_LANG }, #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER, BUILTIN_LANG) { #ID, TYPE, ATTRS, HEADER,\ BUILTIN_LANG }, #include "clang/Basic/Builtins.def" }; const Builtin::Info &Builtin::Context::GetRecord(unsigned ID) const { if (ID < Builtin::FirstTSBuiltin) return BuiltinInfo[ID]; assert(ID - Builtin::FirstTSBuiltin < NumTSRecords && "Invalid builtin ID!"); return TSRecords[ID - Builtin::FirstTSBuiltin]; } Builtin::Context::Context() { // Get the target specific builtins from the target. TSRecords = nullptr; NumTSRecords = 0; } void Builtin::Context::InitializeTarget(const TargetInfo &Target) { assert(NumTSRecords == 0 && "Already initialized target?"); Target.getTargetBuiltins(TSRecords, NumTSRecords); } bool Builtin::Context::BuiltinIsSupported(const Builtin::Info &BuiltinInfo, const LangOptions &LangOpts) { bool BuiltinsUnsupported = LangOpts.NoBuiltin && strchr(BuiltinInfo.Attributes, 'f'); bool MathBuiltinsUnsupported = LangOpts.NoMathBuiltin && BuiltinInfo.HeaderName && llvm::StringRef(BuiltinInfo.HeaderName).equals("math.h"); bool GnuModeUnsupported = !LangOpts.GNUMode && (BuiltinInfo.builtin_lang & GNU_LANG); bool MSModeUnsupported = !LangOpts.MicrosoftExt && (BuiltinInfo.builtin_lang & MS_LANG); bool ObjCUnsupported = !LangOpts.ObjC1 && BuiltinInfo.builtin_lang == OBJC_LANG; return !BuiltinsUnsupported && !MathBuiltinsUnsupported && !GnuModeUnsupported && !MSModeUnsupported && !ObjCUnsupported; } /// InitializeBuiltins - Mark the identifiers for all the builtins with their /// appropriate builtin ID # and mark any non-portable builtin identifiers as /// such. void Builtin::Context::InitializeBuiltins(IdentifierTable &Table, const LangOptions& LangOpts) { // Step #1: mark all target-independent builtins with their ID's. for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i) if (BuiltinIsSupported(BuiltinInfo[i], LangOpts)) { Table.get(BuiltinInfo[i].Name).setBuiltinID(i); } // Step #2: Register target-specific builtins. for (unsigned i = 0, e = NumTSRecords; i != e; ++i) if (BuiltinIsSupported(TSRecords[i], LangOpts)) Table.get(TSRecords[i].Name).setBuiltinID(i+Builtin::FirstTSBuiltin); } void Builtin::Context::GetBuiltinNames(SmallVectorImpl<const char *> &Names) { // Final all target-independent names for (unsigned i = Builtin::NotBuiltin+1; i != Builtin::FirstTSBuiltin; ++i) if (!strchr(BuiltinInfo[i].Attributes, 'f')) Names.push_back(BuiltinInfo[i].Name); // Find target-specific names. for (unsigned i = 0, e = NumTSRecords; i != e; ++i) if (!strchr(TSRecords[i].Attributes, 'f')) Names.push_back(TSRecords[i].Name); } void Builtin::Context::ForgetBuiltin(unsigned ID, IdentifierTable &Table) { Table.get(GetRecord(ID).Name).setBuiltinID(0); } bool Builtin::Context::isLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg, const char *Fmt) const { assert(Fmt && "Not passed a format string"); assert(::strlen(Fmt) == 2 && "Format string needs to be two characters long"); assert(::toupper(Fmt[0]) == Fmt[1] && "Format string is not in the form \"xX\""); const char *Like = ::strpbrk(GetRecord(ID).Attributes, Fmt); if (!Like) return false; HasVAListArg = (*Like == Fmt[1]); ++Like; assert(*Like == ':' && "Format specifier must be followed by a ':'"); ++Like; assert(::strchr(Like, ':') && "Format specifier must end with a ':'"); FormatIdx = ::strtol(Like, nullptr, 10); return true; } bool Builtin::Context::isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg) { return isLike(ID, FormatIdx, HasVAListArg, "pP"); } bool Builtin::Context::isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg) { return isLike(ID, FormatIdx, HasVAListArg, "sS"); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/FileSystemStatCache.cpp
//===--- FileSystemStatCache.cpp - Caching for 'stat' calls ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the FileSystemStatCache interface. // //===----------------------------------------------------------------------===// #include "clang/Basic/FileSystemStatCache.h" #include "clang/Basic/VirtualFileSystem.h" #include "llvm/Support/Path.h" using namespace clang; void FileSystemStatCache::anchor() { } static void copyStatusToFileData(const vfs::Status &Status, FileData &Data) { Data.Name = Status.getName(); Data.Size = Status.getSize(); Data.ModTime = Status.getLastModificationTime().toEpochTime(); Data.UniqueID = Status.getUniqueID(); Data.IsDirectory = Status.isDirectory(); Data.IsNamedPipe = Status.getType() == llvm::sys::fs::file_type::fifo_file; Data.InPCH = false; Data.IsVFSMapped = Status.IsVFSMapped; } /// FileSystemStatCache::get - Get the 'stat' information for the specified /// path, using the cache to accelerate it if possible. This returns true if /// the path does not exist or false if it exists. /// /// If isFile is true, then this lookup should only return success for files /// (not directories). If it is false this lookup should only return /// success for directories (not files). On a successful file lookup, the /// implementation can optionally fill in FileDescriptor with a valid /// descriptor and the client guarantees that it will close it. bool FileSystemStatCache::get(const char *Path, FileData &Data, bool isFile, std::unique_ptr<vfs::File> *F, FileSystemStatCache *Cache, vfs::FileSystem &FS) { LookupResult R; bool isForDir = !isFile; // If we have a cache, use it to resolve the stat query. if (Cache) R = Cache->getStat(Path, Data, isFile, F, FS); else if (isForDir || !F) { // If this is a directory or a file descriptor is not needed and we have // no cache, just go to the file system. llvm::ErrorOr<vfs::Status> Status = FS.status(Path); if (!Status) { R = CacheMissing; } else { R = CacheExists; copyStatusToFileData(*Status, Data); } } else { // Otherwise, we have to go to the filesystem. We can always just use // 'stat' here, but (for files) the client is asking whether the file exists // because it wants to turn around and *open* it. It is more efficient to // do "open+fstat" on success than it is to do "stat+open". // // Because of this, check to see if the file exists with 'open'. If the // open succeeds, use fstat to get the stat info. auto OwnedFile = FS.openFileForRead(Path); if (!OwnedFile) { // If the open fails, our "stat" fails. R = CacheMissing; } else { // Otherwise, the open succeeded. Do an fstat to get the information // about the file. We'll end up returning the open file descriptor to the // client to do what they please with it. llvm::ErrorOr<vfs::Status> Status = (*OwnedFile)->status(); if (Status) { R = CacheExists; copyStatusToFileData(*Status, Data); *F = std::move(*OwnedFile); } else { // fstat rarely fails. If it does, claim the initial open didn't // succeed. R = CacheMissing; *F = nullptr; } } } // If the path doesn't exist, return failure. if (R == CacheMissing) return true; // If the path exists, make sure that its "directoryness" matches the clients // demands. if (Data.IsDirectory != isForDir) { // If not, close the file if opened. if (F) *F = nullptr; return true; } return false; } MemorizeStatCalls::LookupResult MemorizeStatCalls::getStat(const char *Path, FileData &Data, bool isFile, std::unique_ptr<vfs::File> *F, vfs::FileSystem &FS) { LookupResult Result = statChained(Path, Data, isFile, F, FS); // Do not cache failed stats, it is easy to construct common inconsistent // situations if we do, and they are not important for PCH performance (which // currently only needs the stats to construct the initial FileManager // entries). if (Result == CacheMissing) return Result; // Cache file 'stat' results and directories with absolutely paths. if (!Data.IsDirectory || llvm::sys::path::is_absolute(Path)) StatCalls[Path] = Data; return Result; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/Diagnostic.cpp
//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Diagnostic-related interfaces. // //===----------------------------------------------------------------------===// #include "clang/Basic/CharInfo.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/PartialDiagnostic.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/Locale.h" #include "llvm/Support/raw_ostream.h" using namespace clang; const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB, DiagNullabilityKind nullability) { StringRef string; switch (nullability.first) { case NullabilityKind::NonNull: string = nullability.second ? "'nonnull'" : "'_Nonnull'"; break; case NullabilityKind::Nullable: string = nullability.second ? "'nullable'" : "'_Nullable'"; break; case NullabilityKind::Unspecified: string = nullability.second ? "'null_unspecified'" : "'_Null_unspecified'"; break; } DB.AddString(string); return DB; } static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT, StringRef Modifier, StringRef Argument, ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs, SmallVectorImpl<char> &Output, void *Cookie, ArrayRef<intptr_t> QualTypeVals) { StringRef Str = "<can't format argument>"; Output.append(Str.begin(), Str.end()); } DiagnosticsEngine::DiagnosticsEngine( const IntrusiveRefCntPtr<DiagnosticIDs> &diags, DiagnosticOptions *DiagOpts, DiagnosticConsumer *client, bool ShouldOwnClient) : Diags(diags), DiagOpts(DiagOpts), Client(nullptr), SourceMgr(nullptr) { setClient(client, ShouldOwnClient); ArgToStringFn = DummyArgToStringFn; ArgToStringCookie = nullptr; AllExtensionsSilenced = 0; IgnoreAllWarnings = false; WarningsAsErrors = false; EnableAllWarnings = false; ErrorsAsFatal = false; SuppressSystemWarnings = false; SuppressAllDiagnostics = false; ElideType = true; PrintTemplateTree = false; ShowColors = false; ShowOverloads = Ovl_All; ExtBehavior = diag::Severity::Ignored; ErrorLimit = 0; TemplateBacktraceLimit = 0; ConstexprBacktraceLimit = 0; Reset(); } DiagnosticsEngine::~DiagnosticsEngine() { // If we own the diagnostic client, destroy it first so that it can access the // engine from its destructor. setClient(nullptr); } void DiagnosticsEngine::setClient(DiagnosticConsumer *client, bool ShouldOwnClient) { Owner.reset(ShouldOwnClient ? client : nullptr); Client = client; } void DiagnosticsEngine::pushMappings(SourceLocation Loc) { DiagStateOnPushStack.push_back(GetCurDiagState()); } bool DiagnosticsEngine::popMappings(SourceLocation Loc) { if (DiagStateOnPushStack.empty()) return false; if (DiagStateOnPushStack.back() != GetCurDiagState()) { // State changed at some point between push/pop. PushDiagStatePoint(DiagStateOnPushStack.back(), Loc); } DiagStateOnPushStack.pop_back(); return true; } void DiagnosticsEngine::Reset() { ErrorOccurred = false; UncompilableErrorOccurred = false; FatalErrorOccurred = false; UnrecoverableErrorOccurred = false; NumWarnings = 0; NumErrors = 0; TrapNumErrorsOccurred = 0; TrapNumUnrecoverableErrorsOccurred = 0; CurDiagID = ~0U; LastDiagLevel = DiagnosticIDs::Ignored; DelayedDiagID = 0; // Clear state related to #pragma diagnostic. DiagStates.clear(); DiagStatePoints.clear(); DiagStateOnPushStack.clear(); // Create a DiagState and DiagStatePoint representing diagnostic changes // through command-line. DiagStates.emplace_back(); DiagStatePoints.push_back(DiagStatePoint(&DiagStates.back(), FullSourceLoc())); } void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1, StringRef Arg2) { if (DelayedDiagID) return; DelayedDiagID = DiagID; DelayedDiagArg1 = Arg1.str(); DelayedDiagArg2 = Arg2.str(); } void DiagnosticsEngine::ReportDelayed() { Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2; DelayedDiagID = 0; DelayedDiagArg1.clear(); DelayedDiagArg2.clear(); } DiagnosticsEngine::DiagStatePointsTy::iterator DiagnosticsEngine::GetDiagStatePointForLoc(SourceLocation L) const { assert(!DiagStatePoints.empty()); assert(DiagStatePoints.front().Loc.isInvalid() && "Should have created a DiagStatePoint for command-line"); if (!SourceMgr) return DiagStatePoints.end() - 1; FullSourceLoc Loc(L, *SourceMgr); if (Loc.isInvalid()) return DiagStatePoints.end() - 1; DiagStatePointsTy::iterator Pos = DiagStatePoints.end(); FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc; if (LastStateChangePos.isValid() && Loc.isBeforeInTranslationUnitThan(LastStateChangePos)) Pos = std::upper_bound(DiagStatePoints.begin(), DiagStatePoints.end(), DiagStatePoint(nullptr, Loc)); --Pos; return Pos; } void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation L) { assert(Diag < diag::DIAG_UPPER_LIMIT && "Can only map builtin diagnostics"); assert((Diags->isBuiltinWarningOrExtension(Diag) || (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) && "Cannot map errors into warnings!"); assert(!DiagStatePoints.empty()); assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location"); FullSourceLoc Loc = SourceMgr? FullSourceLoc(L, *SourceMgr) : FullSourceLoc(); FullSourceLoc LastStateChangePos = DiagStatePoints.back().Loc; // Don't allow a mapping to a warning override an error/fatal mapping. if (Map == diag::Severity::Warning) { DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag); if (Info.getSeverity() == diag::Severity::Error || Info.getSeverity() == diag::Severity::Fatal) Map = Info.getSeverity(); } DiagnosticMapping Mapping = makeUserMapping(Map, L); // Common case; setting all the diagnostics of a group in one place. if (Loc.isInvalid() || Loc == LastStateChangePos) { GetCurDiagState()->setMapping(Diag, Mapping); return; } assert(SourceMgr != nullptr); // SourceMgr==nullptr is only valid for invalid locations, which cause an earlier exit // Another common case; modifying diagnostic state in a source location // after the previous one. if ((Loc.isValid() && LastStateChangePos.isInvalid()) || LastStateChangePos.isBeforeInTranslationUnitThan(Loc)) { // A diagnostic pragma occurred, create a new DiagState initialized with // the current one and a new DiagStatePoint to record at which location // the new state became active. DiagStates.push_back(*GetCurDiagState()); PushDiagStatePoint(&DiagStates.back(), Loc); GetCurDiagState()->setMapping(Diag, Mapping); return; } // We allow setting the diagnostic state in random source order for // completeness but it should not be actually happening in normal practice. DiagStatePointsTy::iterator Pos = GetDiagStatePointForLoc(Loc); assert(Pos != DiagStatePoints.end()); // Update all diagnostic states that are active after the given location. for (DiagStatePointsTy::iterator I = Pos+1, E = DiagStatePoints.end(); I != E; ++I) { GetCurDiagState()->setMapping(Diag, Mapping); } // If the location corresponds to an existing point, just update its state. if (Pos->Loc == Loc) { GetCurDiagState()->setMapping(Diag, Mapping); return; } // Create a new state/point and fit it into the vector of DiagStatePoints // so that the vector is always ordered according to location. assert(Pos->Loc.isBeforeInTranslationUnitThan(Loc)); DiagStates.push_back(*Pos->State); DiagState *NewState = &DiagStates.back(); GetCurDiagState()->setMapping(Diag, Mapping); DiagStatePoints.insert(Pos+1, DiagStatePoint(NewState, FullSourceLoc(Loc, *SourceMgr))); } bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor, StringRef Group, diag::Severity Map, SourceLocation Loc) { // Get the diagnostics in this group. SmallVector<diag::kind, 256> GroupDiags; if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags)) return true; // Set the mapping. for (diag::kind Diag : GroupDiags) setSeverity(Diag, Map, Loc); return false; } bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled) { // If we are enabling this feature, just set the diagnostic mappings to map to // errors. if (Enabled) return setSeverityForGroup(diag::Flavor::WarningOrError, Group, diag::Severity::Error); // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and // potentially downgrade anything already mapped to be a warning. // Get the diagnostics in this group. SmallVector<diag::kind, 8> GroupDiags; if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group, GroupDiags)) return true; // Perform the mapping change. for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) { DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(GroupDiags[i]); if (Info.getSeverity() == diag::Severity::Error || Info.getSeverity() == diag::Severity::Fatal) Info.setSeverity(diag::Severity::Warning); Info.setNoWarningAsError(true); } return false; } bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled) { // If we are enabling this feature, just set the diagnostic mappings to map to // fatal errors. if (Enabled) return setSeverityForGroup(diag::Flavor::WarningOrError, Group, diag::Severity::Fatal); // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and // potentially downgrade anything already mapped to be an error. // Get the diagnostics in this group. SmallVector<diag::kind, 8> GroupDiags; if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group, GroupDiags)) return true; // Perform the mapping change. for (unsigned i = 0, e = GroupDiags.size(); i != e; ++i) { DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(GroupDiags[i]); if (Info.getSeverity() == diag::Severity::Fatal) Info.setSeverity(diag::Severity::Error); Info.setNoErrorAsFatal(true); } return false; } void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor, diag::Severity Map, SourceLocation Loc) { // Get all the diagnostics. SmallVector<diag::kind, 64> AllDiags; Diags->getAllDiagnostics(Flavor, AllDiags); // Set the mapping. for (unsigned i = 0, e = AllDiags.size(); i != e; ++i) if (Diags->isBuiltinWarningOrExtension(AllDiags[i])) setSeverity(AllDiags[i], Map, Loc); } void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) { assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!"); CurDiagLoc = storedDiag.getLocation(); CurDiagID = storedDiag.getID(); NumDiagArgs = 0; DiagRanges.clear(); DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end()); DiagFixItHints.clear(); DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end()); assert(Client && "DiagnosticConsumer not set!"); Level DiagLevel = storedDiag.getLevel(); Diagnostic Info(this, storedDiag.getMessage()); Client->HandleDiagnostic(DiagLevel, Info); if (Client->IncludeInDiagnosticCounts()) { if (DiagLevel == DiagnosticsEngine::Warning) ++NumWarnings; } CurDiagID = ~0U; } bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) { assert(getClient() && "DiagnosticClient not set!"); bool Emitted; if (Force) { Diagnostic Info(this); // Figure out the diagnostic level of this message. DiagnosticIDs::Level DiagLevel = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this); Emitted = (DiagLevel != DiagnosticIDs::Ignored); if (Emitted) { // Emit the diagnostic regardless of suppression level. Diags->EmitDiag(*this, DiagLevel); } } else { // Process the diagnostic, sending the accumulated information to the // DiagnosticConsumer. Emitted = ProcessDiag(); } // Clear out the current diagnostic object. unsigned DiagID = CurDiagID; Clear(); // If there was a delayed diagnostic, emit it now. if (!Force && DelayedDiagID && DelayedDiagID != DiagID) ReportDelayed(); return Emitted; } DiagnosticConsumer::~DiagnosticConsumer() {} void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) { if (!IncludeInDiagnosticCounts()) return; if (DiagLevel == DiagnosticsEngine::Warning) ++NumWarnings; else if (DiagLevel >= DiagnosticsEngine::Error) ++NumErrors; } /// ModifierIs - Return true if the specified modifier matches specified string. template <std::size_t StrLen> static bool ModifierIs(const char *Modifier, unsigned ModifierLen, const char (&Str)[StrLen]) { return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1); } /// ScanForward - Scans forward, looking for the given character, skipping /// nested clauses and escaped characters. static const char *ScanFormat(const char *I, const char *E, char Target) { unsigned Depth = 0; for ( ; I != E; ++I) { if (Depth == 0 && *I == Target) return I; if (Depth != 0 && *I == '}') Depth--; if (*I == '%') { I++; if (I == E) break; // Escaped characters get implicitly skipped here. // Format specifier. if (!isDigit(*I) && !isPunctuation(*I)) { for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ; if (I == E) break; if (*I == '{') Depth++; } } } return E; } /// HandleSelectModifier - Handle the integer 'select' modifier. This is used /// like this: %select{foo|bar|baz}2. This means that the integer argument /// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'. /// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'. /// This is very useful for certain classes of variant diagnostics. static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo, const char *Argument, unsigned ArgumentLen, SmallVectorImpl<char> &OutStr) { const char *ArgumentEnd = Argument+ArgumentLen; // Skip over 'ValNo' |'s. while (ValNo) { const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|'); assert(NextVal != ArgumentEnd && "Value for integer select modifier was" " larger than the number of options in the diagnostic string!"); Argument = NextVal+1; // Skip this string. --ValNo; } // Get the end of the value. This is either the } or the |. const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|'); // Recursively format the result of the select clause into the output string. DInfo.FormatDiagnostic(Argument, EndPtr, OutStr); } /// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the /// letter 's' to the string if the value is not 1. This is used in cases like /// this: "you have %4 parameter%s4!". // HLSL Change - remove minor profanity static void HandleIntegerSModifier(unsigned ValNo, SmallVectorImpl<char> &OutStr) { if (ValNo != 1) OutStr.push_back('s'); } /// HandleOrdinalModifier - Handle the integer 'ord' modifier. This /// prints the ordinal form of the given integer, with 1 corresponding /// to the first ordinal. Currently this is hard-coded to use the /// English form. static void HandleOrdinalModifier(unsigned ValNo, SmallVectorImpl<char> &OutStr) { assert(ValNo != 0 && "ValNo must be strictly positive!"); llvm::raw_svector_ostream Out(OutStr); // We could use text forms for the first N ordinals, but the numeric // forms are actually nicer in diagnostics because they stand out. Out << ValNo << llvm::getOrdinalSuffix(ValNo); } /// PluralNumber - Parse an unsigned integer and advance Start. static unsigned PluralNumber(const char *&Start, const char *End) { // Programming 101: Parse a decimal number :-) unsigned Val = 0; while (Start != End && *Start >= '0' && *Start <= '9') { Val *= 10; Val += *Start - '0'; ++Start; } return Val; } /// TestPluralRange - Test if Val is in the parsed range. Modifies Start. static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) { if (*Start != '[') { unsigned Ref = PluralNumber(Start, End); return Ref == Val; } ++Start; unsigned Low = PluralNumber(Start, End); assert(*Start == ',' && "Bad plural expression syntax: expected ,"); ++Start; unsigned High = PluralNumber(Start, End); assert(*Start == ']' && "Bad plural expression syntax: expected )"); ++Start; return Low <= Val && Val <= High; } /// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier. static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) { // Empty condition? if (*Start == ':') return true; while (1) { char C = *Start; if (C == '%') { // Modulo expression ++Start; unsigned Arg = PluralNumber(Start, End); assert(*Start == '=' && "Bad plural expression syntax: expected ="); ++Start; unsigned ValMod = ValNo % Arg; if (TestPluralRange(ValMod, Start, End)) return true; } else { assert((C == '[' || (C >= '0' && C <= '9')) && "Bad plural expression syntax: unexpected character"); // Range expression if (TestPluralRange(ValNo, Start, End)) return true; } // Scan for next or-expr part. Start = std::find(Start, End, ','); if (Start == End) break; ++Start; } return false; } /// HandlePluralModifier - Handle the integer 'plural' modifier. This is used /// for complex plural forms, or in languages where all plurals are complex. /// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are /// conditions that are tested in order, the form corresponding to the first /// that applies being emitted. The empty condition is always true, making the /// last form a default case. /// Conditions are simple boolean expressions, where n is the number argument. /// Here are the rules. /// condition := expression | empty /// empty := -> always true /// expression := numeric [',' expression] -> logical or /// numeric := range -> true if n in range /// | '%' number '=' range -> true if n % number in range /// range := number /// | '[' number ',' number ']' -> ranges are inclusive both ends /// /// Here are some examples from the GNU gettext manual written in this form: /// English: /// {1:form0|:form1} /// Latvian: /// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0} /// Gaeilge: /// {1:form0|2:form1|:form2} /// Romanian: /// {1:form0|0,%100=[1,19]:form1|:form2} /// Lithuanian: /// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1} /// Russian (requires repeated form): /// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2} /// Slovak /// {1:form0|[2,4]:form1|:form2} /// Polish (requires repeated form): /// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2} static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo, const char *Argument, unsigned ArgumentLen, SmallVectorImpl<char> &OutStr) { const char *ArgumentEnd = Argument + ArgumentLen; while (1) { assert(Argument < ArgumentEnd && "Plural expression didn't match."); const char *ExprEnd = Argument; while (*ExprEnd != ':') { assert(ExprEnd != ArgumentEnd && "Plural missing expression end"); ++ExprEnd; } if (EvalPluralExpr(ValNo, Argument, ExprEnd)) { Argument = ExprEnd + 1; ExprEnd = ScanFormat(Argument, ArgumentEnd, '|'); // Recursively format the result of the plural clause into the // output string. DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr); return; } Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1; } } /// \brief Returns the friendly description for a token kind that will appear /// without quotes in diagnostic messages. These strings may be translatable in /// future. static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) { switch (Kind) { case tok::identifier: return "identifier"; default: return nullptr; } } /// FormatDiagnostic - Format this diagnostic into a string, substituting the /// formal arguments into the %0 slots. The result is appended onto the Str /// array. void Diagnostic:: FormatDiagnostic(SmallVectorImpl<char> &OutStr) const { if (!StoredDiagMessage.empty()) { OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end()); return; } StringRef Diag = getDiags()->getDiagnosticIDs()->getDescription(getID()); FormatDiagnostic(Diag.begin(), Diag.end(), OutStr); } void Diagnostic:: FormatDiagnostic(const char *DiagStr, const char *DiagEnd, SmallVectorImpl<char> &OutStr) const { // When the diagnostic string is only "%0", the entire string is being given // by an outside source. Remove unprintable characters from this string // and skip all the other string processing. if (DiagEnd - DiagStr == 2 && StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") && getArgKind(0) == DiagnosticsEngine::ak_std_string) { const std::string &S = getArgStdStr(0); for (char c : S) { if (llvm::sys::locale::isPrint(c) || c == '\t') { OutStr.push_back(c); } } return; } /// FormattedArgs - Keep track of all of the arguments formatted by /// ConvertArgToString and pass them into subsequent calls to /// ConvertArgToString, allowing the implementation to avoid redundancies in /// obvious cases. SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs; /// QualTypeVals - Pass a vector of arrays so that QualType names can be /// compared to see if more information is needed to be printed. SmallVector<intptr_t, 2> QualTypeVals; SmallVector<char, 64> Tree; for (unsigned i = 0, e = getNumArgs(); i < e; ++i) if (getArgKind(i) == DiagnosticsEngine::ak_qualtype) QualTypeVals.push_back(getRawArg(i)); while (DiagStr != DiagEnd) { if (DiagStr[0] != '%') { // Append non-%0 substrings to Str if we have one. const char *StrEnd = std::find(DiagStr, DiagEnd, '%'); OutStr.append(DiagStr, StrEnd); DiagStr = StrEnd; continue; } else if (isPunctuation(DiagStr[1])) { OutStr.push_back(DiagStr[1]); // %% -> %. DiagStr += 2; continue; } // Skip the %. ++DiagStr; // This must be a placeholder for a diagnostic argument. The format for a // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". // The digit is a number from 0-9 indicating which argument this comes from. // The modifier is a string of digits from the set [-a-z]+, arguments is a // brace enclosed string. const char *Modifier = nullptr, *Argument = nullptr; unsigned ModifierLen = 0, ArgumentLen = 0; // Check to see if we have a modifier. If so eat it. if (!isDigit(DiagStr[0])) { Modifier = DiagStr; while (DiagStr[0] == '-' || (DiagStr[0] >= 'a' && DiagStr[0] <= 'z')) ++DiagStr; ModifierLen = DiagStr-Modifier; // If we have an argument, get it next. if (DiagStr[0] == '{') { ++DiagStr; // Skip {. Argument = DiagStr; DiagStr = ScanFormat(DiagStr, DiagEnd, '}'); assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!"); ArgumentLen = DiagStr-Argument; ++DiagStr; // Skip }. } } assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic"); unsigned ArgNo = *DiagStr++ - '0'; // Only used for type diffing. unsigned ArgNo2 = ArgNo; DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo); if (ModifierIs(Modifier, ModifierLen, "diff")) { assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) && "Invalid format for diff modifier"); ++DiagStr; // Comma. ArgNo2 = *DiagStr++ - '0'; DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2); if (Kind == DiagnosticsEngine::ak_qualtype && Kind2 == DiagnosticsEngine::ak_qualtype) Kind = DiagnosticsEngine::ak_qualtype_pair; else { // %diff only supports QualTypes. For other kinds of arguments, // use the default printing. For example, if the modifier is: // "%diff{compare $ to $|other text}1,2" // treat it as: // "compare %1 to %2" const char *Pipe = ScanFormat(Argument, Argument + ArgumentLen, '|'); const char *FirstDollar = ScanFormat(Argument, Pipe, '$'); const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$'); const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) }; const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) }; FormatDiagnostic(Argument, FirstDollar, OutStr); FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr); FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr); FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr); FormatDiagnostic(SecondDollar + 1, Pipe, OutStr); continue; } } switch (Kind) { // ---- STRINGS ---- case DiagnosticsEngine::ak_std_string: { const std::string &S = getArgStdStr(ArgNo); assert(ModifierLen == 0 && "No modifiers for strings yet"); OutStr.append(S.begin(), S.end()); break; } case DiagnosticsEngine::ak_c_string: { const char *S = getArgCStr(ArgNo); assert(ModifierLen == 0 && "No modifiers for strings yet"); // Don't crash if get passed a null pointer by accident. if (!S) S = "(null)"; OutStr.append(S, S + strlen(S)); break; } // ---- INTEGERS ---- case DiagnosticsEngine::ak_sint: { int Val = getArgSInt(ArgNo); if (ModifierIs(Modifier, ModifierLen, "select")) { HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "s")) { HandleIntegerSModifier(Val, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "plural")) { HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { HandleOrdinalModifier((unsigned)Val, OutStr); } else { assert(ModifierLen == 0 && "Unknown integer modifier"); llvm::raw_svector_ostream(OutStr) << Val; } break; } case DiagnosticsEngine::ak_uint: { unsigned Val = getArgUInt(ArgNo); if (ModifierIs(Modifier, ModifierLen, "select")) { HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "s")) { HandleIntegerSModifier(Val, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "plural")) { HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr); } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { HandleOrdinalModifier(Val, OutStr); } else { assert(ModifierLen == 0 && "Unknown integer modifier"); llvm::raw_svector_ostream(OutStr) << Val; } break; } // ---- TOKEN SPELLINGS ---- case DiagnosticsEngine::ak_tokenkind: { tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo)); assert(ModifierLen == 0 && "No modifiers for token kinds yet"); llvm::raw_svector_ostream Out(OutStr); if (const char *S = tok::getPunctuatorSpelling(Kind)) // Quoted token spelling for punctuators. Out << '\'' << S << '\''; else if (const char *S = tok::getKeywordSpelling(Kind)) // Unquoted token spelling for keywords. Out << S; else if (const char *S = getTokenDescForDiagnostic(Kind)) // Unquoted translatable token name. Out << S; else if (const char *S = tok::getTokenName(Kind)) // Debug name, shouldn't appear in user-facing diagnostics. Out << '<' << S << '>'; else Out << "(null)"; break; } // ---- NAMES and TYPES ---- case DiagnosticsEngine::ak_identifierinfo: { const IdentifierInfo *II = getArgIdentifier(ArgNo); assert(ModifierLen == 0 && "No modifiers for strings yet"); // Don't crash if get passed a null pointer by accident. if (!II) { const char *S = "(null)"; OutStr.append(S, S + strlen(S)); continue; } llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\''; break; } case DiagnosticsEngine::ak_qualtype: case DiagnosticsEngine::ak_declarationname: case DiagnosticsEngine::ak_nameddecl: case DiagnosticsEngine::ak_nestednamespec: case DiagnosticsEngine::ak_declcontext: case DiagnosticsEngine::ak_attr: getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo), StringRef(Modifier, ModifierLen), StringRef(Argument, ArgumentLen), FormattedArgs, OutStr, QualTypeVals); break; case DiagnosticsEngine::ak_qualtype_pair: // Create a struct with all the info needed for printing. TemplateDiffTypes TDT; TDT.FromType = getRawArg(ArgNo); TDT.ToType = getRawArg(ArgNo2); TDT.ElideType = getDiags()->ElideType; TDT.ShowColors = getDiags()->ShowColors; TDT.TemplateDiffUsed = false; intptr_t val = reinterpret_cast<intptr_t>(&TDT); const char *ArgumentEnd = Argument + ArgumentLen; const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|'); // Print the tree. If this diagnostic already has a tree, skip the // second tree. if (getDiags()->PrintTemplateTree && Tree.empty()) { TDT.PrintFromType = true; TDT.PrintTree = true; getDiags()->ConvertArgToString(Kind, val, StringRef(Modifier, ModifierLen), StringRef(Argument, ArgumentLen), FormattedArgs, Tree, QualTypeVals); // If there is no tree information, fall back to regular printing. if (!Tree.empty()) { FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr); break; } } // Non-tree printing, also the fall-back when tree printing fails. // The fall-back is triggered when the types compared are not templates. const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$'); const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$'); // Append before text FormatDiagnostic(Argument, FirstDollar, OutStr); // Append first type TDT.PrintTree = false; TDT.PrintFromType = true; getDiags()->ConvertArgToString(Kind, val, StringRef(Modifier, ModifierLen), StringRef(Argument, ArgumentLen), FormattedArgs, OutStr, QualTypeVals); if (!TDT.TemplateDiffUsed) FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype, TDT.FromType)); // Append middle text FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr); // Append second type TDT.PrintFromType = false; getDiags()->ConvertArgToString(Kind, val, StringRef(Modifier, ModifierLen), StringRef(Argument, ArgumentLen), FormattedArgs, OutStr, QualTypeVals); if (!TDT.TemplateDiffUsed) FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype, TDT.ToType)); // Append end text FormatDiagnostic(SecondDollar + 1, Pipe, OutStr); break; } // Remember this argument info for subsequent formatting operations. Turn // std::strings into a null terminated string to make it be the same case as // all the other ones. if (Kind == DiagnosticsEngine::ak_qualtype_pair) continue; else if (Kind != DiagnosticsEngine::ak_std_string) FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo))); else FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string, (intptr_t)getArgStdStr(ArgNo).c_str())); } // Append the type tree to the end of the diagnostics. OutStr.append(Tree.begin(), Tree.end()); } StoredDiagnostic::StoredDiagnostic() { } StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, StringRef Message) : ID(ID), Level(Level), Loc(), Message(Message) { } StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info) : ID(Info.getID()), Level(Level) { assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) && "Valid source location without setting a source manager for diagnostic"); if (Info.getLocation().isValid()) Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager()); SmallString<64> Message; Info.FormatDiagnostic(Message); this->Message.assign(Message.begin(), Message.end()); this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end()); this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end()); } StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, StringRef Message, FullSourceLoc Loc, ArrayRef<CharSourceRange> Ranges, ArrayRef<FixItHint> FixIts) : ID(ID), Level(Level), Loc(Loc), Message(Message), Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end()) { } StoredDiagnostic::~StoredDiagnostic() { } /// IncludeInDiagnosticCounts - This method (whose default implementation /// returns true) indicates whether the diagnostics handled by this /// DiagnosticConsumer should be included in the number of diagnostics /// reported by DiagnosticsEngine. bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; } void IgnoringDiagConsumer::anchor() { } ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {} void ForwardingDiagnosticConsumer::HandleDiagnostic( DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) { Target.HandleDiagnostic(DiagLevel, Info); } void ForwardingDiagnosticConsumer::clear() { DiagnosticConsumer::clear(); Target.clear(); } bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const { return Target.IncludeInDiagnosticCounts(); } PartialDiagnostic::StorageAllocator::StorageAllocator() { for (unsigned I = 0; I != NumCached; ++I) FreeList[I] = Cached + I; NumFreeListEntries = NumCached; } PartialDiagnostic::StorageAllocator::~StorageAllocator() { // Don't assert if we are in a CrashRecovery context, as this invariant may // be invalidated during a crash. assert((NumFreeListEntries == NumCached || llvm::CrashRecoveryContext::isRecoveringFromCrash()) && "A partial is on the lamb"); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/Attributes.cpp
#include "clang/Basic/Attributes.h" #include "clang/Basic/IdentifierTable.h" #include "llvm/ADT/StringSwitch.h" using namespace clang; int clang::hasAttribute(AttrSyntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const llvm::Triple &T, const LangOptions &LangOpts) { StringRef Name = Attr->getName(); // Normalize the attribute name, __foo__ becomes foo. if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__")) Name = Name.substr(2, Name.size() - 4); #include "clang/Basic/AttrHasAttributeImpl.inc" return 0; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/CharInfo.cpp
//===--- CharInfo.cpp - Static Data for Classifying ASCII Characters ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Basic/CharInfo.h" using namespace clang::charinfo; // Statically initialize CharInfo table based on ASCII character set // Reference: FreeBSD 7.2 /usr/share/misc/ascii const uint16_t clang::charinfo::InfoTable[256] = { // 0 NUL 1 SOH 2 STX 3 ETX // 4 EOT 5 ENQ 6 ACK 7 BEL 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , // 8 BS 9 HT 10 NL 11 VT //12 NP 13 CR 14 SO 15 SI 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS, CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 , //16 DLE 17 DC1 18 DC2 19 DC3 //20 DC4 21 NAK 22 SYN 23 ETB 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , //24 CAN 25 EM 26 SUB 27 ESC //28 FS 29 GS 30 RS 31 US 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , //32 SP 33 ! 34 " 35 # //36 $ 37 % 38 & 39 ' CHAR_SPACE , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PUNCT , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , //40 ( 41 ) 42 * 43 + //44 , 45 - 46 . 47 / CHAR_PUNCT , CHAR_PUNCT , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL , //48 0 49 1 50 2 51 3 //52 4 53 5 54 6 55 7 CHAR_DIGIT , CHAR_DIGIT , CHAR_DIGIT , CHAR_DIGIT , CHAR_DIGIT , CHAR_DIGIT , CHAR_DIGIT , CHAR_DIGIT , //56 8 57 9 58 : 59 ; //60 < 61 = 62 > 63 ? CHAR_DIGIT , CHAR_DIGIT , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , //64 @ 65 A 66 B 67 C //68 D 69 E 70 F 71 G CHAR_PUNCT , CHAR_XUPPER , CHAR_XUPPER , CHAR_XUPPER , CHAR_XUPPER , CHAR_XUPPER , CHAR_XUPPER , CHAR_UPPER , //72 H 73 I 74 J 75 K //76 L 77 M 78 N 79 O CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , //80 P 81 Q 82 R 83 S //84 T 85 U 86 V 87 W CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , //88 X 89 Y 90 Z 91 [ //92 \ 93 ] 94 ^ 95 _ CHAR_UPPER , CHAR_UPPER , CHAR_UPPER , CHAR_RAWDEL , CHAR_PUNCT , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER , //96 ` 97 a 98 b 99 c //100 d 101 e 102 f 103 g CHAR_PUNCT , CHAR_XLOWER , CHAR_XLOWER , CHAR_XLOWER , CHAR_XLOWER , CHAR_XLOWER , CHAR_XLOWER , CHAR_LOWER , //104 h 105 i 106 j 107 k //108 l 109 m 110 n 111 o CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , //112 p 113 q 114 r 115 s //116 t 117 u 118 v 119 w CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , //120 x 121 y 122 z 123 { //124 | 125 } 126 ~ 127 DEL CHAR_LOWER , CHAR_LOWER , CHAR_LOWER , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0 };
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/OpenMPKinds.cpp
//===--- OpenMPKinds.cpp - Token Kinds Support ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// \brief This file implements the OpenMP enum and support functions. /// //===----------------------------------------------------------------------===// #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/IdentifierTable.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> using namespace clang; OpenMPDirectiveKind clang::getOpenMPDirectiveKind(StringRef Str) { return llvm::StringSwitch<OpenMPDirectiveKind>(Str) #define OPENMP_DIRECTIVE(Name) .Case(#Name, OMPD_##Name) #define OPENMP_DIRECTIVE_EXT(Name, Str) .Case(Str, OMPD_##Name) #include "clang/Basic/OpenMPKinds.def" .Default(OMPD_unknown); } const char *clang::getOpenMPDirectiveName(OpenMPDirectiveKind Kind) { assert(Kind <= OMPD_unknown); switch (Kind) { case OMPD_unknown: return "unknown"; #define OPENMP_DIRECTIVE(Name) \ case OMPD_##Name: \ return #Name; #define OPENMP_DIRECTIVE_EXT(Name, Str) \ case OMPD_##Name: \ return Str; #include "clang/Basic/OpenMPKinds.def" break; } llvm_unreachable("Invalid OpenMP directive kind"); } OpenMPClauseKind clang::getOpenMPClauseKind(StringRef Str) { // 'flush' clause cannot be specified explicitly, because this is an implicit // clause for 'flush' directive. If the 'flush' clause is explicitly specified // the Parser should generate a warning about extra tokens at the end of the // directive. if (Str == "flush") return OMPC_unknown; return llvm::StringSwitch<OpenMPClauseKind>(Str) #define OPENMP_CLAUSE(Name, Class) .Case(#Name, OMPC_##Name) #include "clang/Basic/OpenMPKinds.def" .Default(OMPC_unknown); } const char *clang::getOpenMPClauseName(OpenMPClauseKind Kind) { assert(Kind <= OMPC_unknown); switch (Kind) { case OMPC_unknown: return "unknown"; #define OPENMP_CLAUSE(Name, Class) \ case OMPC_##Name: \ return #Name; #include "clang/Basic/OpenMPKinds.def" case OMPC_threadprivate: return "threadprivate or thread local"; } llvm_unreachable("Invalid OpenMP clause kind"); } unsigned clang::getOpenMPSimpleClauseType(OpenMPClauseKind Kind, StringRef Str) { switch (Kind) { case OMPC_default: return llvm::StringSwitch<OpenMPDefaultClauseKind>(Str) #define OPENMP_DEFAULT_KIND(Name) .Case(#Name, OMPC_DEFAULT_##Name) #include "clang/Basic/OpenMPKinds.def" .Default(OMPC_DEFAULT_unknown); case OMPC_proc_bind: return llvm::StringSwitch<OpenMPProcBindClauseKind>(Str) #define OPENMP_PROC_BIND_KIND(Name) .Case(#Name, OMPC_PROC_BIND_##Name) #include "clang/Basic/OpenMPKinds.def" .Default(OMPC_PROC_BIND_unknown); case OMPC_schedule: return llvm::StringSwitch<OpenMPScheduleClauseKind>(Str) #define OPENMP_SCHEDULE_KIND(Name) .Case(#Name, OMPC_SCHEDULE_##Name) #include "clang/Basic/OpenMPKinds.def" .Default(OMPC_SCHEDULE_unknown); case OMPC_depend: return llvm::StringSwitch<OpenMPDependClauseKind>(Str) #define OPENMP_DEPEND_KIND(Name) .Case(#Name, OMPC_DEPEND_##Name) #include "clang/Basic/OpenMPKinds.def" .Default(OMPC_DEPEND_unknown); case OMPC_unknown: case OMPC_threadprivate: case OMPC_if: case OMPC_final: case OMPC_num_threads: case OMPC_safelen: case OMPC_collapse: case OMPC_private: case OMPC_firstprivate: case OMPC_lastprivate: case OMPC_shared: case OMPC_reduction: case OMPC_linear: case OMPC_aligned: case OMPC_copyin: case OMPC_copyprivate: case OMPC_ordered: case OMPC_nowait: case OMPC_untied: case OMPC_mergeable: case OMPC_flush: case OMPC_read: case OMPC_write: case OMPC_update: case OMPC_capture: case OMPC_seq_cst: break; } llvm_unreachable("Invalid OpenMP simple clause kind"); } const char *clang::getOpenMPSimpleClauseTypeName(OpenMPClauseKind Kind, unsigned Type) { switch (Kind) { case OMPC_default: switch (Type) { case OMPC_DEFAULT_unknown: return "unknown"; #define OPENMP_DEFAULT_KIND(Name) \ case OMPC_DEFAULT_##Name: \ return #Name; #include "clang/Basic/OpenMPKinds.def" } llvm_unreachable("Invalid OpenMP 'default' clause type"); case OMPC_proc_bind: switch (Type) { case OMPC_PROC_BIND_unknown: return "unknown"; #define OPENMP_PROC_BIND_KIND(Name) \ case OMPC_PROC_BIND_##Name: \ return #Name; #include "clang/Basic/OpenMPKinds.def" } llvm_unreachable("Invalid OpenMP 'proc_bind' clause type"); case OMPC_schedule: switch (Type) { case OMPC_SCHEDULE_unknown: return "unknown"; #define OPENMP_SCHEDULE_KIND(Name) \ case OMPC_SCHEDULE_##Name: \ return #Name; #include "clang/Basic/OpenMPKinds.def" } llvm_unreachable("Invalid OpenMP 'schedule' clause type"); case OMPC_depend: switch (Type) { case OMPC_DEPEND_unknown: return "unknown"; #define OPENMP_DEPEND_KIND(Name) \ case OMPC_DEPEND_##Name: \ return #Name; #include "clang/Basic/OpenMPKinds.def" } llvm_unreachable("Invalid OpenMP 'schedule' clause type"); case OMPC_unknown: case OMPC_threadprivate: case OMPC_if: case OMPC_final: case OMPC_num_threads: case OMPC_safelen: case OMPC_collapse: case OMPC_private: case OMPC_firstprivate: case OMPC_lastprivate: case OMPC_shared: case OMPC_reduction: case OMPC_linear: case OMPC_aligned: case OMPC_copyin: case OMPC_copyprivate: case OMPC_ordered: case OMPC_nowait: case OMPC_untied: case OMPC_mergeable: case OMPC_flush: case OMPC_read: case OMPC_write: case OMPC_update: case OMPC_capture: case OMPC_seq_cst: break; } llvm_unreachable("Invalid OpenMP simple clause kind"); } bool clang::isAllowedClauseForDirective(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind) { assert(DKind <= OMPD_unknown); assert(CKind <= OMPC_unknown); switch (DKind) { case OMPD_parallel: switch (CKind) { #define OPENMP_PARALLEL_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_simd: switch (CKind) { #define OPENMP_SIMD_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_for: switch (CKind) { #define OPENMP_FOR_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_for_simd: switch (CKind) { #define OPENMP_FOR_SIMD_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_sections: switch (CKind) { #define OPENMP_SECTIONS_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_single: switch (CKind) { #define OPENMP_SINGLE_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_parallel_for: switch (CKind) { #define OPENMP_PARALLEL_FOR_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_parallel_for_simd: switch (CKind) { #define OPENMP_PARALLEL_FOR_SIMD_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_parallel_sections: switch (CKind) { #define OPENMP_PARALLEL_SECTIONS_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_task: switch (CKind) { #define OPENMP_TASK_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_flush: return CKind == OMPC_flush; break; case OMPD_atomic: switch (CKind) { #define OPENMP_ATOMIC_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_target: switch (CKind) { #define OPENMP_TARGET_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_teams: switch (CKind) { #define OPENMP_TEAMS_CLAUSE(Name) \ case OMPC_##Name: \ return true; #include "clang/Basic/OpenMPKinds.def" default: break; } break; case OMPD_unknown: case OMPD_threadprivate: case OMPD_section: case OMPD_master: case OMPD_critical: case OMPD_taskyield: case OMPD_barrier: case OMPD_taskwait: case OMPD_taskgroup: case OMPD_cancellation_point: case OMPD_cancel: case OMPD_ordered: break; } return false; } bool clang::isOpenMPLoopDirective(OpenMPDirectiveKind DKind) { return DKind == OMPD_simd || DKind == OMPD_for || DKind == OMPD_for_simd || DKind == OMPD_parallel_for || DKind == OMPD_parallel_for_simd; // TODO add next directives. } bool clang::isOpenMPWorksharingDirective(OpenMPDirectiveKind DKind) { return DKind == OMPD_for || DKind == OMPD_for_simd || DKind == OMPD_sections || DKind == OMPD_section || DKind == OMPD_single || DKind == OMPD_parallel_for || DKind == OMPD_parallel_for_simd || DKind == OMPD_parallel_sections; // TODO add next directives. } bool clang::isOpenMPParallelDirective(OpenMPDirectiveKind DKind) { return DKind == OMPD_parallel || DKind == OMPD_parallel_for || DKind == OMPD_parallel_for_simd || DKind == OMPD_parallel_sections; // TODO add next directives. } bool clang::isOpenMPTeamsDirective(OpenMPDirectiveKind DKind) { return DKind == OMPD_teams; // TODO add next directives. } bool clang::isOpenMPSimdDirective(OpenMPDirectiveKind DKind) { return DKind == OMPD_simd || DKind == OMPD_for_simd || DKind == OMPD_parallel_for_simd; // TODO add next directives. } bool clang::isOpenMPPrivate(OpenMPClauseKind Kind) { return Kind == OMPC_private || Kind == OMPC_firstprivate || Kind == OMPC_lastprivate || Kind == OMPC_linear || Kind == OMPC_reduction; // TODO add next clauses like 'reduction'. } bool clang::isOpenMPThreadPrivate(OpenMPClauseKind Kind) { return Kind == OMPC_threadprivate || Kind == OMPC_copyin; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Basic/SanitizerBlacklist.cpp
//===--- SanitizerBlacklist.cpp - Blacklist for sanitizers ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // User-provided blacklist used to disable/alter instrumentation done in // sanitizers. // //===----------------------------------------------------------------------===// #include "clang/Basic/SanitizerBlacklist.h" // // /////////////////////////////////////////////////////////////////////////////// using namespace clang; SanitizerBlacklist::SanitizerBlacklist( const std::vector<std::string> &BlacklistPaths, SourceManager &SM) : SCL(llvm::SpecialCaseList::createOrDie(BlacklistPaths)), SM(SM) {} bool SanitizerBlacklist::isBlacklistedGlobal(StringRef GlobalName, StringRef Category) const { return SCL->inSection("global", GlobalName, Category); } bool SanitizerBlacklist::isBlacklistedType(StringRef MangledTypeName, StringRef Category) const { return SCL->inSection("type", MangledTypeName, Category); } bool SanitizerBlacklist::isBlacklistedFunction(StringRef FunctionName) const { return SCL->inSection("fun", FunctionName); } bool SanitizerBlacklist::isBlacklistedFile(StringRef FileName, StringRef Category) const { return SCL->inSection("src", FileName, Category); } bool SanitizerBlacklist::isBlacklistedLocation(SourceLocation Loc, StringRef Category) const { return !Loc.isInvalid() && isBlacklistedFile(SM.getFilename(SM.getFileLoc(Loc)), Category); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/RAIIObjectsForParser.h
//===--- RAIIObjectsForParser.h - RAII helpers for the parser ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines and implements the some simple RAII objects that are used // by the parser to manage bits in recursion. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LIB_PARSE_RAIIOBJECTSFORPARSER_H #define LLVM_CLANG_LIB_PARSE_RAIIOBJECTSFORPARSER_H #include "clang/Parse/ParseDiagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Sema/DelayedDiagnostic.h" #include "clang/Sema/Sema.h" namespace clang { // TODO: move ParsingClassDefinition here. // TODO: move TentativeParsingAction here. /// \brief A RAII object used to temporarily suppress access-like /// checking. Access-like checks are those associated with /// controlling the use of a declaration, like C++ access control /// errors and deprecation warnings. They are contextually /// dependent, in that they can only be resolved with full /// information about what's being declared. They are also /// suppressed in certain contexts, like the template arguments of /// an explicit instantiation. However, those suppression contexts /// cannot necessarily be fully determined in advance; for /// example, something starting like this: /// template <> class std::vector<A::PrivateType> /// might be the entirety of an explicit instantiation: /// template <> class std::vector<A::PrivateType>; /// or just an elaborated type specifier: /// template <> class std::vector<A::PrivateType> make_vector<>(); /// Therefore this class collects all the diagnostics and permits /// them to be re-delayed in a new context. class SuppressAccessChecks { Sema &S; sema::DelayedDiagnosticPool DiagnosticPool; Sema::ParsingDeclState State; bool Active; public: /// Begin suppressing access-like checks SuppressAccessChecks(Parser &P, bool activate = true) : S(P.getActions()), DiagnosticPool(nullptr) { if (activate) { State = S.PushParsingDeclaration(DiagnosticPool); Active = true; } else { Active = false; } } SuppressAccessChecks(SuppressAccessChecks &&Other) : S(Other.S), DiagnosticPool(std::move(Other.DiagnosticPool)), State(Other.State), Active(Other.Active) { Other.Active = false; } void operator=(SuppressAccessChecks &&Other) = delete; void done() { assert(Active && "trying to end an inactive suppression"); S.PopParsingDeclaration(State, nullptr); Active = false; } void redelay() { assert(!Active && "redelaying without having ended first"); if (!DiagnosticPool.pool_empty()) S.redelayDiagnostics(DiagnosticPool); assert(DiagnosticPool.pool_empty()); } ~SuppressAccessChecks() { if (Active) done(); } }; /// \brief RAII object used to inform the actions that we're /// currently parsing a declaration. This is active when parsing a /// variable's initializer, but not when parsing the body of a /// class or function definition. class ParsingDeclRAIIObject { Sema &Actions; sema::DelayedDiagnosticPool DiagnosticPool; Sema::ParsingDeclState State; bool Popped; ParsingDeclRAIIObject(const ParsingDeclRAIIObject &) = delete; void operator=(const ParsingDeclRAIIObject &) = delete; public: enum NoParent_t { NoParent }; ParsingDeclRAIIObject(Parser &P, NoParent_t _) : Actions(P.getActions()), DiagnosticPool(nullptr) { push(); } /// Creates a RAII object whose pool is optionally parented by another. ParsingDeclRAIIObject(Parser &P, const sema::DelayedDiagnosticPool *parentPool) : Actions(P.getActions()), DiagnosticPool(parentPool) { push(); } /// Creates a RAII object and, optionally, initialize its /// diagnostics pool by stealing the diagnostics from another /// RAII object (which is assumed to be the current top pool). ParsingDeclRAIIObject(Parser &P, ParsingDeclRAIIObject *other) : Actions(P.getActions()), DiagnosticPool(other ? other->DiagnosticPool.getParent() : nullptr) { if (other) { DiagnosticPool.steal(other->DiagnosticPool); other->abort(); } push(); } ~ParsingDeclRAIIObject() { abort(); } sema::DelayedDiagnosticPool &getDelayedDiagnosticPool() { return DiagnosticPool; } const sema::DelayedDiagnosticPool &getDelayedDiagnosticPool() const { return DiagnosticPool; } /// Resets the RAII object for a new declaration. void reset() { abort(); push(); } /// Signals that the context was completed without an appropriate /// declaration being parsed. void abort() { pop(nullptr); } void complete(Decl *D) { assert(!Popped && "ParsingDeclaration has already been popped!"); pop(D); } /// Unregister this object from Sema, but remember all the /// diagnostics that were emitted into it. void abortAndRemember() { pop(nullptr); } private: void push() { State = Actions.PushParsingDeclaration(DiagnosticPool); Popped = false; } void pop(Decl *D) { if (!Popped) { Actions.PopParsingDeclaration(State, D); Popped = true; } } }; /// A class for parsing a DeclSpec. class ParsingDeclSpec : public DeclSpec { ParsingDeclRAIIObject ParsingRAII; public: ParsingDeclSpec(Parser &P) : DeclSpec(P.getAttrFactory()), ParsingRAII(P, ParsingDeclRAIIObject::NoParent) {} ParsingDeclSpec(Parser &P, ParsingDeclRAIIObject *RAII) : DeclSpec(P.getAttrFactory()), ParsingRAII(P, RAII) {} const sema::DelayedDiagnosticPool &getDelayedDiagnosticPool() const { return ParsingRAII.getDelayedDiagnosticPool(); } void complete(Decl *D) { ParsingRAII.complete(D); } void abort() { ParsingRAII.abort(); } }; /// A class for parsing a declarator. class ParsingDeclarator : public Declarator { ParsingDeclRAIIObject ParsingRAII; public: ParsingDeclarator(Parser &P, const ParsingDeclSpec &DS, TheContext C) : Declarator(DS, C), ParsingRAII(P, &DS.getDelayedDiagnosticPool()) { } const ParsingDeclSpec &getDeclSpec() const { return static_cast<const ParsingDeclSpec&>(Declarator::getDeclSpec()); } ParsingDeclSpec &getMutableDeclSpec() const { return const_cast<ParsingDeclSpec&>(getDeclSpec()); } void clear() { Declarator::clear(); ParsingRAII.reset(); } void complete(Decl *D) { ParsingRAII.complete(D); } }; /// A class for parsing a field declarator. class ParsingFieldDeclarator : public FieldDeclarator { ParsingDeclRAIIObject ParsingRAII; public: ParsingFieldDeclarator(Parser &P, const ParsingDeclSpec &DS) : FieldDeclarator(DS), ParsingRAII(P, &DS.getDelayedDiagnosticPool()) { } const ParsingDeclSpec &getDeclSpec() const { return static_cast<const ParsingDeclSpec&>(D.getDeclSpec()); } ParsingDeclSpec &getMutableDeclSpec() const { return const_cast<ParsingDeclSpec&>(getDeclSpec()); } void complete(Decl *D) { ParsingRAII.complete(D); } }; /// ExtensionRAIIObject - This saves the state of extension warnings when /// constructed and disables them. When destructed, it restores them back to /// the way they used to be. This is used to handle __extension__ in the /// parser. class ExtensionRAIIObject { ExtensionRAIIObject(const ExtensionRAIIObject &) = delete; void operator=(const ExtensionRAIIObject &) = delete; DiagnosticsEngine &Diags; public: ExtensionRAIIObject(DiagnosticsEngine &diags) : Diags(diags) { Diags.IncrementAllExtensionsSilenced(); } ~ExtensionRAIIObject() { Diags.DecrementAllExtensionsSilenced(); } }; /// ColonProtectionRAIIObject - This sets the Parser::ColonIsSacred bool and /// restores it when destroyed. This says that "foo:" should not be /// considered a possible typo for "foo::" for error recovery purposes. class ColonProtectionRAIIObject { Parser &P; bool OldVal; public: ColonProtectionRAIIObject(Parser &p, bool Value = true) : P(p), OldVal(P.ColonIsSacred) { P.ColonIsSacred = Value; } /// restore - This can be used to restore the state early, before the dtor /// is run. void restore() { P.ColonIsSacred = OldVal; } ~ColonProtectionRAIIObject() { restore(); } }; /// \brief RAII object that makes '>' behave either as an operator /// or as the closing angle bracket for a template argument list. class GreaterThanIsOperatorScope { bool &GreaterThanIsOperator; bool OldGreaterThanIsOperator; public: GreaterThanIsOperatorScope(bool &GTIO, bool Val) : GreaterThanIsOperator(GTIO), OldGreaterThanIsOperator(GTIO) { GreaterThanIsOperator = Val; } ~GreaterThanIsOperatorScope() { GreaterThanIsOperator = OldGreaterThanIsOperator; } }; class InMessageExpressionRAIIObject { bool &InMessageExpression; bool OldValue; public: InMessageExpressionRAIIObject(Parser &P, bool Value) : InMessageExpression(P.InMessageExpression), OldValue(P.InMessageExpression) { InMessageExpression = Value; } ~InMessageExpressionRAIIObject() { InMessageExpression = OldValue; } }; /// \brief RAII object that makes sure paren/bracket/brace count is correct /// after declaration/statement parsing, even when there's a parsing error. class ParenBraceBracketBalancer { Parser &P; unsigned short ParenCount, BracketCount, BraceCount; public: ParenBraceBracketBalancer(Parser &p) : P(p), ParenCount(p.ParenCount), BracketCount(p.BracketCount), BraceCount(p.BraceCount) { } ~ParenBraceBracketBalancer() { P.ParenCount = ParenCount; P.BracketCount = BracketCount; P.BraceCount = BraceCount; } }; class PoisonSEHIdentifiersRAIIObject { PoisonIdentifierRAIIObject Ident_AbnormalTermination; PoisonIdentifierRAIIObject Ident_GetExceptionCode; PoisonIdentifierRAIIObject Ident_GetExceptionInfo; PoisonIdentifierRAIIObject Ident__abnormal_termination; PoisonIdentifierRAIIObject Ident__exception_code; PoisonIdentifierRAIIObject Ident__exception_info; PoisonIdentifierRAIIObject Ident___abnormal_termination; PoisonIdentifierRAIIObject Ident___exception_code; PoisonIdentifierRAIIObject Ident___exception_info; public: PoisonSEHIdentifiersRAIIObject(Parser &Self, bool NewValue) : Ident_AbnormalTermination(Self.Ident_AbnormalTermination, NewValue), Ident_GetExceptionCode(Self.Ident_GetExceptionCode, NewValue), Ident_GetExceptionInfo(Self.Ident_GetExceptionInfo, NewValue), Ident__abnormal_termination(Self.Ident__abnormal_termination, NewValue), Ident__exception_code(Self.Ident__exception_code, NewValue), Ident__exception_info(Self.Ident__exception_info, NewValue), Ident___abnormal_termination(Self.Ident___abnormal_termination, NewValue), Ident___exception_code(Self.Ident___exception_code, NewValue), Ident___exception_info(Self.Ident___exception_info, NewValue) { } }; /// \brief RAII class that helps handle the parsing of an open/close delimiter /// pair, such as braces { ... } or parentheses ( ... ). class BalancedDelimiterTracker : public GreaterThanIsOperatorScope { Parser& P; tok::TokenKind Kind, Close, FinalToken; SourceLocation (Parser::*Consumer)(); SourceLocation LOpen, LClose; unsigned short &getDepth() { switch (Kind) { case tok::l_brace: return P.BraceCount; case tok::l_square: return P.BracketCount; case tok::l_paren: return P.ParenCount; default: llvm_unreachable("Wrong token kind"); } } enum { MaxDepth = 256 }; bool diagnoseOverflow(); bool diagnoseMissingClose(); public: BalancedDelimiterTracker(Parser& p, tok::TokenKind k, tok::TokenKind FinalToken = tok::semi) : GreaterThanIsOperatorScope(p.GreaterThanIsOperator, true), P(p), Kind(k), FinalToken(FinalToken) { switch (Kind) { default: llvm_unreachable("Unexpected balanced token"); case tok::l_brace: Close = tok::r_brace; Consumer = &Parser::ConsumeBrace; break; case tok::l_paren: Close = tok::r_paren; Consumer = &Parser::ConsumeParen; break; case tok::l_square: Close = tok::r_square; Consumer = &Parser::ConsumeBracket; break; } } SourceLocation getOpenLocation() const { return LOpen; } SourceLocation getCloseLocation() const { return LClose; } SourceRange getRange() const { return SourceRange(LOpen, LClose); } bool consumeOpen() { if (!P.Tok.is(Kind)) return true; if (getDepth() < P.getLangOpts().BracketDepth) { LOpen = (P.*Consumer)(); return false; } return diagnoseOverflow(); } bool expectAndConsume(unsigned DiagID = diag::err_expected, const char *Msg = "", tok::TokenKind SkipToTok = tok::unknown); bool consumeClose() { if (P.Tok.is(Close)) { LClose = (P.*Consumer)(); return false; } else if (P.Tok.is(tok::semi) && P.NextToken().is(Close)) { SourceLocation SemiLoc = P.ConsumeToken(); P.Diag(SemiLoc, diag::err_unexpected_semi) << Close << FixItHint::CreateRemoval(SourceRange(SemiLoc, SemiLoc)); LClose = (P.*Consumer)(); return false; } return diagnoseMissingClose(); } void skipToEnd(); }; } // end namespace clang #endif
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseObjc.cpp
//===--- ParseObjC.cpp - Objective C Parsing ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Objective-C portions of the Parser interface. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "RAIIObjectsForParser.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/CharInfo.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/PrettyDeclStackTrace.h" #include "clang/Sema/Scope.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" using namespace clang; /// Skips attributes after an Objective-C @ directive. Emits a diagnostic. void Parser::MaybeSkipAttributes(tok::ObjCKeywordKind Kind) { ParsedAttributes attrs(AttrFactory); if (Tok.is(tok::kw___attribute)) { if (Kind == tok::objc_interface || Kind == tok::objc_protocol) Diag(Tok, diag::err_objc_postfix_attribute_hint) << (Kind == tok::objc_protocol); else Diag(Tok, diag::err_objc_postfix_attribute); ParseGNUAttributes(attrs); } } /// ParseObjCAtDirectives - Handle parts of the external-declaration production: /// external-declaration: [C99 6.9] /// [OBJC] objc-class-definition /// [OBJC] objc-class-declaration /// [OBJC] objc-alias-declaration /// [OBJC] objc-protocol-definition /// [OBJC] objc-method-definition /// [OBJC] '@' 'end' Parser::DeclGroupPtrTy Parser::ParseObjCAtDirectives() { SourceLocation AtLoc = ConsumeToken(); // the "@" if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCAtDirective(getCurScope()); cutOffParsing(); return DeclGroupPtrTy(); } Decl *SingleDecl = nullptr; switch (Tok.getObjCKeywordID()) { case tok::objc_class: return ParseObjCAtClassDeclaration(AtLoc); case tok::objc_interface: { ParsedAttributes attrs(AttrFactory); SingleDecl = ParseObjCAtInterfaceDeclaration(AtLoc, attrs); break; } case tok::objc_protocol: { ParsedAttributes attrs(AttrFactory); return ParseObjCAtProtocolDeclaration(AtLoc, attrs); } case tok::objc_implementation: return ParseObjCAtImplementationDeclaration(AtLoc); case tok::objc_end: return ParseObjCAtEndDeclaration(AtLoc); case tok::objc_compatibility_alias: SingleDecl = ParseObjCAtAliasDeclaration(AtLoc); break; case tok::objc_synthesize: SingleDecl = ParseObjCPropertySynthesize(AtLoc); break; case tok::objc_dynamic: SingleDecl = ParseObjCPropertyDynamic(AtLoc); break; case tok::objc_import: if (getLangOpts().Modules || getLangOpts().DebuggerSupport) return ParseModuleImport(AtLoc); Diag(AtLoc, diag::err_atimport); SkipUntil(tok::semi); return Actions.ConvertDeclToDeclGroup(nullptr); default: Diag(AtLoc, diag::err_unexpected_at); SkipUntil(tok::semi); SingleDecl = nullptr; break; } return Actions.ConvertDeclToDeclGroup(SingleDecl); } /// /// objc-class-declaration: /// '@' 'class' objc-class-forward-decl (',' objc-class-forward-decl)* ';' /// /// objc-class-forward-decl: /// identifier objc-type-parameter-list[opt] /// Parser::DeclGroupPtrTy Parser::ParseObjCAtClassDeclaration(SourceLocation atLoc) { ConsumeToken(); // the identifier "class" SmallVector<IdentifierInfo *, 8> ClassNames; SmallVector<SourceLocation, 8> ClassLocs; SmallVector<ObjCTypeParamList *, 8> ClassTypeParams; while (1) { MaybeSkipAttributes(tok::objc_class); if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; SkipUntil(tok::semi); return Actions.ConvertDeclToDeclGroup(nullptr); } ClassNames.push_back(Tok.getIdentifierInfo()); ClassLocs.push_back(Tok.getLocation()); ConsumeToken(); // Parse the optional objc-type-parameter-list. ObjCTypeParamList *TypeParams = nullptr; if (Tok.is(tok::less)) { TypeParams = parseObjCTypeParamList(); if (TypeParams) Actions.popObjCTypeParamList(getCurScope(), TypeParams); } ClassTypeParams.push_back(TypeParams); if (!TryConsumeToken(tok::comma)) break; } // Consume the ';'. if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@class")) return Actions.ConvertDeclToDeclGroup(nullptr); return Actions.ActOnForwardClassDeclaration(atLoc, ClassNames.data(), ClassLocs.data(), ClassTypeParams, ClassNames.size()); } void Parser::CheckNestedObjCContexts(SourceLocation AtLoc) { Sema::ObjCContainerKind ock = Actions.getObjCContainerKind(); if (ock == Sema::OCK_None) return; Decl *Decl = Actions.getObjCDeclContext(); if (CurParsedObjCImpl) { CurParsedObjCImpl->finish(AtLoc); } else { Actions.ActOnAtEnd(getCurScope(), AtLoc); } Diag(AtLoc, diag::err_objc_missing_end) << FixItHint::CreateInsertion(AtLoc, "@end\n"); if (Decl) Diag(Decl->getLocStart(), diag::note_objc_container_start) << (int) ock; } /// /// objc-interface: /// objc-class-interface-attributes[opt] objc-class-interface /// objc-category-interface /// /// objc-class-interface: /// '@' 'interface' identifier objc-type-parameter-list[opt] /// objc-superclass[opt] objc-protocol-refs[opt] /// objc-class-instance-variables[opt] /// objc-interface-decl-list /// @end /// /// objc-category-interface: /// '@' 'interface' identifier objc-type-parameter-list[opt] /// '(' identifier[opt] ')' objc-protocol-refs[opt] /// objc-interface-decl-list /// @end /// /// objc-superclass: /// ':' identifier objc-type-arguments[opt] /// /// objc-class-interface-attributes: /// __attribute__((visibility("default"))) /// __attribute__((visibility("hidden"))) /// __attribute__((deprecated)) /// __attribute__((unavailable)) /// __attribute__((objc_exception)) - used by NSException on 64-bit /// __attribute__((objc_root_class)) /// Decl *Parser::ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &attrs) { assert(Tok.isObjCAtKeyword(tok::objc_interface) && "ParseObjCAtInterfaceDeclaration(): Expected @interface"); CheckNestedObjCContexts(AtLoc); ConsumeToken(); // the "interface" identifier // Code completion after '@interface'. if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCInterfaceDecl(getCurScope()); cutOffParsing(); return nullptr; } MaybeSkipAttributes(tok::objc_interface); if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; // missing class or category name. return nullptr; } // We have a class or category name - consume it. IdentifierInfo *nameId = Tok.getIdentifierInfo(); SourceLocation nameLoc = ConsumeToken(); // Parse the objc-type-parameter-list or objc-protocol-refs. For the latter // case, LAngleLoc will be valid and ProtocolIdents will capture the // protocol references (that have not yet been resolved). SourceLocation LAngleLoc, EndProtoLoc; SmallVector<IdentifierLocPair, 8> ProtocolIdents; ObjCTypeParamList *typeParameterList = nullptr; if (Tok.is(tok::less)) { typeParameterList = parseObjCTypeParamListOrProtocolRefs(LAngleLoc, ProtocolIdents, EndProtoLoc); } if (Tok.is(tok::l_paren) && !isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { // we have a category. BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); SourceLocation categoryLoc; IdentifierInfo *categoryId = nullptr; if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCInterfaceCategory(getCurScope(), nameId, nameLoc); cutOffParsing(); return nullptr; } // For ObjC2, the category name is optional (not an error). if (Tok.is(tok::identifier)) { categoryId = Tok.getIdentifierInfo(); categoryLoc = ConsumeToken(); } else if (!getLangOpts().ObjC2) { Diag(Tok, diag::err_expected) << tok::identifier; // missing category name. return nullptr; } T.consumeClose(); if (T.getCloseLocation().isInvalid()) return nullptr; if (!attrs.empty()) { // categories don't support attributes. Diag(nameLoc, diag::err_objc_no_attributes_on_category); attrs.clear(); } // Next, we need to check for any protocol references. assert(LAngleLoc.isInvalid() && "Cannot have already parsed protocols"); SmallVector<Decl *, 8> ProtocolRefs; SmallVector<SourceLocation, 8> ProtocolLocs; if (Tok.is(tok::less) && ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, true, true, LAngleLoc, EndProtoLoc, /*consumeLastToken=*/true)) return nullptr; Decl *CategoryType = Actions.ActOnStartCategoryInterface(AtLoc, nameId, nameLoc, typeParameterList, categoryId, categoryLoc, ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(), EndProtoLoc); if (Tok.is(tok::l_brace)) ParseObjCClassInstanceVariables(CategoryType, tok::objc_private, AtLoc); ParseObjCInterfaceDeclList(tok::objc_not_keyword, CategoryType); if (typeParameterList) Actions.popObjCTypeParamList(getCurScope(), typeParameterList); return CategoryType; } // Parse a class interface. IdentifierInfo *superClassId = nullptr; SourceLocation superClassLoc; SourceLocation typeArgsLAngleLoc; SmallVector<ParsedType, 4> typeArgs; SourceLocation typeArgsRAngleLoc; SmallVector<Decl *, 4> protocols; SmallVector<SourceLocation, 4> protocolLocs; if (Tok.is(tok::colon)) { // a super class is specified. ConsumeToken(); // Code completion of superclass names. if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCSuperclass(getCurScope(), nameId, nameLoc); cutOffParsing(); return nullptr; } if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; // missing super class name. return nullptr; } superClassId = Tok.getIdentifierInfo(); superClassLoc = ConsumeToken(); // Type arguments for the superclass or protocol conformances. if (Tok.is(tok::less)) { parseObjCTypeArgsOrProtocolQualifiers(ParsedType(), typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, LAngleLoc, protocols, protocolLocs, EndProtoLoc, /*consumeLastToken=*/true, /*warnOnIncompleteProtocols=*/true); } } // Next, we need to check for any protocol references. if (LAngleLoc.isValid()) { if (!ProtocolIdents.empty()) { // We already parsed the protocols named when we thought we had a // type parameter list. Translate them into actual protocol references. for (const auto &pair : ProtocolIdents) { protocolLocs.push_back(pair.second); } Actions.FindProtocolDeclaration(/*WarnOnDeclarations=*/true, /*ForObjCContainer=*/true, &ProtocolIdents[0], ProtocolIdents.size(), protocols); } } else if (protocols.empty() && Tok.is(tok::less) && ParseObjCProtocolReferences(protocols, protocolLocs, true, true, LAngleLoc, EndProtoLoc, /*consumeLastToken=*/true)) { return nullptr; } if (Tok.isNot(tok::less)) Actions.ActOnTypedefedProtocols(protocols, superClassId, superClassLoc); Decl *ClsType = Actions.ActOnStartClassInterface(getCurScope(), AtLoc, nameId, nameLoc, typeParameterList, superClassId, superClassLoc, typeArgs, SourceRange(typeArgsLAngleLoc, typeArgsRAngleLoc), protocols.data(), protocols.size(), protocolLocs.data(), EndProtoLoc, attrs.getList()); if (Tok.is(tok::l_brace)) ParseObjCClassInstanceVariables(ClsType, tok::objc_protected, AtLoc); ParseObjCInterfaceDeclList(tok::objc_interface, ClsType); if (typeParameterList) Actions.popObjCTypeParamList(getCurScope(), typeParameterList); return ClsType; } /// Add an attribute for a context-sensitive type nullability to the given /// declarator. static void addContextSensitiveTypeNullability(Parser &P, Declarator &D, NullabilityKind nullability, SourceLocation nullabilityLoc, bool &addedToDeclSpec) { // Create the attribute. auto getNullabilityAttr = [&]() -> AttributeList * { return D.getAttributePool().create( P.getNullabilityKeyword(nullability), SourceRange(nullabilityLoc), nullptr, SourceLocation(), nullptr, 0, AttributeList::AS_ContextSensitiveKeyword); }; if (D.getNumTypeObjects() > 0) { // Add the attribute to the declarator chunk nearest the declarator. auto nullabilityAttr = getNullabilityAttr(); DeclaratorChunk &chunk = D.getTypeObject(0); nullabilityAttr->setNext(chunk.getAttrListRef()); chunk.getAttrListRef() = nullabilityAttr; } else if (!addedToDeclSpec) { // Otherwise, just put it on the declaration specifiers (if one // isn't there already). D.getMutableDeclSpec().addAttributes(getNullabilityAttr()); addedToDeclSpec = true; } } /// Parse an Objective-C type parameter list, if present, or capture /// the locations of the protocol identifiers for a list of protocol /// references. /// /// objc-type-parameter-list: /// '<' objc-type-parameter (',' objc-type-parameter)* '>' /// /// objc-type-parameter: /// objc-type-parameter-variance? identifier objc-type-parameter-bound[opt] /// /// objc-type-parameter-bound: /// ':' type-name /// /// objc-type-parameter-variance: /// '__covariant' /// '__contravariant' /// /// \param lAngleLoc The location of the starting '<'. /// /// \param protocolIdents Will capture the list of identifiers, if the /// angle brackets contain a list of protocol references rather than a /// type parameter list. /// /// \param rAngleLoc The location of the ending '>'. ObjCTypeParamList *Parser::parseObjCTypeParamListOrProtocolRefs( SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList) { assert(Tok.is(tok::less) && "Not at the beginning of a type parameter list"); // Within the type parameter list, don't treat '>' as an operator. GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); // Local function to "flush" the protocol identifiers, turning them into // type parameters. SmallVector<Decl *, 4> typeParams; auto makeProtocolIdentsIntoTypeParameters = [&]() { unsigned index = 0; for (const auto &pair : protocolIdents) { DeclResult typeParam = Actions.actOnObjCTypeParam( getCurScope(), ObjCTypeParamVariance::Invariant, SourceLocation(), index++, pair.first, pair.second, SourceLocation(), ParsedType()); if (typeParam.isUsable()) typeParams.push_back(typeParam.get()); } protocolIdents.clear(); mayBeProtocolList = false; }; bool invalid = false; lAngleLoc = ConsumeToken(); do { // Parse the variance, if any. SourceLocation varianceLoc; ObjCTypeParamVariance variance = ObjCTypeParamVariance::Invariant; if (Tok.is(tok::kw___covariant) || Tok.is(tok::kw___contravariant)) { variance = Tok.is(tok::kw___covariant) ? ObjCTypeParamVariance::Covariant : ObjCTypeParamVariance::Contravariant; varianceLoc = ConsumeToken(); // Once we've seen a variance specific , we know this is not a // list of protocol references. if (mayBeProtocolList) { // Up until now, we have been queuing up parameters because they // might be protocol references. Turn them into parameters now. makeProtocolIdentsIntoTypeParameters(); } } // Parse the identifier. if (!Tok.is(tok::identifier)) { // Code completion. if (Tok.is(tok::code_completion)) { // FIXME: If these aren't protocol references, we'll need different // completions. Actions.CodeCompleteObjCProtocolReferences(protocolIdents.data(), protocolIdents.size()); cutOffParsing(); // FIXME: Better recovery here?. return nullptr; } Diag(Tok, diag::err_objc_expected_type_parameter); invalid = true; break; } IdentifierInfo *paramName = Tok.getIdentifierInfo(); SourceLocation paramLoc = ConsumeToken(); // If there is a bound, parse it. SourceLocation colonLoc; TypeResult boundType; if (TryConsumeToken(tok::colon, colonLoc)) { // Once we've seen a bound, we know this is not a list of protocol // references. if (mayBeProtocolList) { // Up until now, we have been queuing up parameters because they // might be protocol references. Turn them into parameters now. makeProtocolIdentsIntoTypeParameters(); } // type-name boundType = ParseTypeName(); if (boundType.isInvalid()) invalid = true; } else if (mayBeProtocolList) { // If this could still be a protocol list, just capture the identifier. // We don't want to turn it into a parameter. protocolIdents.push_back(std::make_pair(paramName, paramLoc)); continue; } // Create the type parameter. DeclResult typeParam = Actions.actOnObjCTypeParam(getCurScope(), variance, varianceLoc, typeParams.size(), paramName, paramLoc, colonLoc, boundType.isUsable() ? boundType.get() : ParsedType()); if (typeParam.isUsable()) typeParams.push_back(typeParam.get()); } while (TryConsumeToken(tok::comma)); // Parse the '>'. if (invalid) { SkipUntil(tok::greater, tok::at, StopBeforeMatch); if (Tok.is(tok::greater)) ConsumeToken(); } else if (ParseGreaterThanInTemplateList(rAngleLoc, /*ConsumeLastToken=*/true, /*ObjCGenericList=*/true)) { Diag(lAngleLoc, diag::note_matching) << "'<'"; SkipUntil({tok::greater, tok::greaterequal, tok::at, tok::minus, tok::minus, tok::plus, tok::colon, tok::l_paren, tok::l_brace, tok::comma, tok::semi }, StopBeforeMatch); if (Tok.is(tok::greater)) ConsumeToken(); } if (mayBeProtocolList) { // A type parameter list must be followed by either a ':' (indicating the // presence of a superclass) or a '(' (indicating that this is a category // or extension). This disambiguates between an objc-type-parameter-list // and a objc-protocol-refs. if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_paren)) { // Returning null indicates that we don't have a type parameter list. // The results the caller needs to handle the protocol references are // captured in the reference parameters already. return nullptr; } // We have a type parameter list that looks like a list of protocol // references. Turn that parameter list into type parameters. makeProtocolIdentsIntoTypeParameters(); } // Form the type parameter list. ObjCTypeParamList *list = Actions.actOnObjCTypeParamList( getCurScope(), lAngleLoc, typeParams, rAngleLoc); // Clear out the angle locations; they're used by the caller to indicate // whether there are any protocol references. lAngleLoc = SourceLocation(); rAngleLoc = SourceLocation(); return list; } /// Parse an objc-type-parameter-list. ObjCTypeParamList *Parser::parseObjCTypeParamList() { SourceLocation lAngleLoc; SmallVector<IdentifierLocPair, 1> protocolIdents; SourceLocation rAngleLoc; return parseObjCTypeParamListOrProtocolRefs(lAngleLoc, protocolIdents, rAngleLoc, /*mayBeProtocolList=*/false); } /// objc-interface-decl-list: /// empty /// objc-interface-decl-list objc-property-decl [OBJC2] /// objc-interface-decl-list objc-method-requirement [OBJC2] /// objc-interface-decl-list objc-method-proto ';' /// objc-interface-decl-list declaration /// objc-interface-decl-list ';' /// /// objc-method-requirement: [OBJC2] /// @required /// @optional /// void Parser::ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl) { SmallVector<Decl *, 32> allMethods; SmallVector<Decl *, 16> allProperties; SmallVector<DeclGroupPtrTy, 8> allTUVariables; tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword; SourceRange AtEnd; while (1) { // If this is a method prototype, parse it. if (Tok.isOneOf(tok::minus, tok::plus)) { if (Decl *methodPrototype = ParseObjCMethodPrototype(MethodImplKind, false)) allMethods.push_back(methodPrototype); // Consume the ';' here, since ParseObjCMethodPrototype() is re-used for // method definitions. if (ExpectAndConsumeSemi(diag::err_expected_semi_after_method_proto)) { // We didn't find a semi and we error'ed out. Skip until a ';' or '@'. SkipUntil(tok::at, StopAtSemi | StopBeforeMatch); if (Tok.is(tok::semi)) ConsumeToken(); } continue; } if (Tok.is(tok::l_paren)) { Diag(Tok, diag::err_expected_minus_or_plus); ParseObjCMethodDecl(Tok.getLocation(), tok::minus, MethodImplKind, false); continue; } // Ignore excess semicolons. if (Tok.is(tok::semi)) { ConsumeToken(); continue; } // If we got to the end of the file, exit the loop. if (isEofOrEom()) break; // Code completion within an Objective-C interface. if (Tok.is(tok::code_completion)) { Actions.CodeCompleteOrdinaryName(getCurScope(), CurParsedObjCImpl? Sema::PCC_ObjCImplementation : Sema::PCC_ObjCInterface); return cutOffParsing(); } // If we don't have an @ directive, parse it as a function definition. if (Tok.isNot(tok::at)) { // The code below does not consume '}'s because it is afraid of eating the // end of a namespace. Because of the way this code is structured, an // erroneous r_brace would cause an infinite loop if not handled here. if (Tok.is(tok::r_brace)) break; ParsedAttributesWithRange attrs(AttrFactory); allTUVariables.push_back(ParseDeclarationOrFunctionDefinition(attrs)); continue; } // Otherwise, we have an @ directive, eat the @. SourceLocation AtLoc = ConsumeToken(); // the "@" if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCAtDirective(getCurScope()); return cutOffParsing(); } tok::ObjCKeywordKind DirectiveKind = Tok.getObjCKeywordID(); if (DirectiveKind == tok::objc_end) { // @end -> terminate list AtEnd.setBegin(AtLoc); AtEnd.setEnd(Tok.getLocation()); break; } else if (DirectiveKind == tok::objc_not_keyword) { Diag(Tok, diag::err_objc_unknown_at); SkipUntil(tok::semi); continue; } // Eat the identifier. ConsumeToken(); switch (DirectiveKind) { default: // FIXME: If someone forgets an @end on a protocol, this loop will // continue to eat up tons of stuff and spew lots of nonsense errors. It // would probably be better to bail out if we saw an @class or @interface // or something like that. Diag(AtLoc, diag::err_objc_illegal_interface_qual); // Skip until we see an '@' or '}' or ';'. SkipUntil(tok::r_brace, tok::at, StopAtSemi); break; case tok::objc_implementation: case tok::objc_interface: Diag(AtLoc, diag::err_objc_missing_end) << FixItHint::CreateInsertion(AtLoc, "@end\n"); Diag(CDecl->getLocStart(), diag::note_objc_container_start) << (int) Actions.getObjCContainerKind(); ConsumeToken(); break; case tok::objc_required: case tok::objc_optional: // This is only valid on protocols. // FIXME: Should this check for ObjC2 being enabled? if (contextKey != tok::objc_protocol) Diag(AtLoc, diag::err_objc_directive_only_in_protocol); else MethodImplKind = DirectiveKind; break; case tok::objc_property: if (!getLangOpts().ObjC2) Diag(AtLoc, diag::err_objc_properties_require_objc2); ObjCDeclSpec OCDS; SourceLocation LParenLoc; // Parse property attribute list, if any. if (Tok.is(tok::l_paren)) { LParenLoc = Tok.getLocation(); ParseObjCPropertyAttribute(OCDS); } bool addedToDeclSpec = false; auto ObjCPropertyCallback = [&](ParsingFieldDeclarator &FD) { if (FD.D.getIdentifier() == nullptr) { Diag(AtLoc, diag::err_objc_property_requires_field_name) << FD.D.getSourceRange(); return; } if (FD.BitfieldSize) { Diag(AtLoc, diag::err_objc_property_bitfield) << FD.D.getSourceRange(); return; } // Map a nullability property attribute to a context-sensitive keyword // attribute. if (OCDS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) addContextSensitiveTypeNullability(*this, FD.D, OCDS.getNullability(), OCDS.getNullabilityLoc(), addedToDeclSpec); // Install the property declarator into interfaceDecl. IdentifierInfo *SelName = OCDS.getGetterName() ? OCDS.getGetterName() : FD.D.getIdentifier(); Selector GetterSel = PP.getSelectorTable().getNullarySelector(SelName); IdentifierInfo *SetterName = OCDS.getSetterName(); Selector SetterSel; if (SetterName) SetterSel = PP.getSelectorTable().getSelector(1, &SetterName); else SetterSel = SelectorTable::constructSetterSelector( PP.getIdentifierTable(), PP.getSelectorTable(), FD.D.getIdentifier()); bool isOverridingProperty = false; Decl *Property = Actions.ActOnProperty( getCurScope(), AtLoc, LParenLoc, FD, OCDS, GetterSel, SetterSel, &isOverridingProperty, MethodImplKind); if (!isOverridingProperty) allProperties.push_back(Property); FD.complete(Property); }; // Parse all the comma separated declarators. ParsingDeclSpec DS(*this); ParseStructDeclaration(DS, ObjCPropertyCallback); ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); break; } } // We break out of the big loop in two cases: when we see @end or when we see // EOF. In the former case, eat the @end. In the later case, emit an error. if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCAtDirective(getCurScope()); return cutOffParsing(); } else if (Tok.isObjCAtKeyword(tok::objc_end)) { ConsumeToken(); // the "end" identifier } else { Diag(Tok, diag::err_objc_missing_end) << FixItHint::CreateInsertion(Tok.getLocation(), "\n@end\n"); Diag(CDecl->getLocStart(), diag::note_objc_container_start) << (int) Actions.getObjCContainerKind(); AtEnd.setBegin(Tok.getLocation()); AtEnd.setEnd(Tok.getLocation()); } // Insert collected methods declarations into the @interface object. // This passes in an invalid SourceLocation for AtEndLoc when EOF is hit. Actions.ActOnAtEnd(getCurScope(), AtEnd, allMethods, allTUVariables); } /// Diagnose redundant or conflicting nullability information. static void diagnoseRedundantPropertyNullability(Parser &P, ObjCDeclSpec &DS, NullabilityKind nullability, SourceLocation nullabilityLoc){ if (DS.getNullability() == nullability) { P.Diag(nullabilityLoc, diag::warn_nullability_duplicate) << DiagNullabilityKind(nullability, true) << SourceRange(DS.getNullabilityLoc()); return; } P.Diag(nullabilityLoc, diag::err_nullability_conflicting) << DiagNullabilityKind(nullability, true) << DiagNullabilityKind(DS.getNullability(), true) << SourceRange(DS.getNullabilityLoc()); } /// Parse property attribute declarations. /// /// property-attr-decl: '(' property-attrlist ')' /// property-attrlist: /// property-attribute /// property-attrlist ',' property-attribute /// property-attribute: /// getter '=' identifier /// setter '=' identifier ':' /// readonly /// readwrite /// assign /// retain /// copy /// nonatomic /// atomic /// strong /// weak /// unsafe_unretained /// nonnull /// nullable /// null_unspecified /// null_resettable /// void Parser::ParseObjCPropertyAttribute(ObjCDeclSpec &DS) { assert(Tok.getKind() == tok::l_paren); BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); while (1) { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCPropertyFlags(getCurScope(), DS); return cutOffParsing(); } const IdentifierInfo *II = Tok.getIdentifierInfo(); // If this is not an identifier at all, bail out early. if (!II) { T.consumeClose(); return; } SourceLocation AttrName = ConsumeToken(); // consume last attribute name if (II->isStr("readonly")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readonly); else if (II->isStr("assign")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_assign); else if (II->isStr("unsafe_unretained")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_unsafe_unretained); else if (II->isStr("readwrite")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_readwrite); else if (II->isStr("retain")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_retain); else if (II->isStr("strong")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_strong); else if (II->isStr("copy")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_copy); else if (II->isStr("nonatomic")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nonatomic); else if (II->isStr("atomic")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_atomic); else if (II->isStr("weak")) DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_weak); else if (II->isStr("getter") || II->isStr("setter")) { bool IsSetter = II->getNameStart()[0] == 's'; // getter/setter require extra treatment. unsigned DiagID = IsSetter ? diag::err_objc_expected_equal_for_setter : diag::err_objc_expected_equal_for_getter; if (ExpectAndConsume(tok::equal, DiagID)) { SkipUntil(tok::r_paren, StopAtSemi); return; } if (Tok.is(tok::code_completion)) { if (IsSetter) Actions.CodeCompleteObjCPropertySetter(getCurScope()); else Actions.CodeCompleteObjCPropertyGetter(getCurScope()); return cutOffParsing(); } SourceLocation SelLoc; IdentifierInfo *SelIdent = ParseObjCSelectorPiece(SelLoc); if (!SelIdent) { Diag(Tok, diag::err_objc_expected_selector_for_getter_setter) << IsSetter; SkipUntil(tok::r_paren, StopAtSemi); return; } if (IsSetter) { DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_setter); DS.setSetterName(SelIdent); if (ExpectAndConsume(tok::colon, diag::err_expected_colon_after_setter_name)) { SkipUntil(tok::r_paren, StopAtSemi); return; } } else { DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_getter); DS.setGetterName(SelIdent); } } else if (II->isStr("nonnull")) { if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) diagnoseRedundantPropertyNullability(*this, DS, NullabilityKind::NonNull, Tok.getLocation()); DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); DS.setNullability(Tok.getLocation(), NullabilityKind::NonNull); } else if (II->isStr("nullable")) { if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) diagnoseRedundantPropertyNullability(*this, DS, NullabilityKind::Nullable, Tok.getLocation()); DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); DS.setNullability(Tok.getLocation(), NullabilityKind::Nullable); } else if (II->isStr("null_unspecified")) { if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) diagnoseRedundantPropertyNullability(*this, DS, NullabilityKind::Unspecified, Tok.getLocation()); DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified); } else if (II->isStr("null_resettable")) { if (DS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nullability) diagnoseRedundantPropertyNullability(*this, DS, NullabilityKind::Unspecified, Tok.getLocation()); DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_nullability); DS.setNullability(Tok.getLocation(), NullabilityKind::Unspecified); // Also set the null_resettable bit. DS.setPropertyAttributes(ObjCDeclSpec::DQ_PR_null_resettable); } else { Diag(AttrName, diag::err_objc_expected_property_attr) << II; SkipUntil(tok::r_paren, StopAtSemi); return; } if (Tok.isNot(tok::comma)) break; ConsumeToken(); } T.consumeClose(); } /// objc-method-proto: /// objc-instance-method objc-method-decl objc-method-attributes[opt] /// objc-class-method objc-method-decl objc-method-attributes[opt] /// /// objc-instance-method: '-' /// objc-class-method: '+' /// /// objc-method-attributes: [OBJC2] /// __attribute__((deprecated)) /// Decl *Parser::ParseObjCMethodPrototype(tok::ObjCKeywordKind MethodImplKind, bool MethodDefinition) { assert(Tok.isOneOf(tok::minus, tok::plus) && "expected +/-"); tok::TokenKind methodType = Tok.getKind(); SourceLocation mLoc = ConsumeToken(); Decl *MDecl = ParseObjCMethodDecl(mLoc, methodType, MethodImplKind, MethodDefinition); // Since this rule is used for both method declarations and definitions, // the caller is (optionally) responsible for consuming the ';'. return MDecl; } /// objc-selector: /// identifier /// one of /// enum struct union if else while do for switch case default /// break continue return goto asm sizeof typeof __alignof /// unsigned long const short volatile signed restrict _Complex /// in out inout bycopy byref oneway int char float double void _Bool /// IdentifierInfo *Parser::ParseObjCSelectorPiece(SourceLocation &SelectorLoc) { switch (Tok.getKind()) { default: return nullptr; case tok::ampamp: case tok::ampequal: case tok::amp: case tok::pipe: case tok::tilde: case tok::exclaim: case tok::exclaimequal: case tok::pipepipe: case tok::pipeequal: case tok::caret: case tok::caretequal: { std::string ThisTok(PP.getSpelling(Tok)); if (isLetter(ThisTok[0])) { IdentifierInfo *II = &PP.getIdentifierTable().get(ThisTok.data()); Tok.setKind(tok::identifier); SelectorLoc = ConsumeToken(); return II; } return nullptr; } case tok::identifier: case tok::kw_asm: case tok::kw_auto: case tok::kw_bool: case tok::kw_break: case tok::kw_case: case tok::kw_catch: case tok::kw_char: case tok::kw_class: case tok::kw_const: case tok::kw_const_cast: case tok::kw_continue: case tok::kw_default: case tok::kw_delete: case tok::kw_do: case tok::kw_double: case tok::kw_dynamic_cast: case tok::kw_else: case tok::kw_enum: case tok::kw_explicit: case tok::kw_export: case tok::kw_extern: case tok::kw_false: case tok::kw_float: case tok::kw_for: case tok::kw_friend: case tok::kw_goto: case tok::kw_if: case tok::kw_inline: case tok::kw_int: case tok::kw_long: case tok::kw_mutable: case tok::kw_namespace: case tok::kw_new: case tok::kw_operator: case tok::kw_private: case tok::kw_protected: case tok::kw_public: case tok::kw_register: case tok::kw_reinterpret_cast: case tok::kw_restrict: case tok::kw_return: case tok::kw_short: case tok::kw_signed: case tok::kw_sizeof: case tok::kw_static: case tok::kw_static_cast: case tok::kw_struct: case tok::kw_switch: case tok::kw_template: case tok::kw_this: case tok::kw_throw: case tok::kw_true: case tok::kw_try: case tok::kw_typedef: case tok::kw_typeid: case tok::kw_typename: case tok::kw_typeof: case tok::kw_union: case tok::kw_unsigned: case tok::kw_using: case tok::kw_virtual: case tok::kw_void: case tok::kw_volatile: case tok::kw_wchar_t: case tok::kw_while: case tok::kw__Bool: case tok::kw__Complex: case tok::kw___alignof: IdentifierInfo *II = Tok.getIdentifierInfo(); SelectorLoc = ConsumeToken(); return II; } } /// objc-for-collection-in: 'in' /// bool Parser::isTokIdentifier_in() const { // FIXME: May have to do additional look-ahead to only allow for // valid tokens following an 'in'; such as an identifier, unary operators, // '[' etc. return (getLangOpts().ObjC2 && Tok.is(tok::identifier) && Tok.getIdentifierInfo() == ObjCTypeQuals[objc_in]); } /// ParseObjCTypeQualifierList - This routine parses the objective-c's type /// qualifier list and builds their bitmask representation in the input /// argument. /// /// objc-type-qualifiers: /// objc-type-qualifier /// objc-type-qualifiers objc-type-qualifier /// /// objc-type-qualifier: /// 'in' /// 'out' /// 'inout' /// 'oneway' /// 'bycopy' /// 'byref' /// 'nonnull' /// 'nullable' /// 'null_unspecified' /// void Parser::ParseObjCTypeQualifierList(ObjCDeclSpec &DS, Declarator::TheContext Context) { assert(Context == Declarator::ObjCParameterContext || Context == Declarator::ObjCResultContext); while (1) { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCPassingType(getCurScope(), DS, Context == Declarator::ObjCParameterContext); return cutOffParsing(); } if (Tok.isNot(tok::identifier)) return; const IdentifierInfo *II = Tok.getIdentifierInfo(); for (unsigned i = 0; i != objc_NumQuals; ++i) { if (II != ObjCTypeQuals[i] || NextToken().is(tok::less) || NextToken().is(tok::coloncolon)) continue; ObjCDeclSpec::ObjCDeclQualifier Qual; NullabilityKind Nullability; switch (i) { default: llvm_unreachable("Unknown decl qualifier"); case objc_in: Qual = ObjCDeclSpec::DQ_In; break; case objc_out: Qual = ObjCDeclSpec::DQ_Out; break; case objc_inout: Qual = ObjCDeclSpec::DQ_Inout; break; case objc_oneway: Qual = ObjCDeclSpec::DQ_Oneway; break; case objc_bycopy: Qual = ObjCDeclSpec::DQ_Bycopy; break; case objc_byref: Qual = ObjCDeclSpec::DQ_Byref; break; case objc_nonnull: Qual = ObjCDeclSpec::DQ_CSNullability; Nullability = NullabilityKind::NonNull; break; case objc_nullable: Qual = ObjCDeclSpec::DQ_CSNullability; Nullability = NullabilityKind::Nullable; break; case objc_null_unspecified: Qual = ObjCDeclSpec::DQ_CSNullability; Nullability = NullabilityKind::Unspecified; break; } // FIXME: Diagnose redundant specifiers. DS.setObjCDeclQualifier(Qual); if (Qual == ObjCDeclSpec::DQ_CSNullability) DS.setNullability(Tok.getLocation(), Nullability); ConsumeToken(); II = nullptr; break; } // If this wasn't a recognized qualifier, bail out. if (II) return; } } /// Take all the decl attributes out of the given list and add /// them to the given attribute set. static void takeDeclAttributes(ParsedAttributes &attrs, AttributeList *list) { while (list) { AttributeList *cur = list; list = cur->getNext(); if (!cur->isUsedAsTypeAttr()) { // Clear out the next pointer. We're really completely // destroying the internal invariants of the declarator here, // but it doesn't matter because we're done with it. cur->setNext(nullptr); attrs.add(cur); } } } /// takeDeclAttributes - Take all the decl attributes from the given /// declarator and add them to the given list. static void takeDeclAttributes(ParsedAttributes &attrs, Declarator &D) { // First, take ownership of all attributes. attrs.getPool().takeAllFrom(D.getAttributePool()); attrs.getPool().takeAllFrom(D.getDeclSpec().getAttributePool()); // Now actually move the attributes over. takeDeclAttributes(attrs, D.getDeclSpec().getAttributes().getList()); takeDeclAttributes(attrs, D.getAttributes()); for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) takeDeclAttributes(attrs, const_cast<AttributeList*>(D.getTypeObject(i).getAttrs())); } /// objc-type-name: /// '(' objc-type-qualifiers[opt] type-name ')' /// '(' objc-type-qualifiers[opt] ')' /// ParsedType Parser::ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext context, ParsedAttributes *paramAttrs) { assert(context == Declarator::ObjCParameterContext || context == Declarator::ObjCResultContext); assert((paramAttrs != nullptr) == (context == Declarator::ObjCParameterContext)); assert(Tok.is(tok::l_paren) && "expected ("); BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); SourceLocation TypeStartLoc = Tok.getLocation(); ObjCDeclContextSwitch ObjCDC(*this); // Parse type qualifiers, in, inout, etc. ParseObjCTypeQualifierList(DS, context); ParsedType Ty; if (isTypeSpecifierQualifier() || isObjCInstancetype()) { // Parse an abstract declarator. DeclSpec declSpec(AttrFactory); declSpec.setObjCQualifiers(&DS); DeclSpecContext dsContext = DSC_normal; if (context == Declarator::ObjCResultContext) dsContext = DSC_objc_method_result; ParseSpecifierQualifierList(declSpec, AS_none, dsContext); declSpec.SetRangeEnd(Tok.getLocation()); Declarator declarator(declSpec, context); ParseDeclarator(declarator); // If that's not invalid, extract a type. if (!declarator.isInvalidType()) { // Map a nullability specifier to a context-sensitive keyword attribute. bool addedToDeclSpec = false; if (DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) addContextSensitiveTypeNullability(*this, declarator, DS.getNullability(), DS.getNullabilityLoc(), addedToDeclSpec); TypeResult type = Actions.ActOnTypeName(getCurScope(), declarator); if (!type.isInvalid()) Ty = type.get(); // If we're parsing a parameter, steal all the decl attributes // and add them to the decl spec. if (context == Declarator::ObjCParameterContext) takeDeclAttributes(*paramAttrs, declarator); } } if (Tok.is(tok::r_paren)) T.consumeClose(); else if (Tok.getLocation() == TypeStartLoc) { // If we didn't eat any tokens, then this isn't a type. Diag(Tok, diag::err_expected_type); SkipUntil(tok::r_paren, StopAtSemi); } else { // Otherwise, we found *something*, but didn't get a ')' in the right // place. Emit an error then return what we have as the type. T.consumeClose(); } return Ty; } /// objc-method-decl: /// objc-selector /// objc-keyword-selector objc-parmlist[opt] /// objc-type-name objc-selector /// objc-type-name objc-keyword-selector objc-parmlist[opt] /// /// objc-keyword-selector: /// objc-keyword-decl /// objc-keyword-selector objc-keyword-decl /// /// objc-keyword-decl: /// objc-selector ':' objc-type-name objc-keyword-attributes[opt] identifier /// objc-selector ':' objc-keyword-attributes[opt] identifier /// ':' objc-type-name objc-keyword-attributes[opt] identifier /// ':' objc-keyword-attributes[opt] identifier /// /// objc-parmlist: /// objc-parms objc-ellipsis[opt] /// /// objc-parms: /// objc-parms , parameter-declaration /// /// objc-ellipsis: /// , ... /// /// objc-keyword-attributes: [OBJC2] /// __attribute__((unused)) /// Decl *Parser::ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind, bool MethodDefinition) { ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, /*ReturnType=*/ ParsedType()); cutOffParsing(); return nullptr; } // Parse the return type if present. ParsedType ReturnType; ObjCDeclSpec DSRet; if (Tok.is(tok::l_paren)) ReturnType = ParseObjCTypeName(DSRet, Declarator::ObjCResultContext, nullptr); // If attributes exist before the method, parse them. ParsedAttributes methodAttrs(AttrFactory); if (getLangOpts().ObjC2) MaybeParseGNUAttributes(methodAttrs); if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCMethodDecl(getCurScope(), mType == tok::minus, ReturnType); cutOffParsing(); return nullptr; } // Now parse the selector. SourceLocation selLoc; IdentifierInfo *SelIdent = ParseObjCSelectorPiece(selLoc); // An unnamed colon is valid. if (!SelIdent && Tok.isNot(tok::colon)) { // missing selector name. Diag(Tok, diag::err_expected_selector_for_method) << SourceRange(mLoc, Tok.getLocation()); // Skip until we get a ; or @. SkipUntil(tok::at, StopAtSemi | StopBeforeMatch); return nullptr; } SmallVector<DeclaratorChunk::ParamInfo, 8> CParamInfo; if (Tok.isNot(tok::colon)) { // If attributes exist after the method, parse them. if (getLangOpts().ObjC2) MaybeParseGNUAttributes(methodAttrs); Selector Sel = PP.getSelectorTable().getNullarySelector(SelIdent); Decl *Result = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType, selLoc, Sel, nullptr, CParamInfo.data(), CParamInfo.size(), methodAttrs.getList(), MethodImplKind, false, MethodDefinition); PD.complete(Result); return Result; } SmallVector<IdentifierInfo *, 12> KeyIdents; SmallVector<SourceLocation, 12> KeyLocs; SmallVector<Sema::ObjCArgInfo, 12> ArgInfos; ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | Scope::FunctionDeclarationScope | Scope::DeclScope); AttributePool allParamAttrs(AttrFactory); while (1) { ParsedAttributes paramAttrs(AttrFactory); Sema::ObjCArgInfo ArgInfo; // Each iteration parses a single keyword argument. if (ExpectAndConsume(tok::colon)) break; ArgInfo.Type = ParsedType(); if (Tok.is(tok::l_paren)) // Parse the argument type if present. ArgInfo.Type = ParseObjCTypeName(ArgInfo.DeclSpec, Declarator::ObjCParameterContext, &paramAttrs); // If attributes exist before the argument name, parse them. // Regardless, collect all the attributes we've parsed so far. ArgInfo.ArgAttrs = nullptr; if (getLangOpts().ObjC2) { MaybeParseGNUAttributes(paramAttrs); ArgInfo.ArgAttrs = paramAttrs.getList(); } // Code completion for the next piece of the selector. if (Tok.is(tok::code_completion)) { KeyIdents.push_back(SelIdent); Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), mType == tok::minus, /*AtParameterName=*/true, ReturnType, KeyIdents); cutOffParsing(); return nullptr; } if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; // missing argument name. break; } ArgInfo.Name = Tok.getIdentifierInfo(); ArgInfo.NameLoc = Tok.getLocation(); ConsumeToken(); // Eat the identifier. ArgInfos.push_back(ArgInfo); KeyIdents.push_back(SelIdent); KeyLocs.push_back(selLoc); // Make sure the attributes persist. allParamAttrs.takeAllFrom(paramAttrs.getPool()); // Code completion for the next piece of the selector. if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCMethodDeclSelector(getCurScope(), mType == tok::minus, /*AtParameterName=*/false, ReturnType, KeyIdents); cutOffParsing(); return nullptr; } // Check for another keyword selector. SelIdent = ParseObjCSelectorPiece(selLoc); if (!SelIdent && Tok.isNot(tok::colon)) break; if (!SelIdent) { SourceLocation ColonLoc = Tok.getLocation(); if (PP.getLocForEndOfToken(ArgInfo.NameLoc) == ColonLoc) { Diag(ArgInfo.NameLoc, diag::warn_missing_selector_name) << ArgInfo.Name; Diag(ArgInfo.NameLoc, diag::note_missing_selector_name) << ArgInfo.Name; Diag(ColonLoc, diag::note_force_empty_selector_name) << ArgInfo.Name; } } // We have a selector or a colon, continue parsing. } bool isVariadic = false; bool cStyleParamWarned = false; // Parse the (optional) parameter list. while (Tok.is(tok::comma)) { ConsumeToken(); if (Tok.is(tok::ellipsis)) { isVariadic = true; ConsumeToken(); break; } if (!cStyleParamWarned) { Diag(Tok, diag::warn_cstyle_param); cStyleParamWarned = true; } DeclSpec DS(AttrFactory); ParseDeclarationSpecifiers(DS); // Parse the declarator. Declarator ParmDecl(DS, Declarator::PrototypeContext); ParseDeclarator(ParmDecl); IdentifierInfo *ParmII = ParmDecl.getIdentifier(); Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDecl); CParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, ParmDecl.getIdentifierLoc(), Param, nullptr)); } // FIXME: Add support for optional parameter list... // If attributes exist after the method, parse them. if (getLangOpts().ObjC2) MaybeParseGNUAttributes(methodAttrs); if (KeyIdents.size() == 0) return nullptr; Selector Sel = PP.getSelectorTable().getSelector(KeyIdents.size(), &KeyIdents[0]); Decl *Result = Actions.ActOnMethodDeclaration(getCurScope(), mLoc, Tok.getLocation(), mType, DSRet, ReturnType, KeyLocs, Sel, &ArgInfos[0], CParamInfo.data(), CParamInfo.size(), methodAttrs.getList(), MethodImplKind, isVariadic, MethodDefinition); PD.complete(Result); return Result; } /// objc-protocol-refs: /// '<' identifier-list '>' /// bool Parser:: ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &Protocols, SmallVectorImpl<SourceLocation> &ProtocolLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndLoc, bool consumeLastToken) { assert(Tok.is(tok::less) && "expected <"); LAngleLoc = ConsumeToken(); // the "<" SmallVector<IdentifierLocPair, 8> ProtocolIdents; while (1) { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCProtocolReferences(ProtocolIdents.data(), ProtocolIdents.size()); cutOffParsing(); return true; } if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; SkipUntil(tok::greater, StopAtSemi); return true; } ProtocolIdents.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); ProtocolLocs.push_back(Tok.getLocation()); ConsumeToken(); if (!TryConsumeToken(tok::comma)) break; } // Consume the '>'. if (ParseGreaterThanInTemplateList(EndLoc, consumeLastToken, /*ObjCGenericList=*/false)) return true; // Convert the list of protocols identifiers into a list of protocol decls. Actions.FindProtocolDeclaration(WarnOnDeclarations, ForObjCContainer, &ProtocolIdents[0], ProtocolIdents.size(), Protocols); return false; } TypeResult Parser::parseObjCProtocolQualifierType(SourceLocation &rAngleLoc) { assert(Tok.is(tok::less) && "Protocol qualifiers start with '<'"); assert(getLangOpts().ObjC1 && "Protocol qualifiers only exist in Objective-C"); SourceLocation lAngleLoc; SmallVector<Decl *, 8> protocols; SmallVector<SourceLocation, 8> protocolLocs; (void)ParseObjCProtocolReferences(protocols, protocolLocs, false, false, lAngleLoc, rAngleLoc, /*consumeLastToken=*/true); TypeResult result = Actions.actOnObjCProtocolQualifierType(lAngleLoc, protocols, protocolLocs, rAngleLoc); if (result.isUsable()) { Diag(lAngleLoc, diag::warn_objc_protocol_qualifier_missing_id) << FixItHint::CreateInsertion(lAngleLoc, "id") << SourceRange(lAngleLoc, rAngleLoc); } return result; } /// Parse Objective-C type arguments or protocol qualifiers. /// /// objc-type-arguments: /// '<' type-name '...'[opt] (',' type-name '...'[opt])* '>' /// void Parser::parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols) { assert(Tok.is(tok::less) && "Not at the start of type args or protocols"); SourceLocation lAngleLoc = ConsumeToken(); // Whether all of the elements we've parsed thus far are single // identifiers, which might be types or might be protocols. bool allSingleIdentifiers = true; SmallVector<IdentifierInfo *, 4> identifiers; SmallVectorImpl<SourceLocation> &identifierLocs = protocolLocs; // Parse a list of comma-separated identifiers, bailing out if we // see something different. do { // Parse a single identifier. if (Tok.is(tok::identifier) && (NextToken().is(tok::comma) || NextToken().is(tok::greater) || NextToken().is(tok::greatergreater))) { identifiers.push_back(Tok.getIdentifierInfo()); identifierLocs.push_back(ConsumeToken()); continue; } if (Tok.is(tok::code_completion)) { // FIXME: Also include types here. SmallVector<IdentifierLocPair, 4> identifierLocPairs; for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { identifierLocPairs.push_back(IdentifierLocPair(identifiers[i], identifierLocs[i])); } QualType BaseT = Actions.GetTypeFromParser(baseType); if (!BaseT.isNull() && BaseT->acceptsObjCTypeParams()) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); } else { Actions.CodeCompleteObjCProtocolReferences(identifierLocPairs.data(), identifierLocPairs.size()); } cutOffParsing(); return; } allSingleIdentifiers = false; break; } while (TryConsumeToken(tok::comma)); // If we parsed an identifier list, semantic analysis sorts out // whether it refers to protocols or to type arguments. if (allSingleIdentifiers) { // Parse the closing '>'. SourceLocation rAngleLoc; (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken, /*ObjCGenericList=*/true); // Let Sema figure out what we parsed. Actions.actOnObjCTypeArgsOrProtocolQualifiers(getCurScope(), baseType, lAngleLoc, identifiers, identifierLocs, rAngleLoc, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, protocolLAngleLoc, protocols, protocolRAngleLoc, warnOnIncompleteProtocols); return; } // We syntactically matched a type argument, so commit to parsing // type arguments. // Convert the identifiers into type arguments. bool invalid = false; for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { ParsedType typeArg = Actions.getTypeName(*identifiers[i], identifierLocs[i], getCurScope()); if (typeArg) { DeclSpec DS(AttrFactory); const char *prevSpec = nullptr; unsigned diagID; DS.SetTypeSpecType(TST_typename, identifierLocs[i], prevSpec, diagID, typeArg, Actions.getASTContext().getPrintingPolicy()); // Form a declarator to turn this into a type. Declarator D(DS, Declarator::TypeNameContext); TypeResult fullTypeArg = Actions.ActOnTypeName(getCurScope(), D); if (fullTypeArg.isUsable()) typeArgs.push_back(fullTypeArg.get()); else invalid = true; } else { invalid = true; } } // Continue parsing type-names. do { TypeResult typeArg = ParseTypeName(); // Consume the '...' for a pack expansion. SourceLocation ellipsisLoc; TryConsumeToken(tok::ellipsis, ellipsisLoc); if (typeArg.isUsable() && ellipsisLoc.isValid()) { typeArg = Actions.ActOnPackExpansion(typeArg.get(), ellipsisLoc); } if (typeArg.isUsable()) { typeArgs.push_back(typeArg.get()); } else { invalid = true; } } while (TryConsumeToken(tok::comma)); // Parse the closing '>'. SourceLocation rAngleLoc; (void)ParseGreaterThanInTemplateList(rAngleLoc, consumeLastToken, /*ObjCGenericList=*/true); if (invalid) { typeArgs.clear(); return; } // Record left/right angle locations. typeArgsLAngleLoc = lAngleLoc; typeArgsRAngleLoc = rAngleLoc; } void Parser::parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken) { assert(Tok.is(tok::less)); // Parse the first angle-bracket-delimited clause. parseObjCTypeArgsOrProtocolQualifiers(baseType, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, protocolLAngleLoc, protocols, protocolLocs, protocolRAngleLoc, consumeLastToken, /*warnOnIncompleteProtocols=*/false); // An Objective-C object pointer followed by type arguments // can then be followed again by a set of protocol references, e.g., // \c NSArray<NSView><NSTextDelegate> if ((consumeLastToken && Tok.is(tok::less)) || (!consumeLastToken && NextToken().is(tok::less))) { // If we aren't consuming the last token, the prior '>' is still hanging // there. Consume it before we parse the protocol qualifiers. if (!consumeLastToken) ConsumeToken(); if (!protocols.empty()) { SkipUntilFlags skipFlags = SkipUntilFlags(); if (!consumeLastToken) skipFlags = skipFlags | StopBeforeMatch; Diag(Tok, diag::err_objc_type_args_after_protocols) << SourceRange(protocolLAngleLoc, protocolRAngleLoc); SkipUntil(tok::greater, tok::greatergreater, skipFlags); } else { ParseObjCProtocolReferences(protocols, protocolLocs, /*WarnOnDeclarations=*/false, /*ForObjCContainer=*/false, protocolLAngleLoc, protocolRAngleLoc, consumeLastToken); } } } TypeResult Parser::parseObjCTypeArgsAndProtocolQualifiers( SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc) { assert(Tok.is(tok::less)); SourceLocation typeArgsLAngleLoc; SmallVector<ParsedType, 4> typeArgs; SourceLocation typeArgsRAngleLoc; SourceLocation protocolLAngleLoc; SmallVector<Decl *, 4> protocols; SmallVector<SourceLocation, 4> protocolLocs; SourceLocation protocolRAngleLoc; // Parse type arguments and protocol qualifiers. parseObjCTypeArgsAndProtocolQualifiers(type, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, protocolLAngleLoc, protocols, protocolLocs, protocolRAngleLoc, consumeLastToken); // Compute the location of the last token. if (consumeLastToken) endLoc = PrevTokLocation; else endLoc = Tok.getLocation(); return Actions.actOnObjCTypeArgsAndProtocolQualifiers( getCurScope(), loc, type, typeArgsLAngleLoc, typeArgs, typeArgsRAngleLoc, protocolLAngleLoc, protocols, protocolLocs, protocolRAngleLoc); } void Parser::HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing) { if (!RBraceMissing) T.consumeClose(); Actions.ActOnObjCContainerStartDefinition(interfaceDecl); Actions.ActOnLastBitfield(T.getCloseLocation(), AllIvarDecls); Actions.ActOnObjCContainerFinishDefinition(); // Call ActOnFields() even if we don't have any decls. This is useful // for code rewriting tools that need to be aware of the empty list. Actions.ActOnFields(getCurScope(), atLoc, interfaceDecl, AllIvarDecls, T.getOpenLocation(), T.getCloseLocation(), nullptr); } /// objc-class-instance-variables: /// '{' objc-instance-variable-decl-list[opt] '}' /// /// objc-instance-variable-decl-list: /// objc-visibility-spec /// objc-instance-variable-decl ';' /// ';' /// objc-instance-variable-decl-list objc-visibility-spec /// objc-instance-variable-decl-list objc-instance-variable-decl ';' /// objc-instance-variable-decl-list ';' /// /// objc-visibility-spec: /// @private /// @protected /// @public /// @package [OBJC2] /// /// objc-instance-variable-decl: /// struct-declaration /// void Parser::ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc) { assert(Tok.is(tok::l_brace) && "expected {"); SmallVector<Decl *, 32> AllIvarDecls; ParseScope ClassScope(this, Scope::DeclScope|Scope::ClassScope); ObjCDeclContextSwitch ObjCDC(*this); BalancedDelimiterTracker T(*this, tok::l_brace); T.consumeOpen(); // While we still have something to read, read the instance variables. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { // Each iteration of this loop reads one objc-instance-variable-decl. // Check for extraneous top-level semicolon. if (Tok.is(tok::semi)) { ConsumeExtraSemi(InstanceVariableList); continue; } // Set the default visibility to private. if (TryConsumeToken(tok::at)) { // parse objc-visibility-spec if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCAtVisibility(getCurScope()); return cutOffParsing(); } switch (Tok.getObjCKeywordID()) { case tok::objc_private: case tok::objc_public: case tok::objc_protected: case tok::objc_package: visibility = Tok.getObjCKeywordID(); ConsumeToken(); continue; case tok::objc_end: Diag(Tok, diag::err_objc_unexpected_atend); Tok.setLocation(Tok.getLocation().getLocWithOffset(-1)); Tok.setKind(tok::at); Tok.setLength(1); PP.EnterToken(Tok); HelperActionsForIvarDeclarations(interfaceDecl, atLoc, T, AllIvarDecls, true); return; default: Diag(Tok, diag::err_objc_illegal_visibility_spec); continue; } } if (Tok.is(tok::code_completion)) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_ObjCInstanceVariableList); return cutOffParsing(); } auto ObjCIvarCallback = [&](ParsingFieldDeclarator &FD) { Actions.ActOnObjCContainerStartDefinition(interfaceDecl); // Install the declarator into the interface decl. FD.D.setObjCIvar(true); Decl *Field = Actions.ActOnIvar( getCurScope(), FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D, FD.BitfieldSize, visibility); Actions.ActOnObjCContainerFinishDefinition(); if (Field) AllIvarDecls.push_back(Field); FD.complete(Field); }; // Parse all the comma separated declarators. ParsingDeclSpec DS(*this); ParseStructDeclaration(DS, ObjCIvarCallback); if (Tok.is(tok::semi)) { ConsumeToken(); } else { Diag(Tok, diag::err_expected_semi_decl_list); // Skip to end of block or statement SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); } } HelperActionsForIvarDeclarations(interfaceDecl, atLoc, T, AllIvarDecls, false); return; } /// objc-protocol-declaration: /// objc-protocol-definition /// objc-protocol-forward-reference /// /// objc-protocol-definition: /// \@protocol identifier /// objc-protocol-refs[opt] /// objc-interface-decl-list /// \@end /// /// objc-protocol-forward-reference: /// \@protocol identifier-list ';' /// /// "\@protocol identifier ;" should be resolved as "\@protocol /// identifier-list ;": objc-interface-decl-list may not start with a /// semicolon in the first alternative if objc-protocol-refs are omitted. Parser::DeclGroupPtrTy Parser::ParseObjCAtProtocolDeclaration(SourceLocation AtLoc, ParsedAttributes &attrs) { assert(Tok.isObjCAtKeyword(tok::objc_protocol) && "ParseObjCAtProtocolDeclaration(): Expected @protocol"); ConsumeToken(); // the "protocol" identifier if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCProtocolDecl(getCurScope()); cutOffParsing(); return DeclGroupPtrTy(); } MaybeSkipAttributes(tok::objc_protocol); if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; // missing protocol name. return DeclGroupPtrTy(); } // Save the protocol name, then consume it. IdentifierInfo *protocolName = Tok.getIdentifierInfo(); SourceLocation nameLoc = ConsumeToken(); if (TryConsumeToken(tok::semi)) { // forward declaration of one protocol. IdentifierLocPair ProtoInfo(protocolName, nameLoc); return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtoInfo, 1, attrs.getList()); } CheckNestedObjCContexts(AtLoc); if (Tok.is(tok::comma)) { // list of forward declarations. SmallVector<IdentifierLocPair, 8> ProtocolRefs; ProtocolRefs.push_back(std::make_pair(protocolName, nameLoc)); // Parse the list of forward declarations. while (1) { ConsumeToken(); // the ',' if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; SkipUntil(tok::semi); return DeclGroupPtrTy(); } ProtocolRefs.push_back(IdentifierLocPair(Tok.getIdentifierInfo(), Tok.getLocation())); ConsumeToken(); // the identifier if (Tok.isNot(tok::comma)) break; } // Consume the ';'. if (ExpectAndConsume(tok::semi, diag::err_expected_after, "@protocol")) return DeclGroupPtrTy(); return Actions.ActOnForwardProtocolDeclaration(AtLoc, &ProtocolRefs[0], ProtocolRefs.size(), attrs.getList()); } // Last, and definitely not least, parse a protocol declaration. SourceLocation LAngleLoc, EndProtoLoc; SmallVector<Decl *, 8> ProtocolRefs; SmallVector<SourceLocation, 8> ProtocolLocs; if (Tok.is(tok::less) && ParseObjCProtocolReferences(ProtocolRefs, ProtocolLocs, false, true, LAngleLoc, EndProtoLoc, /*consumeLastToken=*/true)) return DeclGroupPtrTy(); Decl *ProtoType = Actions.ActOnStartProtocolInterface(AtLoc, protocolName, nameLoc, ProtocolRefs.data(), ProtocolRefs.size(), ProtocolLocs.data(), EndProtoLoc, attrs.getList()); ParseObjCInterfaceDeclList(tok::objc_protocol, ProtoType); return Actions.ConvertDeclToDeclGroup(ProtoType); } /// objc-implementation: /// objc-class-implementation-prologue /// objc-category-implementation-prologue /// /// objc-class-implementation-prologue: /// @implementation identifier objc-superclass[opt] /// objc-class-instance-variables[opt] /// /// objc-category-implementation-prologue: /// @implementation identifier ( identifier ) Parser::DeclGroupPtrTy Parser::ParseObjCAtImplementationDeclaration(SourceLocation AtLoc) { assert(Tok.isObjCAtKeyword(tok::objc_implementation) && "ParseObjCAtImplementationDeclaration(): Expected @implementation"); CheckNestedObjCContexts(AtLoc); ConsumeToken(); // the "implementation" identifier // Code completion after '@implementation'. if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCImplementationDecl(getCurScope()); cutOffParsing(); return DeclGroupPtrTy(); } MaybeSkipAttributes(tok::objc_implementation); if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; // missing class or category name. return DeclGroupPtrTy(); } // We have a class or category name - consume it. IdentifierInfo *nameId = Tok.getIdentifierInfo(); SourceLocation nameLoc = ConsumeToken(); // consume class or category name Decl *ObjCImpDecl = nullptr; // Neither a type parameter list nor a list of protocol references is // permitted here. Parse and diagnose them. if (Tok.is(tok::less)) { SourceLocation lAngleLoc, rAngleLoc; SmallVector<IdentifierLocPair, 8> protocolIdents; SourceLocation diagLoc = Tok.getLocation(); if (parseObjCTypeParamListOrProtocolRefs(lAngleLoc, protocolIdents, rAngleLoc)) { Diag(diagLoc, diag::err_objc_parameterized_implementation) << SourceRange(diagLoc, PrevTokLocation); } else if (lAngleLoc.isValid()) { Diag(lAngleLoc, diag::err_unexpected_protocol_qualifier) << FixItHint::CreateRemoval(SourceRange(lAngleLoc, rAngleLoc)); } } if (Tok.is(tok::l_paren)) { // we have a category implementation. ConsumeParen(); SourceLocation categoryLoc, rparenLoc; IdentifierInfo *categoryId = nullptr; if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCImplementationCategory(getCurScope(), nameId, nameLoc); cutOffParsing(); return DeclGroupPtrTy(); } if (Tok.is(tok::identifier)) { categoryId = Tok.getIdentifierInfo(); categoryLoc = ConsumeToken(); } else { Diag(Tok, diag::err_expected) << tok::identifier; // missing category name. return DeclGroupPtrTy(); } if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected) << tok::r_paren; SkipUntil(tok::r_paren); // don't stop at ';' return DeclGroupPtrTy(); } rparenLoc = ConsumeParen(); if (Tok.is(tok::less)) { // we have illegal '<' try to recover Diag(Tok, diag::err_unexpected_protocol_qualifier); SourceLocation protocolLAngleLoc, protocolRAngleLoc; SmallVector<Decl *, 4> protocols; SmallVector<SourceLocation, 4> protocolLocs; (void)ParseObjCProtocolReferences(protocols, protocolLocs, /*warnOnIncompleteProtocols=*/false, /*ForObjCContainer=*/false, protocolLAngleLoc, protocolRAngleLoc, /*consumeLastToken=*/true); } ObjCImpDecl = Actions.ActOnStartCategoryImplementation( AtLoc, nameId, nameLoc, categoryId, categoryLoc); } else { // We have a class implementation SourceLocation superClassLoc; IdentifierInfo *superClassId = nullptr; if (TryConsumeToken(tok::colon)) { // We have a super class if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; // missing super class name. return DeclGroupPtrTy(); } superClassId = Tok.getIdentifierInfo(); superClassLoc = ConsumeToken(); // Consume super class name } ObjCImpDecl = Actions.ActOnStartClassImplementation( AtLoc, nameId, nameLoc, superClassId, superClassLoc); if (Tok.is(tok::l_brace)) // we have ivars ParseObjCClassInstanceVariables(ObjCImpDecl, tok::objc_private, AtLoc); else if (Tok.is(tok::less)) { // we have illegal '<' try to recover Diag(Tok, diag::err_unexpected_protocol_qualifier); SourceLocation protocolLAngleLoc, protocolRAngleLoc; SmallVector<Decl *, 4> protocols; SmallVector<SourceLocation, 4> protocolLocs; (void)ParseObjCProtocolReferences(protocols, protocolLocs, /*warnOnIncompleteProtocols=*/false, /*ForObjCContainer=*/false, protocolLAngleLoc, protocolRAngleLoc, /*consumeLastToken=*/true); } } assert(ObjCImpDecl); SmallVector<Decl *, 8> DeclsInGroup; { ObjCImplParsingDataRAII ObjCImplParsing(*this, ObjCImpDecl); while (!ObjCImplParsing.isFinished() && !isEofOrEom()) { ParsedAttributesWithRange attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); MaybeParseMicrosoftAttributes(attrs); if (DeclGroupPtrTy DGP = ParseExternalDeclaration(attrs)) { DeclGroupRef DG = DGP.get(); DeclsInGroup.append(DG.begin(), DG.end()); } } } return Actions.ActOnFinishObjCImplementation(ObjCImpDecl, DeclsInGroup); } Parser::DeclGroupPtrTy Parser::ParseObjCAtEndDeclaration(SourceRange atEnd) { assert(Tok.isObjCAtKeyword(tok::objc_end) && "ParseObjCAtEndDeclaration(): Expected @end"); ConsumeToken(); // the "end" identifier if (CurParsedObjCImpl) CurParsedObjCImpl->finish(atEnd); else // missing @implementation Diag(atEnd.getBegin(), diag::err_expected_objc_container); return DeclGroupPtrTy(); } Parser::ObjCImplParsingDataRAII::~ObjCImplParsingDataRAII() { if (!Finished) { finish(P.Tok.getLocation()); if (P.isEofOrEom()) { P.Diag(P.Tok, diag::err_objc_missing_end) << FixItHint::CreateInsertion(P.Tok.getLocation(), "\n@end\n"); P.Diag(Dcl->getLocStart(), diag::note_objc_container_start) << Sema::OCK_Implementation; } } P.CurParsedObjCImpl = nullptr; assert(LateParsedObjCMethods.empty()); } void Parser::ObjCImplParsingDataRAII::finish(SourceRange AtEnd) { assert(!Finished); P.Actions.DefaultSynthesizeProperties(P.getCurScope(), Dcl); for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], true/*Methods*/); P.Actions.ActOnAtEnd(P.getCurScope(), AtEnd); if (HasCFunction) for (size_t i = 0; i < LateParsedObjCMethods.size(); ++i) P.ParseLexedObjCMethodDefs(*LateParsedObjCMethods[i], false/*c-functions*/); /// \brief Clear and free the cached objc methods. for (LateParsedObjCMethodContainer::iterator I = LateParsedObjCMethods.begin(), E = LateParsedObjCMethods.end(); I != E; ++I) delete *I; LateParsedObjCMethods.clear(); Finished = true; } /// compatibility-alias-decl: /// @compatibility_alias alias-name class-name ';' /// Decl *Parser::ParseObjCAtAliasDeclaration(SourceLocation atLoc) { assert(Tok.isObjCAtKeyword(tok::objc_compatibility_alias) && "ParseObjCAtAliasDeclaration(): Expected @compatibility_alias"); ConsumeToken(); // consume compatibility_alias if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; return nullptr; } IdentifierInfo *aliasId = Tok.getIdentifierInfo(); SourceLocation aliasLoc = ConsumeToken(); // consume alias-name if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; return nullptr; } IdentifierInfo *classId = Tok.getIdentifierInfo(); SourceLocation classLoc = ConsumeToken(); // consume class-name; ExpectAndConsume(tok::semi, diag::err_expected_after, "@compatibility_alias"); return Actions.ActOnCompatibilityAlias(atLoc, aliasId, aliasLoc, classId, classLoc); } /// property-synthesis: /// @synthesize property-ivar-list ';' /// /// property-ivar-list: /// property-ivar /// property-ivar-list ',' property-ivar /// /// property-ivar: /// identifier /// identifier '=' identifier /// Decl *Parser::ParseObjCPropertySynthesize(SourceLocation atLoc) { assert(Tok.isObjCAtKeyword(tok::objc_synthesize) && "ParseObjCPropertySynthesize(): Expected '@synthesize'"); ConsumeToken(); // consume synthesize while (true) { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCPropertyDefinition(getCurScope()); cutOffParsing(); return nullptr; } if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_synthesized_property_name); SkipUntil(tok::semi); return nullptr; } IdentifierInfo *propertyIvar = nullptr; IdentifierInfo *propertyId = Tok.getIdentifierInfo(); SourceLocation propertyLoc = ConsumeToken(); // consume property name SourceLocation propertyIvarLoc; if (TryConsumeToken(tok::equal)) { // property '=' ivar-name if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCPropertySynthesizeIvar(getCurScope(), propertyId); cutOffParsing(); return nullptr; } if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; break; } propertyIvar = Tok.getIdentifierInfo(); propertyIvarLoc = ConsumeToken(); // consume ivar-name } Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, true, propertyId, propertyIvar, propertyIvarLoc); if (Tok.isNot(tok::comma)) break; ConsumeToken(); // consume ',' } ExpectAndConsume(tok::semi, diag::err_expected_after, "@synthesize"); return nullptr; } /// property-dynamic: /// @dynamic property-list /// /// property-list: /// identifier /// property-list ',' identifier /// Decl *Parser::ParseObjCPropertyDynamic(SourceLocation atLoc) { assert(Tok.isObjCAtKeyword(tok::objc_dynamic) && "ParseObjCPropertyDynamic(): Expected '@dynamic'"); ConsumeToken(); // consume dynamic while (true) { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCPropertyDefinition(getCurScope()); cutOffParsing(); return nullptr; } if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; SkipUntil(tok::semi); return nullptr; } IdentifierInfo *propertyId = Tok.getIdentifierInfo(); SourceLocation propertyLoc = ConsumeToken(); // consume property name Actions.ActOnPropertyImplDecl(getCurScope(), atLoc, propertyLoc, false, propertyId, nullptr, SourceLocation()); if (Tok.isNot(tok::comma)) break; ConsumeToken(); // consume ',' } ExpectAndConsume(tok::semi, diag::err_expected_after, "@dynamic"); return nullptr; } /// objc-throw-statement: /// throw expression[opt]; /// StmtResult Parser::ParseObjCThrowStmt(SourceLocation atLoc) { ExprResult Res; ConsumeToken(); // consume throw if (Tok.isNot(tok::semi)) { Res = ParseExpression(); if (Res.isInvalid()) { SkipUntil(tok::semi); return StmtError(); } } // consume ';' ExpectAndConsume(tok::semi, diag::err_expected_after, "@throw"); return Actions.ActOnObjCAtThrowStmt(atLoc, Res.get(), getCurScope()); } /// objc-synchronized-statement: /// @synchronized '(' expression ')' compound-statement /// StmtResult Parser::ParseObjCSynchronizedStmt(SourceLocation atLoc) { ConsumeToken(); // consume synchronized if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen_after) << "@synchronized"; return StmtError(); } // The operand is surrounded with parentheses. ConsumeParen(); // '(' ExprResult operand(ParseExpression()); if (Tok.is(tok::r_paren)) { ConsumeParen(); // ')' } else { if (!operand.isInvalid()) Diag(Tok, diag::err_expected) << tok::r_paren; // Skip forward until we see a left brace, but don't consume it. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); } // Require a compound statement. if (Tok.isNot(tok::l_brace)) { if (!operand.isInvalid()) Diag(Tok, diag::err_expected) << tok::l_brace; return StmtError(); } // Check the @synchronized operand now. if (!operand.isInvalid()) operand = Actions.ActOnObjCAtSynchronizedOperand(atLoc, operand.get()); // Parse the compound statement within a new scope. ParseScope bodyScope(this, Scope::DeclScope); StmtResult body(ParseCompoundStatementBody()); bodyScope.Exit(); // If there was a semantic or parse error earlier with the // operand, fail now. if (operand.isInvalid()) return StmtError(); if (body.isInvalid()) body = Actions.ActOnNullStmt(Tok.getLocation()); return Actions.ActOnObjCAtSynchronizedStmt(atLoc, operand.get(), body.get()); } /// objc-try-catch-statement: /// @try compound-statement objc-catch-list[opt] /// @try compound-statement objc-catch-list[opt] @finally compound-statement /// /// objc-catch-list: /// @catch ( parameter-declaration ) compound-statement /// objc-catch-list @catch ( catch-parameter-declaration ) compound-statement /// catch-parameter-declaration: /// parameter-declaration /// '...' [OBJC2] /// StmtResult Parser::ParseObjCTryStmt(SourceLocation atLoc) { bool catch_or_finally_seen = false; ConsumeToken(); // consume try if (Tok.isNot(tok::l_brace)) { Diag(Tok, diag::err_expected) << tok::l_brace; return StmtError(); } StmtVector CatchStmts; StmtResult FinallyStmt; ParseScope TryScope(this, Scope::DeclScope); StmtResult TryBody(ParseCompoundStatementBody()); TryScope.Exit(); if (TryBody.isInvalid()) TryBody = Actions.ActOnNullStmt(Tok.getLocation()); while (Tok.is(tok::at)) { // At this point, we need to lookahead to determine if this @ is the start // of an @catch or @finally. We don't want to consume the @ token if this // is an @try or @encode or something else. Token AfterAt = GetLookAheadToken(1); if (!AfterAt.isObjCAtKeyword(tok::objc_catch) && !AfterAt.isObjCAtKeyword(tok::objc_finally)) break; SourceLocation AtCatchFinallyLoc = ConsumeToken(); if (Tok.isObjCAtKeyword(tok::objc_catch)) { Decl *FirstPart = nullptr; ConsumeToken(); // consume catch if (Tok.is(tok::l_paren)) { ConsumeParen(); ParseScope CatchScope(this, Scope::DeclScope|Scope::AtCatchScope); if (Tok.isNot(tok::ellipsis)) { DeclSpec DS(AttrFactory); ParseDeclarationSpecifiers(DS); Declarator ParmDecl(DS, Declarator::ObjCCatchContext); ParseDeclarator(ParmDecl); // Inform the actions module about the declarator, so it // gets added to the current scope. FirstPart = Actions.ActOnObjCExceptionDecl(getCurScope(), ParmDecl); } else ConsumeToken(); // consume '...' SourceLocation RParenLoc; if (Tok.is(tok::r_paren)) RParenLoc = ConsumeParen(); else // Skip over garbage, until we get to ')'. Eat the ')'. SkipUntil(tok::r_paren, StopAtSemi); StmtResult CatchBody(true); if (Tok.is(tok::l_brace)) CatchBody = ParseCompoundStatementBody(); else Diag(Tok, diag::err_expected) << tok::l_brace; if (CatchBody.isInvalid()) CatchBody = Actions.ActOnNullStmt(Tok.getLocation()); StmtResult Catch = Actions.ActOnObjCAtCatchStmt(AtCatchFinallyLoc, RParenLoc, FirstPart, CatchBody.get()); if (!Catch.isInvalid()) CatchStmts.push_back(Catch.get()); } else { Diag(AtCatchFinallyLoc, diag::err_expected_lparen_after) << "@catch clause"; return StmtError(); } catch_or_finally_seen = true; } else { assert(Tok.isObjCAtKeyword(tok::objc_finally) && "Lookahead confused?"); ConsumeToken(); // consume finally ParseScope FinallyScope(this, Scope::DeclScope); StmtResult FinallyBody(true); if (Tok.is(tok::l_brace)) FinallyBody = ParseCompoundStatementBody(); else Diag(Tok, diag::err_expected) << tok::l_brace; if (FinallyBody.isInvalid()) FinallyBody = Actions.ActOnNullStmt(Tok.getLocation()); FinallyStmt = Actions.ActOnObjCAtFinallyStmt(AtCatchFinallyLoc, FinallyBody.get()); catch_or_finally_seen = true; break; } } if (!catch_or_finally_seen) { Diag(atLoc, diag::err_missing_catch_finally); return StmtError(); } return Actions.ActOnObjCAtTryStmt(atLoc, TryBody.get(), CatchStmts, FinallyStmt.get()); } /// objc-autoreleasepool-statement: /// @autoreleasepool compound-statement /// StmtResult Parser::ParseObjCAutoreleasePoolStmt(SourceLocation atLoc) { ConsumeToken(); // consume autoreleasepool if (Tok.isNot(tok::l_brace)) { Diag(Tok, diag::err_expected) << tok::l_brace; return StmtError(); } // Enter a scope to hold everything within the compound stmt. Compound // statements can always hold declarations. ParseScope BodyScope(this, Scope::DeclScope); StmtResult AutoreleasePoolBody(ParseCompoundStatementBody()); BodyScope.Exit(); if (AutoreleasePoolBody.isInvalid()) AutoreleasePoolBody = Actions.ActOnNullStmt(Tok.getLocation()); return Actions.ActOnObjCAutoreleasePoolStmt(atLoc, AutoreleasePoolBody.get()); } /// StashAwayMethodOrFunctionBodyTokens - Consume the tokens and store them /// for later parsing. void Parser::StashAwayMethodOrFunctionBodyTokens(Decl *MDecl) { LexedMethod* LM = new LexedMethod(this, MDecl); CurParsedObjCImpl->LateParsedObjCMethods.push_back(LM); CachedTokens &Toks = LM->Toks; // Begin by storing the '{' or 'try' or ':' token. Toks.push_back(Tok); if (Tok.is(tok::kw_try)) { ConsumeToken(); if (Tok.is(tok::colon)) { Toks.push_back(Tok); ConsumeToken(); while (Tok.isNot(tok::l_brace)) { ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false); ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); } } Toks.push_back(Tok); // also store '{' } else if (Tok.is(tok::colon)) { ConsumeToken(); while (Tok.isNot(tok::l_brace)) { ConsumeAndStoreUntil(tok::l_paren, Toks, /*StopAtSemi=*/false); ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); } Toks.push_back(Tok); // also store '{' } ConsumeBrace(); // Consume everything up to (and including) the matching right brace. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); while (Tok.is(tok::kw_catch)) { ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); } } /// objc-method-def: objc-method-proto ';'[opt] '{' body '}' /// Decl *Parser::ParseObjCMethodDefinition() { Decl *MDecl = ParseObjCMethodPrototype(); PrettyDeclStackTraceEntry CrashInfo(Actions, MDecl, Tok.getLocation(), "parsing Objective-C method"); // parse optional ';' if (Tok.is(tok::semi)) { if (CurParsedObjCImpl) { Diag(Tok, diag::warn_semicolon_before_method_body) << FixItHint::CreateRemoval(Tok.getLocation()); } ConsumeToken(); } // We should have an opening brace now. if (Tok.isNot(tok::l_brace)) { Diag(Tok, diag::err_expected_method_body); // Skip over garbage, until we get to '{'. Don't eat the '{'. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); // If we didn't find the '{', bail out. if (Tok.isNot(tok::l_brace)) return nullptr; } if (!MDecl) { ConsumeBrace(); SkipUntil(tok::r_brace); return nullptr; } // Allow the rest of sema to find private method decl implementations. Actions.AddAnyMethodToGlobalPool(MDecl); assert (CurParsedObjCImpl && "ParseObjCMethodDefinition - Method out of @implementation"); // Consume the tokens and store them for later parsing. StashAwayMethodOrFunctionBodyTokens(MDecl); return MDecl; } StmtResult Parser::ParseObjCAtStatement(SourceLocation AtLoc) { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCAtStatement(getCurScope()); cutOffParsing(); return StmtError(); } if (Tok.isObjCAtKeyword(tok::objc_try)) return ParseObjCTryStmt(AtLoc); if (Tok.isObjCAtKeyword(tok::objc_throw)) return ParseObjCThrowStmt(AtLoc); if (Tok.isObjCAtKeyword(tok::objc_synchronized)) return ParseObjCSynchronizedStmt(AtLoc); if (Tok.isObjCAtKeyword(tok::objc_autoreleasepool)) return ParseObjCAutoreleasePoolStmt(AtLoc); if (Tok.isObjCAtKeyword(tok::objc_import) && getLangOpts().DebuggerSupport) { SkipUntil(tok::semi); return Actions.ActOnNullStmt(Tok.getLocation()); } ExprResult Res(ParseExpressionWithLeadingAt(AtLoc)); if (Res.isInvalid()) { // If the expression is invalid, skip ahead to the next semicolon. Not // doing this opens us up to the possibility of infinite loops if // ParseExpression does not consume any tokens. SkipUntil(tok::semi); return StmtError(); } // Otherwise, eat the semicolon. ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); return Actions.ActOnExprStmt(Res); } ExprResult Parser::ParseObjCAtExpression(SourceLocation AtLoc) { switch (Tok.getKind()) { case tok::code_completion: Actions.CodeCompleteObjCAtExpression(getCurScope()); cutOffParsing(); return ExprError(); case tok::minus: case tok::plus: { tok::TokenKind Kind = Tok.getKind(); SourceLocation OpLoc = ConsumeToken(); if (!Tok.is(tok::numeric_constant)) { const char *Symbol = nullptr; switch (Kind) { case tok::minus: Symbol = "-"; break; case tok::plus: Symbol = "+"; break; default: llvm_unreachable("missing unary operator case"); } Diag(Tok, diag::err_nsnumber_nonliteral_unary) << Symbol; return ExprError(); } ExprResult Lit(Actions.ActOnNumericConstant(Tok)); if (Lit.isInvalid()) { return Lit; } ConsumeToken(); // Consume the literal token. Lit = Actions.ActOnUnaryOp(getCurScope(), OpLoc, Kind, Lit.get()); if (Lit.isInvalid()) return Lit; return ParsePostfixExpressionSuffix( Actions.BuildObjCNumericLiteral(AtLoc, Lit.get())); } case tok::string_literal: // primary-expression: string-literal case tok::wide_string_literal: return ParsePostfixExpressionSuffix(ParseObjCStringLiteral(AtLoc)); case tok::char_constant: return ParsePostfixExpressionSuffix(ParseObjCCharacterLiteral(AtLoc)); case tok::numeric_constant: return ParsePostfixExpressionSuffix(ParseObjCNumericLiteral(AtLoc)); case tok::kw_true: // Objective-C++, etc. case tok::kw___objc_yes: // c/c++/objc/objc++ __objc_yes return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, true)); case tok::kw_false: // Objective-C++, etc. case tok::kw___objc_no: // c/c++/objc/objc++ __objc_no return ParsePostfixExpressionSuffix(ParseObjCBooleanLiteral(AtLoc, false)); case tok::l_square: // Objective-C array literal return ParsePostfixExpressionSuffix(ParseObjCArrayLiteral(AtLoc)); case tok::l_brace: // Objective-C dictionary literal return ParsePostfixExpressionSuffix(ParseObjCDictionaryLiteral(AtLoc)); case tok::l_paren: // Objective-C boxed expression return ParsePostfixExpressionSuffix(ParseObjCBoxedExpr(AtLoc)); default: if (Tok.getIdentifierInfo() == nullptr) return ExprError(Diag(AtLoc, diag::err_unexpected_at)); switch (Tok.getIdentifierInfo()->getObjCKeywordID()) { case tok::objc_encode: return ParsePostfixExpressionSuffix(ParseObjCEncodeExpression(AtLoc)); case tok::objc_protocol: return ParsePostfixExpressionSuffix(ParseObjCProtocolExpression(AtLoc)); case tok::objc_selector: return ParsePostfixExpressionSuffix(ParseObjCSelectorExpression(AtLoc)); default: { const char *str = nullptr; if (GetLookAheadToken(1).is(tok::l_brace)) { char ch = Tok.getIdentifierInfo()->getNameStart()[0]; str = ch == 't' ? "try" : (ch == 'f' ? "finally" : (ch == 'a' ? "autoreleasepool" : nullptr)); } if (str) { SourceLocation kwLoc = Tok.getLocation(); return ExprError(Diag(AtLoc, diag::err_unexpected_at) << FixItHint::CreateReplacement(kwLoc, str)); } else return ExprError(Diag(AtLoc, diag::err_unexpected_at)); } } } } /// \brief Parse the receiver of an Objective-C++ message send. /// /// This routine parses the receiver of a message send in /// Objective-C++ either as a type or as an expression. Note that this /// routine must not be called to parse a send to 'super', since it /// has no way to return such a result. /// /// \param IsExpr Whether the receiver was parsed as an expression. /// /// \param TypeOrExpr If the receiver was parsed as an expression (\c /// IsExpr is true), the parsed expression. If the receiver was parsed /// as a type (\c IsExpr is false), the parsed type. /// /// \returns True if an error occurred during parsing or semantic /// analysis, in which case the arguments do not have valid /// values. Otherwise, returns false for a successful parse. /// /// objc-receiver: [C++] /// 'super' [not parsed here] /// expression /// simple-type-specifier /// typename-specifier bool Parser::ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr) { InMessageExpressionRAIIObject InMessage(*this, true); if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_typename, tok::annot_cxxscope)) TryAnnotateTypeOrScopeToken(); if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) { // objc-receiver: // expression // Make sure any typos in the receiver are corrected or diagnosed, so that // proper recovery can happen. FIXME: Perhaps filter the corrected expr to // only the things that are valid ObjC receivers? ExprResult Receiver = Actions.CorrectDelayedTyposInExpr(ParseExpression()); if (Receiver.isInvalid()) return true; IsExpr = true; TypeOrExpr = Receiver.get(); return false; } // objc-receiver: // typename-specifier // simple-type-specifier // expression (that starts with one of the above) DeclSpec DS(AttrFactory); ParseCXXSimpleTypeSpecifier(DS); if (Tok.is(tok::l_paren)) { // If we see an opening parentheses at this point, we are // actually parsing an expression that starts with a // function-style cast, e.g., // // postfix-expression: // simple-type-specifier ( expression-list [opt] ) // typename-specifier ( expression-list [opt] ) // // Parse the remainder of this case, then the (optional) // postfix-expression suffix, followed by the (optional) // right-hand side of the binary expression. We have an // instance method. ExprResult Receiver = ParseCXXTypeConstructExpression(DS); if (!Receiver.isInvalid()) Receiver = ParsePostfixExpressionSuffix(Receiver.get()); if (!Receiver.isInvalid()) Receiver = ParseRHSOfBinaryExpression(Receiver.get(), prec::Comma); if (Receiver.isInvalid()) return true; IsExpr = true; TypeOrExpr = Receiver.get(); return false; } // We have a class message. Turn the simple-type-specifier or // typename-specifier we parsed into a type and parse the // remainder of the class message. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); TypeResult Type = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); if (Type.isInvalid()) return true; IsExpr = false; TypeOrExpr = Type.get().getAsOpaquePtr(); return false; } /// \brief Determine whether the parser is currently referring to a an /// Objective-C message send, using a simplified heuristic to avoid overhead. /// /// This routine will only return true for a subset of valid message-send /// expressions. bool Parser::isSimpleObjCMessageExpression() { assert(Tok.is(tok::l_square) && getLangOpts().ObjC1 && "Incorrect start for isSimpleObjCMessageExpression"); return GetLookAheadToken(1).is(tok::identifier) && GetLookAheadToken(2).is(tok::identifier); } bool Parser::isStartOfObjCClassMessageMissingOpenBracket() { if (!getLangOpts().ObjC1 || !NextToken().is(tok::identifier) || InMessageExpression) return false; ParsedType Type; if (Tok.is(tok::annot_typename)) Type = getTypeAnnotation(Tok); else if (Tok.is(tok::identifier)) Type = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope()); else return false; if (!Type.get().isNull() && Type.get()->isObjCObjectOrInterfaceType()) { const Token &AfterNext = GetLookAheadToken(2); if (AfterNext.isOneOf(tok::colon, tok::r_square)) { if (Tok.is(tok::identifier)) TryAnnotateTypeOrScopeToken(); return Tok.is(tok::annot_typename); } } return false; } /// objc-message-expr: /// '[' objc-receiver objc-message-args ']' /// /// objc-receiver: [C] /// 'super' /// expression /// class-name /// type-name /// ExprResult Parser::ParseObjCMessageExpression() { assert(Tok.is(tok::l_square) && "'[' expected"); SourceLocation LBracLoc = ConsumeBracket(); // consume '[' if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCMessageReceiver(getCurScope()); cutOffParsing(); return ExprError(); } InMessageExpressionRAIIObject InMessage(*this, true); if (getLangOpts().CPlusPlus) { // We completely separate the C and C++ cases because C++ requires // more complicated (read: slower) parsing. // Handle send to super. // FIXME: This doesn't benefit from the same typo-correction we // get in Objective-C. if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope()) return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), ParsedType(), nullptr); // Parse the receiver, which is either a type or an expression. bool IsExpr; void *TypeOrExpr = nullptr; if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) { SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } if (IsExpr) return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), ParsedType(), static_cast<Expr*>(TypeOrExpr)); return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), ParsedType::getFromOpaquePtr(TypeOrExpr), nullptr); } if (Tok.is(tok::identifier)) { IdentifierInfo *Name = Tok.getIdentifierInfo(); SourceLocation NameLoc = Tok.getLocation(); ParsedType ReceiverType; switch (Actions.getObjCMessageKind(getCurScope(), Name, NameLoc, Name == Ident_super, NextToken().is(tok::period), ReceiverType)) { case Sema::ObjCSuperMessage: return ParseObjCMessageExpressionBody(LBracLoc, ConsumeToken(), ParsedType(), nullptr); case Sema::ObjCClassMessage: if (!ReceiverType) { SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } ConsumeToken(); // the type name // Parse type arguments and protocol qualifiers. if (Tok.is(tok::less)) { SourceLocation NewEndLoc; TypeResult NewReceiverType = parseObjCTypeArgsAndProtocolQualifiers(NameLoc, ReceiverType, /*consumeLastToken=*/true, NewEndLoc); if (!NewReceiverType.isUsable()) { SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } ReceiverType = NewReceiverType.get(); } return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), ReceiverType, nullptr); case Sema::ObjCInstanceMessage: // Fall through to parse an expression. break; } } // Otherwise, an arbitrary expression can be the receiver of a send. ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression()); if (Res.isInvalid()) { SkipUntil(tok::r_square, StopAtSemi); return Res; } return ParseObjCMessageExpressionBody(LBracLoc, SourceLocation(), ParsedType(), Res.get()); } /// \brief Parse the remainder of an Objective-C message following the /// '[' objc-receiver. /// /// This routine handles sends to super, class messages (sent to a /// class name), and instance messages (sent to an object), and the /// target is represented by \p SuperLoc, \p ReceiverType, or \p /// ReceiverExpr, respectively. Only one of these parameters may have /// a valid value. /// /// \param LBracLoc The location of the opening '['. /// /// \param SuperLoc If this is a send to 'super', the location of the /// 'super' keyword that indicates a send to the superclass. /// /// \param ReceiverType If this is a class message, the type of the /// class we are sending a message to. /// /// \param ReceiverExpr If this is an instance message, the expression /// used to compute the receiver object. /// /// objc-message-args: /// objc-selector /// objc-keywordarg-list /// /// objc-keywordarg-list: /// objc-keywordarg /// objc-keywordarg-list objc-keywordarg /// /// objc-keywordarg: /// selector-name[opt] ':' objc-keywordexpr /// /// objc-keywordexpr: /// nonempty-expr-list /// /// nonempty-expr-list: /// assignment-expression /// nonempty-expr-list , assignment-expression /// ExprResult Parser::ParseObjCMessageExpressionBody(SourceLocation LBracLoc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr) { InMessageExpressionRAIIObject InMessage(*this, true); if (Tok.is(tok::code_completion)) { if (SuperLoc.isValid()) Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, None, false); else if (ReceiverType) Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, None, false); else Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, None, false); cutOffParsing(); return ExprError(); } // Parse objc-selector SourceLocation Loc; IdentifierInfo *selIdent = ParseObjCSelectorPiece(Loc); SmallVector<IdentifierInfo *, 12> KeyIdents; SmallVector<SourceLocation, 12> KeyLocs; ExprVector KeyExprs; if (Tok.is(tok::colon)) { while (1) { // Each iteration parses a single keyword argument. KeyIdents.push_back(selIdent); KeyLocs.push_back(Loc); if (ExpectAndConsume(tok::colon)) { // We must manually skip to a ']', otherwise the expression skipper will // stop at the ']' when it skips to the ';'. We want it to skip beyond // the enclosing expression. SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } /// Parse the expression after ':' if (Tok.is(tok::code_completion)) { if (SuperLoc.isValid()) Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, KeyIdents, /*AtArgumentEpression=*/true); else if (ReceiverType) Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, KeyIdents, /*AtArgumentEpression=*/true); else Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, KeyIdents, /*AtArgumentEpression=*/true); cutOffParsing(); return ExprError(); } ExprResult Expr; if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); Expr = ParseBraceInitializer(); } else Expr = ParseAssignmentExpression(); ExprResult Res(Expr); if (Res.isInvalid()) { // We must manually skip to a ']', otherwise the expression skipper will // stop at the ']' when it skips to the ';'. We want it to skip beyond // the enclosing expression. SkipUntil(tok::r_square, StopAtSemi); return Res; } // We have a valid expression. KeyExprs.push_back(Res.get()); // Code completion after each argument. if (Tok.is(tok::code_completion)) { if (SuperLoc.isValid()) Actions.CodeCompleteObjCSuperMessage(getCurScope(), SuperLoc, KeyIdents, /*AtArgumentEpression=*/false); else if (ReceiverType) Actions.CodeCompleteObjCClassMessage(getCurScope(), ReceiverType, KeyIdents, /*AtArgumentEpression=*/false); else Actions.CodeCompleteObjCInstanceMessage(getCurScope(), ReceiverExpr, KeyIdents, /*AtArgumentEpression=*/false); cutOffParsing(); return ExprError(); } // Check for another keyword selector. selIdent = ParseObjCSelectorPiece(Loc); if (!selIdent && Tok.isNot(tok::colon)) break; // We have a selector or a colon, continue parsing. } // Parse the, optional, argument list, comma separated. while (Tok.is(tok::comma)) { SourceLocation commaLoc = ConsumeToken(); // Eat the ','. /// Parse the expression after ',' ExprResult Res(ParseAssignmentExpression()); if (Tok.is(tok::colon)) Res = Actions.CorrectDelayedTyposInExpr(Res); if (Res.isInvalid()) { if (Tok.is(tok::colon)) { Diag(commaLoc, diag::note_extra_comma_message_arg) << FixItHint::CreateRemoval(commaLoc); } // We must manually skip to a ']', otherwise the expression skipper will // stop at the ']' when it skips to the ';'. We want it to skip beyond // the enclosing expression. SkipUntil(tok::r_square, StopAtSemi); return Res; } // We have a valid expression. KeyExprs.push_back(Res.get()); } } else if (!selIdent) { Diag(Tok, diag::err_expected) << tok::identifier; // missing selector name. // We must manually skip to a ']', otherwise the expression skipper will // stop at the ']' when it skips to the ';'. We want it to skip beyond // the enclosing expression. SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } if (Tok.isNot(tok::r_square)) { Diag(Tok, diag::err_expected) << (Tok.is(tok::identifier) ? tok::colon : tok::r_square); // We must manually skip to a ']', otherwise the expression skipper will // stop at the ']' when it skips to the ';'. We want it to skip beyond // the enclosing expression. SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } SourceLocation RBracLoc = ConsumeBracket(); // consume ']' unsigned nKeys = KeyIdents.size(); if (nKeys == 0) { KeyIdents.push_back(selIdent); KeyLocs.push_back(Loc); } Selector Sel = PP.getSelectorTable().getSelector(nKeys, &KeyIdents[0]); if (SuperLoc.isValid()) return Actions.ActOnSuperMessage(getCurScope(), SuperLoc, Sel, LBracLoc, KeyLocs, RBracLoc, KeyExprs); else if (ReceiverType) return Actions.ActOnClassMessage(getCurScope(), ReceiverType, Sel, LBracLoc, KeyLocs, RBracLoc, KeyExprs); return Actions.ActOnInstanceMessage(getCurScope(), ReceiverExpr, Sel, LBracLoc, KeyLocs, RBracLoc, KeyExprs); } ExprResult Parser::ParseObjCStringLiteral(SourceLocation AtLoc) { ExprResult Res(ParseStringLiteralExpression()); if (Res.isInvalid()) return Res; // @"foo" @"bar" is a valid concatenated string. Eat any subsequent string // expressions. At this point, we know that the only valid thing that starts // with '@' is an @"". SmallVector<SourceLocation, 4> AtLocs; ExprVector AtStrings; AtLocs.push_back(AtLoc); AtStrings.push_back(Res.get()); while (Tok.is(tok::at)) { AtLocs.push_back(ConsumeToken()); // eat the @. // Invalid unless there is a string literal. if (!isTokenStringLiteral()) return ExprError(Diag(Tok, diag::err_objc_concat_string)); ExprResult Lit(ParseStringLiteralExpression()); if (Lit.isInvalid()) return Lit; AtStrings.push_back(Lit.get()); } return Actions.ParseObjCStringLiteral(&AtLocs[0], AtStrings.data(), AtStrings.size()); } /// ParseObjCBooleanLiteral - /// objc-scalar-literal : '@' boolean-keyword /// ; /// boolean-keyword: 'true' | 'false' | '__objc_yes' | '__objc_no' /// ; ExprResult Parser::ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue) { SourceLocation EndLoc = ConsumeToken(); // consume the keyword. return Actions.ActOnObjCBoolLiteral(AtLoc, EndLoc, ArgValue); } /// ParseObjCCharacterLiteral - /// objc-scalar-literal : '@' character-literal /// ; ExprResult Parser::ParseObjCCharacterLiteral(SourceLocation AtLoc) { ExprResult Lit(Actions.ActOnCharacterConstant(Tok)); if (Lit.isInvalid()) { return Lit; } ConsumeToken(); // Consume the literal token. return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()); } /// ParseObjCNumericLiteral - /// objc-scalar-literal : '@' scalar-literal /// ; /// scalar-literal : | numeric-constant /* any numeric constant. */ /// ; ExprResult Parser::ParseObjCNumericLiteral(SourceLocation AtLoc) { ExprResult Lit(Actions.ActOnNumericConstant(Tok)); if (Lit.isInvalid()) { return Lit; } ConsumeToken(); // Consume the literal token. return Actions.BuildObjCNumericLiteral(AtLoc, Lit.get()); } /// ParseObjCBoxedExpr - /// objc-box-expression: /// @( assignment-expression ) ExprResult Parser::ParseObjCBoxedExpr(SourceLocation AtLoc) { if (Tok.isNot(tok::l_paren)) return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@"); BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); ExprResult ValueExpr(ParseAssignmentExpression()); if (T.consumeClose()) return ExprError(); if (ValueExpr.isInvalid()) return ExprError(); // Wrap the sub-expression in a parenthesized expression, to distinguish // a boxed expression from a literal. SourceLocation LPLoc = T.getOpenLocation(), RPLoc = T.getCloseLocation(); ValueExpr = Actions.ActOnParenExpr(LPLoc, RPLoc, ValueExpr.get()); return Actions.BuildObjCBoxedExpr(SourceRange(AtLoc, RPLoc), ValueExpr.get()); } ExprResult Parser::ParseObjCArrayLiteral(SourceLocation AtLoc) { ExprVector ElementExprs; // array elements. ConsumeBracket(); // consume the l_square. while (Tok.isNot(tok::r_square)) { // Parse list of array element expressions (all must be id types). ExprResult Res(ParseAssignmentExpression()); if (Res.isInvalid()) { // We must manually skip to a ']', otherwise the expression skipper will // stop at the ']' when it skips to the ';'. We want it to skip beyond // the enclosing expression. SkipUntil(tok::r_square, StopAtSemi); return Res; } // Parse the ellipsis that indicates a pack expansion. if (Tok.is(tok::ellipsis)) Res = Actions.ActOnPackExpansion(Res.get(), ConsumeToken()); if (Res.isInvalid()) return true; ElementExprs.push_back(Res.get()); if (Tok.is(tok::comma)) ConsumeToken(); // Eat the ','. else if (Tok.isNot(tok::r_square)) return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_square << tok::comma); } SourceLocation EndLoc = ConsumeBracket(); // location of ']' MultiExprArg Args(ElementExprs); return Actions.BuildObjCArrayLiteral(SourceRange(AtLoc, EndLoc), Args); } ExprResult Parser::ParseObjCDictionaryLiteral(SourceLocation AtLoc) { SmallVector<ObjCDictionaryElement, 4> Elements; // dictionary elements. ConsumeBrace(); // consume the l_square. while (Tok.isNot(tok::r_brace)) { // Parse the comma separated key : value expressions. ExprResult KeyExpr; { ColonProtectionRAIIObject X(*this); KeyExpr = ParseAssignmentExpression(); if (KeyExpr.isInvalid()) { // We must manually skip to a '}', otherwise the expression skipper will // stop at the '}' when it skips to the ';'. We want it to skip beyond // the enclosing expression. SkipUntil(tok::r_brace, StopAtSemi); return KeyExpr; } } if (ExpectAndConsume(tok::colon)) { SkipUntil(tok::r_brace, StopAtSemi); return ExprError(); } ExprResult ValueExpr(ParseAssignmentExpression()); if (ValueExpr.isInvalid()) { // We must manually skip to a '}', otherwise the expression skipper will // stop at the '}' when it skips to the ';'. We want it to skip beyond // the enclosing expression. SkipUntil(tok::r_brace, StopAtSemi); return ValueExpr; } // Parse the ellipsis that designates this as a pack expansion. SourceLocation EllipsisLoc; if (getLangOpts().CPlusPlus) TryConsumeToken(tok::ellipsis, EllipsisLoc); // We have a valid expression. Collect it in a vector so we can // build the argument list. ObjCDictionaryElement Element = { KeyExpr.get(), ValueExpr.get(), EllipsisLoc, None }; Elements.push_back(Element); if (!TryConsumeToken(tok::comma) && Tok.isNot(tok::r_brace)) return ExprError(Diag(Tok, diag::err_expected_either) << tok::r_brace << tok::comma); } SourceLocation EndLoc = ConsumeBrace(); // Create the ObjCDictionaryLiteral. return Actions.BuildObjCDictionaryLiteral(SourceRange(AtLoc, EndLoc), Elements.data(), Elements.size()); } /// objc-encode-expression: /// \@encode ( type-name ) ExprResult Parser::ParseObjCEncodeExpression(SourceLocation AtLoc) { assert(Tok.isObjCAtKeyword(tok::objc_encode) && "Not an @encode expression!"); SourceLocation EncLoc = ConsumeToken(); if (Tok.isNot(tok::l_paren)) return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@encode"); BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); TypeResult Ty = ParseTypeName(); T.consumeClose(); if (Ty.isInvalid()) return ExprError(); return Actions.ParseObjCEncodeExpression(AtLoc, EncLoc, T.getOpenLocation(), Ty.get(), T.getCloseLocation()); } /// objc-protocol-expression /// \@protocol ( protocol-name ) ExprResult Parser::ParseObjCProtocolExpression(SourceLocation AtLoc) { SourceLocation ProtoLoc = ConsumeToken(); if (Tok.isNot(tok::l_paren)) return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@protocol"); BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); if (Tok.isNot(tok::identifier)) return ExprError(Diag(Tok, diag::err_expected) << tok::identifier); IdentifierInfo *protocolId = Tok.getIdentifierInfo(); SourceLocation ProtoIdLoc = ConsumeToken(); T.consumeClose(); return Actions.ParseObjCProtocolExpression(protocolId, AtLoc, ProtoLoc, T.getOpenLocation(), ProtoIdLoc, T.getCloseLocation()); } /// objc-selector-expression /// @selector '(' '('[opt] objc-keyword-selector ')'[opt] ')' ExprResult Parser::ParseObjCSelectorExpression(SourceLocation AtLoc) { SourceLocation SelectorLoc = ConsumeToken(); if (Tok.isNot(tok::l_paren)) return ExprError(Diag(Tok, diag::err_expected_lparen_after) << "@selector"); SmallVector<IdentifierInfo *, 12> KeyIdents; SourceLocation sLoc; BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); bool HasOptionalParen = Tok.is(tok::l_paren); if (HasOptionalParen) ConsumeParen(); if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); cutOffParsing(); return ExprError(); } IdentifierInfo *SelIdent = ParseObjCSelectorPiece(sLoc); if (!SelIdent && // missing selector name. Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) return ExprError(Diag(Tok, diag::err_expected) << tok::identifier); KeyIdents.push_back(SelIdent); unsigned nColons = 0; if (Tok.isNot(tok::r_paren)) { while (1) { if (TryConsumeToken(tok::coloncolon)) { // Handle :: in C++. ++nColons; KeyIdents.push_back(nullptr); } else if (ExpectAndConsume(tok::colon)) // Otherwise expect ':'. return ExprError(); ++nColons; if (Tok.is(tok::r_paren)) break; if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCSelector(getCurScope(), KeyIdents); cutOffParsing(); return ExprError(); } // Check for another keyword selector. SourceLocation Loc; SelIdent = ParseObjCSelectorPiece(Loc); KeyIdents.push_back(SelIdent); if (!SelIdent && Tok.isNot(tok::colon) && Tok.isNot(tok::coloncolon)) break; } } if (HasOptionalParen && Tok.is(tok::r_paren)) ConsumeParen(); // ')' T.consumeClose(); Selector Sel = PP.getSelectorTable().getSelector(nColons, &KeyIdents[0]); return Actions.ParseObjCSelectorExpression(Sel, AtLoc, SelectorLoc, T.getOpenLocation(), T.getCloseLocation(), !HasOptionalParen); } void Parser::ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod) { // MCDecl might be null due to error in method or c-function prototype, etc. Decl *MCDecl = LM.D; bool skip = MCDecl && ((parseMethod && !Actions.isObjCMethodDecl(MCDecl)) || (!parseMethod && Actions.isObjCMethodDecl(MCDecl))); if (skip) return; // Save the current token position. SourceLocation OrigLoc = Tok.getLocation(); assert(!LM.Toks.empty() && "ParseLexedObjCMethodDef - Empty body!"); // Append the current token at the end of the new token stream so that it // doesn't get lost. LM.Toks.push_back(Tok); PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false); // Consume the previously pushed token. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); assert(Tok.isOneOf(tok::l_brace, tok::kw_try, tok::colon) && "Inline objective-c method not starting with '{' or 'try' or ':'"); // Enter a scope for the method or c-function body. ParseScope BodyScope(this, parseMethod ? Scope::ObjCMethodScope|Scope::FnScope|Scope::DeclScope : Scope::FnScope|Scope::DeclScope); // Tell the actions module that we have entered a method or c-function definition // with the specified Declarator for the method/function. if (parseMethod) Actions.ActOnStartOfObjCMethodDef(getCurScope(), MCDecl); else Actions.ActOnStartOfFunctionDef(getCurScope(), MCDecl); if (Tok.is(tok::kw_try)) ParseFunctionTryBlock(MCDecl, BodyScope); else { if (Tok.is(tok::colon)) ParseConstructorInitializer(MCDecl); ParseFunctionStatementBody(MCDecl, BodyScope); } if (Tok.getLocation() != OrigLoc) { // Due to parsing error, we either went over the cached tokens or // there are still cached tokens left. If it's the latter case skip the // leftover tokens. // Since this is an uncommon situation that should be avoided, use the // expensive isBeforeInTranslationUnit call. if (PP.getSourceManager().isBeforeInTranslationUnit(Tok.getLocation(), OrigLoc)) while (Tok.getLocation() != OrigLoc && Tok.isNot(tok::eof)) ConsumeAnyToken(); } return; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseAST.cpp
//===--- ParseAST.cpp - Provide the clang::ParseAST method ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the clang::ParseAST method. // //===----------------------------------------------------------------------===// #include "clang/Parse/ParseAST.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/Stmt.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Sema/CodeCompleteConsumer.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/Sema.h" #include "clang/Sema/SemaConsumer.h" #include "clang/Sema/SemaHLSL.h" // HLSL Change #include "llvm/Support/CrashRecoveryContext.h" #include "llvm/Support/TimeProfiler.h" #include <cstdio> #include <memory> using namespace clang; namespace { /// If a crash happens while the parser is active, an entry is printed for it. class PrettyStackTraceParserEntry : public llvm::PrettyStackTraceEntry { const Parser &P; public: PrettyStackTraceParserEntry(const Parser &p) : P(p) {} void print(raw_ostream &OS) const override; }; /// If a crash happens while the parser is active, print out a line indicating /// what the current token is. void PrettyStackTraceParserEntry::print(raw_ostream &OS) const { const Token &Tok = P.getCurToken(); if (Tok.is(tok::eof)) { OS << "<eof> parser at end of file\n"; return; } if (Tok.getLocation().isInvalid()) { OS << "<unknown> parser at unknown location\n"; return; } const Preprocessor &PP = P.getPreprocessor(); Tok.getLocation().print(OS, PP.getSourceManager()); if (Tok.isAnnotation()) { OS << ": at annotation token\n"; } else { // Do the equivalent of PP.getSpelling(Tok) except for the parts that would // allocate memory. bool Invalid = false; const SourceManager &SM = P.getPreprocessor().getSourceManager(); unsigned Length = Tok.getLength(); const char *Spelling = SM.getCharacterData(Tok.getLocation(), &Invalid); if (Invalid) { OS << ": unknown current parser token\n"; return; } OS << ": current parser token '" << StringRef(Spelling, Length) << "'\n"; } } } // namespace //===----------------------------------------------------------------------===// // Public interface to the file //===----------------------------------------------------------------------===// /// ParseAST - Parse the entire file specified, notifying the ASTConsumer as /// the file is parsed. This inserts the parsed decls into the translation unit /// held by Ctx. /// void clang::ParseAST(Preprocessor &PP, ASTConsumer *Consumer, ASTContext &Ctx, bool PrintStats, TranslationUnitKind TUKind, CodeCompleteConsumer *CompletionConsumer, bool SkipFunctionBodies) { std::unique_ptr<Sema> S( new Sema(PP, Ctx, *Consumer, TUKind, CompletionConsumer)); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(S.get()); ParseAST(*S.get(), PrintStats, SkipFunctionBodies); } void clang::ParseAST(Sema &S, bool PrintStats, bool SkipFunctionBodies) { // HLSL Change - Support hierarchial time tracing. llvm::TimeTraceScope TimeScope("Frontend", StringRef("")); // Collect global stats on Decls/Stmts (until we have a module streamer). if (PrintStats) { Decl::EnableStatistics(); Stmt::EnableStatistics(); } // Also turn on collection of stats inside of the Sema object. bool OldCollectStats = PrintStats; std::swap(OldCollectStats, S.CollectStats); ASTConsumer *Consumer = &S.getASTConsumer(); std::unique_ptr<Parser> ParseOP( new Parser(S.getPreprocessor(), S, SkipFunctionBodies)); Parser &P = *ParseOP.get(); PrettyStackTraceParserEntry CrashInfo(P); // Recover resources if we crash before exiting this method. llvm::CrashRecoveryContextCleanupRegistrar<Parser> CleanupParser(ParseOP.get()); S.getPreprocessor().EnterMainSourceFile(); P.Initialize(); // C11 6.9p1 says translation units must have at least one top-level // declaration. C++ doesn't have this restriction. We also don't want to // complain if we have a precompiled header, although technically if the PCH // is empty we should still emit the (pedantic) diagnostic. Parser::DeclGroupPtrTy ADecl; ExternalASTSource *External = S.getASTContext().getExternalSource(); if (External) External->StartTranslationUnit(Consumer); if (!S.getDiagnostics().hasUnrecoverableErrorOccurred()) { // HLSL Change: Skip if fatal error already occurred if (P.ParseTopLevelDecl(ADecl)) { if (!External && !S.getLangOpts().CPlusPlus) P.Diag(diag::ext_empty_translation_unit); } else { do { // If we got a null return and something *was* parsed, ignore it. This // is due to a top-level semicolon, an action override, or a parse error // skipping something. if (ADecl && !Consumer->HandleTopLevelDecl(ADecl.get())) return; } while (!P.ParseTopLevelDecl(ADecl)); } } // HLSL Change: Skip if fatal error already occurred // Process any TopLevelDecls generated by #pragma weak. for (Decl *D : S.WeakTopLevelDecls()) Consumer->HandleTopLevelDecl(DeclGroupRef(D)); // HLSL Change Starts // Provide the opportunity to generate translation-unit level validation // errors in the front-end, without relying on code generation being // available. hlsl::DiagnoseTranslationUnit(&S); // HLSL Change Ends Consumer->HandleTranslationUnit(S.getASTContext()); std::swap(OldCollectStats, S.CollectStats); if (PrintStats) { llvm::errs() << "\nSTATISTICS:\n"; P.getActions().PrintStats(); S.getASTContext().PrintStats(); Decl::PrintStats(); Stmt::PrintStats(); Consumer->PrintStats(); } }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseDecl.cpp
//===--- ParseDecl.cpp - Declaration Parsing ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Declaration portions of the Parser interfaces. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "RAIIObjectsForParser.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclTemplate.h" #include "clang/Basic/AddressSpaces.h" #include "clang/Basic/Attributes.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/TargetInfo.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/PrettyDeclStackTrace.h" #include "clang/Sema/Scope.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringSwitch.h" #include "dxc/Support/Global.h" // HLSL Change #include "clang/Sema/SemaHLSL.h" // HLSL Change #include "clang/AST/UnresolvedSet.h" // HLSL Change #include "dxc/DXIL/DxilShaderModel.h" // HLSL Change #include "dxc/DXIL/DxilConstants.h" // HLSL Change using namespace clang; //===----------------------------------------------------------------------===// // C99 6.7: Declarations. //===----------------------------------------------------------------------===// /// ParseTypeName /// type-name: [C99 6.7.6] /// specifier-qualifier-list abstract-declarator[opt] /// /// Called type-id in C++. TypeResult Parser::ParseTypeName(SourceRange *Range, Declarator::TheContext Context, AccessSpecifier AS, Decl **OwnedType, ParsedAttributes *Attrs) { DeclSpecContext DSC = getDeclSpecContextFromDeclaratorContext(Context); if (DSC == DSC_normal) DSC = DSC_type_specifier; // Parse the common declaration-specifiers piece. DeclSpec DS(AttrFactory); if (Attrs) DS.addAttributes(Attrs->getList()); ParseSpecifierQualifierList(DS, AS, DSC); if (OwnedType) *OwnedType = DS.isTypeSpecOwned() ? DS.getRepAsDecl() : nullptr; // Parse the abstract-declarator, if present. Declarator DeclaratorInfo(DS, Context); ParseDeclarator(DeclaratorInfo); if (Range) *Range = DeclaratorInfo.getSourceRange(); if (DeclaratorInfo.isInvalidType()) return true; return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); } /// isAttributeLateParsed - Return true if the attribute has arguments that /// require late parsing. static bool isAttributeLateParsed(const IdentifierInfo &II) { #define CLANG_ATTR_LATE_PARSED_LIST return llvm::StringSwitch<bool>(II.getName()) #include "clang/Parse/AttrParserStringSwitches.inc" .Default(false); #undef CLANG_ATTR_LATE_PARSED_LIST } /// ParseGNUAttributes - Parse a non-empty attributes list. /// /// [GNU] attributes: /// attribute /// attributes attribute /// /// [GNU] attribute: /// '__attribute__' '(' '(' attribute-list ')' ')' /// /// [GNU] attribute-list: /// attrib /// attribute_list ',' attrib /// /// [GNU] attrib: /// empty /// attrib-name /// attrib-name '(' identifier ')' /// attrib-name '(' identifier ',' nonempty-expr-list ')' /// attrib-name '(' argument-expression-list [C99 6.5.2] ')' /// /// [GNU] attrib-name: /// identifier /// typespec /// typequal /// storageclass /// /// Whether an attribute takes an 'identifier' is determined by the /// attrib-name. GCC's behavior here is not worth imitating: /// /// * In C mode, if the attribute argument list starts with an identifier /// followed by a ',' or an ')', and the identifier doesn't resolve to /// a type, it is parsed as an identifier. If the attribute actually /// wanted an expression, it's out of luck (but it turns out that no /// attributes work that way, because C constant expressions are very /// limited). /// * In C++ mode, if the attribute argument list starts with an identifier, /// and the attribute *wants* an identifier, it is parsed as an identifier. /// At block scope, any additional tokens between the identifier and the /// ',' or ')' are ignored, otherwise they produce a parse error. /// /// We follow the C++ model, but don't allow junk after the identifier. void Parser::ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc, LateParsedAttrList *LateAttrs, Declarator *D) { assert(Tok.is(tok::kw___attribute) && "Not a GNU attribute list!"); while (Tok.is(tok::kw___attribute)) { ConsumeToken(); if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "attribute")) { SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ; return; } if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "(")) { SkipUntil(tok::r_paren, StopAtSemi); // skip until ) or ; return; } // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok.getLocation(), diag::err_hlsl_unsupported_attributes); SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); goto AfterAttributeParsing; } // HLSL Change Stops // Parse the attribute-list. e.g. __attribute__(( weak, alias("__f") )) while (true) { // Allow empty/non-empty attributes. ((__vector_size__(16),,,,)) if (TryConsumeToken(tok::comma)) continue; // Expect an identifier or declaration specifier (const, int, etc.) if (Tok.isAnnotation()) break; IdentifierInfo *AttrName = Tok.getIdentifierInfo(); if (!AttrName) break; SourceLocation AttrNameLoc = ConsumeToken(); if (Tok.isNot(tok::l_paren)) { attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, AttributeList::AS_GNU); continue; } // Handle "parameterized" attributes if (!LateAttrs || !isAttributeLateParsed(*AttrName)) { ParseGNUAttributeArgs(AttrName, AttrNameLoc, attrs, endLoc, nullptr, SourceLocation(), AttributeList::AS_GNU, D); continue; } // Handle attributes with arguments that require late parsing. LateParsedAttribute *LA = new LateParsedAttribute(this, *AttrName, AttrNameLoc); LateAttrs->push_back(LA); // Attributes in a class are parsed at the end of the class, along // with other late-parsed declarations. if (!ClassStack.empty() && !LateAttrs->parseSoon()) getCurrentClass().LateParsedDeclarations.push_back(LA); // consume everything up to and including the matching right parens ConsumeAndStoreUntil(tok::r_paren, LA->Toks, true, false); Token Eof; Eof.startToken(); Eof.setLocation(Tok.getLocation()); LA->Toks.push_back(Eof); } AfterAttributeParsing: // HLSL Change - skip attribute parsing if (ExpectAndConsume(tok::r_paren)) SkipUntil(tok::r_paren, StopAtSemi); SourceLocation Loc = Tok.getLocation(); if (ExpectAndConsume(tok::r_paren)) SkipUntil(tok::r_paren, StopAtSemi); if (endLoc) *endLoc = Loc; } } // HLSL Change Starts: Implementation for Semantic, Register, packoffset semantics. static void ParseRegisterNumberForHLSL(const StringRef name, char *registerType, unsigned *registerNumber, unsigned *diagId) { DXASSERT_NOMSG(registerType != nullptr); DXASSERT_NOMSG(registerNumber != nullptr); DXASSERT_NOMSG(diagId != nullptr); char firstLetter = name[0]; if (firstLetter >= 'A' && firstLetter <= 'Z') firstLetter += 'a' - 'A'; StringRef validExplicitRegisterTypes("bcistu"); if (validExplicitRegisterTypes.find(firstLetter) == StringRef::npos) { *diagId = diag::err_hlsl_unsupported_register_type; *registerType = 0; *registerNumber = 0; return; } *registerType = name[0]; // It's valid to omit the register number. if (name.size() > 1) { StringRef numName = name.substr(1); uint32_t num; errno = 0; if (numName.getAsInteger(10, num)) { *diagId = diag::err_hlsl_unsupported_register_number; return; } *registerNumber = num; } else { *registerNumber = 0; } *diagId = 0; } static void ParsePackSubcomponent(const StringRef name, unsigned* subcomponent, unsigned* diagId) { DXASSERT_NOMSG(subcomponent != nullptr); DXASSERT_NOMSG(diagId != nullptr); char registerType; ParseRegisterNumberForHLSL(name, &registerType, subcomponent, diagId); if (registerType != 'c' && registerType != 'C') { *diagId = diag::err_hlsl_unsupported_register_type; return; } } static void ParsePackComponent( const StringRef name, hlsl::ConstantPacking* cp, unsigned* diagId) { DXASSERT(name.size(), "otherwise an empty string was parsed as an identifier"); *diagId = 0; if (name.size() != 1) { *diagId = diag::err_hlsl_unsupported_packoffset_component; return; } switch (name[0]) { case 'r': case 'x': cp->ComponentOffset = 0; break; case 'g': case 'y': cp->ComponentOffset = 1; break; case 'b': case 'z': cp->ComponentOffset = 2; break; case 'a': case 'w': cp->ComponentOffset = 3; break; default: *diagId = diag::err_hlsl_unsupported_packoffset_component; break; } } static bool IsShaderProfileShort(const StringRef profile) { // Look for vs, ps, gs, hs, cs. if (profile.size() != 2) return false; if (profile[1] != 's') { return false; } char profileChar = profile[0]; return profileChar == 'v' || profileChar == 'p' || profileChar == 'g' || profileChar == 'g' || profileChar == 'c'; } static bool IsShaderProfileLike(const StringRef profile) { bool foundUnderscore = false; bool foundDigit = false; bool foundLetter = false; for (auto ch : profile) { if ('0' <= ch && ch <= '9') foundDigit = true; else if ('a' <= ch && ch <= 'z') foundLetter = true; else if (ch == '_') foundUnderscore = true; else return false; } return foundUnderscore && foundDigit && foundLetter; } static void ParseSpaceForHLSL(const StringRef name, uint32_t *spaceValue, unsigned *diagId) { DXASSERT_NOMSG(spaceValue != nullptr); DXASSERT_NOMSG(diagId != nullptr); *diagId = 0; *spaceValue = 0; if (!name.substr(0, sizeof("space")-1).equals("space")) { *diagId = diag::err_hlsl_expected_space; return; } // Otherwise, strncmp above would have been != 0. assert(name.size() >= strlen("space")); StringRef numName = name.substr(sizeof("space")-1); // Disallow missing space names. if (numName.getAsInteger(10, *spaceValue)) { *diagId = diag::err_hlsl_unsupported_space_number; return; } } bool Parser::MaybeParseHLSLAttributes(std::vector<hlsl::UnusualAnnotation *> &target) { if (!getLangOpts().HLSL) { return false; } ASTContext& context = getActions().getASTContext(); while (1) { if (!Tok.is(tok::colon)) { return false; } bool identifierIsPayloadAnnotation = false; if (NextToken().is(tok::identifier)) { StringRef identifier = NextToken().getIdentifierInfo()->getName(); identifierIsPayloadAnnotation = identifier == "read" || identifier == "write"; } if (identifierIsPayloadAnnotation) { hlsl::PayloadAccessAnnotation mod; if (NextToken().getIdentifierInfo()->getName() == "read") mod.qualifier = hlsl::DXIL::PayloadAccessQualifier::Read; else mod.qualifier = hlsl::DXIL::PayloadAccessQualifier::Write; // : read/write ( shader stage *[,shader stage]) ConsumeToken(); // consume the colon. mod.Loc = Tok.getLocation(); ConsumeToken(); // consume the read/write identifier if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "payload access qualifier")) { return true; } while(Tok.is(tok::identifier)) { hlsl::DXIL::PayloadAccessShaderStage stage = hlsl::DXIL::PayloadAccessShaderStage::Invalid; StringRef shaderStage = Tok.getIdentifierInfo()->getName(); if (shaderStage != "caller" && shaderStage != "anyhit" && shaderStage != "closesthit" && shaderStage != "miss") { Diag(Tok.getLocation(), diag::err_hlsl_payload_access_qualifier_unsupported_shader) << shaderStage; return true; } if (shaderStage == "caller") { stage = hlsl::DXIL::PayloadAccessShaderStage::Caller; } else if (shaderStage == "closesthit") { stage = hlsl::DXIL::PayloadAccessShaderStage::Closesthit; } else if (shaderStage == "miss") { stage = hlsl::DXIL::PayloadAccessShaderStage::Miss; } else if (shaderStage == "anyhit") { stage = hlsl::DXIL::PayloadAccessShaderStage::Anyhit; } mod.ShaderStages.push_back(stage); ConsumeToken(); // consume shader type if (Tok.is(tok::comma)) // check if we have a list of shader types ConsumeToken(); } while (Tok.is(tok::identifier)); if (ExpectAndConsume(tok::r_paren, diag::err_expected_rparen_after, "payload access qualifier")) { return true; } if (mod.ShaderStages.empty()) mod.qualifier = hlsl::DXIL::PayloadAccessQualifier::NoAccess; target.push_back(new (context) hlsl::PayloadAccessAnnotation(mod)); }else if (NextToken().is(tok::kw_register)) { hlsl::RegisterAssignment r; // : register ([shader_profile], Type#[subcomponent] [,spaceX]) ConsumeToken(); // consume colon. r.Loc = Tok.getLocation(); ConsumeToken(); // consume kw_register. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "register")) { return true; } if (!Tok.is(tok::identifier)) { Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; SkipUntil(tok::r_paren, StopAtSemi); // skip through ) return true; } StringRef identifierText = Tok.getIdentifierInfo()->getName(); if (IsShaderProfileLike(identifierText) || IsShaderProfileShort(identifierText)) { r.ShaderProfile = Tok.getIdentifierInfo()->getName(); ConsumeToken(); // consume shader model if (ExpectAndConsume(tok::comma, diag::err_expected)) { SkipUntil(tok::r_paren, StopAtSemi); // skip through ) return true; } } if (!Tok.is(tok::identifier)) { Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; SkipUntil(tok::r_paren, StopAtSemi); // skip through ) return true; } DXASSERT(Tok.is(tok::identifier), "otherwise previous code should have failed"); unsigned diagId; bool hasOnlySpace = false; identifierText = Tok.getIdentifierInfo()->getName(); if (identifierText.substr(0, sizeof("space")-1).equals("space")) { hasOnlySpace = true; } else { ParseRegisterNumberForHLSL( Tok.getIdentifierInfo()->getName(), &r.RegisterType, &r.RegisterNumber, &diagId); if (diagId == 0) { r.setIsValid(true); } else { r.setIsValid(false); Diag(Tok.getLocation(), diagId); } ConsumeToken(); // consume register (type'#') ExprResult subcomponentResult; if (Tok.is(tok::l_square)) { BalancedDelimiterTracker brackets(*this, tok::l_square); brackets.consumeOpen(); ExprResult result; if (Tok.isNot(tok::r_square)) { subcomponentResult = ParseConstantExpression(); r.IsValid = r.IsValid && !subcomponentResult.isInvalid(); Expr::EvalResult evalResult; if (!subcomponentResult.get()->EvaluateAsRValue(evalResult, context) || evalResult.hasSideEffects() || (!evalResult.Val.isInt() && !evalResult.Val.isFloat())) { Diag(Tok.getLocation(), diag::err_hlsl_unsupported_register_noninteger); r.setIsValid(false); } else { llvm::APSInt intResult; if (evalResult.Val.isFloat()) { bool isExact; // TODO: consider what to do when convertToInteger fails evalResult.Val.getFloat().convertToInteger(intResult, llvm::APFloat::roundingMode::rmTowardZero, &isExact); } else { DXASSERT(evalResult.Val.isInt(), "otherwise prior test in this function should have failed"); intResult = evalResult.Val.getInt(); } if (intResult.isNegative()) { Diag(Tok.getLocation(), diag::err_hlsl_unsupported_register_noninteger); r.setIsValid(false); } else { r.RegisterOffset = intResult.getLimitedValue(); } } } else { Diag(Tok.getLocation(), diag::err_expected_expression); r.setIsValid(false); } if (brackets.consumeClose()) { SkipUntil(tok::r_paren, StopAtSemi); // skip through ) return true; } } } if (hasOnlySpace) { uint32_t RegisterSpaceValue = 0; ParseSpaceForHLSL(Tok.getIdentifierInfo()->getName(), &RegisterSpaceValue, &diagId); if (diagId != 0) { Diag(Tok.getLocation(), diagId); r.setIsValid(false); } else { r.RegisterSpace = RegisterSpaceValue; r.setIsValid(true); } ConsumeToken(); // consume identifier } else { if (Tok.is(tok::comma)) { ConsumeToken(); // consume comma if (!Tok.is(tok::identifier)) { Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; SkipUntil(tok::r_paren, StopAtSemi); // skip through ) return true; } unsigned RegisterSpaceVal = 0; ParseSpaceForHLSL(Tok.getIdentifierInfo()->getName(), &RegisterSpaceVal, &diagId); if (diagId != 0) { Diag(Tok.getLocation(), diagId); r.setIsValid(false); } else { r.RegisterSpace = RegisterSpaceVal; } ConsumeToken(); // consume identifier } } if (ExpectAndConsume(tok::r_paren, diag::err_expected)) { SkipUntil(tok::r_paren, StopAtSemi); // skip through ) return true; } target.push_back(new (context) hlsl::RegisterAssignment(r)); } else if (NextToken().is(tok::kw_packoffset)) { // : packoffset(c[Subcomponent][.component]) hlsl::ConstantPacking cp; cp.setIsValid(true); ConsumeToken(); // consume colon. cp.Loc = Tok.getLocation(); ConsumeToken(); // consume kw_packoffset. if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "packoffset")) { SkipUntil(tok::r_paren, StopAtSemi); // skip through ) return true; } if (!Tok.is(tok::identifier)) { Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; SkipUntil(tok::r_paren, StopAtSemi); // skip through ) return true; } unsigned diagId; ParsePackSubcomponent(Tok.getIdentifierInfo()->getName(), &cp.Subcomponent, &diagId); if (diagId != 0) { cp.setIsValid(false); Diag(Tok.getLocation(), diagId); } ConsumeToken(); // consume subcomponent identifier. StringRef component; if (Tok.is(tok::period)) { ConsumeToken(); // consume period if (!Tok.is(tok::identifier)) { Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; SkipUntil(tok::r_paren, StopAtSemi); // skip through ) return true; } ParsePackComponent(Tok.getIdentifierInfo()->getName(), &cp, &diagId); if (diagId != 0) { cp.setIsValid(false); Diag(Tok.getLocation(), diagId); } ConsumeToken(); } if (ExpectAndConsume(tok::r_paren, diag::err_expected)) { SkipUntil(tok::r_paren, StopAtSemi); // skip through ) return true; } target.push_back(new (context) hlsl::ConstantPacking(cp)); } else if (NextToken().is(tok::identifier)) { // : SEMANTIC ConsumeToken(); // consume colon. StringRef semanticName = Tok.getIdentifierInfo()->getName(); if (semanticName.equals("VFACE")) { Diag(Tok.getLocation(), diag::warn_unsupported_target_attribute) << semanticName; } else { LookupResult R(Actions, Tok.getIdentifierInfo(), Tok.getLocation(), Sema::LookupOrdinaryName); if (Actions.LookupName(R, getCurScope())) { for (UnresolvedSetIterator I = R.begin(), E = R.end(); I != E; ++I) { NamedDecl *D = (*I)->getUnderlyingDecl(); if (D->getKind() == Decl::Kind::Var) { VarDecl *VD = static_cast<VarDecl *>(D); if (VD->getType()->isIntegralOrEnumerationType()) { Diag(Tok.getLocation(), diag::warn_hlsl_semantic_identifier_collision) << semanticName; break; } } } } } hlsl::SemanticDecl *pUA = new (context) hlsl::SemanticDecl(semanticName); pUA->Loc = Tok.getLocation(); Actions.DiagnoseSemanticDecl(pUA); ConsumeToken(); // consume semantic target.push_back(pUA); } else { // Not an HLSL semantic/register/packoffset construct. return false; } } return true; } // HLSL Change Ends /// \brief Normalizes an attribute name by dropping prefixed and suffixed __. static std::string normalizeAttrName(StringRef Name) { // HLSL Change: return std::string if (Name.size() >= 4 && Name.startswith("__") && Name.endswith("__")) Name = Name.drop_front(2).drop_back(2); return Name.lower(); // HLSL Change: make lowercase } /// \brief Determine whether the given attribute has an identifier argument. static bool attributeHasIdentifierArg(const IdentifierInfo &II) { #define CLANG_ATTR_IDENTIFIER_ARG_LIST return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) #include "clang/Parse/AttrParserStringSwitches.inc" .Default(false); #undef CLANG_ATTR_IDENTIFIER_ARG_LIST } /// \brief Determine whether the given attribute parses a type argument. static bool attributeIsTypeArgAttr(const IdentifierInfo &II) { #define CLANG_ATTR_TYPE_ARG_LIST return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) #include "clang/Parse/AttrParserStringSwitches.inc" .Default(false); #undef CLANG_ATTR_TYPE_ARG_LIST } /// \brief Determine whether the given attribute requires parsing its arguments /// in an unevaluated context or not. static bool attributeParsedArgsUnevaluated(const IdentifierInfo &II) { #define CLANG_ATTR_ARG_CONTEXT_LIST return llvm::StringSwitch<bool>(normalizeAttrName(II.getName())) #include "clang/Parse/AttrParserStringSwitches.inc" .Default(false); #undef CLANG_ATTR_ARG_CONTEXT_LIST } IdentifierLoc *Parser::ParseIdentifierLoc() { assert(Tok.is(tok::identifier) && "expected an identifier"); IdentifierLoc *IL = IdentifierLoc::create(Actions.Context, Tok.getLocation(), Tok.getIdentifierInfo()); ConsumeToken(); return IL; } void Parser::ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax) { assert(!getLangOpts().HLSL && "there are no attributes with types in HLSL"); // HLSL Change BalancedDelimiterTracker Parens(*this, tok::l_paren); Parens.consumeOpen(); TypeResult T; if (Tok.isNot(tok::r_paren)) T = ParseTypeName(); if (Parens.consumeClose()) return; if (T.isInvalid()) return; if (T.isUsable()) Attrs.addNewTypeAttr(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()), ScopeName, ScopeLoc, T.get(), Syntax); else Attrs.addNew(&AttrName, SourceRange(AttrNameLoc, Parens.getCloseLocation()), ScopeName, ScopeLoc, nullptr, 0, Syntax); } unsigned Parser::ParseAttributeArgsCommon( IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax) { // Ignore the left paren location for now. ConsumeParen(); ArgsVector ArgExprs; if (Tok.is(tok::identifier)) { // If this attribute wants an 'identifier' argument, make it so. bool IsIdentifierArg = attributeHasIdentifierArg(*AttrName); AttributeList::Kind AttrKind = AttributeList::getKind(AttrName, ScopeName, Syntax); // If we don't know how to parse this attribute, but this is the only // token in this argument, assume it's meant to be an identifier. if (AttrKind == AttributeList::UnknownAttribute || AttrKind == AttributeList::IgnoredAttribute) { const Token &Next = NextToken(); IsIdentifierArg = Next.isOneOf(tok::r_paren, tok::comma); } if (IsIdentifierArg) ArgExprs.push_back(ParseIdentifierLoc()); } if (!ArgExprs.empty() ? Tok.is(tok::comma) : Tok.isNot(tok::r_paren)) { // Eat the comma. if (!ArgExprs.empty()) ConsumeToken(); // Parse the non-empty comma-separated list of expressions. do { std::unique_ptr<EnterExpressionEvaluationContext> Unevaluated; if (attributeParsedArgsUnevaluated(*AttrName)) Unevaluated.reset( new EnterExpressionEvaluationContext(Actions, Sema::Unevaluated)); ExprResult ArgExpr( Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression())); if (ArgExpr.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return 0; } ArgExprs.push_back(ArgExpr.get()); // Eat the comma, move to the next argument } while (TryConsumeToken(tok::comma)); } SourceLocation RParen = Tok.getLocation(); if (!ExpectAndConsume(tok::r_paren)) { SourceLocation AttrLoc = ScopeLoc.isValid() ? ScopeLoc : AttrNameLoc; Attrs.addNew(AttrName, SourceRange(AttrLoc, RParen), ScopeName, ScopeLoc, ArgExprs.data(), ArgExprs.size(), Syntax); } if (EndLoc) *EndLoc = RParen; return static_cast<unsigned>(ArgExprs.size()); } /// Parse the arguments to a parameterized GNU attribute or /// a C++11 attribute in "gnu" namespace. void Parser::ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax, Declarator *D) { assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); AttributeList::Kind AttrKind = AttributeList::getKind(AttrName, ScopeName, Syntax); // HLSL Change Starts if (getLangOpts().HLSL) { switch (AttrKind) { case AttributeList::AT_HLSLAllowUAVCondition: case AttributeList::AT_HLSLBranch: case AttributeList::AT_HLSLCall: case AttributeList::AT_HLSLClipPlanes: case AttributeList::AT_HLSLDomain: case AttributeList::AT_HLSLEarlyDepthStencil: case AttributeList::AT_HLSLFastOpt: case AttributeList::AT_HLSLFlatten: case AttributeList::AT_HLSLForceCase: case AttributeList::AT_HLSLInstance: case AttributeList::AT_HLSLLoop: case AttributeList::AT_HLSLMaxTessFactor: case AttributeList::AT_HLSLNumThreads: case AttributeList::AT_HLSLShader: case AttributeList::AT_HLSLExperimental: case AttributeList::AT_HLSLNodeLaunch: case AttributeList::AT_HLSLNodeId: case AttributeList::AT_HLSLNodeIsProgramEntry: case AttributeList::AT_HLSLNodeLocalRootArgumentsTableIndex: case AttributeList::AT_HLSLNodeShareInputOf: case AttributeList::AT_HLSLNodeDispatchGrid: case AttributeList::AT_HLSLNodeMaxDispatchGrid: case AttributeList::AT_HLSLNodeMaxRecursionDepth: case AttributeList::AT_HLSLMaxRecordsSharedWith: case AttributeList::AT_HLSLMaxRecords: case AttributeList::AT_HLSLNodeArraySize: case AttributeList::AT_HLSLRootSignature: case AttributeList::AT_HLSLOutputControlPoints: case AttributeList::AT_HLSLOutputTopology: case AttributeList::AT_HLSLPartitioning: case AttributeList::AT_HLSLPatchConstantFunc: case AttributeList::AT_HLSLMaxVertexCount: case AttributeList::AT_HLSLUnroll: case AttributeList::AT_HLSLWaveSize: case AttributeList::AT_NoInline: // The following are not accepted in [attribute(param)] syntax: // case AttributeList::AT_HLSLCentroid: // case AttributeList::AT_HLSLGroupShared: // case AttributeList::AT_HLSLIn: // case AttributeList::AT_HLSLInOut: // case AttributeList::AT_HLSLLinear: // case AttributeList::AT_HLSLCenter: // case AttributeList::AT_HLSLNoInterpolation: // case AttributeList::AT_HLSLNoPerspective: // case AttributeList::AT_HLSLOut: // case AttributeList::AT_HLSLPrecise: // case AttributeList::AT_HLSLSample: // case AttributeList::AT_HLSLSemantic: // case AttributeList::AT_HLSLShared: // case AttributeList::AT_HLSLUniform: // case AttributeList::AT_HLSLPoint: // case AttributeList::AT_HLSLLine: // case AttributeList::AT_HLSLLineAdj: // case AttributeList::AT_HLSLTriangle: // case AttributeList::AT_HLSLTriangleAdj: // case AttributeList::AT_HLSLIndices: // case AttributeList::AT_HLSLVertices: // case AttributeList::AT_HLSLPrimitives: // case AttributeList::AT_HLSLPayload: // case AttributeList::AT_HLSLAllowSparseNodes: goto GenericAttributeParse; default: Diag(AttrNameLoc, diag::warn_unknown_attribute_ignored) << AttrName; ConsumeParen(); BalancedDelimiterTracker tracker(*this, tok::l_paren); tracker.skipToEnd(); return; } } // HLSL Change Ends if (AttrKind == AttributeList::AT_Availability) { ParseAvailabilityAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, ScopeLoc, Syntax); return; } else if (AttrKind == AttributeList::AT_ObjCBridgeRelated) { ParseObjCBridgeRelatedAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, ScopeLoc, Syntax); return; } else if (AttrKind == AttributeList::AT_TypeTagForDatatype) { ParseTypeTagForDatatypeAttribute(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, ScopeLoc, Syntax); return; } else if (attributeIsTypeArgAttr(*AttrName)) { ParseAttributeWithTypeArg(*AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, ScopeLoc, Syntax); return; } // These may refer to the function arguments, but need to be parsed early to // participate in determining whether it's a redeclaration. { // HLSL Change - add a scope to this block. std::unique_ptr<ParseScope> PrototypeScope; if (normalizeAttrName(AttrName->getName()) == "enable_if" && D && D->isFunctionDeclarator()) { DeclaratorChunk::FunctionTypeInfo FTI = D->getFunctionTypeInfo(); PrototypeScope.reset(new ParseScope(this, Scope::FunctionPrototypeScope | Scope::FunctionDeclarationScope | Scope::DeclScope)); for (unsigned i = 0; i != FTI.NumParams; ++i) { ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); Actions.ActOnReenterCXXMethodParameter(getCurScope(), Param); } } } // HLSL Change - close scope to this block. GenericAttributeParse: // HLSL Change - add a location to begin HLSL attribute parsing ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, ScopeLoc, Syntax); } bool Parser::ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs) { assert(!getLangOpts().HLSL && "__declspec should be skipped in HLSL"); // HLSL Change // If the attribute isn't known, we will not attempt to parse any // arguments. if (!hasAttribute(AttrSyntax::Declspec, nullptr, AttrName, getTargetInfo().getTriple(), getLangOpts())) { // Eat the left paren, then skip to the ending right paren. ConsumeParen(); SkipUntil(tok::r_paren); return false; } SourceLocation OpenParenLoc = Tok.getLocation(); if (AttrName->getName() == "property") { // The property declspec is more complex in that it can take one or two // assignment expressions as a parameter, but the lhs of the assignment // must be named get or put. BalancedDelimiterTracker T(*this, tok::l_paren); T.expectAndConsume(diag::err_expected_lparen_after, AttrName->getNameStart(), tok::r_paren); enum AccessorKind { AK_Invalid = -1, AK_Put = 0, AK_Get = 1 // indices into AccessorNames }; IdentifierInfo *AccessorNames[] = {nullptr, nullptr}; bool HasInvalidAccessor = false; // Parse the accessor specifications. while (true) { // Stop if this doesn't look like an accessor spec. if (!Tok.is(tok::identifier)) { // If the user wrote a completely empty list, use a special diagnostic. if (Tok.is(tok::r_paren) && !HasInvalidAccessor && AccessorNames[AK_Put] == nullptr && AccessorNames[AK_Get] == nullptr) { Diag(AttrNameLoc, diag::err_ms_property_no_getter_or_putter); break; } Diag(Tok.getLocation(), diag::err_ms_property_unknown_accessor); break; } AccessorKind Kind; SourceLocation KindLoc = Tok.getLocation(); StringRef KindStr = Tok.getIdentifierInfo()->getName(); if (KindStr == "get") { Kind = AK_Get; } else if (KindStr == "put") { Kind = AK_Put; // Recover from the common mistake of using 'set' instead of 'put'. } else if (KindStr == "set") { Diag(KindLoc, diag::err_ms_property_has_set_accessor) << FixItHint::CreateReplacement(KindLoc, "put"); Kind = AK_Put; // Handle the mistake of forgetting the accessor kind by skipping // this accessor. } else if (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)) { Diag(KindLoc, diag::err_ms_property_missing_accessor_kind); ConsumeToken(); HasInvalidAccessor = true; goto next_property_accessor; // Otherwise, complain about the unknown accessor kind. } else { Diag(KindLoc, diag::err_ms_property_unknown_accessor); HasInvalidAccessor = true; Kind = AK_Invalid; // Try to keep parsing unless it doesn't look like an accessor spec. if (!NextToken().is(tok::equal)) break; } // Consume the identifier. ConsumeToken(); // Consume the '='. if (!TryConsumeToken(tok::equal)) { Diag(Tok.getLocation(), diag::err_ms_property_expected_equal) << KindStr; break; } // Expect the method name. if (!Tok.is(tok::identifier)) { Diag(Tok.getLocation(), diag::err_ms_property_expected_accessor_name); break; } if (Kind == AK_Invalid) { // Just drop invalid accessors. } else if (AccessorNames[Kind] != nullptr) { // Complain about the repeated accessor, ignore it, and keep parsing. Diag(KindLoc, diag::err_ms_property_duplicate_accessor) << KindStr; } else { AccessorNames[Kind] = Tok.getIdentifierInfo(); } ConsumeToken(); next_property_accessor: // Keep processing accessors until we run out. if (TryConsumeToken(tok::comma)) continue; // If we run into the ')', stop without consuming it. if (Tok.is(tok::r_paren)) break; Diag(Tok.getLocation(), diag::err_ms_property_expected_comma_or_rparen); break; } // Only add the property attribute if it was well-formed. if (!HasInvalidAccessor) Attrs.addNewPropertyAttr(AttrName, AttrNameLoc, nullptr, SourceLocation(), AccessorNames[AK_Get], AccessorNames[AK_Put], AttributeList::AS_Declspec); T.skipToEnd(); return !HasInvalidAccessor; } unsigned NumArgs = ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, nullptr, nullptr, SourceLocation(), AttributeList::AS_Declspec); // If this attribute's args were parsed, and it was expected to have // arguments but none were provided, emit a diagnostic. const AttributeList *Attr = Attrs.getList(); if (Attr && Attr->getMaxArgs() && !NumArgs) { Diag(OpenParenLoc, diag::err_attribute_requires_arguments) << AttrName; return false; } return true; } /// [MS] decl-specifier: /// __declspec ( extended-decl-modifier-seq ) /// /// [MS] extended-decl-modifier-seq: /// extended-decl-modifier[opt] /// extended-decl-modifier extended-decl-modifier-seq void Parser::ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End) { assert((getLangOpts().MicrosoftExt || getLangOpts().Borland || getLangOpts().CUDA) && "Incorrect language options for parsing __declspec"); assert(Tok.is(tok::kw___declspec) && "Not a declspec!"); while (Tok.is(tok::kw___declspec)) { SourceLocation prior = ConsumeToken(); // HLSL Change - capture prior location BalancedDelimiterTracker T(*this, tok::l_paren); if (T.expectAndConsume(diag::err_expected_lparen_after, "__declspec", tok::r_paren)) return; // HLSL Change Starts if (getLangOpts().HLSL) { Diag(prior, diag::err_hlsl_unsupported_construct) << "__declspec"; T.skipToEnd(); return; } // HLSL Change Ends // An empty declspec is perfectly legal and should not warn. Additionally, // you can specify multiple attributes per declspec. while (Tok.isNot(tok::r_paren)) { // Attribute not present. if (TryConsumeToken(tok::comma)) continue; // We expect either a well-known identifier or a generic string. Anything // else is a malformed declspec. bool IsString = Tok.getKind() == tok::string_literal; if (!IsString && Tok.getKind() != tok::identifier && Tok.getKind() != tok::kw_restrict) { Diag(Tok, diag::err_ms_declspec_type); T.skipToEnd(); return; } IdentifierInfo *AttrName; SourceLocation AttrNameLoc; if (IsString) { SmallString<8> StrBuffer; bool Invalid = false; StringRef Str = PP.getSpelling(Tok, StrBuffer, &Invalid); if (Invalid) { T.skipToEnd(); return; } AttrName = PP.getIdentifierInfo(Str); AttrNameLoc = ConsumeStringToken(); } else { AttrName = Tok.getIdentifierInfo(); AttrNameLoc = ConsumeToken(); } bool AttrHandled = false; // Parse attribute arguments. if (Tok.is(tok::l_paren)) AttrHandled = ParseMicrosoftDeclSpecArgs(AttrName, AttrNameLoc, Attrs); else if (AttrName->getName() == "property") // The property attribute must have an argument list. Diag(Tok.getLocation(), diag::err_expected_lparen_after) << AttrName->getName(); if (!AttrHandled) Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, AttributeList::AS_Declspec); } T.consumeClose(); if (End) *End = T.getCloseLocation(); } } void Parser::ParseMicrosoftTypeAttributes(ParsedAttributes &attrs) { // Treat these like attributes while (true) { switch (Tok.getKind()) { case tok::kw___fastcall: case tok::kw___stdcall: case tok::kw___thiscall: case tok::kw___cdecl: case tok::kw___vectorcall: case tok::kw___ptr64: case tok::kw___w64: case tok::kw___ptr32: case tok::kw___unaligned: case tok::kw___sptr: case tok::kw___uptr: { IdentifierInfo *AttrName = Tok.getIdentifierInfo(); SourceLocation AttrNameLoc = ConsumeToken(); // HLSL Change Starts if (getLangOpts().HLSL) { Diag(AttrNameLoc, diag::err_hlsl_unsupported_construct) << AttrName; break; } // HLSL Change Ends attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, AttributeList::AS_Keyword); break; } default: return; } } } void Parser::DiagnoseAndSkipExtendedMicrosoftTypeAttributes() { SourceLocation StartLoc = Tok.getLocation(); SourceLocation EndLoc = SkipExtendedMicrosoftTypeAttributes(); if (EndLoc.isValid()) { SourceRange Range(StartLoc, EndLoc); Diag(StartLoc, diag::warn_microsoft_qualifiers_ignored) << Range; } } SourceLocation Parser::SkipExtendedMicrosoftTypeAttributes() { SourceLocation EndLoc; while (true) { switch (Tok.getKind()) { case tok::kw_const: case tok::kw_volatile: case tok::kw___fastcall: case tok::kw___stdcall: case tok::kw___thiscall: case tok::kw___cdecl: case tok::kw___vectorcall: case tok::kw___ptr32: case tok::kw___ptr64: case tok::kw___w64: case tok::kw___unaligned: case tok::kw___sptr: case tok::kw___uptr: EndLoc = ConsumeToken(); break; default: return EndLoc; } } } void Parser::ParseBorlandTypeAttributes(ParsedAttributes &attrs) { assert(!getLangOpts().HLSL && "_pascal isn't a keyword in HLSL"); // HLSL Change // Treat these like attributes while (Tok.is(tok::kw___pascal)) { IdentifierInfo *AttrName = Tok.getIdentifierInfo(); SourceLocation AttrNameLoc = ConsumeToken(); attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, AttributeList::AS_Keyword); } } void Parser::ParseOpenCLAttributes(ParsedAttributes &attrs) { assert(!getLangOpts().HLSL && "_kernel isn't a keyword in HLSL"); // HLSL Change // Treat these like attributes while (Tok.is(tok::kw___kernel)) { IdentifierInfo *AttrName = Tok.getIdentifierInfo(); SourceLocation AttrNameLoc = ConsumeToken(); attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, AttributeList::AS_Keyword); } } void Parser::ParseOpenCLQualifiers(ParsedAttributes &Attrs) { assert(!getLangOpts().HLSL && "disabled path for HLSL"); // HLSL Change IdentifierInfo *AttrName = Tok.getIdentifierInfo(); SourceLocation AttrNameLoc = Tok.getLocation(); Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, AttributeList::AS_Keyword); } void Parser::ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs) { assert(!getLangOpts().HLSL && "disabled path for HLSL"); // HLSL Change // Treat these like attributes, even though they're type specifiers. while (true) { switch (Tok.getKind()) { case tok::kw__Nonnull: case tok::kw__Nullable: case tok::kw__Null_unspecified: { IdentifierInfo *AttrName = Tok.getIdentifierInfo(); SourceLocation AttrNameLoc = ConsumeToken(); if (!getLangOpts().ObjC1) Diag(AttrNameLoc, diag::ext_nullability) << AttrName; attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, AttributeList::AS_Keyword); break; } default: return; } } } static bool VersionNumberSeparator(const char Separator) { return (Separator == '.' || Separator == '_'); } /// \brief Parse a version number. /// /// version: /// simple-integer /// simple-integer ',' simple-integer /// simple-integer ',' simple-integer ',' simple-integer VersionTuple Parser::ParseVersionTuple(SourceRange &Range) { assert(!getLangOpts().HLSL && "version tuple parsing is part of the availability attribute, which isn't handled in HLSL"); // HLSL Change Range = Tok.getLocation(); if (!Tok.is(tok::numeric_constant)) { Diag(Tok, diag::err_expected_version); SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); return VersionTuple(); } // Parse the major (and possibly minor and subminor) versions, which // are stored in the numeric constant. We utilize a quirk of the // lexer, which is that it handles something like 1.2.3 as a single // numeric constant, rather than two separate tokens. SmallString<512> Buffer; Buffer.resize(Tok.getLength()+1); const char *ThisTokBegin = &Buffer[0]; // Get the spelling of the token, which eliminates trigraphs, etc. bool Invalid = false; unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid); if (Invalid) return VersionTuple(); // Parse the major version. unsigned AfterMajor = 0; unsigned Major = 0; while (AfterMajor < ActualLength && isDigit(ThisTokBegin[AfterMajor])) { Major = Major * 10 + ThisTokBegin[AfterMajor] - '0'; ++AfterMajor; } if (AfterMajor == 0) { Diag(Tok, diag::err_expected_version); SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); return VersionTuple(); } if (AfterMajor == ActualLength) { ConsumeToken(); // We only had a single version component. if (Major == 0) { Diag(Tok, diag::err_zero_version); return VersionTuple(); } return VersionTuple(Major); } const char AfterMajorSeparator = ThisTokBegin[AfterMajor]; if (!VersionNumberSeparator(AfterMajorSeparator) || (AfterMajor + 1 == ActualLength)) { Diag(Tok, diag::err_expected_version); SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); return VersionTuple(); } // Parse the minor version. unsigned AfterMinor = AfterMajor + 1; unsigned Minor = 0; while (AfterMinor < ActualLength && isDigit(ThisTokBegin[AfterMinor])) { Minor = Minor * 10 + ThisTokBegin[AfterMinor] - '0'; ++AfterMinor; } if (AfterMinor == ActualLength) { ConsumeToken(); // We had major.minor. if (Major == 0 && Minor == 0) { Diag(Tok, diag::err_zero_version); return VersionTuple(); } return VersionTuple(Major, Minor, (AfterMajorSeparator == '_')); } const char AfterMinorSeparator = ThisTokBegin[AfterMinor]; // If what follows is not a '.' or '_', we have a problem. if (!VersionNumberSeparator(AfterMinorSeparator)) { Diag(Tok, diag::err_expected_version); SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); return VersionTuple(); } // Warn if separators, be it '.' or '_', do not match. if (AfterMajorSeparator != AfterMinorSeparator) Diag(Tok, diag::warn_expected_consistent_version_separator); // Parse the subminor version. unsigned AfterSubminor = AfterMinor + 1; unsigned Subminor = 0; while (AfterSubminor < ActualLength && isDigit(ThisTokBegin[AfterSubminor])) { Subminor = Subminor * 10 + ThisTokBegin[AfterSubminor] - '0'; ++AfterSubminor; } if (AfterSubminor != ActualLength) { Diag(Tok, diag::err_expected_version); SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch | StopAtCodeCompletion); return VersionTuple(); } ConsumeToken(); return VersionTuple(Major, Minor, Subminor, (AfterMajorSeparator == '_')); } /// \brief Parse the contents of the "availability" attribute. /// /// availability-attribute: /// 'availability' '(' platform ',' version-arg-list, opt-message')' /// /// platform: /// identifier /// /// version-arg-list: /// version-arg /// version-arg ',' version-arg-list /// /// version-arg: /// 'introduced' '=' version /// 'deprecated' '=' version /// 'obsoleted' = version /// 'unavailable' /// opt-message: /// 'message' '=' <string> void Parser::ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax) { assert(!getLangOpts().HLSL && "availability attribute isn't handled in HLSL"); // HLSL Change enum { Introduced, Deprecated, Obsoleted, Unknown }; AvailabilityChange Changes[Unknown]; ExprResult MessageExpr; // Opening '('. BalancedDelimiterTracker T(*this, tok::l_paren); if (T.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_paren; return; } // Parse the platform name, if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_availability_expected_platform); SkipUntil(tok::r_paren, StopAtSemi); return; } IdentifierLoc *Platform = ParseIdentifierLoc(); // Parse the ',' following the platform name. if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::r_paren, StopAtSemi); return; } // If we haven't grabbed the pointers for the identifiers // "introduced", "deprecated", and "obsoleted", do so now. if (!Ident_introduced) { Ident_introduced = PP.getIdentifierInfo("introduced"); Ident_deprecated = PP.getIdentifierInfo("deprecated"); Ident_obsoleted = PP.getIdentifierInfo("obsoleted"); Ident_unavailable = PP.getIdentifierInfo("unavailable"); Ident_message = PP.getIdentifierInfo("message"); } // Parse the set of introductions/deprecations/removals. SourceLocation UnavailableLoc; do { if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_availability_expected_change); SkipUntil(tok::r_paren, StopAtSemi); return; } IdentifierInfo *Keyword = Tok.getIdentifierInfo(); SourceLocation KeywordLoc = ConsumeToken(); if (Keyword == Ident_unavailable) { if (UnavailableLoc.isValid()) { Diag(KeywordLoc, diag::err_availability_redundant) << Keyword << SourceRange(UnavailableLoc); } UnavailableLoc = KeywordLoc; continue; } if (Tok.isNot(tok::equal)) { Diag(Tok, diag::err_expected_after) << Keyword << tok::equal; SkipUntil(tok::r_paren, StopAtSemi); return; } ConsumeToken(); if (Keyword == Ident_message) { if (Tok.isNot(tok::string_literal)) { Diag(Tok, diag::err_expected_string_literal) << /*Source='availability attribute'*/2; SkipUntil(tok::r_paren, StopAtSemi); return; } MessageExpr = ParseStringLiteralExpression(); // Also reject wide string literals. if (StringLiteral *MessageStringLiteral = cast_or_null<StringLiteral>(MessageExpr.get())) { if (MessageStringLiteral->getCharByteWidth() != 1) { Diag(MessageStringLiteral->getSourceRange().getBegin(), diag::err_expected_string_literal) << /*Source='availability attribute'*/ 2; SkipUntil(tok::r_paren, StopAtSemi); return; } } break; } // Special handling of 'NA' only when applied to introduced or // deprecated. if ((Keyword == Ident_introduced || Keyword == Ident_deprecated) && Tok.is(tok::identifier)) { IdentifierInfo *NA = Tok.getIdentifierInfo(); if (NA->getName() == "NA") { ConsumeToken(); if (Keyword == Ident_introduced) UnavailableLoc = KeywordLoc; continue; } } SourceRange VersionRange; VersionTuple Version = ParseVersionTuple(VersionRange); if (Version.empty()) { SkipUntil(tok::r_paren, StopAtSemi); return; } unsigned Index; if (Keyword == Ident_introduced) Index = Introduced; else if (Keyword == Ident_deprecated) Index = Deprecated; else if (Keyword == Ident_obsoleted) Index = Obsoleted; else Index = Unknown; if (Index < Unknown) { if (!Changes[Index].KeywordLoc.isInvalid()) { Diag(KeywordLoc, diag::err_availability_redundant) << Keyword << SourceRange(Changes[Index].KeywordLoc, Changes[Index].VersionRange.getEnd()); } Changes[Index].KeywordLoc = KeywordLoc; Changes[Index].Version = Version; Changes[Index].VersionRange = VersionRange; } else { Diag(KeywordLoc, diag::err_availability_unknown_change) << Keyword << VersionRange; } } while (TryConsumeToken(tok::comma)); // Closing ')'. if (T.consumeClose()) return; if (endLoc) *endLoc = T.getCloseLocation(); // The 'unavailable' availability cannot be combined with any other // availability changes. Make sure that hasn't happened. if (UnavailableLoc.isValid()) { bool Complained = false; for (unsigned Index = Introduced; Index != Unknown; ++Index) { if (Changes[Index].KeywordLoc.isValid()) { if (!Complained) { Diag(UnavailableLoc, diag::warn_availability_and_unavailable) << SourceRange(Changes[Index].KeywordLoc, Changes[Index].VersionRange.getEnd()); Complained = true; } // Clear out the availability. Changes[Index] = AvailabilityChange(); } } } // Record this attribute attrs.addNew(&Availability, SourceRange(AvailabilityLoc, T.getCloseLocation()), ScopeName, ScopeLoc, Platform, Changes[Introduced], Changes[Deprecated], Changes[Obsoleted], UnavailableLoc, MessageExpr.get(), Syntax); } /// \brief Parse the contents of the "objc_bridge_related" attribute. /// objc_bridge_related '(' related_class ',' opt-class_method ',' opt-instance_method ')' /// related_class: /// Identifier /// /// opt-class_method: /// Identifier: | <empty> /// /// opt-instance_method: /// Identifier | <empty> /// void Parser::ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax) { // Opening '('. BalancedDelimiterTracker T(*this, tok::l_paren); if (T.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_paren; return; } // Parse the related class name. if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_objcbridge_related_expected_related_class); SkipUntil(tok::r_paren, StopAtSemi); return; } IdentifierLoc *RelatedClass = ParseIdentifierLoc(); if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::r_paren, StopAtSemi); return; } // Parse optional class method name. IdentifierLoc *ClassMethod = nullptr; if (Tok.is(tok::identifier)) { ClassMethod = ParseIdentifierLoc(); if (!TryConsumeToken(tok::colon)) { Diag(Tok, diag::err_objcbridge_related_selector_name); SkipUntil(tok::r_paren, StopAtSemi); return; } } if (!TryConsumeToken(tok::comma)) { if (Tok.is(tok::colon)) Diag(Tok, diag::err_objcbridge_related_selector_name); else Diag(Tok, diag::err_expected) << tok::comma; SkipUntil(tok::r_paren, StopAtSemi); return; } // Parse optional instance method name. IdentifierLoc *InstanceMethod = nullptr; if (Tok.is(tok::identifier)) InstanceMethod = ParseIdentifierLoc(); else if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected) << tok::r_paren; SkipUntil(tok::r_paren, StopAtSemi); return; } // Closing ')'. if (T.consumeClose()) return; if (endLoc) *endLoc = T.getCloseLocation(); // Record this attribute attrs.addNew(&ObjCBridgeRelated, SourceRange(ObjCBridgeRelatedLoc, T.getCloseLocation()), ScopeName, ScopeLoc, RelatedClass, ClassMethod, InstanceMethod, Syntax); } // Late Parsed Attributes: // See other examples of late parsing in lib/Parse/ParseCXXInlineMethods void Parser::LateParsedDeclaration::ParseLexedAttributes() {} void Parser::LateParsedClass::ParseLexedAttributes() { Self->ParseLexedAttributes(*Class); } void Parser::LateParsedAttribute::ParseLexedAttributes() { Self->ParseLexedAttribute(*this, true, false); } /// Wrapper class which calls ParseLexedAttribute, after setting up the /// scope appropriately. void Parser::ParseLexedAttributes(ParsingClass &Class) { // Deal with templates // FIXME: Test cases to make sure this does the right thing for templates. bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope); if (HasTemplateScope) Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); // Set or update the scope flags. bool AlreadyHasClassScope = Class.TopLevelClass; unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope; ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope); ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope); // Enter the scope of nested classes if (!AlreadyHasClassScope) Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); if (!Class.LateParsedDeclarations.empty()) { for (unsigned i = 0, ni = Class.LateParsedDeclarations.size(); i < ni; ++i){ Class.LateParsedDeclarations[i]->ParseLexedAttributes(); } } if (!AlreadyHasClassScope) Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); } /// \brief Parse all attributes in LAs, and attach them to Decl D. void Parser::ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition) { assert(LAs.parseSoon() && "Attribute list should be marked for immediate parsing."); for (unsigned i = 0, ni = LAs.size(); i < ni; ++i) { if (D) LAs[i]->addDecl(D); ParseLexedAttribute(*LAs[i], EnterScope, OnDefinition); delete LAs[i]; } LAs.clear(); } /// \brief Finish parsing an attribute for which parsing was delayed. /// This will be called at the end of parsing a class declaration /// for each LateParsedAttribute. We consume the saved tokens and /// create an attribute with the arguments filled in. We add this /// to the Attribute list for the decl. void Parser::ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition) { // HLSL Change Starts if (getLangOpts().HLSL) { assert(LA.Toks.empty() && "otherwise a late parse attribute was created in HLSL and code to skip this is missing"); return; } // HLSL Change Ends // Create a fake EOF so that attribute parsing won't go off the end of the // attribute. Token AttrEnd; AttrEnd.startToken(); AttrEnd.setKind(tok::eof); AttrEnd.setLocation(Tok.getLocation()); AttrEnd.setEofData(LA.Toks.data()); LA.Toks.push_back(AttrEnd); // Append the current token at the end of the new token stream so that it // doesn't get lost. LA.Toks.push_back(Tok); PP.EnterTokenStream(LA.Toks.data(), LA.Toks.size(), true, false); // Consume the previously pushed token. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); ParsedAttributes Attrs(AttrFactory); SourceLocation endLoc; if (LA.Decls.size() > 0) { Decl *D = LA.Decls[0]; NamedDecl *ND = dyn_cast<NamedDecl>(D); RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext()); // Allow 'this' within late-parsed attributes. Sema::CXXThisScopeRAII ThisScope(Actions, RD, /*TypeQuals=*/0, ND && ND->isCXXInstanceMember()); if (LA.Decls.size() == 1) { // If the Decl is templatized, add template parameters to scope. bool HasTemplateScope = EnterScope && D->isTemplateDecl(); ParseScope TempScope(this, Scope::TemplateParamScope, HasTemplateScope); if (HasTemplateScope) Actions.ActOnReenterTemplateScope(Actions.CurScope, D); // If the Decl is on a function, add function parameters to the scope. bool HasFunScope = EnterScope && D->isFunctionOrFunctionTemplate(); ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope, HasFunScope); if (HasFunScope) Actions.ActOnReenterFunctionContext(Actions.CurScope, D); ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc, nullptr, SourceLocation(), AttributeList::AS_GNU, nullptr); if (HasFunScope) { Actions.ActOnExitFunctionContext(); FnScope.Exit(); // Pop scope, and remove Decls from IdResolver } if (HasTemplateScope) { TempScope.Exit(); } } else { // If there are multiple decls, then the decl cannot be within the // function scope. ParseGNUAttributeArgs(&LA.AttrName, LA.AttrNameLoc, Attrs, &endLoc, nullptr, SourceLocation(), AttributeList::AS_GNU, nullptr); } } else { Diag(Tok, diag::warn_attribute_no_decl) << LA.AttrName.getName(); } const AttributeList *AL = Attrs.getList(); if (OnDefinition && AL && !AL->isCXX11Attribute() && AL->isKnownToGCC()) Diag(Tok, diag::warn_attribute_on_function_definition) << &LA.AttrName; for (unsigned i = 0, ni = LA.Decls.size(); i < ni; ++i) Actions.ActOnFinishDelayedAttribute(getCurScope(), LA.Decls[i], Attrs); // Due to a parsing error, we either went over the cached tokens or // there are still cached tokens left, so we skip the leftover tokens. while (Tok.isNot(tok::eof)) ConsumeAnyToken(); if (Tok.is(tok::eof) && Tok.getEofData() == AttrEnd.getEofData()) ConsumeAnyToken(); } void Parser::ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax) { assert(!getLangOpts().HLSL && "HLSL does not support attributes with types"); // HLSL Change assert(Tok.is(tok::l_paren) && "Attribute arg list not starting with '('"); BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; T.skipToEnd(); return; } IdentifierLoc *ArgumentKind = ParseIdentifierLoc(); if (ExpectAndConsume(tok::comma)) { T.skipToEnd(); return; } SourceRange MatchingCTypeRange; TypeResult MatchingCType = ParseTypeName(&MatchingCTypeRange); if (MatchingCType.isInvalid()) { T.skipToEnd(); return; } bool LayoutCompatible = false; bool MustBeNull = false; while (TryConsumeToken(tok::comma)) { if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; T.skipToEnd(); return; } IdentifierInfo *Flag = Tok.getIdentifierInfo(); if (Flag->isStr("layout_compatible")) LayoutCompatible = true; else if (Flag->isStr("must_be_null")) MustBeNull = true; else { Diag(Tok, diag::err_type_safety_unknown_flag) << Flag; T.skipToEnd(); return; } ConsumeToken(); // consume flag } if (!T.consumeClose()) { Attrs.addNewTypeTagForDatatype(&AttrName, AttrNameLoc, ScopeName, ScopeLoc, ArgumentKind, MatchingCType.get(), LayoutCompatible, MustBeNull, Syntax); } if (EndLoc) *EndLoc = T.getCloseLocation(); } /// DiagnoseProhibitedCXX11Attribute - We have found the opening square brackets /// of a C++11 attribute-specifier in a location where an attribute is not /// permitted. By C++11 [dcl.attr.grammar]p6, this is ill-formed. Diagnose this /// situation. /// /// \return \c true if we skipped an attribute-like chunk of tokens, \c false if /// this doesn't appear to actually be an attribute-specifier, and the caller /// should try to parse it. bool Parser::DiagnoseProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square)); switch (isCXX11AttributeSpecifier(/*Disambiguate*/true)) { case CAK_NotAttributeSpecifier: // No diagnostic: we're in Obj-C++11 and this is not actually an attribute. return false; case CAK_InvalidAttributeSpecifier: Diag(Tok.getLocation(), diag::err_l_square_l_square_not_attribute); return false; case CAK_AttributeSpecifier: // Parse and discard the attributes. SourceLocation BeginLoc = ConsumeBracket(); ConsumeBracket(); SkipUntil(tok::r_square); assert(Tok.is(tok::r_square) && "isCXX11AttributeSpecifier lied"); SourceLocation EndLoc = ConsumeBracket(); Diag(BeginLoc, diag::err_attributes_not_allowed) << SourceRange(BeginLoc, EndLoc); return true; } llvm_unreachable("All cases handled above."); } /// \brief We have found the opening square brackets of a C++11 /// attribute-specifier in a location where an attribute is not permitted, but /// we know where the attributes ought to be written. Parse them anyway, and /// provide a fixit moving them to the right place. void Parser::DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { assert((Tok.is(tok::l_square) && NextToken().is(tok::l_square)) || Tok.is(tok::kw_alignas)); // Consume the attributes. SourceLocation Loc = Tok.getLocation(); ParseCXX11Attributes(Attrs); CharSourceRange AttrRange(SourceRange(Loc, Attrs.Range.getEnd()), true); Diag(Loc, diag::err_attributes_not_allowed) << FixItHint::CreateInsertionFromRange(CorrectLocation, AttrRange) << FixItHint::CreateRemoval(AttrRange); } void Parser::DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs) { Diag(attrs.Range.getBegin(), diag::err_attributes_not_allowed) << attrs.Range; } void Parser::ProhibitCXX11Attributes(ParsedAttributesWithRange &attrs) { AttributeList *AttrList = attrs.getList(); while (AttrList) { if (AttrList->isCXX11Attribute()) { Diag(AttrList->getLoc(), diag::err_attribute_not_type_attr) << AttrList->getName(); AttrList->setInvalid(); } AttrList = AttrList->getNext(); } } // As an exception to the rule, __declspec(align(...)) before the // class-key affects the type instead of the variable. void Parser::handleDeclspecAlignBeforeClassKey(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK) { if (TUK == Sema::TUK_Reference) return; ParsedAttributes &PA = DS.getAttributes(); AttributeList *AL = PA.getList(); AttributeList *Prev = nullptr; while (AL) { AttributeList *Next = AL->getNext(); // We only consider attributes using the appropriate '__declspec' spelling, // this behavior doesn't extend to any other spellings. if (AL->getKind() == AttributeList::AT_Aligned && AL->isDeclspecAttribute()) { // Stitch the attribute into the tag's attribute list. AL->setNext(nullptr); Attrs.add(AL); // Remove the attribute from the variable's attribute list. if (Prev) { // Set the last variable attribute's next attribute to be the attribute // after the current one. Prev->setNext(Next); } else { // Removing the head of the list requires us to reset the head to the // next attribute. PA.set(Next); } } else { Prev = AL; } AL = Next; } } /// ParseDeclaration - Parse a full 'declaration', which consists of /// declaration-specifiers, some number of declarators, and a semicolon. /// 'Context' should be a Declarator::TheContext value. This returns the /// location of the semicolon in DeclEnd. /// /// declaration: [C99 6.7] /// block-declaration -> /// simple-declaration /// others [FIXME] /// [C++] template-declaration /// [C++] namespace-definition /// [C++] using-directive /// [C++] using-declaration /// [C++11/C11] static_assert-declaration /// others... [FIXME] /// Parser::DeclGroupPtrTy Parser::ParseDeclaration(unsigned Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs) { ParenBraceBracketBalancer BalancerRAIIObj(*this); // Must temporarily exit the objective-c container scope for // parsing c none objective-c decls. ObjCDeclContextSwitch ObjCDC(*this); Decl *SingleDecl = nullptr; Decl *OwnedType = nullptr; switch (Tok.getKind()) { case tok::kw_template: // HLSL Change Starts if (getLangOpts().HLSL && getLangOpts().HLSLVersion < hlsl::LangStd::v2021) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); SkipMalformedDecl(); return DeclGroupPtrTy(); } // HLSL Change Ends ProhibitAttributes(attrs); SingleDecl = ParseDeclarationStartingWithTemplate(Context, DeclEnd); break; case tok::kw_inline: // Could be the start of an inline namespace. Allowed as an ext in C++03. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_namespace) && !getLangOpts().HLSL) { // HLSL Change - disallowed in HLSL ProhibitAttributes(attrs); SourceLocation InlineLoc = ConsumeToken(); SingleDecl = ParseNamespace(Context, DeclEnd, InlineLoc); break; } return ParseSimpleDeclaration(Context, DeclEnd, attrs, true); // HLSL Change Starts case tok::kw_cbuffer: case tok::kw_tbuffer: SingleDecl = ParseCTBuffer(Context, DeclEnd, attrs); break; // HLSL Change Ends case tok::kw_namespace: ProhibitAttributes(attrs); SingleDecl = ParseNamespace(Context, DeclEnd); break; case tok::kw_using: SingleDecl = ParseUsingDirectiveOrDeclaration(Context, ParsedTemplateInfo(), DeclEnd, attrs, &OwnedType); break; case tok::kw_static_assert: case tok::kw__Static_assert: ProhibitAttributes(attrs); SingleDecl = ParseStaticAssertDeclaration(DeclEnd); break; default: return ParseSimpleDeclaration(Context, DeclEnd, attrs, true); } // This routine returns a DeclGroup, if the thing we parsed only contains a // single decl, convert it now. Alias declarations can also declare a type; // include that too if it is present. return Actions.ConvertDeclToDeclGroup(SingleDecl, OwnedType); } /// simple-declaration: [C99 6.7: declaration] [C++ 7p1: dcl.dcl] /// declaration-specifiers init-declarator-list[opt] ';' /// [C++11] attribute-specifier-seq decl-specifier-seq[opt] /// init-declarator-list ';' ///[C90/C++]init-declarator-list ';' [TODO] /// [OMP] threadprivate-directive [TODO] /// /// for-range-declaration: [C++11 6.5p1: stmt.ranged] /// attribute-specifier-seq[opt] type-specifier-seq declarator /// /// If RequireSemi is false, this does not check for a ';' at the end of the /// declaration. If it is true, it checks for and eats it. /// /// If FRI is non-null, we might be parsing a for-range-declaration instead /// of a simple-declaration. If we find that we are, we also parse the /// for-range-initializer, and place it here. Parser::DeclGroupPtrTy Parser::ParseSimpleDeclaration(unsigned Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &Attrs, bool RequireSemi, ForRangeInit *FRI) { // Parse the common declaration-specifiers piece. ParsingDeclSpec DS(*this); DeclSpecContext DSContext = getDeclSpecContextFromDeclaratorContext(Context); ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS_none, DSContext); // If we had a free-standing type definition with a missing semicolon, we // may get this far before the problem becomes obvious. if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(DS, AS_none, DSContext)) return DeclGroupPtrTy(); // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" // declaration-specifiers init-declarator-list[opt] ';' if (Tok.is(tok::semi)) { ProhibitAttributes(Attrs); DeclEnd = Tok.getLocation(); if (RequireSemi) ConsumeToken(); Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS); DS.complete(TheDecl); return Actions.ConvertDeclToDeclGroup(TheDecl); } DS.takeAttributesFrom(Attrs); return ParseDeclGroup(DS, Context, &DeclEnd, FRI); } /// Returns true if this might be the start of a declarator, or a common typo /// for a declarator. bool Parser::MightBeDeclarator(unsigned Context) { switch (Tok.getKind()) { case tok::annot_cxxscope: case tok::annot_template_id: case tok::caret: case tok::code_completion: case tok::coloncolon: case tok::ellipsis: case tok::kw___attribute: case tok::kw_operator: case tok::l_paren: case tok::star: return true; case tok::amp: case tok::ampamp: return getLangOpts().CPlusPlus && !getLangOpts().HLSL; // HLSL Change case tok::l_square: // Might be an attribute on an unnamed bit-field. return Context == Declarator::MemberContext && getLangOpts().CPlusPlus11 && NextToken().is(tok::l_square); case tok::colon: // Might be a typo for '::' or an unnamed bit-field. return Context == Declarator::MemberContext || getLangOpts().CPlusPlus; case tok::identifier: switch (NextToken().getKind()) { case tok::code_completion: case tok::coloncolon: case tok::comma: case tok::equal: case tok::equalequal: // Might be a typo for '='. case tok::kw_alignas: case tok::kw_asm: case tok::kw___attribute: case tok::l_brace: case tok::l_paren: case tok::l_square: case tok::less: case tok::r_brace: case tok::r_paren: case tok::r_square: case tok::semi: return true; case tok::colon: // At namespace scope, 'identifier:' is probably a typo for 'identifier::' // and in block scope it's probably a label. Inside a class definition, // this is a bit-field. return Context == Declarator::MemberContext || (getLangOpts().CPlusPlus && Context == Declarator::FileContext); case tok::identifier: // Possible virt-specifier. return getLangOpts().CPlusPlus11 && isCXX11VirtSpecifier(NextToken()); default: return false; } default: return false; } } /// Skip until we reach something which seems like a sensible place to pick /// up parsing after a malformed declaration. This will sometimes stop sooner /// than SkipUntil(tok::r_brace) would, but will never stop later. void Parser::SkipMalformedDecl() { while (true) { switch (Tok.getKind()) { case tok::l_brace: // Skip until matching }, then stop. We've probably skipped over // a malformed class or function definition or similar. ConsumeBrace(); SkipUntil(tok::r_brace); if (Tok.isOneOf(tok::comma, tok::l_brace, tok::kw_try)) { // This declaration isn't over yet. Keep skipping. continue; } TryConsumeToken(tok::semi); return; case tok::l_square: ConsumeBracket(); SkipUntil(tok::r_square); continue; case tok::l_paren: ConsumeParen(); SkipUntil(tok::r_paren); continue; case tok::r_brace: return; case tok::semi: ConsumeToken(); return; case tok::kw_inline: // 'inline namespace' at the start of a line is almost certainly // a good place to pick back up parsing, except in an Objective-C // @interface context. if (Tok.isAtStartOfLine() && NextToken().is(tok::kw_namespace) && (!ParsingInObjCContainer || CurParsedObjCImpl)) return; break; case tok::kw_namespace: // 'namespace' at the start of a line is almost certainly a good // place to pick back up parsing, except in an Objective-C // @interface context. if (Tok.isAtStartOfLine() && (!ParsingInObjCContainer || CurParsedObjCImpl)) return; break; case tok::at: // @end is very much like } in Objective-C contexts. if (getLangOpts().HLSL) break; // HLSL Change if (NextToken().isObjCAtKeyword(tok::objc_end) && ParsingInObjCContainer) return; break; case tok::minus: case tok::plus: // - and + probably start new method declarations in Objective-C contexts. if (getLangOpts().HLSL) break; // HLSL Change if (Tok.isAtStartOfLine() && ParsingInObjCContainer) return; break; case tok::eof: case tok::annot_module_begin: case tok::annot_module_end: case tok::annot_module_include: return; default: break; } ConsumeAnyToken(); } } /// ParseDeclGroup - Having concluded that this is either a function /// definition or a group of object declarations, actually parse the /// result. Parser::DeclGroupPtrTy Parser::ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context, SourceLocation *DeclEnd, ForRangeInit *FRI) { assert(FRI == nullptr || !getLangOpts().HLSL); // HLSL Change: HLSL does not support for (T t : ...) // Parse the first declarator. ParsingDeclarator D(*this, DS, static_cast<Declarator::TheContext>(Context)); ParseDeclarator(D); // Bail out if the first declarator didn't seem well-formed. if (!D.hasName() && !D.mayOmitIdentifier()) { SkipMalformedDecl(); return DeclGroupPtrTy(); } // HLSL Change Starts: change global variables that will be in constant buffer to be constant by default // Global variables that are groupshared, static, or typedef // will not be part of constant buffer and therefore should not be const by default. // global variable can be inside a global structure as a static member. // Check if the global is a static member and skip global const pass. // in backcompat mode, the check for global const is deferred to later stage in CGMSHLSLRuntime::FinishCodeGen() bool CheckGlobalConst = getLangOpts().HLSL && getLangOpts().EnableDX9CompatMode && getLangOpts().HLSLVersion <= hlsl::LangStd::v2016 ? false : true; if (NestedNameSpecifier *nameSpecifier = D.getCXXScopeSpec().getScopeRep()) { if (nameSpecifier->getKind() == NestedNameSpecifier::SpecifierKind::TypeSpec) { const Type *type = D.getCXXScopeSpec().getScopeRep()->getAsType(); if (type->getTypeClass() == Type::TypeClass::Record) { CXXRecordDecl *RD = type->getAsCXXRecordDecl(); for (auto it = RD->decls_begin(), itEnd = RD->decls_end(); it != itEnd; ++it) { if (const VarDecl *VD = dyn_cast<VarDecl>(*it)) { StringRef fieldName = VD->getName(); std::string declName = Actions.GetNameForDeclarator(D).getAsString(); if (fieldName.equals(declName) && VD->getStorageClass() == StorageClass::SC_Static) { CheckGlobalConst = false; const char *prevSpec = nullptr; unsigned int DiagID; DS.SetStorageClassSpec( Actions, DeclSpec::SCS::SCS_static, D.getDeclSpec().getLocStart(), prevSpec, DiagID, Actions.getASTContext().getPrintingPolicy()); break; } } } } } } if (getLangOpts().HLSL && !D.isFunctionDeclarator() && D.getContext() == Declarator::TheContext::FileContext && DS.getStorageClassSpec() != DeclSpec::SCS::SCS_static && DS.getStorageClassSpec() != DeclSpec::SCS::SCS_typedef && CheckGlobalConst ) { // Check whether or not there is a 'groupshared' attribute AttributeList *attrList = DS.getAttributes().getList(); bool isGroupShared = false; while (attrList) { if (attrList->getName()->getName().compare( StringRef(tok::getTokenName(tok::kw_groupshared))) == 0) { isGroupShared = true; break; } attrList = attrList->getNext(); } if (!isGroupShared) { // check whether or not the given data is the typename or primitive types if (DS.isTypeRep()) { QualType type = DS.getRepAsType().get(); // canonical types of HLSL Object types are not canonical for some // reason. other HLSL Object types of vector/matrix/array should be // treated as const. if (type.getCanonicalType().isCanonical() && IsTypeNumeric(&Actions, type)) { unsigned int diagID; const char *prevSpec; DS.SetTypeQual(DeclSpec::TQ_const, D.getDeclSpec().getLocStart(), prevSpec, diagID, getLangOpts()); } } else { // If not a typename, it is a basic type and should be treated as const. unsigned int diagID; const char *prevSpec; DS.SetTypeQual(DeclSpec::TQ_const, D.getDeclSpec().getLocStart(), prevSpec, diagID, getLangOpts()); } } } // HLSL Change Ends // Save late-parsed attributes for now; they need to be parsed in the // appropriate function scope after the function Decl has been constructed. // These will be parsed in ParseFunctionDefinition or ParseLexedAttrList. LateParsedAttrList LateParsedAttrs(true); if (D.isFunctionDeclarator()) { MaybeParseGNUAttributes(D, &LateParsedAttrs); // HLSL Change Starts: parse semantic after function declarator if (getLangOpts().HLSL) if (MaybeParseHLSLAttributes(D)) D.setInvalidType(); // HLSL Change Ends // The _Noreturn keyword can't appear here, unlike the GNU noreturn // attribute. If we find the keyword here, tell the user to put it // at the start instead. if (Tok.is(tok::kw__Noreturn)) { SourceLocation Loc = ConsumeToken(); const char *PrevSpec; unsigned DiagID; // We can offer a fixit if it's valid to mark this function as _Noreturn // and we don't have any other declarators in this declaration. bool Fixit = !DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID); MaybeParseGNUAttributes(D, &LateParsedAttrs); Fixit &= Tok.isOneOf(tok::semi, tok::l_brace, tok::kw_try); Diag(Loc, diag::err_c11_noreturn_misplaced) << (Fixit ? FixItHint::CreateRemoval(Loc) : FixItHint()) << (Fixit ? FixItHint::CreateInsertion(D.getLocStart(), "_Noreturn ") : FixItHint()); } } // Check to see if we have a function *definition* which must have a body. if (D.isFunctionDeclarator() && // Look at the next token to make sure that this isn't a function // declaration. We have to check this because __attribute__ might be the // start of a function definition in GCC-extended K&R C. !isDeclarationAfterDeclarator()) { // Function definitions are only allowed at file scope and in C++ classes. // The C++ inline method definition case is handled elsewhere, so we only // need to handle the file scope definition case. if (Context == Declarator::FileContext) { if (isStartOfFunctionDefinition(D)) { if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { Diag(Tok, diag::err_function_declared_typedef); // Recover by treating the 'typedef' as spurious. DS.ClearStorageClassSpecs(); } Decl *TheDecl = ParseFunctionDefinition(D, ParsedTemplateInfo(), &LateParsedAttrs); return Actions.ConvertDeclToDeclGroup(TheDecl); } if (isDeclarationSpecifier()) { // If there is an invalid declaration specifier right after the // function prototype, then we must be in a missing semicolon case // where this isn't actually a body. Just fall through into the code // that handles it as a prototype, and let the top-level code handle // the erroneous declspec where it would otherwise expect a comma or // semicolon. } else { Diag(Tok, diag::err_expected_fn_body); SkipUntil(tok::semi); return DeclGroupPtrTy(); } } else { if (Tok.is(tok::l_brace)) { Diag(Tok, diag::err_function_definition_not_allowed); SkipMalformedDecl(); return DeclGroupPtrTy(); } } } if (!getLangOpts().HLSL && ParseAsmAttributesAfterDeclarator(D)) // HLSL Change - no asm attributes for HLSL return DeclGroupPtrTy(); // C++0x [stmt.iter]p1: Check if we have a for-range-declarator. If so, we // must parse and analyze the for-range-initializer before the declaration is // analyzed. // // Handle the Objective-C for-in loop variable similarly, although we // don't need to parse the container in advance. if (!getLangOpts().HLSL && FRI && (Tok.is(tok::colon) || isTokIdentifier_in())) { // HLSL Change bool IsForRangeLoop = false; if (TryConsumeToken(tok::colon, FRI->ColonLoc)) { IsForRangeLoop = true; if (Tok.is(tok::l_brace)) FRI->RangeExpr = ParseBraceInitializer(); else FRI->RangeExpr = ParseExpression(); } Decl *ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); if (IsForRangeLoop) Actions.ActOnCXXForRangeDecl(ThisDecl); Actions.FinalizeDeclaration(ThisDecl); D.complete(ThisDecl); return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, ThisDecl); } SmallVector<Decl *, 8> DeclsInGroup; Decl *FirstDecl = ParseDeclarationAfterDeclaratorAndAttributes( D, ParsedTemplateInfo(), FRI); if (LateParsedAttrs.size() > 0) ParseLexedAttributeList(LateParsedAttrs, FirstDecl, true, false); D.complete(FirstDecl); if (FirstDecl) DeclsInGroup.push_back(FirstDecl); bool ExpectSemi = Context != Declarator::ForContext; // If we don't have a comma, it is either the end of the list (a ';') or an // error, bail out. SourceLocation CommaLoc; while (TryConsumeToken(tok::comma, CommaLoc)) { if (Tok.isAtStartOfLine() && ExpectSemi && !MightBeDeclarator(Context)) { // This comma was followed by a line-break and something which can't be // the start of a declarator. The comma was probably a typo for a // semicolon. Diag(CommaLoc, diag::err_expected_semi_declaration) << FixItHint::CreateReplacement(CommaLoc, ";"); ExpectSemi = false; break; } // Parse the next declarator. D.clear(); D.setCommaLoc(CommaLoc); // Accept attributes in an init-declarator. In the first declarator in a // declaration, these would be part of the declspec. In subsequent // declarators, they become part of the declarator itself, so that they // don't apply to declarators after *this* one. Examples: // short __attribute__((common)) var; -> declspec // short var __attribute__((common)); -> declarator // short x, __attribute__((common)) var; -> declarator MaybeParseGNUAttributes(D); // MSVC parses but ignores qualifiers after the comma as an extension. if (getLangOpts().MicrosoftExt) DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); ParseDeclarator(D); if (!D.isInvalidType()) { Decl *ThisDecl = ParseDeclarationAfterDeclarator(D); D.complete(ThisDecl); if (ThisDecl) DeclsInGroup.push_back(ThisDecl); } } if (DeclEnd) *DeclEnd = Tok.getLocation(); if (ExpectSemi && ExpectAndConsumeSemi(Context == Declarator::FileContext ? diag::err_invalid_token_after_toplevel_declarator : diag::err_expected_semi_declaration)) { // Okay, there was no semicolon and one was expected. If we see a // declaration specifier, just assume it was missing and continue parsing. // Otherwise things are very confused and we skip to recover. if (!isDeclarationSpecifier()) { SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); TryConsumeToken(tok::semi); } } return Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup); } /// Parse an optional simple-asm-expr and attributes, and attach them to a /// declarator. Returns true on an error. bool Parser::ParseAsmAttributesAfterDeclarator(Declarator &D) { // If a simple-asm-expr is present, parse it. if (Tok.is(tok::kw_asm)) { SourceLocation Loc; ExprResult AsmLabel(ParseSimpleAsm(&Loc)); if (AsmLabel.isInvalid()) { SkipUntil(tok::semi, StopBeforeMatch); return true; } D.setAsmLabel(AsmLabel.get()); D.SetRangeEnd(Loc); } MaybeParseGNUAttributes(D); return false; } /// \brief Parse 'declaration' after parsing 'declaration-specifiers /// declarator'. This method parses the remainder of the declaration /// (including any attributes or initializer, among other things) and /// finalizes the declaration. /// /// init-declarator: [C99 6.7] /// declarator /// declarator '=' initializer /// [GNU] declarator simple-asm-expr[opt] attributes[opt] /// [GNU] declarator simple-asm-expr[opt] attributes[opt] '=' initializer /// [C++] declarator initializer[opt] /// /// [C++] initializer: /// [C++] '=' initializer-clause /// [C++] '(' expression-list ')' /// [C++0x] '=' 'default' [TODO] /// [C++0x] '=' 'delete' /// [C++0x] braced-init-list /// /// According to the standard grammar, =default and =delete are function /// definitions, but that definitely doesn't fit with the parser here. /// Decl *Parser::ParseDeclarationAfterDeclarator( Declarator &D, const ParsedTemplateInfo &TemplateInfo) { if (!getLangOpts().HLSL && ParseAsmAttributesAfterDeclarator(D)) // HLSL Change - remove asm attribute support return nullptr; return ParseDeclarationAfterDeclaratorAndAttributes(D, TemplateInfo); } Decl *Parser::ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo, ForRangeInit *FRI) { // Inform the current actions module that we just parsed this declarator. Decl *ThisDecl = nullptr; switch (TemplateInfo.Kind) { case ParsedTemplateInfo::NonTemplate: ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); break; case ParsedTemplateInfo::Template: case ParsedTemplateInfo::ExplicitSpecialization: { ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), *TemplateInfo.TemplateParams, D); if (VarTemplateDecl *VT = dyn_cast_or_null<VarTemplateDecl>(ThisDecl)) // Re-direct this decl to refer to the templated decl so that we can // initialize it. ThisDecl = VT->getTemplatedDecl(); break; } case ParsedTemplateInfo::ExplicitInstantiation: { if (Tok.is(tok::semi)) { DeclResult ThisRes = Actions.ActOnExplicitInstantiation( getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, D); if (ThisRes.isInvalid()) { SkipUntil(tok::semi, StopBeforeMatch); return nullptr; } ThisDecl = ThisRes.get(); } else { // FIXME: This check should be for a variable template instantiation only. // Check that this is a valid instantiation if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { // If the declarator-id is not a template-id, issue a diagnostic and // recover by ignoring the 'template' keyword. Diag(Tok, diag::err_template_defn_explicit_instantiation) << 2 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc); ThisDecl = Actions.ActOnDeclarator(getCurScope(), D); } else { SourceLocation LAngleLoc = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_with_definition) << SourceRange(TemplateInfo.TemplateLoc) << FixItHint::CreateInsertion(LAngleLoc, "<>"); // Recover as if it were an explicit specialization. TemplateParameterLists FakedParamLists; FakedParamLists.push_back(Actions.ActOnTemplateParameterList( 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr, 0, LAngleLoc)); ThisDecl = Actions.ActOnTemplateDeclarator(getCurScope(), FakedParamLists, D); } } break; } } bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType(); // Parse declarator '=' initializer. // If a '==' or '+=' is found, suggest a fixit to '='. if (isTokenEqualOrEqualTypo()) { SourceLocation EqualLoc = ConsumeToken(); // HLSL Change Starts - skip legacy effects sampler_state { ... } assignment and warn if (Tok.is(tok::kw_sampler_state)) { Diag(Tok.getLocation(), diag::warn_hlsl_effect_sampler_state); SkipUntil(tok::l_brace); // skip until '{' SkipUntil(tok::r_brace); // skip until '}' } else // HLSL Change Ends if (Tok.is(tok::kw_delete)) { if (D.isFunctionDeclarator()) Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) << 1 /* delete */; else Diag(ConsumeToken(), diag::err_deleted_non_function); } else if (Tok.is(tok::kw_default)) { if (D.isFunctionDeclarator()) Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) << 0 /* default */; else Diag(ConsumeToken(), diag::err_default_special_members); } else { if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { EnterScope(0); Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); } if (Tok.is(tok::code_completion)) { Actions.CodeCompleteInitializer(getCurScope(), ThisDecl); Actions.FinalizeDeclaration(ThisDecl); cutOffParsing(); return nullptr; } // HLSL Change Begin. // Skip the initializer of effect object. if (D.isInvalidType()) { SkipUntil(tok::semi, StopBeforeMatch); // skip until ';' Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto); return nullptr; } // HLSL Change End. ExprResult Init(ParseInitializer()); // If this is the only decl in (possibly) range based for statement, // our best guess is that the user meant ':' instead of '='. if (Tok.is(tok::r_paren) && FRI && D.isFirstDeclarator()) { Diag(EqualLoc, diag::err_single_decl_assign_in_for_range) << FixItHint::CreateReplacement(EqualLoc, ":"); // We are trying to stop parser from looking for ';' in this for // statement, therefore preventing spurious errors to be issued. FRI->ColonLoc = EqualLoc; Init = ExprError(); FRI->RangeExpr = Init; } if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); ExitScope(); } if (Init.isInvalid()) { SmallVector<tok::TokenKind, 2> StopTokens; StopTokens.push_back(tok::comma); if (D.getContext() == Declarator::ForContext) StopTokens.push_back(tok::r_paren); SkipUntil(StopTokens, StopAtSemi | StopBeforeMatch); Actions.ActOnInitializerError(ThisDecl); } else Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/false, TypeContainsAuto); } } else if (Tok.is(tok::l_paren)) { // Parse C++ direct initializer: '(' expression-list ')' BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); ExprVector Exprs; CommaLocsTy CommaLocs; if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { EnterScope(0); Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); } if (ParseExpressionList(Exprs, CommaLocs, [&] { Actions.CodeCompleteConstructor(getCurScope(), cast<VarDecl>(ThisDecl)->getType()->getCanonicalTypeInternal(), ThisDecl->getLocation(), Exprs); })) { Actions.ActOnInitializerError(ThisDecl); SkipUntil(tok::r_paren, StopAtSemi); if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); ExitScope(); } } else { // Match the ')'. T.consumeClose(); assert(!Exprs.empty() && Exprs.size()-1 == CommaLocs.size() && "Unexpected number of commas!"); if (getLangOpts().CPlusPlus && D.getCXXScopeSpec().isSet()) { Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); ExitScope(); } ExprResult Initializer = Actions.ActOnParenListExpr(T.getOpenLocation(), T.getCloseLocation(), Exprs); Actions.AddInitializerToDecl(ThisDecl, Initializer.get(), /*DirectInit=*/true, TypeContainsAuto); } } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace) && (!CurParsedObjCImpl || !D.isFunctionDeclarator())) { // Parse C++0x braced-init-list. Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); if (D.getCXXScopeSpec().isSet()) { EnterScope(0); Actions.ActOnCXXEnterDeclInitializer(getCurScope(), ThisDecl); } ExprResult Init(ParseBraceInitializer()); if (D.getCXXScopeSpec().isSet()) { Actions.ActOnCXXExitDeclInitializer(getCurScope(), ThisDecl); ExitScope(); } if (Init.isInvalid()) { Actions.ActOnInitializerError(ThisDecl); } else Actions.AddInitializerToDecl(ThisDecl, Init.get(), /*DirectInit=*/true, TypeContainsAuto); // HLSL Change Starts } else if (getLangOpts().HLSL && Tok.is(tok::l_brace) && !D.isFunctionDeclarator()) { // HLSL allows for a block definition here that it silently ignores. // This is to allow for effects state block definitions. Detect a // block here, warn about effect deprecation, and ignore the block. Diag(Tok.getLocation(), diag::warn_hlsl_effect_state_block); ConsumeBrace(); SkipUntil(tok::r_brace); // skip until '}' // Braces could have been used to initialize an array. // In this case we require users to use braces with the equal sign. // Otherwise, the array will be treated as an uninitialized declaration. Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto); // HLSL Change Ends } else { Actions.ActOnUninitializedDecl(ThisDecl, TypeContainsAuto); } Actions.FinalizeDeclaration(ThisDecl); return ThisDecl; } /// ParseSpecifierQualifierList /// specifier-qualifier-list: /// type-specifier specifier-qualifier-list[opt] /// type-qualifier specifier-qualifier-list[opt] /// [GNU] attributes specifier-qualifier-list[opt] /// void Parser::ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSC) { /// specifier-qualifier-list is a subset of declaration-specifiers. Just /// parse declaration-specifiers and complain about extra stuff. /// TODO: diagnose attribute-specifiers and alignment-specifiers. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC); // Validate declspec for type-name. unsigned Specs = DS.getParsedSpecifiers(); if (isTypeSpecifier(DSC) && !DS.hasTypeSpecifier()) { Diag(Tok, diag::err_expected_type); DS.SetTypeSpecError(); } else if (Specs == DeclSpec::PQ_None && !DS.hasAttributes()) { Diag(Tok, diag::err_typename_requires_specqual); if (!DS.hasTypeSpecifier()) DS.SetTypeSpecError(); } // Issue diagnostic and remove storage class if present. if (Specs & DeclSpec::PQ_StorageClassSpecifier) { if (DS.getStorageClassSpecLoc().isValid()) Diag(DS.getStorageClassSpecLoc(),diag::err_typename_invalid_storageclass); else Diag(DS.getThreadStorageClassSpecLoc(), diag::err_typename_invalid_storageclass); DS.ClearStorageClassSpecs(); } // Issue diagnostic and remove function specfier if present. if (Specs & DeclSpec::PQ_FunctionSpecifier) { if (DS.isInlineSpecified()) Diag(DS.getInlineSpecLoc(), diag::err_typename_invalid_functionspec); if (DS.isVirtualSpecified()) Diag(DS.getVirtualSpecLoc(), diag::err_typename_invalid_functionspec); if (DS.isExplicitSpecified()) Diag(DS.getExplicitSpecLoc(), diag::err_typename_invalid_functionspec); DS.ClearFunctionSpecs(); } // Issue diagnostic and remove constexpr specfier if present. if (DS.isConstexprSpecified() && DSC != DSC_condition) { Diag(DS.getConstexprSpecLoc(), diag::err_typename_invalid_constexpr); DS.ClearConstexprSpec(); } } /// isValidAfterIdentifierInDeclaratorAfterDeclSpec - Return true if the /// specified token is valid after the identifier in a declarator which /// immediately follows the declspec. For example, these things are valid: /// /// int x [ 4]; // direct-declarator /// int x ( int y); // direct-declarator /// int(int x ) // direct-declarator /// int x ; // simple-declaration /// int x = 17; // init-declarator-list /// int x , y; // init-declarator-list /// int x __asm__ ("foo"); // init-declarator-list /// int x : 4; // struct-declarator /// int x { 5}; // C++'0x unified initializers /// /// This is not, because 'x' does not immediately follow the declspec (though /// ')' happens to be valid anyway). /// int (x) /// static bool isValidAfterIdentifierInDeclarator(const Token &T) { return T.isOneOf(tok::l_square, tok::l_paren, tok::r_paren, tok::semi, tok::comma, tok::equal, tok::kw_asm, tok::l_brace, tok::colon); } /// ParseImplicitInt - This method is called when we have an non-typename /// identifier in a declspec (which normally terminates the decl spec) when /// the declspec has no type specifier. In this case, the declspec is either /// malformed or is "implicit int" (in K&R and C89). /// /// This method handles diagnosing this prettily and returns false if the /// declspec is done being processed. If it recovers and thinks there may be /// other pieces of declspec after it, it returns true. /// bool Parser::ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs) { assert(Tok.is(tok::identifier) && "should have identifier"); SourceLocation Loc = Tok.getLocation(); // If we see an identifier that is not a type name, we normally would // parse it as the identifer being declared. However, when a typename // is typo'd or the definition is not included, this will incorrectly // parse the typename as the identifier name and fall over misparsing // later parts of the diagnostic. // // As such, we try to do some look-ahead in cases where this would // otherwise be an "implicit-int" case to see if this is invalid. For // example: "static foo_t x = 4;" In this case, if we parsed foo_t as // an identifier with implicit int, we'd get a parse error because the // next token is obviously invalid for a type. Parse these as a case // with an invalid type specifier. assert(!DS.hasTypeSpecifier() && "Type specifier checked above"); // Since we know that this either implicit int (which is rare) or an // error, do lookahead to try to do better recovery. This never applies // within a type specifier. Outside of C++, we allow this even if the // language doesn't "officially" support implicit int -- we support // implicit int as an extension in C99 and C11. if (!isTypeSpecifier(DSC) && !getLangOpts().CPlusPlus && isValidAfterIdentifierInDeclarator(NextToken())) { // If this token is valid for implicit int, e.g. "static x = 4", then // we just avoid eating the identifier, so it will be parsed as the // identifier in the declarator. return false; } if (getLangOpts().CPlusPlus && DS.getStorageClassSpec() == DeclSpec::SCS_auto) { // Don't require a type specifier if we have the 'auto' storage class // specifier in C++98 -- we'll promote it to a type specifier. if (SS) AnnotateScopeToken(*SS, /*IsNewAnnotation*/false); return false; } // Otherwise, if we don't consume this token, we are going to emit an // error anyway. Try to recover from various common problems. Check // to see if this was a reference to a tag name without a tag specified. // This is a common problem in C (saying 'foo' instead of 'struct foo'). // // C++ doesn't need this, and isTagName doesn't take SS. if (SS == nullptr) { const char *TagName = nullptr, *FixitTagName = nullptr; tok::TokenKind TagKind = tok::unknown; switch (Actions.isTagName(*Tok.getIdentifierInfo(), getCurScope())) { default: break; case DeclSpec::TST_enum: TagName="enum" ; FixitTagName = "enum " ; TagKind=tok::kw_enum ;break; case DeclSpec::TST_union: TagName="union" ; FixitTagName = "union " ;TagKind=tok::kw_union ;break; case DeclSpec::TST_struct: TagName="struct"; FixitTagName = "struct ";TagKind=tok::kw_struct;break; case DeclSpec::TST_interface: TagName="__interface"; FixitTagName = "__interface "; TagKind=tok::kw___interface;break; case DeclSpec::TST_class: TagName="class" ; FixitTagName = "class " ;TagKind=tok::kw_class ;break; } if (TagName) { IdentifierInfo *TokenName = Tok.getIdentifierInfo(); LookupResult R(Actions, TokenName, SourceLocation(), Sema::LookupOrdinaryName); Diag(Loc, diag::err_use_of_tag_name_without_tag) << TokenName << TagName << getLangOpts().CPlusPlus << FixItHint::CreateInsertion(Tok.getLocation(), FixitTagName); if (Actions.LookupParsedName(R, getCurScope(), SS)) { for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) << TokenName << TagName; } // Parse this as a tag as if the missing tag were present. if (TagKind == tok::kw_enum) ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSC_normal); else ParseClassSpecifier(TagKind, Loc, DS, TemplateInfo, AS, /*EnteringContext*/ false, DSC_normal, Attrs); return true; } } // Determine whether this identifier could plausibly be the name of something // being declared (with a missing type). if (!isTypeSpecifier(DSC) && (!SS || DSC == DSC_top_level || DSC == DSC_class)) { // Look ahead to the next token to try to figure out what this declaration // was supposed to be. switch (NextToken().getKind()) { case tok::l_paren: { // static x(4); // 'x' is not a type // x(int n); // 'x' is not a type // x (*p)[]; // 'x' is a type // // Since we're in an error case, we can afford to perform a tentative // parse to determine which case we're in. TentativeParsingAction PA(*this); ConsumeToken(); TPResult TPR = TryParseDeclarator(/*mayBeAbstract*/false); PA.Revert(); if (TPR != TPResult::False) { // The identifier is followed by a parenthesized declarator. // It's supposed to be a type. break; } // If we're in a context where we could be declaring a constructor, // check whether this is a constructor declaration with a bogus name. if (DSC == DSC_class || (DSC == DSC_top_level && SS)) { IdentifierInfo *II = Tok.getIdentifierInfo(); if (Actions.isCurrentClassNameTypo(II, SS)) { Diag(Loc, diag::err_constructor_bad_name) << Tok.getIdentifierInfo() << II << FixItHint::CreateReplacement(Tok.getLocation(), II->getName()); Tok.setIdentifierInfo(II); } } LLVM_FALLTHROUGH; // HLSL Change } case tok::comma: case tok::equal: case tok::kw_asm: case tok::l_brace: case tok::l_square: case tok::semi: // This looks like a variable or function declaration. The type is // probably missing. We're done parsing decl-specifiers. if (SS) AnnotateScopeToken(*SS, /*IsNewAnnotation*/false); return false; default: // This is probably supposed to be a type. This includes cases like: // int f(itn); // struct S { unsinged : 4; }; break; } } // This is almost certainly an invalid type name. Let Sema emit a diagnostic // and attempt to recover. ParsedType T; IdentifierInfo *II = Tok.getIdentifierInfo(); Actions.DiagnoseUnknownTypeName(II, Loc, getCurScope(), SS, T, getLangOpts().CPlusPlus && NextToken().is(tok::less)); if (T) { // The action has suggested that the type T could be used. Set that as // the type in the declaration specifiers, consume the would-be type // name token, and we're done. const char *PrevSpec; unsigned DiagID; DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T, Actions.getASTContext().getPrintingPolicy()); DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); // There may be other declaration specifiers after this. return true; } else if (II != Tok.getIdentifierInfo()) { // If no type was suggested, the correction is to a keyword Tok.setKind(II->getTokenID()); // There may be other declaration specifiers after this. return true; } // Otherwise, the action had no suggestion for us. Mark this as an error. DS.SetTypeSpecError(); DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); // TODO: Could inject an invalid typedef decl in an enclosing scope to // avoid rippling error messages on subsequent uses of the same type, // could be useful if #include was forgotten. return false; } /// \brief Determine the declaration specifier context from the declarator /// context. /// /// \param Context the declarator context, which is one of the /// Declarator::TheContext enumerator values. Parser::DeclSpecContext Parser::getDeclSpecContextFromDeclaratorContext(unsigned Context) { if (Context == Declarator::MemberContext) return DSC_class; if (Context == Declarator::FileContext) return DSC_top_level; if (Context == Declarator::TemplateTypeArgContext) return DSC_template_type_arg; if (Context == Declarator::TrailingReturnContext) return DSC_trailing; if (Context == Declarator::AliasDeclContext || Context == Declarator::AliasTemplateContext) return DSC_alias_declaration; return DSC_normal; } /// ParseAlignArgument - Parse the argument to an alignment-specifier. /// /// FIXME: Simply returns an alignof() expression if the argument is a /// type. Ideally, the type should be propagated directly into Sema. /// /// [C11] type-id /// [C11] constant-expression /// [C++0x] type-id ...[opt] /// [C++0x] assignment-expression ...[opt] ExprResult Parser::ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc) { ExprResult ER; if (isTypeIdInParens()) { SourceLocation TypeLoc = Tok.getLocation(); ParsedType Ty = ParseTypeName().get(); SourceRange TypeRange(Start, Tok.getLocation()); ER = Actions.ActOnUnaryExprOrTypeTraitExpr(TypeLoc, UETT_AlignOf, true, Ty.getAsOpaquePtr(), TypeRange); } else ER = ParseConstantExpression(); if (getLangOpts().CPlusPlus11) TryConsumeToken(tok::ellipsis, EllipsisLoc); return ER; } /// ParseAlignmentSpecifier - Parse an alignment-specifier, and add the /// attribute to Attrs. /// /// alignment-specifier: /// [C11] '_Alignas' '(' type-id ')' /// [C11] '_Alignas' '(' constant-expression ')' /// [C++11] 'alignas' '(' type-id ...[opt] ')' /// [C++11] 'alignas' '(' assignment-expression ...[opt] ')' void Parser::ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *EndLoc) { assert(Tok.isOneOf(tok::kw_alignas, tok::kw__Alignas) && "Not an alignment-specifier!"); IdentifierInfo *KWName = Tok.getIdentifierInfo(); SourceLocation KWLoc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.expectAndConsume()) return; SourceLocation EllipsisLoc; ExprResult ArgExpr = ParseAlignArgument(T.getOpenLocation(), EllipsisLoc); if (ArgExpr.isInvalid()) { T.skipToEnd(); return; } T.consumeClose(); if (EndLoc) *EndLoc = T.getCloseLocation(); ArgsVector ArgExprs; ArgExprs.push_back(ArgExpr.get()); Attrs.addNew(KWName, KWLoc, nullptr, KWLoc, ArgExprs.data(), 1, AttributeList::AS_Keyword, EllipsisLoc); } /// Determine whether we're looking at something that might be a declarator /// in a simple-declaration. If it can't possibly be a declarator, maybe /// diagnose a missing semicolon after a prior tag definition in the decl /// specifier. /// /// \return \c true if an error occurred and this can't be any kind of /// declaration. bool Parser::DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs) { assert(DS.hasTagDefinition() && "shouldn't call this"); bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level); if (getLangOpts().CPlusPlus && Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype, tok::annot_template_id) && TryAnnotateCXXScopeToken(EnteringContext)) { SkipMalformedDecl(); return true; } bool HasScope = Tok.is(tok::annot_cxxscope); // Make a copy in case GetLookAheadToken invalidates the result of NextToken. Token AfterScope = HasScope ? NextToken() : Tok; // Determine whether the following tokens could possibly be a // declarator. bool MightBeDeclarator = true; if (Tok.isOneOf(tok::kw_typename, tok::annot_typename)) { // A declarator-id can't start with 'typename'. MightBeDeclarator = false; } else if (AfterScope.is(tok::annot_template_id)) { // If we have a type expressed as a template-id, this cannot be a // declarator-id (such a type cannot be redeclared in a simple-declaration). TemplateIdAnnotation *Annot = static_cast<TemplateIdAnnotation *>(AfterScope.getAnnotationValue()); if (Annot->Kind == TNK_Type_template) MightBeDeclarator = false; } else if (AfterScope.is(tok::identifier)) { const Token &Next = HasScope ? GetLookAheadToken(2) : NextToken(); // These tokens cannot come after the declarator-id in a // simple-declaration, and are likely to come after a type-specifier. if (Next.isOneOf(tok::star, tok::amp, tok::ampamp, tok::identifier, tok::annot_cxxscope, tok::coloncolon)) { // Missing a semicolon. MightBeDeclarator = false; } else if (HasScope) { // If the declarator-id has a scope specifier, it must redeclare a // previously-declared entity. If that's a type (and this is not a // typedef), that's an error. CXXScopeSpec SS; Actions.RestoreNestedNameSpecifierAnnotation( Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS); IdentifierInfo *Name = AfterScope.getIdentifierInfo(); Sema::NameClassification Classification = Actions.ClassifyName( getCurScope(), SS, Name, AfterScope.getLocation(), Next, /*IsAddressOfOperand*/false); switch (Classification.getKind()) { case Sema::NC_Error: SkipMalformedDecl(); return true; case Sema::NC_Keyword: case Sema::NC_NestedNameSpecifier: llvm_unreachable("typo correction and nested name specifiers not " "possible here"); case Sema::NC_Type: case Sema::NC_TypeTemplate: // Not a previously-declared non-type entity. MightBeDeclarator = false; break; case Sema::NC_Unknown: case Sema::NC_Expression: case Sema::NC_VarTemplate: case Sema::NC_FunctionTemplate: // Might be a redeclaration of a prior entity. break; } } } if (MightBeDeclarator) return false; const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy(); Diag(PP.getLocForEndOfToken(DS.getRepAsDecl()->getLocEnd()), diag::err_expected_after) << DeclSpec::getSpecifierName(DS.getTypeSpecType(), PPol) << tok::semi; // Try to recover from the typo, by dropping the tag definition and parsing // the problematic tokens as a type. // // FIXME: Split the DeclSpec into pieces for the standalone // declaration and pieces for the following declaration, instead // of assuming that all the other pieces attach to new declaration, // and call ParsedFreeStandingDeclSpec as appropriate. DS.ClearTypeSpecType(); ParsedTemplateInfo NotATemplate; ParseDeclarationSpecifiers(DS, NotATemplate, AS, DSContext, LateAttrs); return false; } /// ParseDeclarationSpecifiers /// declaration-specifiers: [C99 6.7] /// storage-class-specifier declaration-specifiers[opt] /// type-specifier declaration-specifiers[opt] /// [C99] function-specifier declaration-specifiers[opt] /// [C11] alignment-specifier declaration-specifiers[opt] /// [GNU] attributes declaration-specifiers[opt] /// [Clang] '__module_private__' declaration-specifiers[opt] /// [ObjC1] '__kindof' declaration-specifiers[opt] /// /// storage-class-specifier: [C99 6.7.1] /// 'typedef' /// 'extern' /// 'static' /// 'auto' /// 'register' /// [C++] 'mutable' /// [C++11] 'thread_local' /// [C11] '_Thread_local' /// [GNU] '__thread' /// function-specifier: [C99 6.7.4] /// [C99] 'inline' /// [C++] 'virtual' /// [C++] 'explicit' /// [OpenCL] '__kernel' /// 'friend': [C++ dcl.friend] /// 'constexpr': [C++0x dcl.constexpr] /// void Parser::ParseDeclarationSpecifiers(DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs) { if (DS.getSourceRange().isInvalid()) { // Start the range at the current token but make the end of the range // invalid. This will make the entire range invalid unless we successfully // consume a token. DS.SetRangeStart(Tok.getLocation()); DS.SetRangeEnd(SourceLocation()); } bool EnteringContext = (DSContext == DSC_class || DSContext == DSC_top_level); bool AttrsLastTime = false; ParsedAttributesWithRange attrs(AttrFactory); // We use Sema's policy to get bool macros right. const PrintingPolicy &Policy = Actions.getPrintingPolicy(); while (1) { bool isInvalid = false; bool isStorageClass = false; const char *PrevSpec = nullptr; unsigned DiagID = 0; SourceLocation Loc = Tok.getLocation(); switch (Tok.getKind()) { default: DoneWithDeclSpec: if (!AttrsLastTime) ProhibitAttributes(attrs); else { // Reject C++11 attributes that appertain to decl specifiers as // we don't support any C++11 attributes that appertain to decl // specifiers. This also conforms to what g++ 4.8 is doing. ProhibitCXX11Attributes(attrs); DS.takeAttributesFrom(attrs); } // If this is not a declaration specifier token, we're done reading decl // specifiers. First verify that DeclSpec's are consistent. DS.Finish(Diags, PP, Policy); return; case tok::l_square: case tok::kw_alignas: if (!getLangOpts().CPlusPlus11 || !isCXX11AttributeSpecifier()) goto DoneWithDeclSpec; ProhibitAttributes(attrs); // FIXME: It would be good to recover by accepting the attributes, // but attempting to do that now would cause serious // madness in terms of diagnostics. attrs.clear(); attrs.Range = SourceRange(); ParseCXX11Attributes(attrs); AttrsLastTime = true; continue; case tok::code_completion: { Sema::ParserCompletionContext CCC = Sema::PCC_Namespace; if (DS.hasTypeSpecifier()) { bool AllowNonIdentifiers = (getCurScope()->getFlags() & (Scope::ControlScope | Scope::BlockScope | Scope::TemplateParamScope | Scope::FunctionPrototypeScope | Scope::AtCatchScope)) == 0; bool AllowNestedNameSpecifiers = DSContext == DSC_top_level || (DSContext == DSC_class && DS.isFriendSpecified()); Actions.CodeCompleteDeclSpec(getCurScope(), DS, AllowNonIdentifiers, AllowNestedNameSpecifiers); return cutOffParsing(); } if (getCurScope()->getFnParent() || getCurScope()->getBlockParent()) CCC = Sema::PCC_LocalDeclarationSpecifiers; else if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) CCC = DSContext == DSC_class? Sema::PCC_MemberTemplate : Sema::PCC_Template; else if (DSContext == DSC_class) CCC = Sema::PCC_Class; else if (CurParsedObjCImpl) CCC = Sema::PCC_ObjCImplementation; Actions.CodeCompleteOrdinaryName(getCurScope(), CCC); return cutOffParsing(); } case tok::coloncolon: // ::foo::bar // C++ scope specifier. Annotate and loop, or bail out on error. if (TryAnnotateCXXScopeToken(EnteringContext)) { if (!DS.hasTypeSpecifier()) DS.SetTypeSpecError(); goto DoneWithDeclSpec; } if (Tok.is(tok::coloncolon)) // ::new or ::delete goto DoneWithDeclSpec; continue; case tok::annot_cxxscope: { if (DS.hasTypeSpecifier() || DS.isTypeAltiVecVector()) goto DoneWithDeclSpec; CXXScopeSpec SS; Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS); // We are looking for a qualified typename. Token Next = NextToken(); if (Next.is(tok::annot_template_id) && static_cast<TemplateIdAnnotation *>(Next.getAnnotationValue()) ->Kind == TNK_Type_template) { // We have a qualified template-id, e.g., N::A<int> // C++ [class.qual]p2: // In a lookup in which the constructor is an acceptable lookup // result and the nested-name-specifier nominates a class C: // // - if the name specified after the // nested-name-specifier, when looked up in C, is the // injected-class-name of C (Clause 9), or // // - if the name specified after the nested-name-specifier // is the same as the identifier or the // simple-template-id's template-name in the last // component of the nested-name-specifier, // // the name is instead considered to name the constructor of // class C. // // Thus, if the template-name is actually the constructor // name, then the code is ill-formed; this interpretation is // reinforced by the NAD status of core issue 635. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); if ((DSContext == DSC_top_level || DSContext == DSC_class) && TemplateId->Name && Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { if (isConstructorDeclarator(/*Unqualified*/false)) { // The user meant this to be an out-of-line constructor // definition, but template arguments are not allowed // there. Just allow this as a constructor; we'll // complain about it later. goto DoneWithDeclSpec; } // The user meant this to name a type, but it actually names // a constructor with some extraneous template // arguments. Complain, then parse it as a type as the user // intended. Diag(TemplateId->TemplateNameLoc, diag::err_out_of_line_template_id_names_constructor) << TemplateId->Name; } DS.getTypeSpecScope() = SS; ConsumeToken(); // The C++ scope. assert(Tok.is(tok::annot_template_id) && "ParseOptionalCXXScopeSpecifier not working"); AnnotateTemplateIdTokenAsType(); continue; } if (Next.is(tok::annot_typename)) { DS.getTypeSpecScope() = SS; ConsumeToken(); // The C++ scope. if (Tok.getAnnotationValue()) { ParsedType T = getTypeAnnotation(Tok); isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Tok.getAnnotationEndLoc(), PrevSpec, DiagID, T, Policy); if (isInvalid) break; } else DS.SetTypeSpecError(); DS.SetRangeEnd(Tok.getAnnotationEndLoc()); ConsumeToken(); // The typename } if (Next.isNot(tok::identifier)) goto DoneWithDeclSpec; // If we're in a context where the identifier could be a class name, // check whether this is a constructor declaration. if ((DSContext == DSC_top_level || DSContext == DSC_class) && Actions.isCurrentClassName(*Next.getIdentifierInfo(), getCurScope(), &SS)) { if (isConstructorDeclarator(/*Unqualified*/false)) goto DoneWithDeclSpec; // As noted in C++ [class.qual]p2 (cited above), when the name // of the class is qualified in a context where it could name // a constructor, its a constructor name. However, we've // looked at the declarator, and the user probably meant this // to be a type. Complain that it isn't supposed to be treated // as a type, then proceed to parse it as a type. Diag(Next.getLocation(), diag::err_out_of_line_type_names_constructor) << Next.getIdentifierInfo(); } ParsedType TypeRep = Actions.getTypeName(*Next.getIdentifierInfo(), Next.getLocation(), getCurScope(), &SS, false, false, ParsedType(), /*IsCtorOrDtorName=*/false, /*NonTrivialSourceInfo=*/true); // If the referenced identifier is not a type, then this declspec is // erroneous: We already checked about that it has no type specifier, and // C++ doesn't have implicit int. Diagnose it as a typo w.r.t. to the // typename. if (!TypeRep) { ConsumeToken(); // Eat the scope spec so the identifier is current. ParsedAttributesWithRange Attrs(AttrFactory); if (ParseImplicitInt(DS, &SS, TemplateInfo, AS, DSContext, Attrs)) { if (!Attrs.empty()) { AttrsLastTime = true; attrs.takeAllFrom(Attrs); } continue; } goto DoneWithDeclSpec; } DS.getTypeSpecScope() = SS; ConsumeToken(); // The C++ scope. isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, TypeRep, Policy); if (isInvalid) break; DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); // The typename. continue; } case tok::annot_typename: { // If we've previously seen a tag definition, we were almost surely // missing a semicolon after it. if (DS.hasTypeSpecifier() && DS.hasTagDefinition()) goto DoneWithDeclSpec; // HLSL Change Starts // Remember the current state of the default matrix orientation, // since it can change between any two tokens with #pragma pack_matrix if (Parser::Actions.HasDefaultMatrixPack) DS.SetDefaultMatrixPackRowMajor(Parser::Actions.DefaultMatrixPackRowMajor); // HLSL Change Ends if (Tok.getAnnotationValue()) { ParsedType T = getTypeAnnotation(Tok); isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, T, Policy); } else DS.SetTypeSpecError(); if (isInvalid) break; DS.SetRangeEnd(Tok.getAnnotationEndLoc()); ConsumeToken(); // The typename continue; } case tok::kw___is_signed: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - __is_signed is reserved for HLSL // GNU libstdc++ 4.4 uses __is_signed as an identifier, but Clang // typically treats it as a trait. If we see __is_signed as it appears // in libstdc++, e.g., // // static const bool __is_signed; // // then treat __is_signed as an identifier rather than as a keyword. if (DS.getTypeSpecType() == TST_bool && DS.getTypeQualifiers() == DeclSpec::TQ_const && DS.getStorageClassSpec() == DeclSpec::SCS_static) TryKeywordIdentFallback(true); // We're done with the declaration-specifiers. goto DoneWithDeclSpec; // typedef-name case tok::kw___super: case tok::kw_decltype: case tok::identifier: { // This identifier can only be a typedef name if we haven't already seen // a type-specifier. Without this check we misparse: // typedef int X; struct Y { short X; }; as 'short int'. if (DS.hasTypeSpecifier()) goto DoneWithDeclSpec; // In C++, check to see if this is a scope specifier like foo::bar::, if // so handle it as such. This is important for ctor parsing. if (getLangOpts().CPlusPlus) { if (TryAnnotateCXXScopeToken(EnteringContext)) { DS.SetTypeSpecError(); goto DoneWithDeclSpec; } if (!Tok.is(tok::identifier)) continue; } // Check for need to substitute AltiVec keyword tokens. if (TryAltiVecToken(DS, Loc, PrevSpec, DiagID, isInvalid)) break; // [AltiVec] 2.2: [If the 'vector' specifier is used] The syntax does not // allow the use of a typedef name as a type specifier. if (DS.isTypeAltiVecVector()) goto DoneWithDeclSpec; if (DSContext == DSC_objc_method_result && isObjCInstancetype()) { ParsedType TypeRep = Actions.ActOnObjCInstanceType(Loc); assert(TypeRep); isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, TypeRep, Policy); if (isInvalid) break; DS.SetRangeEnd(Loc); ConsumeToken(); continue; } ParsedType TypeRep = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope()); // MSVC: If we weren't able to parse a default template argument, and it's // just a simple identifier, create a DependentNameType. This will allow // us to defer the name lookup to template instantiation time, as long we // forge a NestedNameSpecifier for the current context. if (!TypeRep && DSContext == DSC_template_type_arg && getLangOpts().MSVCCompat && getCurScope()->isTemplateParamScope()) { TypeRep = Actions.ActOnDelayedDefaultTemplateArg( *Tok.getIdentifierInfo(), Tok.getLocation()); } // If this is not a typedef name, don't parse it as part of the declspec, // it must be an implicit int or an error. if (!TypeRep) { ParsedAttributesWithRange Attrs(AttrFactory); if (ParseImplicitInt(DS, nullptr, TemplateInfo, AS, DSContext, Attrs)) { if (!Attrs.empty()) { AttrsLastTime = true; attrs.takeAllFrom(Attrs); } continue; } goto DoneWithDeclSpec; } // If we're in a context where the identifier could be a class name, // check whether this is a constructor declaration. if (getLangOpts().CPlusPlus && DSContext == DSC_class && Actions.isCurrentClassName(*Tok.getIdentifierInfo(), getCurScope()) && isConstructorDeclarator(/*Unqualified*/true)) goto DoneWithDeclSpec; // HLSL Change Starts // Modify TypeRep for unsigned vectors/matrix QualType qt = TypeRep.get(); QualType newType = ApplyTypeSpecSignToParsedType(&Actions, qt, DS.getTypeSpecSign(), Loc); isInvalid = DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, ParsedType::make(newType), Policy); // Remember the current state of the default matrix orientation, // since it can change between any two tokens with #pragma pack_matrix if (Parser::Actions.HasDefaultMatrixPack) DS.SetDefaultMatrixPackRowMajor(Parser::Actions.DefaultMatrixPackRowMajor); // HLSL Change Ends if (isInvalid) break; DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); // The identifier // Objective-C supports type arguments and protocol references // following an Objective-C object or object pointer // type. Handle either one of them. if (Tok.is(tok::less) && getLangOpts().ObjC1) { SourceLocation NewEndLoc; TypeResult NewTypeRep = parseObjCTypeArgsAndProtocolQualifiers( Loc, TypeRep, /*consumeLastToken=*/true, NewEndLoc); if (NewTypeRep.isUsable()) { DS.UpdateTypeRep(NewTypeRep.get()); DS.SetRangeEnd(NewEndLoc); } } // Need to support trailing type qualifiers (e.g. "id<p> const"). // If a type specifier follows, it will be diagnosed elsewhere. continue; } // type-name case tok::annot_template_id: { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); if (TemplateId->Kind != TNK_Type_template) { // This template-id does not refer to a type name, so we're // done with the type-specifiers. goto DoneWithDeclSpec; } // If we're in a context where the template-id could be a // constructor name or specialization, check whether this is a // constructor declaration. if (getLangOpts().CPlusPlus && DSContext == DSC_class && Actions.isCurrentClassName(*TemplateId->Name, getCurScope()) && isConstructorDeclarator(TemplateId->SS.isEmpty())) goto DoneWithDeclSpec; // Turn the template-id annotation token into a type annotation // token, then try again to parse it as a type-specifier. AnnotateTemplateIdTokenAsType(); continue; } // GNU attributes support. case tok::kw___attribute: ParseGNUAttributes(DS.getAttributes(), nullptr, LateAttrs); continue; // Microsoft declspec support. case tok::kw___declspec: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - __declspec is reserved for HLSL ParseMicrosoftDeclSpecs(DS.getAttributes()); continue; // Microsoft single token adornments. case tok::kw___forceinline: { if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - __forceinline is reserved for HLSL isInvalid = DS.setFunctionSpecForceInline(Loc, PrevSpec, DiagID); IdentifierInfo *AttrName = Tok.getIdentifierInfo(); SourceLocation AttrNameLoc = Tok.getLocation(); DS.getAttributes().addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, AttributeList::AS_Keyword); break; } case tok::kw___sptr: case tok::kw___uptr: case tok::kw___ptr64: case tok::kw___ptr32: case tok::kw___w64: case tok::kw___cdecl: case tok::kw___stdcall: case tok::kw___fastcall: case tok::kw___thiscall: case tok::kw___vectorcall: case tok::kw___unaligned: // HLSL Change Starts HLSLReservedKeyword: if (getLangOpts().HLSL) { PrevSpec = ""; // unused by diagnostic. DiagID = diag::err_hlsl_reserved_keyword; isInvalid = true; break; } else // HLSL Change Ends ParseMicrosoftTypeAttributes(DS.getAttributes()); continue; // Borland single token adornments. case tok::kw___pascal: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // HLSL Change - __pascal isn't a keyword for HLSL ParseBorlandTypeAttributes(DS.getAttributes()); continue; // OpenCL single token adornments. case tok::kw___kernel: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // HLSL Change - __kernel isn't a keyword for HLSL ParseOpenCLAttributes(DS.getAttributes()); continue; // Nullability type specifiers. case tok::kw__Nonnull: case tok::kw__Nullable: case tok::kw__Null_unspecified: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // HLSL Change - not a keyword for HLSL ParseNullabilityTypeSpecifiers(DS.getAttributes()); continue; // Objective-C 'kindof' types. case tok::kw___kindof: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // HLSL Change - not a keyword for HLSL DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc, nullptr, 0, AttributeList::AS_Keyword); (void)ConsumeToken(); continue; // storage-class-specifier case tok::kw_typedef: isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_typedef, Loc, PrevSpec, DiagID, Policy); isStorageClass = true; break; case tok::kw_extern: if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread) Diag(Tok, diag::ext_thread_before) << "extern"; isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_extern, Loc, PrevSpec, DiagID, Policy); isStorageClass = true; break; case tok::kw___private_extern__: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // HLSL Change - not a keyword for HLSL isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_private_extern, Loc, PrevSpec, DiagID, Policy); isStorageClass = true; break; case tok::kw_static: if (DS.getThreadStorageClassSpec() == DeclSpec::TSCS___thread) Diag(Tok, diag::ext_thread_before) << "static"; isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_static, Loc, PrevSpec, DiagID, Policy); isStorageClass = true; break; // HLSL Change Starts case tok::kw_shared: case tok::kw_groupshared: case tok::kw_uniform: case tok::kw_in: case tok::kw_out: case tok::kw_inout: case tok::kw_linear: case tok::kw_nointerpolation: case tok::kw_noperspective: case tok::kw_centroid: case tok::kw_column_major: case tok::kw_row_major: case tok::kw_snorm: case tok::kw_unorm: case tok::kw_point: case tok::kw_line: case tok::kw_lineadj: case tok::kw_triangle: case tok::kw_triangleadj: case tok::kw_export: if (getLangOpts().HLSL) { if (DS.getTypeSpecType() != DeclSpec::TST_unspecified) { PrevSpec = ""; DiagID = diag::err_hlsl_modifier_after_type; isInvalid = true; } else { DS.getAttributes().addNew(Tok.getIdentifierInfo(), Tok.getLocation(), 0, SourceLocation(), 0, 0, AttributeList::AS_CXX11); } } break; case tok::kw_precise: case tok::kw_sample: case tok::kw_globallycoherent: case tok::kw_center: case tok::kw_indices: case tok::kw_vertices: case tok::kw_primitives: case tok::kw_payload: // Back-compat: 'precise', 'globallycoherent', 'center' and 'sample' are keywords when used as an interpolation // modifiers, but in FXC they can also be used an identifiers. If the decl type has already been specified // we need to update the token to be handled as an identifier. // Similarly 'indices', 'vertices', 'primitives' and 'payload' are keywords // when used as a type qualifer in mesh shader, but may still be used as a variable name. if (getLangOpts().HLSL) { if (DS.getTypeSpecType() != DeclSpec::TST_unspecified) { Tok.setKind(tok::identifier); continue; } DS.getAttributes().addNew(Tok.getIdentifierInfo(), Tok.getLocation(), 0, SourceLocation(), 0, 0, AttributeList::AS_CXX11); } break; // HLSL Change Ends case tok::kw_auto: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - auto is reserved for HLSL if (getLangOpts().CPlusPlus11) { if (isKnownToBeTypeSpecifier(GetLookAheadToken(1))) { isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, PrevSpec, DiagID, Policy); if (!isInvalid) Diag(Tok, diag::ext_auto_storage_class) << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); } else isInvalid = DS.SetTypeSpecType(DeclSpec::TST_auto, Loc, PrevSpec, DiagID, Policy); } else isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_auto, Loc, PrevSpec, DiagID, Policy); isStorageClass = true; break; case tok::kw_register: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_register, Loc, PrevSpec, DiagID, Policy); isStorageClass = true; break; case tok::kw_mutable: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetStorageClassSpec(Actions, DeclSpec::SCS_mutable, Loc, PrevSpec, DiagID, Policy); isStorageClass = true; break; case tok::kw___thread: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS___thread, Loc, PrevSpec, DiagID); isStorageClass = true; break; case tok::kw_thread_local: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // HLSL Change - HLSL does not recognize these keywords isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS_thread_local, Loc, PrevSpec, DiagID); break; case tok::kw__Thread_local: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetStorageClassSpecThread(DeclSpec::TSCS__Thread_local, Loc, PrevSpec, DiagID); isStorageClass = true; break; // function-specifier case tok::kw_inline: isInvalid = DS.setFunctionSpecInline(Loc, PrevSpec, DiagID); break; case tok::kw_virtual: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - virtual is reserved for HLSL isInvalid = DS.setFunctionSpecVirtual(Loc, PrevSpec, DiagID); break; case tok::kw_explicit: isInvalid = DS.setFunctionSpecExplicit(Loc, PrevSpec, DiagID); break; case tok::kw__Noreturn: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - noreturn is reserved for HLSL if (!getLangOpts().C11) Diag(Loc, diag::ext_c11_noreturn); isInvalid = DS.setFunctionSpecNoreturn(Loc, PrevSpec, DiagID); break; // alignment-specifier case tok::kw__Alignas: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - _Alignas is reserved for HLSL if (!getLangOpts().C11) Diag(Tok, diag::ext_c11_alignment) << Tok.getName(); ParseAlignmentSpecifier(DS.getAttributes()); continue; // friend case tok::kw_friend: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - friend is reserved for HLSL if (DSContext == DSC_class) isInvalid = DS.SetFriendSpec(Loc, PrevSpec, DiagID); else { PrevSpec = ""; // not actually used by the diagnostic DiagID = diag::err_friend_invalid_in_context; isInvalid = true; } break; // Modules case tok::kw___module_private__: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.setModulePrivateSpec(Loc, PrevSpec, DiagID); break; // constexpr case tok::kw_constexpr: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetConstexprSpec(Loc, PrevSpec, DiagID); break; // concept case tok::kw_concept: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetConceptSpec(Loc, PrevSpec, DiagID); break; // type-specifier case tok::kw_short: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_long: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL if (DS.getTypeSpecWidth() != DeclSpec::TSW_long) isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy); else isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy); break; case tok::kw___int64: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_signed: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); break; case tok::kw_unsigned: isInvalid = DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID); break; case tok::kw__Complex: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_complex, Loc, PrevSpec, DiagID); break; case tok::kw__Imaginary: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetTypeSpecComplex(DeclSpec::TSC_imaginary, Loc, PrevSpec, DiagID); break; case tok::kw_void: isInvalid = DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_char: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - char is reserved for HLSL isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_int: isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy); break; case tok::kw___int128: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy); break; // HLSL Change Starts case tok::kw_half: isInvalid = DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_float: isInvalid = DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_double: isInvalid = DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_wchar_t: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_char16_t: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_char32_t: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL isInvalid = DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_bool: case tok::kw__Bool: if (Tok.is(tok::kw_bool) && DS.getTypeSpecType() != DeclSpec::TST_unspecified && DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { PrevSpec = ""; // Not used by the diagnostic. DiagID = getLangOpts().HLSL ? diag::err_hlsl_bool_redeclaration : diag::err_bool_redeclaration; // HLSL Change // For better error recovery. Tok.setKind(tok::identifier); isInvalid = true; } else { isInvalid = DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy); } break; case tok::kw__Decimal32: isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal32, Loc, PrevSpec, DiagID, Policy); break; case tok::kw__Decimal64: isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal64, Loc, PrevSpec, DiagID, Policy); break; case tok::kw__Decimal128: isInvalid = DS.SetTypeSpecType(DeclSpec::TST_decimal128, Loc, PrevSpec, DiagID, Policy); break; case tok::kw___vector: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // MS Change - HLSL does not recognize this keyword isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy); break; case tok::kw___pixel: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // MS Change - HLSL does not recognize this keyword isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy); break; case tok::kw___bool: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // MS Change - HLSL does not recognize this keyword isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy); break; case tok::kw___unknown_anytype: isInvalid = DS.SetTypeSpecType(TST_unknown_anytype, Loc, PrevSpec, DiagID, Policy); break; // class-specifier: case tok::kw_class: case tok::kw_struct: case tok::kw___interface: case tok::kw_interface: // HLSL Change case tok::kw_union: { // HLSL Change Starts if (getLangOpts().HLSL) { if (Tok.is(tok::kw_union) || Tok.is(tok::kw___interface)) { goto HLSLReservedKeyword; } } // HLSL Change Ends tok::TokenKind Kind = Tok.getKind(); ConsumeToken(); // These are attributes following class specifiers. // To produce better diagnostic, we parse them when // parsing class specifier. ParsedAttributesWithRange Attributes(AttrFactory); ParseClassSpecifier(Kind, Loc, DS, TemplateInfo, AS, EnteringContext, DSContext, Attributes); // If there are attributes following class specifier, // take them over and handle them here. if (!Attributes.empty()) { AttrsLastTime = true; attrs.takeAllFrom(Attributes); } continue; } // enum-specifier: case tok::kw_enum: ConsumeToken(); ParseEnumSpecifier(Loc, DS, TemplateInfo, AS, DSContext); continue; // cv-qualifier: case tok::kw_const: isInvalid = DS.SetTypeQual(DeclSpec::TQ_const, Loc, PrevSpec, DiagID, getLangOpts()); break; case tok::kw_volatile: isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, getLangOpts()); break; case tok::kw_restrict: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // HLSL Change - HLSL does not recognize this keyword isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, getLangOpts()); break; // C++ typename-specifier: case tok::kw_typename: if (getLangOpts().HLSL && getLangOpts().HLSLVersion < hlsl::LangStd::v2021) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL if (TryAnnotateTypeOrScopeToken()) { DS.SetTypeSpecError(); goto DoneWithDeclSpec; } if (!Tok.is(tok::kw_typename)) continue; break; // GNU typeof support. case tok::kw_typeof: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL ParseTypeofSpecifier(DS); continue; case tok::annot_decltype: ParseDecltypeSpecifier(DS); continue; case tok::kw___underlying_type: ParseUnderlyingTypeSpecifier(DS); continue; case tok::kw__Atomic: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL // C11 6.7.2.4/4: // If the _Atomic keyword is immediately followed by a left parenthesis, // it is interpreted as a type specifier (with a type name), not as a // type qualifier. if (NextToken().is(tok::l_paren)) { ParseAtomicSpecifier(DS); continue; } isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, getLangOpts()); break; // OpenCL qualifiers: case tok::kw___generic: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL // generic address space is introduced only in OpenCL v2.0 // see OpenCL C Spec v2.0 s6.5.5 if (Actions.getLangOpts().OpenCLVersion < 200) { DiagID = diag::err_opencl_unknown_type_specifier; PrevSpec = Tok.getIdentifierInfo()->getNameStart(); isInvalid = true; break; }; ParseOpenCLQualifiers(DS.getAttributes()); // HLSL Change - break; // avoid dead-code fallthrough case tok::kw___private: case tok::kw___global: case tok::kw___local: case tok::kw___constant: case tok::kw___read_only: case tok::kw___write_only: case tok::kw___read_write: if (getLangOpts().HLSL) { assert(false); goto DoneWithDeclSpec; } // MS Change - HLSL does not recognize these keywords ParseOpenCLQualifiers(DS.getAttributes()); break; case tok::less: // GCC ObjC supports types like "<SomeProtocol>" as a synonym for // "id<SomeProtocol>". This is hopelessly old fashioned and dangerous, // but we support it. if (DS.hasTypeSpecifier() || !getLangOpts().ObjC1) goto DoneWithDeclSpec; SourceLocation StartLoc = Tok.getLocation(); SourceLocation EndLoc; TypeResult Type = parseObjCProtocolQualifierType(EndLoc); if (Type.isUsable()) { if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, StartLoc, PrevSpec, DiagID, Type.get(), Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; DS.SetRangeEnd(EndLoc); } else { DS.SetTypeSpecError(); } // Need to support trailing type qualifiers (e.g. "id<p> const"). // If a type specifier follows, it will be diagnosed elsewhere. continue; } bool consume = DiagID != diag::err_bool_redeclaration; // HLSL Change // If the specifier wasn't legal, issue a diagnostic. if (isInvalid) { assert(PrevSpec && "Method did not return previous specifier!"); assert(DiagID); if (DiagID == diag::ext_duplicate_declspec) Diag(Tok, DiagID) << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); else if (DiagID == diag::err_opencl_unknown_type_specifier) Diag(Tok, DiagID) << PrevSpec << isStorageClass; else if (DiagID == diag::err_hlsl_reserved_keyword) Diag(Tok, DiagID) << Tok.getName(); // HLSL Change else if (DiagID == diag::err_hlsl_modifier_after_type) Diag(Tok, DiagID); // HLSL Change else Diag(Tok, DiagID) << PrevSpec; // HLSL Change Starts if (DiagID == diag::err_hlsl_reserved_keyword) { if (Tok.is(tok::kw__Alignas) || Tok.is(tok::kw_alignas) || Tok.is(tok::kw_alignof) || Tok.is(tok::kw__Alignof) || Tok.is(tok::kw___declspec) || Tok.is(tok::kw__Atomic) || Tok.is(tok::kw_typeof)) { // These are of the form keyword(stuff) decl; // After issuing the diagnostic, consume the keyword and everything between the parens. consume = false; ConsumeToken(); if (Tok.is(tok::l_paren)) { BalancedDelimiterTracker brackets(*this, tok::l_paren); brackets.consumeOpen(); brackets.skipToEnd(); } } } // HLSL Change Ends } DS.SetRangeEnd(Tok.getLocation()); if (consume) // HLSL Change ConsumeToken(); AttrsLastTime = false; } } /// ParseStructDeclaration - Parse a struct declaration without the terminating /// semicolon. /// /// struct-declaration: /// specifier-qualifier-list struct-declarator-list /// [GNU] __extension__ struct-declaration /// [GNU] specifier-qualifier-list /// struct-declarator-list: /// struct-declarator /// struct-declarator-list ',' struct-declarator /// [GNU] struct-declarator-list ',' attributes[opt] struct-declarator /// struct-declarator: /// declarator /// [GNU] declarator attributes[opt] /// declarator[opt] ':' constant-expression /// [GNU] declarator[opt] ':' constant-expression attributes[opt] /// void Parser::ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback) { if (Tok.is(tok::kw___extension__)) { // __extension__ silences extension warnings in the subexpression. ExtensionRAIIObject O(Diags); // Use RAII to do this. ConsumeToken(); return ParseStructDeclaration(DS, FieldsCallback); } // Parse the common specifier-qualifiers-list piece. ParseSpecifierQualifierList(DS); // If there are no declarators, this is a free-standing declaration // specifier. Let the actions module cope with it. if (Tok.is(tok::semi)) { Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS_none, DS); DS.complete(TheDecl); return; } // Read struct-declarators until we find the semicolon. bool FirstDeclarator = true; SourceLocation CommaLoc; while (1) { ParsingFieldDeclarator DeclaratorInfo(*this, DS); DeclaratorInfo.D.setCommaLoc(CommaLoc); // Attributes are only allowed here on successive declarators. if (!FirstDeclarator) MaybeParseGNUAttributes(DeclaratorInfo.D); /// struct-declarator: declarator /// struct-declarator: declarator[opt] ':' constant-expression if (Tok.isNot(tok::colon)) { // Don't parse FOO:BAR as if it were a typo for FOO::BAR. ColonProtectionRAIIObject X(*this); ParseDeclarator(DeclaratorInfo.D); } else DeclaratorInfo.D.SetIdentifier(nullptr, Tok.getLocation()); if (TryConsumeToken(tok::colon)) { ExprResult Res(ParseConstantExpression()); if (Res.isInvalid()) SkipUntil(tok::semi, StopBeforeMatch); else { // HLSL Change: no support for bitfields in HLSL if (getLangOpts().HLSL) Diag(Res.get()->getLocStart(), diag::err_hlsl_unsupported_construct) << "bitfield"; DeclaratorInfo.BitfieldSize = Res.get(); } } // If attributes exist after the declarator, parse them. MaybeParseGNUAttributes(DeclaratorInfo.D); // We're done with this declarator; invoke the callback. FieldsCallback(DeclaratorInfo); // If we don't have a comma, it is either the end of the list (a ';') // or an error, bail out. if (!TryConsumeToken(tok::comma, CommaLoc)) return; FirstDeclarator = false; } } /// ParseStructUnionBody /// struct-contents: /// struct-declaration-list /// [EXT] empty /// [GNU] "struct-declaration-list" without terminatoring ';' /// struct-declaration-list: /// struct-declaration /// struct-declaration-list struct-declaration /// [OBC] '@' 'defs' '(' class-name ')' /// void Parser::ParseStructUnionBody(SourceLocation RecordLoc, unsigned TagType, Decl *TagDecl) { PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, "parsing struct/union body"); assert(!getLangOpts().CPlusPlus && "C++ declarations not supported"); BalancedDelimiterTracker T(*this, tok::l_brace); if (T.consumeOpen()) return; ParseScope StructScope(this, Scope::ClassScope|Scope::DeclScope); Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); SmallVector<Decl *, 32> FieldDecls; // While we still have something to read, read the declarations in the struct. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { // Each iteration of this loop reads one struct-declaration. // Check for extraneous top-level semicolon. if (Tok.is(tok::semi)) { ConsumeExtraSemi(InsideStruct, TagType); continue; } // Parse _Static_assert declaration. if (Tok.is(tok::kw__Static_assert)) { SourceLocation DeclEnd; ParseStaticAssertDeclaration(DeclEnd); continue; } if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_pack)) { // HLSL Change - this annotation is never produced HandlePragmaPack(); continue; } if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_align)) { // HLSL Change - this annotation is never produced HandlePragmaAlign(); continue; } if (Tok.is(tok::annot_pragma_pack)) { HandlePragmaPack(); continue; } if (Tok.is(tok::annot_pragma_align)) { HandlePragmaAlign(); continue; } if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_openmp)) { // HLSL Change - annot_pragma_openmp is never produced for HLSL // Result can be ignored, because it must be always empty. auto Res = ParseOpenMPDeclarativeDirective(); assert(!Res); // Silence possible warnings. (void)Res; continue; } if (getLangOpts().HLSL || !Tok.is(tok::at)) { // HLSL Change - '@' is never produced for HLSL lexing auto CFieldCallback = [&](ParsingFieldDeclarator &FD) { // Install the declarator into the current TagDecl. Decl *Field = Actions.ActOnField(getCurScope(), TagDecl, FD.D.getDeclSpec().getSourceRange().getBegin(), FD.D, FD.BitfieldSize); FieldDecls.push_back(Field); FD.complete(Field); }; // Parse all the comma separated declarators. ParsingDeclSpec DS(*this); ParseStructDeclaration(DS, CFieldCallback); } else { // Handle @defs ConsumeToken(); if (!Tok.isObjCAtKeyword(tok::objc_defs)) { Diag(Tok, diag::err_unexpected_at); SkipUntil(tok::semi); continue; } ConsumeToken(); ExpectAndConsume(tok::l_paren); if (!Tok.is(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; SkipUntil(tok::semi); continue; } SmallVector<Decl *, 16> Fields; Actions.ActOnDefs(getCurScope(), TagDecl, Tok.getLocation(), Tok.getIdentifierInfo(), Fields); FieldDecls.insert(FieldDecls.end(), Fields.begin(), Fields.end()); ConsumeToken(); ExpectAndConsume(tok::r_paren); } if (TryConsumeToken(tok::semi)) continue; if (Tok.is(tok::r_brace)) { ExpectAndConsume(tok::semi, diag::ext_expected_semi_decl_list); break; } ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list); // Skip to end of block or statement to avoid ext-warning on extra ';'. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); // If we stopped at a ';', eat it. TryConsumeToken(tok::semi); } T.consumeClose(); ParsedAttributes attrs(AttrFactory); // If attributes exist after struct contents, parse them. MaybeParseGNUAttributes(attrs); Actions.ActOnFields(getCurScope(), RecordLoc, TagDecl, FieldDecls, T.getOpenLocation(), T.getCloseLocation(), attrs.getList()); StructScope.Exit(); Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getCloseLocation()); } /// ParseEnumSpecifier /// enum-specifier: [C99 6.7.2.2] /// 'enum' identifier[opt] '{' enumerator-list '}' ///[C99/C++]'enum' identifier[opt] '{' enumerator-list ',' '}' /// [GNU] 'enum' attributes[opt] identifier[opt] '{' enumerator-list ',' [opt] /// '}' attributes[opt] /// [MS] 'enum' __declspec[opt] identifier[opt] '{' enumerator-list ',' [opt] /// '}' /// 'enum' identifier /// [GNU] 'enum' attributes[opt] identifier /// /// [C++11] enum-head '{' enumerator-list[opt] '}' /// [C++11] enum-head '{' enumerator-list ',' '}' /// /// enum-head: [C++11] /// enum-key attribute-specifier-seq[opt] identifier[opt] enum-base[opt] /// enum-key attribute-specifier-seq[opt] nested-name-specifier /// identifier enum-base[opt] /// /// enum-key: [C++11] /// 'enum' /// 'enum' 'class' /// 'enum' 'struct' /// /// enum-base: [C++11] /// ':' type-specifier-seq /// /// [C++] elaborated-type-specifier: /// [C++] 'enum' '::'[opt] nested-name-specifier[opt] identifier /// void Parser::ParseEnumSpecifier(SourceLocation StartLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC) { // HLSL Change Starts if (getLangOpts().HLSL && getLangOpts().HLSLVersion < hlsl::LangStd::v2017) { Diag(Tok, diag::err_hlsl_enum); // Skip the rest of this declarator, up until the comma or semicolon. SkipUntil(tok::comma, StopAtSemi); return; } // HLSL Change Ends // Parse the tag portion of this. if (Tok.is(tok::code_completion)) { // Code completion for an enum name. Actions.CodeCompleteTag(getCurScope(), DeclSpec::TST_enum); return cutOffParsing(); } // If attributes exist after tag, parse them. ParsedAttributesWithRange attrs(AttrFactory); MaybeParseGNUAttributes(attrs); MaybeParseCXX11Attributes(attrs); MaybeParseMicrosoftDeclSpecs(attrs); MaybeParseHLSLAttributes(attrs); SourceLocation ScopedEnumKWLoc; bool IsScopedUsingClassTag = false; // In C++11, recognize 'enum class' and 'enum struct'. if (Tok.isOneOf(tok::kw_class, tok::kw_struct)) { // HLSL Change: Supress C++11 warning if (!getLangOpts().HLSL) Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_scoped_enum : diag::ext_scoped_enum); IsScopedUsingClassTag = Tok.is(tok::kw_class); ScopedEnumKWLoc = ConsumeToken(); // Attributes are not allowed between these keywords. Diagnose, // but then just treat them like they appeared in the right place. ProhibitAttributes(attrs); // They are allowed afterwards, though. MaybeParseGNUAttributes(attrs); MaybeParseCXX11Attributes(attrs); MaybeParseMicrosoftDeclSpecs(attrs); } // C++11 [temp.explicit]p12: // The usual access controls do not apply to names used to specify // explicit instantiations. // We extend this to also cover explicit specializations. Note that // we don't suppress if this turns out to be an elaborated type // specifier. bool shouldDelayDiagsInTag = (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); // Enum definitions should not be parsed in a trailing-return-type. bool AllowDeclaration = DSC != DSC_trailing; bool AllowFixedUnderlyingType = AllowDeclaration && (getLangOpts().CPlusPlus11 || getLangOpts().MicrosoftExt || getLangOpts().ObjC2 || getLangOpts().HLSLVersion >= hlsl::LangStd::v2017); CXXScopeSpec &SS = DS.getTypeSpecScope(); if (getLangOpts().CPlusPlus) { // "enum foo : bar;" is not a potential typo for "enum foo::bar;" // if a fixed underlying type is allowed. ColonProtectionRAIIObject X(*this, AllowFixedUnderlyingType); CXXScopeSpec Spec; if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(), /*EnteringContext=*/true)) return; if (Spec.isSet() && Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; if (Tok.isNot(tok::l_brace)) { // Has no name and is not a definition. // Skip the rest of this declarator, up until the comma or semicolon. SkipUntil(tok::comma, StopAtSemi); return; } } SS = Spec; } // Must have either 'enum name' or 'enum {...}'. if (Tok.isNot(tok::identifier) && Tok.isNot(tok::l_brace) && !(AllowFixedUnderlyingType && Tok.is(tok::colon))) { Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace; // Skip the rest of this declarator, up until the comma or semicolon. SkipUntil(tok::comma, StopAtSemi); return; } // If an identifier is present, consume and remember it. IdentifierInfo *Name = nullptr; SourceLocation NameLoc; if (Tok.is(tok::identifier)) { Name = Tok.getIdentifierInfo(); NameLoc = ConsumeToken(); } if (!Name && ScopedEnumKWLoc.isValid()) { // C++0x 7.2p2: The optional identifier shall not be omitted in the // declaration of a scoped enumeration. Diag(Tok, diag::err_scoped_enum_missing_identifier); ScopedEnumKWLoc = SourceLocation(); IsScopedUsingClassTag = false; } // Okay, end the suppression area. We'll decide whether to emit the // diagnostics in a second. if (shouldDelayDiagsInTag) diagsFromTag.done(); TypeResult BaseType; // Parse the fixed underlying type. bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; if (AllowFixedUnderlyingType && Tok.is(tok::colon)) { bool PossibleBitfield = false; if (CanBeBitfield) { // If we're in class scope, this can either be an enum declaration with // an underlying type, or a declaration of a bitfield member. We try to // use a simple disambiguation scheme first to catch the common cases // (integer literal, sizeof); if it's still ambiguous, we then consider // anything that's a simple-type-specifier followed by '(' as an // expression. This suffices because function types are not valid // underlying types anyway. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::ConstantEvaluated); TPResult TPR = isExpressionOrTypeSpecifierSimple(NextToken().getKind()); // If the next token starts an expression, we know we're parsing a // bit-field. This is the common case. if (TPR == TPResult::True) PossibleBitfield = true; // If the next token starts a type-specifier-seq, it may be either a // a fixed underlying type or the start of a function-style cast in C++; // lookahead one more token to see if it's obvious that we have a // fixed underlying type. else if (TPR == TPResult::False && GetLookAheadToken(2).getKind() == tok::semi) { // Consume the ':'. ConsumeToken(); } else { // We have the start of a type-specifier-seq, so we have to perform // tentative parsing to determine whether we have an expression or a // type. TentativeParsingAction TPA(*this); // Consume the ':'. ConsumeToken(); // If we see a type specifier followed by an open-brace, we have an // ambiguity between an underlying type and a C++11 braced // function-style cast. Resolve this by always treating it as an // underlying type. // FIXME: The standard is not entirely clear on how to disambiguate in // this case. if ((getLangOpts().CPlusPlus && isCXXDeclarationSpecifier(TPResult::True) != TPResult::True) || (!getLangOpts().CPlusPlus && !isDeclarationSpecifier(true))) { // We'll parse this as a bitfield later. PossibleBitfield = true; TPA.Revert(); } else { // We have a type-specifier-seq. TPA.Commit(); } } } else { // Consume the ':'. ConsumeToken(); } if (!PossibleBitfield) { SourceRange Range; BaseType = ParseTypeName(&Range); if (getLangOpts().CPlusPlus11) { Diag(StartLoc, diag::warn_cxx98_compat_enum_fixed_underlying_type); } else if (!getLangOpts().ObjC2) { if (getLangOpts().CPlusPlus) Diag(StartLoc, diag::ext_cxx11_enum_fixed_underlying_type) << Range; else Diag(StartLoc, diag::ext_c_enum_fixed_underlying_type) << Range; } } } // There are four options here. If we have 'friend enum foo;' then this is a // friend declaration, and cannot have an accompanying definition. If we have // 'enum foo;', then this is a forward declaration. If we have // 'enum foo {...' then this is a definition. Otherwise we have something // like 'enum foo xyz', a reference. // // This is needed to handle stuff like this right (C99 6.7.2.3p11): // enum foo {..}; void bar() { enum foo; } <- new foo in bar. // enum foo {..}; void bar() { enum foo x; } <- use of old foo. // Sema::TagUseKind TUK; if (!AllowDeclaration) { TUK = Sema::TUK_Reference; } else if (Tok.is(tok::l_brace)) { if (DS.isFriendSpecified()) { Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) << SourceRange(DS.getFriendSpecLoc()); ConsumeBrace(); SkipUntil(tok::r_brace, StopAtSemi); TUK = Sema::TUK_Friend; } else { TUK = Sema::TUK_Definition; } } else if (!isTypeSpecifier(DSC) && (Tok.is(tok::semi) || (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(CanBeBitfield)))) { TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; if (Tok.isNot(tok::semi)) { // A semicolon was missing after this declaration. Diagnose and recover. ExpectAndConsume(tok::semi, diag::err_expected_after, "enum"); PP.EnterToken(Tok); Tok.setKind(tok::semi); } } else { TUK = Sema::TUK_Reference; } // If this is an elaborated type specifier, and we delayed // diagnostics before, just merge them into the current pool. if (TUK == Sema::TUK_Reference && shouldDelayDiagsInTag) { diagsFromTag.redelay(); } MultiTemplateParamsArg TParams; if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && TUK != Sema::TUK_Reference) { if (!getLangOpts().CPlusPlus11 || !SS.isSet()) { // Skip the rest of this declarator, up until the comma or semicolon. Diag(Tok, diag::err_enum_template); SkipUntil(tok::comma, StopAtSemi); return; } if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { // Enumerations can't be explicitly instantiated. DS.SetTypeSpecError(); Diag(StartLoc, diag::err_explicit_instantiation_enum); return; } assert(TemplateInfo.TemplateParams && "no template parameters"); TParams = MultiTemplateParamsArg(TemplateInfo.TemplateParams->data(), TemplateInfo.TemplateParams->size()); } if (TUK == Sema::TUK_Reference) ProhibitAttributes(attrs); if (!Name && TUK != Sema::TUK_Definition) { Diag(Tok, diag::err_enumerator_unnamed_no_def); // Skip the rest of this declarator, up until the comma or semicolon. SkipUntil(tok::comma, StopAtSemi); return; } handleDeclspecAlignBeforeClassKey(attrs, DS, TUK); Sema::SkipBodyInfo SkipBody; if (!Name && TUK == Sema::TUK_Definition && Tok.is(tok::l_brace) && NextToken().is(tok::identifier)) SkipBody = Actions.shouldSkipAnonEnumBody(getCurScope(), NextToken().getIdentifierInfo(), NextToken().getLocation()); bool Owned = false; bool IsDependent = false; const char *PrevSpec = nullptr; unsigned DiagID; Decl *TagDecl = Actions.ActOnTag(getCurScope(), DeclSpec::TST_enum, TUK, StartLoc, SS, Name, NameLoc, attrs.getList(), AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent, ScopedEnumKWLoc, IsScopedUsingClassTag, BaseType, DSC == DSC_type_specifier, &SkipBody); if (SkipBody.ShouldSkip) { assert(TUK == Sema::TUK_Definition && "can only skip a definition"); BalancedDelimiterTracker T(*this, tok::l_brace); T.consumeOpen(); T.skipToEnd(); if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec, DiagID, TagDecl, Owned, Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; return; } if (IsDependent) { // This enum has a dependent nested-name-specifier. Handle it as a // dependent tag. if (!Name) { DS.SetTypeSpecError(); Diag(Tok, diag::err_expected_type_name_after_typename); return; } TypeResult Type = Actions.ActOnDependentTag( getCurScope(), DeclSpec::TST_enum, TUK, SS, Name, StartLoc, NameLoc); if (Type.isInvalid()) { DS.SetTypeSpecError(); return; } if (DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec, DiagID, Type.get(), Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; return; } if (!TagDecl) { // The action failed to produce an enumeration tag. If this is a // definition, consume the entire definition. if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) { ConsumeBrace(); SkipUntil(tok::r_brace, StopAtSemi); } DS.SetTypeSpecError(); return; } if (Tok.is(tok::l_brace) && TUK != Sema::TUK_Reference) ParseEnumBody(StartLoc, TagDecl); if (DS.SetTypeSpecType(DeclSpec::TST_enum, StartLoc, NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec, DiagID, TagDecl, Owned, Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; } /// ParseEnumBody - Parse a {} enclosed enumerator-list. /// enumerator-list: /// enumerator /// enumerator-list ',' enumerator /// enumerator: /// enumeration-constant attributes[opt] /// enumeration-constant attributes[opt] '=' constant-expression /// enumeration-constant: /// identifier /// void Parser::ParseEnumBody(SourceLocation StartLoc, Decl *EnumDecl) { assert(getLangOpts().HLSLVersion >= hlsl::LangStd::v2017 && "HLSL does not support enums before 2017"); // HLSL Change // Enter the scope of the enum body and start the definition. ParseScope EnumScope(this, Scope::DeclScope | Scope::EnumScope); Actions.ActOnTagStartDefinition(getCurScope(), EnumDecl); BalancedDelimiterTracker T(*this, tok::l_brace); T.consumeOpen(); // C does not allow an empty enumerator-list, C++ does [dcl.enum]. if (Tok.is(tok::r_brace) && !getLangOpts().CPlusPlus) Diag(Tok, diag::error_empty_enum); SmallVector<Decl *, 32> EnumConstantDecls; SmallVector<SuppressAccessChecks, 32> EnumAvailabilityDiags; Decl *LastEnumConstDecl = nullptr; // Parse the enumerator-list. while (Tok.isNot(tok::r_brace)) { // Parse enumerator. If failed, try skipping till the start of the next // enumerator definition. if (Tok.isNot(tok::identifier)) { Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch) && TryConsumeToken(tok::comma)) continue; break; } IdentifierInfo *Ident = Tok.getIdentifierInfo(); SourceLocation IdentLoc = ConsumeToken(); // If attributes exist after the enumerator, parse them. ParsedAttributesWithRange attrs(AttrFactory); MaybeParseGNUAttributes(attrs); ProhibitAttributes(attrs); // GNU-style attributes are prohibited. if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) { if (!getLangOpts().CPlusPlus1z) Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute) << 1 /*enumerator*/; ParseCXX11Attributes(attrs); } MaybeParseHLSLAttributes(attrs); SourceLocation EqualLoc; ExprResult AssignedVal; EnumAvailabilityDiags.emplace_back(*this); if (TryConsumeToken(tok::equal, EqualLoc)) { AssignedVal = ParseConstantExpression(); if (AssignedVal.isInvalid()) SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch); } // Install the enumerator constant into EnumDecl. Decl *EnumConstDecl = Actions.ActOnEnumConstant(getCurScope(), EnumDecl, LastEnumConstDecl, IdentLoc, Ident, attrs.getList(), EqualLoc, AssignedVal.get()); EnumAvailabilityDiags.back().done(); EnumConstantDecls.push_back(EnumConstDecl); LastEnumConstDecl = EnumConstDecl; if (Tok.is(tok::identifier)) { // We're missing a comma between enumerators. SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); Diag(Loc, diag::err_enumerator_list_missing_comma) << FixItHint::CreateInsertion(Loc, ", "); continue; } // Emumerator definition must be finished, only comma or r_brace are // allowed here. SourceLocation CommaLoc; if (Tok.isNot(tok::r_brace) && !TryConsumeToken(tok::comma, CommaLoc)) { if (EqualLoc.isValid()) Diag(Tok.getLocation(), diag::err_expected_either) << tok::r_brace << tok::comma; else Diag(Tok.getLocation(), diag::err_expected_end_of_enumerator); if (SkipUntil(tok::comma, tok::r_brace, StopBeforeMatch)) { if (TryConsumeToken(tok::comma, CommaLoc)) continue; } else { break; } } // If comma is followed by r_brace, emit appropriate warning. if (Tok.is(tok::r_brace) && CommaLoc.isValid()) { if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) Diag(CommaLoc, getLangOpts().CPlusPlus ? diag::ext_enumerator_list_comma_cxx : diag::ext_enumerator_list_comma_c) << FixItHint::CreateRemoval(CommaLoc); else if (getLangOpts().CPlusPlus11) Diag(CommaLoc, diag::warn_cxx98_compat_enumerator_list_comma) << FixItHint::CreateRemoval(CommaLoc); break; } } // Eat the }. T.consumeClose(); // If attributes exist after the identifier list, parse them. ParsedAttributes attrs(AttrFactory); MaybeParseGNUAttributes(attrs); Actions.ActOnEnumBody(StartLoc, T.getOpenLocation(), T.getCloseLocation(), EnumDecl, EnumConstantDecls, getCurScope(), attrs.getList()); // Now handle enum constant availability diagnostics. assert(EnumConstantDecls.size() == EnumAvailabilityDiags.size()); for (size_t i = 0, e = EnumConstantDecls.size(); i != e; ++i) { ParsingDeclRAIIObject PD(*this, ParsingDeclRAIIObject::NoParent); EnumAvailabilityDiags[i].redelay(); PD.complete(EnumConstantDecls[i]); } EnumScope.Exit(); Actions.ActOnTagFinishDefinition(getCurScope(), EnumDecl, T.getCloseLocation()); // The next token must be valid after an enum definition. If not, a ';' // was probably forgotten. bool CanBeBitfield = getCurScope()->getFlags() & Scope::ClassScope; if (!isValidAfterTypeSpecifier(CanBeBitfield)) { ExpectAndConsume(tok::semi, diag::err_expected_after, "enum"); // Push this token back into the preprocessor and change our current token // to ';' so that the rest of the code recovers as though there were an // ';' after the definition. PP.EnterToken(Tok); Tok.setKind(tok::semi); } } /// isTypeSpecifierQualifier - Return true if the current token could be the /// start of a type-qualifier-list. bool Parser::isTypeQualifier() const { assert(!getLangOpts().HLSL && "not updated for HLSL, unreachable (only called from Parser::ParseAsmStatement)"); // HLSL Change switch (Tok.getKind()) { default: return false; // type-qualifier case tok::kw_const: case tok::kw_volatile: case tok::kw_restrict: case tok::kw___private: case tok::kw___local: case tok::kw___global: case tok::kw___constant: case tok::kw___generic: case tok::kw___read_only: case tok::kw___read_write: case tok::kw___write_only: return true; } } /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool Parser::isKnownToBeTypeSpecifier(const Token &Tok) const { switch (Tok.getKind()) { default: return false; // type-specifiers case tok::kw_short: case tok::kw_long: case tok::kw___int64: case tok::kw___int128: case tok::kw_signed: case tok::kw_unsigned: case tok::kw__Complex: case tok::kw__Imaginary: case tok::kw_void: case tok::kw_char: case tok::kw_wchar_t: case tok::kw_char16_t: case tok::kw_char32_t: case tok::kw_int: case tok::kw_half: case tok::kw_float: case tok::kw_double: case tok::kw_bool: case tok::kw__Bool: case tok::kw__Decimal32: case tok::kw__Decimal64: case tok::kw__Decimal128: case tok::kw___vector: // struct-or-union-specifier (C99) or class-specifier (C++) case tok::kw_class: case tok::kw_struct: case tok::kw___interface: case tok::kw_union: // enum-specifier case tok::kw_enum: // typedef-name case tok::annot_typename: return true; } } /// isTypeSpecifierQualifier - Return true if the current token could be the /// start of a specifier-qualifier-list. bool Parser::isTypeSpecifierQualifier() { assert(!getLangOpts().HLSL && "not updated for HLSL, unreachable (only called from Parser::ParseObjCTypeName)"); // HLSL Change switch (Tok.getKind()) { default: return false; case tok::identifier: // foo::bar if (TryAltiVecVectorToken()) return true; LLVM_FALLTHROUGH; // HLSL Change. case tok::kw_typename: // typename T::type // Annotate typenames and C++ scope specifiers. If we get one, just // recurse to handle whatever we get. if (TryAnnotateTypeOrScopeToken()) return true; if (Tok.is(tok::identifier)) return false; return isTypeSpecifierQualifier(); case tok::coloncolon: // ::foo::bar if (NextToken().is(tok::kw_new) || // ::new NextToken().is(tok::kw_delete)) // ::delete return false; if (TryAnnotateTypeOrScopeToken()) return true; return isTypeSpecifierQualifier(); // GNU attributes support. case tok::kw___attribute: // GNU typeof support. case tok::kw_typeof: // type-specifiers case tok::kw_short: case tok::kw_long: case tok::kw___int64: case tok::kw___int128: case tok::kw_signed: case tok::kw_unsigned: case tok::kw__Complex: case tok::kw__Imaginary: case tok::kw_void: case tok::kw_char: case tok::kw_wchar_t: case tok::kw_char16_t: case tok::kw_char32_t: case tok::kw_int: case tok::kw_half: case tok::kw_float: case tok::kw_double: case tok::kw_bool: case tok::kw__Bool: case tok::kw__Decimal32: case tok::kw__Decimal64: case tok::kw__Decimal128: case tok::kw___vector: // struct-or-union-specifier (C99) or class-specifier (C++) case tok::kw_class: case tok::kw_struct: case tok::kw___interface: case tok::kw_union: // enum-specifier case tok::kw_enum: // type-qualifier case tok::kw_const: case tok::kw_volatile: case tok::kw_restrict: // Debugger support. case tok::kw___unknown_anytype: // typedef-name case tok::annot_typename: // HLSL Change Starts case tok::kw_column_major: case tok::kw_row_major: case tok::kw_snorm: case tok::kw_unorm: // HLSL Change Ends return true; // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. case tok::less: return getLangOpts().ObjC1; case tok::kw___cdecl: case tok::kw___stdcall: case tok::kw___fastcall: case tok::kw___thiscall: case tok::kw___vectorcall: case tok::kw___w64: case tok::kw___ptr64: case tok::kw___ptr32: case tok::kw___pascal: case tok::kw___unaligned: case tok::kw__Nonnull: case tok::kw__Nullable: case tok::kw__Null_unspecified: case tok::kw___kindof: case tok::kw___private: case tok::kw___local: case tok::kw___global: case tok::kw___constant: case tok::kw___generic: case tok::kw___read_only: case tok::kw___read_write: case tok::kw___write_only: return true; // C11 _Atomic case tok::kw__Atomic: return true; } } /// isDeclarationSpecifier() - Return true if the current token is part of a /// declaration specifier. /// /// \param DisambiguatingWithExpression True to indicate that the purpose of /// this check is to disambiguate between an expression and a declaration. bool Parser::isDeclarationSpecifier(bool DisambiguatingWithExpression) { switch (Tok.getKind()) { default: return false; case tok::identifier: // foo::bar // Unfortunate hack to support "Class.factoryMethod" notation. if (getLangOpts().ObjC1 && NextToken().is(tok::period)) return false; if (TryAltiVecVectorToken()) return true; LLVM_FALLTHROUGH; // HLSL Change. case tok::kw_decltype: // decltype(T())::type case tok::kw_typename: // typename T::type // Annotate typenames and C++ scope specifiers. If we get one, just // recurse to handle whatever we get. if (TryAnnotateTypeOrScopeToken()) return true; if (Tok.is(tok::identifier)) return false; // If we're in Objective-C and we have an Objective-C class type followed // by an identifier and then either ':' or ']', in a place where an // expression is permitted, then this is probably a class message send // missing the initial '['. In this case, we won't consider this to be // the start of a declaration. if (DisambiguatingWithExpression && isStartOfObjCClassMessageMissingOpenBracket()) return false; return isDeclarationSpecifier(); case tok::coloncolon: // ::foo::bar if (NextToken().is(tok::kw_new) || // ::new NextToken().is(tok::kw_delete)) // ::delete return false; // Annotate typenames and C++ scope specifiers. If we get one, just // recurse to handle whatever we get. if (TryAnnotateTypeOrScopeToken()) return true; return isDeclarationSpecifier(); // HLSL Change Starts case tok::kw_precise: case tok::kw_center: case tok::kw_shared: case tok::kw_groupshared: case tok::kw_globallycoherent: case tok::kw_uniform: case tok::kw_in: case tok::kw_out: case tok::kw_inout: case tok::kw_linear: case tok::kw_nointerpolation: case tok::kw_noperspective: case tok::kw_sample: case tok::kw_centroid: case tok::kw_column_major: case tok::kw_row_major: case tok::kw_snorm: case tok::kw_unorm: case tok::kw_point: case tok::kw_line: case tok::kw_lineadj: case tok::kw_triangle: case tok::kw_triangleadj: case tok::kw_export: case tok::kw_indices: case tok::kw_vertices: case tok::kw_primitives: case tok::kw_payload: return true; // HLSL Change Ends // storage-class-specifier case tok::kw_typedef: case tok::kw_extern: case tok::kw___private_extern__: case tok::kw_static: case tok::kw_auto: case tok::kw_register: case tok::kw___thread: case tok::kw_thread_local: case tok::kw__Thread_local: // Modules case tok::kw___module_private__: // Debugger support case tok::kw___unknown_anytype: // type-specifiers case tok::kw_short: case tok::kw_long: case tok::kw___int64: case tok::kw___int128: case tok::kw_signed: case tok::kw_unsigned: case tok::kw__Complex: case tok::kw__Imaginary: case tok::kw_void: case tok::kw_char: case tok::kw_wchar_t: case tok::kw_char16_t: case tok::kw_char32_t: case tok::kw_int: case tok::kw_half: case tok::kw_float: case tok::kw_double: case tok::kw_bool: case tok::kw__Bool: case tok::kw__Decimal32: case tok::kw__Decimal64: case tok::kw__Decimal128: case tok::kw___vector: // struct-or-union-specifier (C99) or class-specifier (C++) case tok::kw_class: case tok::kw_struct: case tok::kw_union: case tok::kw___interface: // enum-specifier case tok::kw_enum: // type-qualifier case tok::kw_const: case tok::kw_volatile: case tok::kw_restrict: // function-specifier case tok::kw_inline: case tok::kw_virtual: case tok::kw_explicit: case tok::kw__Noreturn: // alignment-specifier case tok::kw__Alignas: // friend keyword. case tok::kw_friend: // static_assert-declaration case tok::kw__Static_assert: // GNU typeof support. case tok::kw_typeof: // GNU attributes. case tok::kw___attribute: // C++11 decltype and constexpr. case tok::annot_decltype: case tok::kw_constexpr: // C++ Concepts TS - concept case tok::kw_concept: // C11 _Atomic case tok::kw__Atomic: return true; // GNU ObjC bizarre protocol extension: <proto1,proto2> with implicit 'id'. case tok::less: return getLangOpts().ObjC1; // typedef-name case tok::annot_typename: return !DisambiguatingWithExpression || !isStartOfObjCClassMessageMissingOpenBracket(); case tok::kw___declspec: case tok::kw___cdecl: case tok::kw___stdcall: case tok::kw___fastcall: case tok::kw___thiscall: case tok::kw___vectorcall: case tok::kw___w64: case tok::kw___sptr: case tok::kw___uptr: case tok::kw___ptr64: case tok::kw___ptr32: case tok::kw___forceinline: case tok::kw___pascal: case tok::kw___unaligned: case tok::kw__Nonnull: case tok::kw__Nullable: case tok::kw__Null_unspecified: case tok::kw___kindof: case tok::kw___private: case tok::kw___local: case tok::kw___global: case tok::kw___constant: case tok::kw___generic: case tok::kw___read_only: case tok::kw___read_write: case tok::kw___write_only: return true; } } bool Parser::isConstructorDeclarator(bool IsUnqualified) { TentativeParsingAction TPA(*this); // Parse the C++ scope specifier. CXXScopeSpec SS; if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/true)) { TPA.Revert(); return false; } // Parse the constructor name. if (Tok.isOneOf(tok::identifier, tok::annot_template_id)) { // We already know that we have a constructor name; just consume // the token. ConsumeToken(); } else { TPA.Revert(); return false; } // Current class name must be followed by a left parenthesis. if (Tok.isNot(tok::l_paren)) { TPA.Revert(); return false; } ConsumeParen(); // A right parenthesis, or ellipsis followed by a right parenthesis signals // that we have a constructor. if (Tok.is(tok::r_paren) || (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren))) { TPA.Revert(); return true; } // A C++11 attribute here signals that we have a constructor, and is an // attribute on the first constructor parameter. if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier(/*Disambiguate*/ false, /*OuterMightBeMessageSend*/ true)) { TPA.Revert(); return true; } // If we need to, enter the specified scope. DeclaratorScopeObj DeclScopeObj(*this, SS); if (SS.isSet() && Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) DeclScopeObj.EnterDeclaratorScope(); // Optionally skip Microsoft attributes. ParsedAttributes Attrs(AttrFactory); MaybeParseMicrosoftAttributes(Attrs); // Check whether the next token(s) are part of a declaration // specifier, in which case we have the start of a parameter and, // therefore, we know that this is a constructor. bool IsConstructor = false; if (isDeclarationSpecifier()) IsConstructor = true; else if (Tok.is(tok::identifier) || (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier))) { // We've seen "C ( X" or "C ( X::Y", but "X" / "X::Y" is not a type. // This might be a parenthesized member name, but is more likely to // be a constructor declaration with an invalid argument type. Keep // looking. if (Tok.is(tok::annot_cxxscope)) ConsumeToken(); ConsumeToken(); // If this is not a constructor, we must be parsing a declarator, // which must have one of the following syntactic forms (see the // grammar extract at the start of ParseDirectDeclarator): switch (Tok.getKind()) { case tok::l_paren: // C(X ( int)); case tok::l_square: // C(X [ 5]); // C(X [ [attribute]]); case tok::coloncolon: // C(X :: Y); // C(X :: *p); // Assume this isn't a constructor, rather than assuming it's a // constructor with an unnamed parameter of an ill-formed type. break; case tok::r_paren: // C(X ) if (NextToken().is(tok::colon) || NextToken().is(tok::kw_try)) { // Assume these were meant to be constructors: // C(X) : (the name of a bit-field cannot be parenthesized). // C(X) try (this is otherwise ill-formed). IsConstructor = true; } if (NextToken().is(tok::semi) || NextToken().is(tok::l_brace)) { // If we have a constructor name within the class definition, // assume these were meant to be constructors: // C(X) { // C(X) ; // ... because otherwise we would be declaring a non-static data // member that is ill-formed because it's of the same type as its // surrounding class. // // FIXME: We can actually do this whether or not the name is qualified, // because if it is qualified in this context it must be being used as // a constructor name. However, we do not implement that rule correctly // currently, so we're somewhat conservative here. IsConstructor = IsUnqualified; } break; default: IsConstructor = true; break; } } TPA.Revert(); return IsConstructor; } /// ParseTypeQualifierListOpt /// type-qualifier-list: [C99 6.7.5] /// type-qualifier /// [vendor] attributes /// [ only if AttrReqs & AR_VendorAttributesParsed ] /// type-qualifier-list type-qualifier /// [vendor] type-qualifier-list attributes /// [ only if AttrReqs & AR_VendorAttributesParsed ] /// [C++0x] attribute-specifier[opt] is allowed before cv-qualifier-seq /// [ only if AttReqs & AR_CXX11AttributesParsed ] /// Note: vendor can be GNU, MS, etc and can be explicitly controlled via /// AttrRequirements bitmask values. void Parser::ParseTypeQualifierListOpt(DeclSpec &DS, unsigned AttrReqs, bool AtomicAllowed, bool IdentifierRequired) { if (getLangOpts().CPlusPlus11 && (AttrReqs & AR_CXX11AttributesParsed) && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); ParseCXX11Attributes(attrs); DS.takeAttributesFrom(attrs); } SourceLocation EndLoc; while (1) { bool isInvalid = false; const char *PrevSpec = nullptr; unsigned DiagID = 0; SourceLocation Loc = Tok.getLocation(); // HLSL Change Starts // This is a simpler version of the switch available below; HLSL does not allow // most constructs in this position. if (getLangOpts().HLSL) { switch (Tok.getKind()) { case tok::code_completion: Actions.CodeCompleteTypeQualifiers(DS); return cutOffParsing(); case tok::kw___attribute: if (AttrReqs & AR_GNUAttributesParsed) { ParseGNUAttributes(DS.getAttributes()); continue; // do *not* consume the next token! } // otherwise, FALL THROUGH! LLVM_FALLTHROUGH; // HLSL Change default: // If this is not a type-qualifier token, we're done reading type // qualifiers. First verify that DeclSpec's are consistent. DS.Finish(Diags, PP, Actions.getPrintingPolicy()); if (EndLoc.isValid()) DS.SetRangeEnd(EndLoc); return; } // If the specifier combination wasn't legal, issue a diagnostic. EndLoc = ConsumeToken(); continue; } // HLSL Change Ends switch (Tok.getKind()) { case tok::code_completion: Actions.CodeCompleteTypeQualifiers(DS); return cutOffParsing(); case tok::kw_const: isInvalid = DS.SetTypeQual(DeclSpec::TQ_const , Loc, PrevSpec, DiagID, getLangOpts()); break; case tok::kw_volatile: isInvalid = DS.SetTypeQual(DeclSpec::TQ_volatile, Loc, PrevSpec, DiagID, getLangOpts()); break; case tok::kw_restrict: isInvalid = DS.SetTypeQual(DeclSpec::TQ_restrict, Loc, PrevSpec, DiagID, getLangOpts()); break; case tok::kw__Atomic: if (!AtomicAllowed) goto DoneWithTypeQuals; isInvalid = DS.SetTypeQual(DeclSpec::TQ_atomic, Loc, PrevSpec, DiagID, getLangOpts()); break; // OpenCL qualifiers: case tok::kw___private: case tok::kw___global: case tok::kw___local: case tok::kw___constant: case tok::kw___generic: case tok::kw___read_only: case tok::kw___write_only: case tok::kw___read_write: ParseOpenCLQualifiers(DS.getAttributes()); break; case tok::kw___uptr: // GNU libc headers in C mode use '__uptr' as an identifer which conflicts // with the MS modifier keyword. if ((AttrReqs & AR_DeclspecAttributesParsed) && !getLangOpts().CPlusPlus && IdentifierRequired && DS.isEmpty() && NextToken().is(tok::semi)) { if (TryKeywordIdentFallback(false)) continue; } LLVM_FALLTHROUGH; // HLSL Change case tok::kw___sptr: case tok::kw___w64: case tok::kw___ptr64: case tok::kw___ptr32: case tok::kw___cdecl: case tok::kw___stdcall: case tok::kw___fastcall: case tok::kw___thiscall: case tok::kw___vectorcall: case tok::kw___unaligned: if (AttrReqs & AR_DeclspecAttributesParsed) { ParseMicrosoftTypeAttributes(DS.getAttributes()); continue; } goto DoneWithTypeQuals; case tok::kw___pascal: if (AttrReqs & AR_VendorAttributesParsed) { ParseBorlandTypeAttributes(DS.getAttributes()); continue; } goto DoneWithTypeQuals; // Nullability type specifiers. case tok::kw__Nonnull: case tok::kw__Nullable: case tok::kw__Null_unspecified: ParseNullabilityTypeSpecifiers(DS.getAttributes()); continue; // Objective-C 'kindof' types. case tok::kw___kindof: DS.getAttributes().addNew(Tok.getIdentifierInfo(), Loc, nullptr, Loc, nullptr, 0, AttributeList::AS_Keyword); (void)ConsumeToken(); continue; case tok::kw___attribute: if (AttrReqs & AR_GNUAttributesParsedAndRejected) // When GNU attributes are expressly forbidden, diagnose their usage. Diag(Tok, diag::err_attributes_not_allowed); // Parse the attributes even if they are rejected to ensure that error // recovery is graceful. if (AttrReqs & AR_GNUAttributesParsed || AttrReqs & AR_GNUAttributesParsedAndRejected) { ParseGNUAttributes(DS.getAttributes()); continue; // do *not* consume the next token! } // otherwise, FALL THROUGH! LLVM_FALLTHROUGH; // HLSL Change default: DoneWithTypeQuals: // If this is not a type-qualifier token, we're done reading type // qualifiers. First verify that DeclSpec's are consistent. DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy()); if (EndLoc.isValid()) DS.SetRangeEnd(EndLoc); return; } // If the specifier combination wasn't legal, issue a diagnostic. if (isInvalid) { assert(PrevSpec && "Method did not return previous specifier!"); Diag(Tok, DiagID) << PrevSpec; } EndLoc = ConsumeToken(); } } /// ParseDeclarator - Parse and verify a newly-initialized declarator. /// void Parser::ParseDeclarator(Declarator &D) { /// This implements the 'declarator' production in the C grammar, then checks /// for well-formedness and issues diagnostics. ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); } static bool isPtrOperatorToken(tok::TokenKind Kind, const LangOptions &Lang, unsigned TheContext) { if (Kind == tok::star || Kind == tok::caret) return true; if (!Lang.CPlusPlus) return false; if (Kind == tok::amp) return true; // We parse rvalue refs in C++03, because otherwise the errors are scary. // But we must not parse them in conversion-type-ids and new-type-ids, since // those can be legitimately followed by a && operator. // (The same thing can in theory happen after a trailing-return-type, but // since those are a C++11 feature, there is no rejects-valid issue there.) if (Kind == tok::ampamp) return Lang.CPlusPlus11 || (TheContext != Declarator::ConversionIdContext && TheContext != Declarator::CXXNewContext); return false; } /// ParseDeclaratorInternal - Parse a C or C++ declarator. The direct-declarator /// is parsed by the function passed to it. Pass null, and the direct-declarator /// isn't parsed at all, making this function effectively parse the C++ /// ptr-operator production. /// /// If the grammar of this construct is extended, matching changes must also be /// made to TryParseDeclarator and MightBeDeclarator, and possibly to /// isConstructorDeclarator. /// /// declarator: [C99 6.7.5] [C++ 8p4, dcl.decl] /// [C] pointer[opt] direct-declarator /// [C++] direct-declarator /// [C++] ptr-operator declarator /// /// pointer: [C99 6.7.5] /// '*' type-qualifier-list[opt] /// '*' type-qualifier-list[opt] pointer /// /// ptr-operator: /// '*' cv-qualifier-seq[opt] /// '&' /// [C++0x] '&&' /// [GNU] '&' restrict[opt] attributes[opt] /// [GNU?] '&&' restrict[opt] attributes[opt] /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] void Parser::ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser) { if (Diags.hasAllExtensionsSilenced()) D.setExtension(); // C++ member pointers start with a '::' or a nested-name. // Member pointers get special handling, since there's no place for the // scope spec in the generic path below. if (getLangOpts().CPlusPlus && (Tok.is(tok::coloncolon) || (Tok.is(tok::identifier) && (NextToken().is(tok::coloncolon) || NextToken().is(tok::less))) || Tok.is(tok::annot_cxxscope))) { bool EnteringContext = D.getContext() == Declarator::FileContext || D.getContext() == Declarator::MemberContext; CXXScopeSpec SS; ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext); if (SS.isNotEmpty()) { if (Tok.isNot(tok::star)) { // The scope spec really belongs to the direct-declarator. if (D.mayHaveIdentifier()) D.getCXXScopeSpec() = SS; else AnnotateScopeToken(SS, true); if (DirectDeclParser) (this->*DirectDeclParser)(D); return; } // HLSL Change Starts - No pointer support in HLSL. if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_pointer); D.SetIdentifier(0, Tok.getLocation()); D.setInvalidType(); return; } // HLSL Change Ends SourceLocation Loc = ConsumeToken(); D.SetRangeEnd(Loc); DeclSpec DS(AttrFactory); ParseTypeQualifierListOpt(DS); D.ExtendWithDeclSpec(DS); // Recurse to parse whatever is left. ParseDeclaratorInternal(D, DirectDeclParser); // Sema will have to catch (syntactically invalid) pointers into global // scope. It has to catch pointers into namespace scope anyway. D.AddTypeInfo(DeclaratorChunk::getMemberPointer(SS,DS.getTypeQualifiers(), DS.getLocEnd()), DS.getAttributes(), /* Don't replace range end. */SourceLocation()); return; } } tok::TokenKind Kind = Tok.getKind(); // HLSL Change Starts - HLSL doesn't support pointers, references or blocks if (getLangOpts().HLSL && isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) { Diag(Tok, diag::err_hlsl_unsupported_pointer); } // HLSL Change Ends // Not a pointer, C++ reference, or block. if (!isPtrOperatorToken(Kind, getLangOpts(), D.getContext())) { if (DirectDeclParser) (this->*DirectDeclParser)(D); return; } // Otherwise, '*' -> pointer, '^' -> block, '&' -> lvalue reference, // '&&' -> rvalue reference SourceLocation Loc = ConsumeToken(); // Eat the *, ^, & or &&. D.SetRangeEnd(Loc); if (Kind == tok::star || Kind == tok::caret) { // Is a pointer. DeclSpec DS(AttrFactory); // GNU attributes are not allowed here in a new-type-id, but Declspec and // C++11 attributes are allowed. unsigned Reqs = AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed | ((D.getContext() != Declarator::CXXNewContext) ? AR_GNUAttributesParsed : AR_GNUAttributesParsedAndRejected); ParseTypeQualifierListOpt(DS, Reqs, true, !D.mayOmitIdentifier()); D.ExtendWithDeclSpec(DS); // Recursively parse the declarator. ParseDeclaratorInternal(D, DirectDeclParser); if (Kind == tok::star) // Remember that we parsed a pointer type, and remember the type-quals. D.AddTypeInfo(DeclaratorChunk::getPointer(DS.getTypeQualifiers(), Loc, DS.getConstSpecLoc(), DS.getVolatileSpecLoc(), DS.getRestrictSpecLoc(), DS.getAtomicSpecLoc()), DS.getAttributes(), SourceLocation()); else // Remember that we parsed a Block type, and remember the type-quals. D.AddTypeInfo(DeclaratorChunk::getBlockPointer(DS.getTypeQualifiers(), Loc), DS.getAttributes(), SourceLocation()); } else { // Is a reference DeclSpec DS(AttrFactory); // Complain about rvalue references in C++03, but then go on and build // the declarator. if (Kind == tok::ampamp) Diag(Loc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_rvalue_reference : diag::ext_rvalue_reference); // GNU-style and C++11 attributes are allowed here, as is restrict. ParseTypeQualifierListOpt(DS); D.ExtendWithDeclSpec(DS); // C++ 8.3.2p1: cv-qualified references are ill-formed except when the // cv-qualifiers are introduced through the use of a typedef or of a // template type argument, in which case the cv-qualifiers are ignored. if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { if (DS.getTypeQualifiers() & DeclSpec::TQ_const) Diag(DS.getConstSpecLoc(), diag::err_invalid_reference_qualifier_application) << "const"; if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) Diag(DS.getVolatileSpecLoc(), diag::err_invalid_reference_qualifier_application) << "volatile"; // 'restrict' is permitted as an extension. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) Diag(DS.getAtomicSpecLoc(), diag::err_invalid_reference_qualifier_application) << "_Atomic"; } // Recursively parse the declarator. ParseDeclaratorInternal(D, DirectDeclParser); if (D.getNumTypeObjects() > 0) { // C++ [dcl.ref]p4: There shall be no references to references. DeclaratorChunk& InnerChunk = D.getTypeObject(D.getNumTypeObjects() - 1); if (InnerChunk.Kind == DeclaratorChunk::Reference) { if (const IdentifierInfo *II = D.getIdentifier()) Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) << II; else Diag(InnerChunk.Loc, diag::err_illegal_decl_reference_to_reference) << "type name"; // Once we've complained about the reference-to-reference, we // can go ahead and build the (technically ill-formed) // declarator: reference collapsing will take care of it. } } // Remember that we parsed a reference type. D.AddTypeInfo(DeclaratorChunk::getReference(DS.getTypeQualifiers(), Loc, Kind == tok::amp), DS.getAttributes(), SourceLocation()); } } // When correcting from misplaced brackets before the identifier, the location // is saved inside the declarator so that other diagnostic messages can use // them. This extracts and returns that location, or returns the provided // location if a stored location does not exist. static SourceLocation getMissingDeclaratorIdLoc(Declarator &D, SourceLocation Loc) { if (D.getName().StartLocation.isInvalid() && D.getName().EndLocation.isValid()) return D.getName().EndLocation; return Loc; } /// ParseDirectDeclarator /// direct-declarator: [C99 6.7.5] /// [C99] identifier /// '(' declarator ')' /// [GNU] '(' attributes declarator ')' /// [C90] direct-declarator '[' constant-expression[opt] ']' /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' /// [C++11] direct-declarator '[' constant-expression[opt] ']' /// attribute-specifier-seq[opt] /// direct-declarator '(' parameter-type-list ')' /// direct-declarator '(' identifier-list[opt] ')' /// [GNU] direct-declarator '(' parameter-forward-declarations /// parameter-type-list[opt] ')' /// [C++] direct-declarator '(' parameter-declaration-clause ')' /// cv-qualifier-seq[opt] exception-specification[opt] /// [C++11] direct-declarator '(' parameter-declaration-clause ')' /// attribute-specifier-seq[opt] cv-qualifier-seq[opt] /// ref-qualifier[opt] exception-specification[opt] /// [C++] declarator-id /// [C++11] declarator-id attribute-specifier-seq[opt] /// /// declarator-id: [C++ 8] /// '...'[opt] id-expression /// '::'[opt] nested-name-specifier[opt] type-name /// /// id-expression: [C++ 5.1] /// unqualified-id /// qualified-id /// /// unqualified-id: [C++ 5.1] /// identifier /// operator-function-id /// conversion-function-id /// '~' class-name /// template-id /// /// Note, any additional constructs added here may need corresponding changes /// in isConstructorDeclarator. void Parser::ParseDirectDeclarator(Declarator &D) { DeclaratorScopeObj DeclScopeObj(*this, D.getCXXScopeSpec()); if (getLangOpts().CPlusPlus && D.mayHaveIdentifier()) { // Don't parse FOO:BAR as if it were a typo for FOO::BAR inside a class, in // this context it is a bitfield. Also in range-based for statement colon // may delimit for-range-declaration. ColonProtectionRAIIObject X(*this, D.getContext() == Declarator::MemberContext || (D.getContext() == Declarator::ForContext && getLangOpts().CPlusPlus11)); // ParseDeclaratorInternal might already have parsed the scope. if (D.getCXXScopeSpec().isEmpty()) { bool EnteringContext = D.getContext() == Declarator::FileContext || D.getContext() == Declarator::MemberContext; ParseOptionalCXXScopeSpecifier(D.getCXXScopeSpec(), ParsedType(), EnteringContext); } if (D.getCXXScopeSpec().isValid()) { if (Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) // Change the declaration context for name lookup, until this function // is exited (and the declarator has been parsed). DeclScopeObj.EnterDeclaratorScope(); } // C++0x [dcl.fct]p14: // There is a syntactic ambiguity when an ellipsis occurs at the end of a // parameter-declaration-clause without a preceding comma. In this case, // the ellipsis is parsed as part of the abstract-declarator if the type // of the parameter either names a template parameter pack that has not // been expanded or contains auto; otherwise, it is parsed as part of the // parameter-declaration-clause. if (Tok.is(tok::ellipsis) && D.getCXXScopeSpec().isEmpty() && !getLangOpts().HLSL && // HLSL Change: do not support ellipsis !((D.getContext() == Declarator::PrototypeContext || D.getContext() == Declarator::LambdaExprParameterContext || D.getContext() == Declarator::BlockLiteralContext) && NextToken().is(tok::r_paren) && !D.hasGroupingParens() && !Actions.containsUnexpandedParameterPacks(D) && D.getDeclSpec().getTypeSpecType() != TST_auto)) { SourceLocation EllipsisLoc = ConsumeToken(); if (isPtrOperatorToken(Tok.getKind(), getLangOpts(), D.getContext())) { // The ellipsis was put in the wrong place. Recover, and explain to // the user what they should have done. ParseDeclarator(D); if (EllipsisLoc.isValid()) DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); return; } else D.setEllipsisLoc(EllipsisLoc); // The ellipsis can't be followed by a parenthesized declarator. We // check for that in ParseParenDeclarator, after we have disambiguated // the l_paren token. } // HLSL Change Starts // FXC compatiblity: these are keywords when used as modifiers, but in // FXC they can also be used an identifiers. If the next token is a // punctuator, then we are using them as identifers. Need to change // the token type to tok::identifier and fall through to the next case. // Similarly 'indices', 'vertices', 'primitives' and 'payload' are keywords // when used as a type qualifer in mesh shader, but may still be used as a // variable name. // E.g., <type> left, center, right; if (getLangOpts().HLSL) { switch (Tok.getKind()) { case tok::kw_center: case tok::kw_globallycoherent: case tok::kw_precise: case tok::kw_sample: case tok::kw_indices: case tok::kw_vertices: case tok::kw_primitives: case tok::kw_payload: if (tok::isPunctuator(NextToken().getKind())) Tok.setKind(tok::identifier); break; default: break; } } // HLSL Change Ends if (Tok.isOneOf(tok::identifier, tok::kw_operator, tok::annot_template_id, tok::tilde)) { // We found something that indicates the start of an unqualified-id. // Parse that unqualified-id. bool AllowConstructorName; if (getLangOpts().HLSL) AllowConstructorName = false; else // HLSL Change - disallow constructor names if (D.getDeclSpec().hasTypeSpecifier()) AllowConstructorName = false; else if (D.getCXXScopeSpec().isSet()) AllowConstructorName = (D.getContext() == Declarator::FileContext || D.getContext() == Declarator::MemberContext); else AllowConstructorName = (D.getContext() == Declarator::MemberContext); SourceLocation TemplateKWLoc; bool HadScope = D.getCXXScopeSpec().isValid(); if (ParseUnqualifiedId(D.getCXXScopeSpec(), /*EnteringContext=*/true, /*AllowDestructorName=*/true, AllowConstructorName, ParsedType(), TemplateKWLoc, D.getName()) || // Once we're past the identifier, if the scope was bad, mark the // whole declarator bad. D.getCXXScopeSpec().isInvalid()) { D.SetIdentifier(nullptr, Tok.getLocation()); D.setInvalidType(true); } else { // ParseUnqualifiedId might have parsed a scope specifier during error // recovery. If it did so, enter that scope. if (!HadScope && D.getCXXScopeSpec().isValid() && Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) DeclScopeObj.EnterDeclaratorScope(); // Parsed the unqualified-id; update range information and move along. if (D.getSourceRange().getBegin().isInvalid()) D.SetRangeBegin(D.getName().getSourceRange().getBegin()); D.SetRangeEnd(D.getName().getSourceRange().getEnd()); } goto PastIdentifier; } } else if (Tok.is(tok::identifier) && D.mayHaveIdentifier()) { assert(!getLangOpts().CPlusPlus && "There's a C++-specific check for tok::identifier above"); assert(Tok.getIdentifierInfo() && "Not an identifier?"); D.SetIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); D.SetRangeEnd(Tok.getLocation()); ConsumeToken(); goto PastIdentifier; } else if (Tok.is(tok::identifier) && D.diagnoseIdentifier()) { // A virt-specifier isn't treated as an identifier if it appears after a // trailing-return-type. if (D.getContext() != Declarator::TrailingReturnContext || !isCXX11VirtSpecifier(Tok)) { Diag(Tok.getLocation(), diag::err_unexpected_unqualified_id) << FixItHint::CreateRemoval(Tok.getLocation()); D.SetIdentifier(nullptr, Tok.getLocation()); ConsumeToken(); goto PastIdentifier; } } if (Tok.is(tok::l_paren)) { // direct-declarator: '(' declarator ')' // direct-declarator: '(' attributes declarator ')' // Example: 'char (*X)' or 'int (*XX)(void)' ParseParenDeclarator(D); // If the declarator was parenthesized, we entered the declarator // scope when parsing the parenthesized declarator, then exited // the scope already. Re-enter the scope, if we need to. if (D.getCXXScopeSpec().isSet()) { // If there was an error parsing parenthesized declarator, declarator // scope may have been entered before. Don't do it again. if (!D.isInvalidType() && Actions.ShouldEnterDeclaratorScope(getCurScope(), D.getCXXScopeSpec())) // Change the declaration context for name lookup, until this function // is exited (and the declarator has been parsed). DeclScopeObj.EnterDeclaratorScope(); } } else if (D.mayOmitIdentifier()) { // This could be something simple like "int" (in which case the declarator // portion is empty), if an abstract-declarator is allowed. D.SetIdentifier(nullptr, Tok.getLocation()); // The grammar for abstract-pack-declarator does not allow grouping parens. // FIXME: Revisit this once core issue 1488 is resolved. if (D.hasEllipsis() && D.hasGroupingParens()) Diag(PP.getLocForEndOfToken(D.getEllipsisLoc()), diag::ext_abstract_pack_declarator_parens); } else { if (Tok.getKind() == tok::annot_pragma_parser_crash) LLVM_BUILTIN_TRAP; if (Tok.is(tok::l_square)) return ParseMisplacedBracketDeclarator(D); if (D.getContext() == Declarator::MemberContext) { Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), diag::err_expected_member_name_or_semi) << (D.getDeclSpec().isEmpty() ? SourceRange() : D.getDeclSpec().getSourceRange()); } else if (getLangOpts().CPlusPlus) { if (Tok.isOneOf(tok::period, tok::arrow)) Diag(Tok, diag::err_invalid_operator_on_type) << Tok.is(tok::arrow); else { SourceLocation Loc = D.getCXXScopeSpec().getEndLoc(); if (Tok.isAtStartOfLine() && Loc.isValid()) Diag(PP.getLocForEndOfToken(Loc), diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus; else if (Tok.isHLSLReserved()) // HLSL Change - check for some reserved keywords used as identifiers Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); else Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus; } } else { Diag(getMissingDeclaratorIdLoc(D, Tok.getLocation()), diag::err_expected_either) << tok::identifier << tok::l_paren; } D.SetIdentifier(nullptr, Tok.getLocation()); D.setInvalidType(true); } PastIdentifier: assert(D.isPastIdentifier() && "Haven't past the location of the identifier yet?"); // Don't parse attributes unless we have parsed an unparenthesized name. if (D.hasName() && !D.getNumTypeObjects()) MaybeParseCXX11Attributes(D); while (1) { if (Tok.is(tok::l_paren)) { // Enter function-declaration scope, limiting any declarators to the // function prototype scope, including parameter declarators. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope|Scope::DeclScope| (D.isFunctionDeclaratorAFunctionDeclaration() ? Scope::FunctionDeclarationScope : 0)); // The paren may be part of a C++ direct initializer, eg. "int x(1);". // In such a case, check if we actually have a function declarator; if it // is not, the declarator has been fully parsed. bool IsAmbiguous = false; if (getLangOpts().CPlusPlus && D.mayBeFollowedByCXXDirectInit() && !getLangOpts().HLSL) { // HLSL Change: HLSL does not support direct initializers // The name of the declarator, if any, is tentatively declared within // a possible direct initializer. TentativelyDeclaredIdentifiers.push_back(D.getIdentifier()); bool IsFunctionDecl = isCXXFunctionDeclarator(&IsAmbiguous); TentativelyDeclaredIdentifiers.pop_back(); if (!IsFunctionDecl) break; } ParsedAttributes attrs(AttrFactory); BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); ParseFunctionDeclarator(D, attrs, T, IsAmbiguous); PrototypeScope.Exit(); } else if (Tok.is(tok::l_square)) { ParseBracketDeclarator(D); } else { break; } } // HLSL Change Starts - register/semantic and effect annotation skipping if (getLangOpts().HLSL) { if (MaybeParseHLSLAttributes(D)) D.setInvalidType(); if (Tok.is(tok::less)) { // Consume effects annotations Diag(Tok.getLocation(), diag::warn_hlsl_effect_annotation); ConsumeToken(); while (!Tok.is(tok::greater) && !Tok.is(tok::eof)) { SkipUntil(tok::semi); // skip through ; } if (Tok.is(tok::greater)) ConsumeToken(); } } // HLSL Change Ends } /// ParseParenDeclarator - We parsed the declarator D up to a paren. This is /// only called before the identifier, so these are most likely just grouping /// parens for precedence. If we find that these are actually function /// parameter parens in an abstract-declarator, we call ParseFunctionDeclarator. /// /// direct-declarator: /// '(' declarator ')' /// [GNU] '(' attributes declarator ')' /// direct-declarator '(' parameter-type-list ')' /// direct-declarator '(' identifier-list[opt] ')' /// [GNU] direct-declarator '(' parameter-forward-declarations /// parameter-type-list[opt] ')' /// void Parser::ParseParenDeclarator(Declarator &D) { BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); assert(!D.isPastIdentifier() && "Should be called before passing identifier"); // Eat any attributes before we look at whether this is a grouping or function // declarator paren. If this is a grouping paren, the attribute applies to // the type being built up, for example: // int (__attribute__(()) *x)(long y) // If this ends up not being a grouping paren, the attribute applies to the // first argument, for example: // int (__attribute__(()) int x) // In either case, we need to eat any attributes to be able to determine what // sort of paren this is. // ParsedAttributes attrs(AttrFactory); bool RequiresArg = false; if (Tok.is(tok::kw___attribute)) { ParseGNUAttributes(attrs); // We require that the argument list (if this is a non-grouping paren) be // present even if the attribute list was empty. RequiresArg = true; } // Eat any Microsoft extensions. ParseMicrosoftTypeAttributes(attrs); // Eat any Borland extensions. if (Tok.is(tok::kw___pascal) && !getLangOpts().HLSL) // HLSL Change - _pascal isn't a keyword in HLSL ParseBorlandTypeAttributes(attrs); // If we haven't past the identifier yet (or where the identifier would be // stored, if this is an abstract declarator), then this is probably just // grouping parens. However, if this could be an abstract-declarator, then // this could also be the start of function arguments (consider 'void()'). bool isGrouping; if (!D.mayOmitIdentifier()) { // If this can't be an abstract-declarator, this *must* be a grouping // paren, because we haven't seen the identifier yet. isGrouping = true; } else if (Tok.is(tok::r_paren) || // 'int()' is a function. (getLangOpts().CPlusPlus && Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) || // C++ int(...) isDeclarationSpecifier() || // 'int(int)' is a function. isCXX11AttributeSpecifier()) { // 'int([[]]int)' is a function. // This handles C99 6.7.5.3p11: in "typedef int X; void foo(X)", X is // considered to be a type, not a K&R identifier-list. isGrouping = false; } else { // Otherwise, this is a grouping paren, e.g. 'int (*X)' or 'int(X)'. isGrouping = true; } // If this is a grouping paren, handle: // direct-declarator: '(' declarator ')' // direct-declarator: '(' attributes declarator ')' if (isGrouping) { SourceLocation EllipsisLoc = D.getEllipsisLoc(); D.setEllipsisLoc(SourceLocation()); bool hadGroupingParens = D.hasGroupingParens(); D.setGroupingParens(true); ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); // Match the ')'. T.consumeClose(); D.AddTypeInfo(DeclaratorChunk::getParen(T.getOpenLocation(), T.getCloseLocation()), attrs, T.getCloseLocation()); D.setGroupingParens(hadGroupingParens); // An ellipsis cannot be placed outside parentheses. if (EllipsisLoc.isValid()) DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, D); return; } // Okay, if this wasn't a grouping paren, it must be the start of a function // argument list. Recognize that this declarator will never have an // identifier (and remember where it would have been), then call into // ParseFunctionDeclarator to handle of argument list. D.SetIdentifier(nullptr, Tok.getLocation()); // Enter function-declaration scope, limiting any declarators to the // function prototype scope, including parameter declarators. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | Scope::DeclScope | (D.isFunctionDeclaratorAFunctionDeclaration() ? Scope::FunctionDeclarationScope : 0)); ParseFunctionDeclarator(D, attrs, T, false, RequiresArg); PrototypeScope.Exit(); } /// ParseFunctionDeclarator - We are after the identifier and have parsed the /// declarator D up to a paren, which indicates that we are parsing function /// arguments. /// /// If FirstArgAttrs is non-null, then the caller parsed those arguments /// immediately after the open paren - they should be considered to be the /// first argument of a parameter. /// /// If RequiresArg is true, then the first argument of the function is required /// to be present and required to not be an identifier list. /// /// For C++, after the parameter-list, it also parses the cv-qualifier-seq[opt], /// (C++11) ref-qualifier[opt], exception-specification[opt], /// (C++11) attribute-specifier-seq[opt], and (C++11) trailing-return-type[opt]. /// /// [C++11] exception-specification: /// dynamic-exception-specification /// noexcept-specification /// void Parser::ParseFunctionDeclarator(Declarator &D, ParsedAttributes &FirstArgAttrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg) { assert(getCurScope()->isFunctionPrototypeScope() && "Should call from a Function scope"); // lparen is already consumed! assert(D.isPastIdentifier() && "Should not call before identifier!"); // This should be true when the function has typed arguments. // Otherwise, it is treated as a K&R-style function. bool HasProto = false; // Build up an array of information about the parsed arguments. SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; // Remember where we see an ellipsis, if any. SourceLocation EllipsisLoc; DeclSpec DS(AttrFactory); bool RefQualifierIsLValueRef = true; SourceLocation RefQualifierLoc; SourceLocation ConstQualifierLoc; SourceLocation VolatileQualifierLoc; SourceLocation RestrictQualifierLoc; ExceptionSpecificationType ESpecType = EST_None; SourceRange ESpecRange; SmallVector<ParsedType, 2> DynamicExceptions; SmallVector<SourceRange, 2> DynamicExceptionRanges; ExprResult NoexceptExpr; CachedTokens *ExceptionSpecTokens = 0; ParsedAttributes FnAttrs(AttrFactory); TypeResult TrailingReturnType; /* LocalEndLoc is the end location for the local FunctionTypeLoc. EndLoc is the end location for the function declarator. They differ for trailing return types. */ SourceLocation StartLoc, LocalEndLoc, EndLoc; SourceLocation LParenLoc, RParenLoc; LParenLoc = Tracker.getOpenLocation(); StartLoc = LParenLoc; if (isFunctionDeclaratorIdentifierList()) { if (RequiresArg) Diag(Tok, diag::err_argument_required_after_attribute); ParseFunctionDeclaratorIdentifierList(D, ParamInfo); Tracker.consumeClose(); RParenLoc = Tracker.getCloseLocation(); LocalEndLoc = RParenLoc; EndLoc = RParenLoc; } else { if (Tok.isNot(tok::r_paren)) ParseParameterDeclarationClause(D, FirstArgAttrs, ParamInfo, EllipsisLoc); else if (RequiresArg) Diag(Tok, diag::err_argument_required_after_attribute); HasProto = ParamInfo.size() || getLangOpts().CPlusPlus; // If we have the closing ')', eat it. Tracker.consumeClose(); RParenLoc = Tracker.getCloseLocation(); LocalEndLoc = RParenLoc; EndLoc = RParenLoc; if (getLangOpts().CPlusPlus) { // FIXME: Accept these components in any order, and produce fixits to // correct the order if the user gets it wrong. Ideally we should deal // with the pure-specifier in the same way. // Parse cv-qualifier-seq[opt]. ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, /*AtomicAllowed*/ false); if (!DS.getSourceRange().getEnd().isInvalid()) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(DS.getSourceRange().getEnd(), diag::err_hlsl_unsupported_construct) << "qualifiers"; } // HLSL Change Ends EndLoc = DS.getSourceRange().getEnd(); ConstQualifierLoc = DS.getConstSpecLoc(); VolatileQualifierLoc = DS.getVolatileSpecLoc(); RestrictQualifierLoc = DS.getRestrictSpecLoc(); } // Parse ref-qualifier[opt]. if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) EndLoc = RefQualifierLoc; // C++11 [expr.prim.general]p3: // If a declaration declares a member function or member function // template of a class X, the expression this is a prvalue of type // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq // and the end of the function-definition, member-declarator, or // declarator. // FIXME: currently, "static" case isn't handled correctly. bool IsCXX11MemberFunction = getLangOpts().CPlusPlus11 && D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && (D.getContext() == Declarator::MemberContext ? !D.getDeclSpec().isFriendSpecified() : D.getContext() == Declarator::FileContext && D.getCXXScopeSpec().isValid() && Actions.CurContext->isRecord()); Sema::CXXThisScopeRAII ThisScope(Actions, dyn_cast<CXXRecordDecl>(Actions.CurContext), DS.getTypeQualifiers() | (D.getDeclSpec().isConstexprSpecified() && !getLangOpts().CPlusPlus14 ? Qualifiers::Const : 0), IsCXX11MemberFunction); // Parse exception-specification[opt]. bool Delayed = D.isFirstDeclarationOfMember() && D.isFunctionDeclaratorAFunctionDeclaration(); if (Delayed && Actions.isLibstdcxxEagerExceptionSpecHack(D) && GetLookAheadToken(0).is(tok::kw_noexcept) && GetLookAheadToken(1).is(tok::l_paren) && GetLookAheadToken(2).is(tok::kw_noexcept) && GetLookAheadToken(3).is(tok::l_paren) && GetLookAheadToken(4).is(tok::identifier) && GetLookAheadToken(4).getIdentifierInfo()->isStr("swap")) { // HACK: We've got an exception-specification // noexcept(noexcept(swap(...))) // or // noexcept(noexcept(swap(...)) && noexcept(swap(...))) // on a 'swap' member function. This is a libstdc++ bug; the lookup // for 'swap' will only find the function we're currently declaring, // whereas it expects to find a non-member swap through ADL. Turn off // delayed parsing to give it a chance to find what it expects. Delayed = false; } ESpecType = tryParseExceptionSpecification(Delayed, ESpecRange, DynamicExceptions, DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens); if (ESpecType != EST_None) EndLoc = ESpecRange.getEnd(); // Parse attribute-specifier-seq[opt]. Per DR 979 and DR 1297, this goes // after the exception-specification. MaybeParseCXX11Attributes(FnAttrs); // HLSL Change: comment only - a call to MaybeParseHLSLAttributes would go here if we allowed attributes at this point // Parse trailing-return-type[opt]. LocalEndLoc = EndLoc; if (getLangOpts().CPlusPlus11 && Tok.is(tok::arrow)) { assert(!getLangOpts().HLSL); // HLSL Change: otherwise this would need to deal with this Diag(Tok, diag::warn_cxx98_compat_trailing_return_type); if (D.getDeclSpec().getTypeSpecType() == TST_auto) StartLoc = D.getDeclSpec().getTypeSpecTypeLoc(); LocalEndLoc = Tok.getLocation(); SourceRange Range; TrailingReturnType = ParseTrailingReturnType(Range); EndLoc = Range.getEnd(); } } } // Remember that we parsed a function type, and remember the attributes. D.AddTypeInfo(DeclaratorChunk::getFunction(HasProto, IsAmbiguous, LParenLoc, ParamInfo.data(), ParamInfo.size(), EllipsisLoc, RParenLoc, DS.getTypeQualifiers(), RefQualifierIsLValueRef, RefQualifierLoc, ConstQualifierLoc, VolatileQualifierLoc, RestrictQualifierLoc, /*MutableLoc=*/SourceLocation(), ESpecType, ESpecRange.getBegin(), DynamicExceptions.data(), DynamicExceptionRanges.data(), DynamicExceptions.size(), NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr, ExceptionSpecTokens, StartLoc, LocalEndLoc, D, TrailingReturnType), FnAttrs, EndLoc); } /// ParseRefQualifier - Parses a member function ref-qualifier. Returns /// true if a ref-qualifier is found. bool Parser::ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc) { if (Tok.isOneOf(tok::amp, tok::ampamp)) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "reference qualifiers on functions"; } else // HLSL Change Ends Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_ref_qualifier : diag::ext_ref_qualifier); RefQualifierIsLValueRef = Tok.is(tok::amp); RefQualifierLoc = ConsumeToken(); return true; } return false; } /// isFunctionDeclaratorIdentifierList - This parameter list may have an /// identifier list form for a K&R-style function: void foo(a,b,c) /// /// Note that identifier-lists are only allowed for normal declarators, not for /// abstract-declarators. bool Parser::isFunctionDeclaratorIdentifierList() { return !getLangOpts().CPlusPlus && Tok.is(tok::identifier) && !TryAltiVecVectorToken() // K&R identifier lists can't have typedefs as identifiers, per C99 // 6.7.5.3p11. && (TryAnnotateTypeOrScopeToken() || !Tok.is(tok::annot_typename)) // Identifier lists follow a really simple grammar: the identifiers can // be followed *only* by a ", identifier" or ")". However, K&R // identifier lists are really rare in the brave new modern world, and // it is very common for someone to typo a type in a non-K&R style // list. If we are presented with something like: "void foo(intptr x, // float y)", we don't want to start parsing the function declarator as // though it is a K&R style declarator just because intptr is an // invalid type. // // To handle this, we check to see if the token after the first // identifier is a "," or ")". Only then do we parse it as an // identifier list. && (NextToken().is(tok::comma) || NextToken().is(tok::r_paren)); } /// ParseFunctionDeclaratorIdentifierList - While parsing a function declarator /// we found a K&R-style identifier list instead of a typed parameter list. /// /// After returning, ParamInfo will hold the parsed parameters. /// /// identifier-list: [C99 6.7.5] /// identifier /// identifier-list ',' identifier /// void Parser::ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo) { assert(!getLangOpts().HLSL); // HLSL Change - K&R parameter lists are never recognized // If there was no identifier specified for the declarator, either we are in // an abstract-declarator, or we are in a parameter declarator which was found // to be abstract. In abstract-declarators, identifier lists are not valid: // diagnose this. if (!D.getIdentifier()) Diag(Tok, diag::ext_ident_list_in_param); // Maintain an efficient lookup of params we have seen so far. llvm::SmallSet<const IdentifierInfo*, 16> ParamsSoFar; do { // If this isn't an identifier, report the error and skip until ')'. if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); // Forget we parsed anything. ParamInfo.clear(); return; } IdentifierInfo *ParmII = Tok.getIdentifierInfo(); // Reject 'typedef int y; int test(x, y)', but continue parsing. if (Actions.getTypeName(*ParmII, Tok.getLocation(), getCurScope())) Diag(Tok, diag::err_unexpected_typedef_ident) << ParmII; // Verify that the argument identifier has not already been mentioned. if (!ParamsSoFar.insert(ParmII).second) { Diag(Tok, diag::err_param_redefinition) << ParmII; } else { // Remember this identifier in ParamInfo. ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, Tok.getLocation(), nullptr)); } // Eat the identifier. ConsumeToken(); // The list continues if we see a comma. } while (TryConsumeToken(tok::comma)); } /// ParseParameterDeclarationClause - Parse a (possibly empty) parameter-list /// after the opening parenthesis. This function will not parse a K&R-style /// identifier list. /// /// D is the declarator being parsed. If FirstArgAttrs is non-null, then the /// caller parsed those arguments immediately after the open paren - they should /// be considered to be part of the first parameter. /// /// After returning, ParamInfo will hold the parsed parameters. EllipsisLoc will /// be the location of the ellipsis, if any was parsed. /// /// parameter-type-list: [C99 6.7.5] /// parameter-list /// parameter-list ',' '...' /// [C++] parameter-list '...' /// /// parameter-list: [C99 6.7.5] /// parameter-declaration /// parameter-list ',' parameter-declaration /// /// parameter-declaration: [C99 6.7.5] /// declaration-specifiers declarator /// [C++] declaration-specifiers declarator '=' assignment-expression /// [C++11] initializer-clause /// [GNU] declaration-specifiers declarator attributes /// declaration-specifiers abstract-declarator[opt] /// [C++] declaration-specifiers abstract-declarator[opt] /// '=' assignment-expression /// [GNU] declaration-specifiers abstract-declarator[opt] attributes /// [C++11] attribute-specifier-seq parameter-declaration /// void Parser::ParseParameterDeclarationClause( Declarator &D, ParsedAttributes &FirstArgAttrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc) { do { // FIXME: Issue a diagnostic if we parsed an attribute-specifier-seq // before deciding this was a parameter-declaration-clause. if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) break; // Parse the declaration-specifiers. // Just use the ParsingDeclaration "scope" of the declarator. DeclSpec DS(AttrFactory); // Parse any C++11 attributes. MaybeParseCXX11Attributes(DS.getAttributes()); MaybeParseHLSLAttributes(DS.getAttributes()); // HLSL Change // Skip any Microsoft attributes before a param. MaybeParseMicrosoftAttributes(DS.getAttributes()); SourceLocation DSStart = Tok.getLocation(); // If the caller parsed attributes for the first argument, add them now. // Take them so that we only apply the attributes to the first parameter. // FIXME: If we can leave the attributes in the token stream somehow, we can // get rid of a parameter (FirstArgAttrs) and this statement. It might be // too much hassle. DS.takeAttributesFrom(FirstArgAttrs); ParseDeclarationSpecifiers(DS); // Parse the declarator. This is "PrototypeContext" or // "LambdaExprParameterContext", because we must accept either // 'declarator' or 'abstract-declarator' here. Declarator ParmDeclarator(DS, D.getContext() == Declarator::LambdaExprContext ? Declarator::LambdaExprParameterContext : Declarator::PrototypeContext); ParseDeclarator(ParmDeclarator); // HLSL Change Starts: Parse HLSL Semantic on function parameters if (MaybeParseHLSLAttributes(ParmDeclarator)) { ParmDeclarator.setInvalidType(); return; } // HLSL Change Ends // Parse GNU attributes, if present. MaybeParseGNUAttributes(ParmDeclarator); // Remember this parsed parameter in ParamInfo. IdentifierInfo *ParmII = ParmDeclarator.getIdentifier(); // DefArgToks is used when the parsing of default arguments needs // to be delayed. CachedTokens *DefArgToks = nullptr; // If no parameter was specified, verify that *something* was specified, // otherwise we have a missing type and identifier. if (DS.isEmpty() && ParmDeclarator.getIdentifier() == nullptr && ParmDeclarator.getNumTypeObjects() == 0) { // Completely missing, emit error. Diag(DSStart, diag::err_missing_param); } else { // Otherwise, we have something. Add it and let semantic analysis try // to grok it and add the result to the ParamInfo we are building. // Last chance to recover from a misplaced ellipsis in an attempted // parameter pack declaration. if (Tok.is(tok::ellipsis) && (NextToken().isNot(tok::r_paren) || (!ParmDeclarator.getEllipsisLoc().isValid() && !Actions.isUnexpandedParameterPackPermitted())) && Actions.containsUnexpandedParameterPacks(ParmDeclarator)) DiagnoseMisplacedEllipsisInDeclarator(ConsumeToken(), ParmDeclarator); // Inform the actions module about the parameter declarator, so it gets // added to the current scope. Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); // Parse the default argument, if any. We parse the default // arguments in all dialects; the semantic analysis in // ActOnParamDefaultArgument will reject the default argument in // C. if (Tok.is(tok::equal)) { SourceLocation EqualLoc = Tok.getLocation(); // Parse the default argument if (D.getContext() == Declarator::MemberContext) { // If we're inside a class definition, cache the tokens // corresponding to the default argument. We'll actually parse // them when we see the end of the class definition. // FIXME: Can we use a smart pointer for Toks? DefArgToks = new CachedTokens; SourceLocation ArgStartLoc = NextToken().getLocation(); if (!ConsumeAndStoreInitializer(*DefArgToks, CIK_DefaultArgument)) { delete DefArgToks; DefArgToks = nullptr; Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); } else { Actions.ActOnParamUnparsedDefaultArgument(Param, EqualLoc, ArgStartLoc); } } else { // Consume the '='. ConsumeToken(); // The argument isn't actually potentially evaluated unless it is // used. EnterExpressionEvaluationContext Eval(Actions, Sema::PotentiallyEvaluatedIfUsed, Param); ExprResult DefArgResult; if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); DefArgResult = ParseBraceInitializer(); } else DefArgResult = ParseAssignmentExpression(); DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult); if (DefArgResult.isInvalid()) { Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch); } else { // Inform the actions module about the default argument Actions.ActOnParamDefaultArgument(Param, EqualLoc, DefArgResult.get()); } } } ParamInfo.push_back(DeclaratorChunk::ParamInfo(ParmII, ParmDeclarator.getIdentifierLoc(), Param, DefArgToks)); } if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) { if (!getLangOpts().CPlusPlus) { // We have ellipsis without a preceding ',', which is ill-formed // in C. Complain and provide the fix. Diag(EllipsisLoc, diag::err_missing_comma_before_ellipsis) << FixItHint::CreateInsertion(EllipsisLoc, ", "); } else if (ParmDeclarator.getEllipsisLoc().isValid() || Actions.containsUnexpandedParameterPacks(ParmDeclarator)) { // It looks like this was supposed to be a parameter pack. Warn and // point out where the ellipsis should have gone. SourceLocation ParmEllipsis = ParmDeclarator.getEllipsisLoc(); Diag(EllipsisLoc, diag::warn_misplaced_ellipsis_vararg) << ParmEllipsis.isValid() << ParmEllipsis; if (ParmEllipsis.isValid()) { Diag(ParmEllipsis, diag::note_misplaced_ellipsis_vararg_existing_ellipsis); } else { Diag(ParmDeclarator.getIdentifierLoc(), diag::note_misplaced_ellipsis_vararg_add_ellipsis) << FixItHint::CreateInsertion(ParmDeclarator.getIdentifierLoc(), "...") << !ParmDeclarator.hasName(); } Diag(EllipsisLoc, diag::note_misplaced_ellipsis_vararg_add_comma) << FixItHint::CreateInsertion(EllipsisLoc, ", "); } // We can't have any more parameters after an ellipsis. break; } // If the next token is a comma, consume it and keep reading arguments. } while (TryConsumeToken(tok::comma)); // HLSL Change Starts if (getLangOpts().HLSL && EllipsisLoc.isValid()) { Diag(EllipsisLoc, diag::err_hlsl_unsupported_construct) << "variadic arguments"; } // HLSL Change Ends } /// [C90] direct-declarator '[' constant-expression[opt] ']' /// [C99] direct-declarator '[' type-qual-list[opt] assignment-expr[opt] ']' /// [C99] direct-declarator '[' 'static' type-qual-list[opt] assign-expr ']' /// [C99] direct-declarator '[' type-qual-list 'static' assignment-expr ']' /// [C99] direct-declarator '[' type-qual-list[opt] '*' ']' /// [C++11] direct-declarator '[' constant-expression[opt] ']' /// attribute-specifier-seq[opt] void Parser::ParseBracketDeclarator(Declarator &D) { if (CheckProhibitedCXX11Attribute()) return; BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); // C array syntax has many features, but by-far the most common is [] and [4]. // This code does a fast path to handle some of the most obvious cases. if (Tok.getKind() == tok::r_square) { T.consumeClose(); ParsedAttributes attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); // HLSL Change: comment only - MaybeParseHLSLAttributes would go here if allowed at this point // Remember that we parsed the empty array type. D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, nullptr, T.getOpenLocation(), T.getCloseLocation()), attrs, T.getCloseLocation()); return; } else if (Tok.getKind() == tok::numeric_constant && GetLookAheadToken(1).is(tok::r_square)) { // [4] is very common. Parse the numeric constant expression. ExprResult ExprRes(Actions.ActOnNumericConstant(Tok, getCurScope())); ConsumeToken(); T.consumeClose(); ParsedAttributes attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); // HLSL Change: comment only - MaybeParseHLSLAttributes would go here if allowed at this point // Remember that we parsed a array type, and remember its features. D.AddTypeInfo(DeclaratorChunk::getArray(0, false, false, ExprRes.get(), T.getOpenLocation(), T.getCloseLocation()), attrs, T.getCloseLocation()); return; } // If valid, this location is the position where we read the 'static' keyword. SourceLocation StaticLoc; TryConsumeToken(tok::kw_static, StaticLoc); // If there is a type-qualifier-list, read it now. // Type qualifiers in an array subscript are a C99 feature. DeclSpec DS(AttrFactory); ParseTypeQualifierListOpt(DS, AR_CXX11AttributesParsed); // If we haven't already read 'static', check to see if there is one after the // type-qualifier-list. if (!StaticLoc.isValid()) TryConsumeToken(tok::kw_static, StaticLoc); // Handle "direct-declarator [ type-qual-list[opt] * ]". bool isStar = false; ExprResult NumElements; // Handle the case where we have '[*]' as the array size. However, a leading // star could be the start of an expression, for example 'X[*p + 4]'. Verify // the token after the star is a ']'. Since stars in arrays are // infrequent, use of lookahead is not costly here. if (Tok.is(tok::star) && GetLookAheadToken(1).is(tok::r_square)) { ConsumeToken(); // Eat the '*'. if (StaticLoc.isValid()) { Diag(StaticLoc, diag::err_unspecified_vla_size_with_static); StaticLoc = SourceLocation(); // Drop the static. } isStar = true; } else if (Tok.isNot(tok::r_square)) { // Note, in C89, this production uses the constant-expr production instead // of assignment-expr. The only difference is that assignment-expr allows // things like '=' and '*='. Sema rejects these in C89 mode because they // are not i-c-e's, so we don't need to distinguish between the two here. // Parse the constant-expression or assignment-expression now (depending // on dialect). if (getLangOpts().CPlusPlus) { NumElements = ParseConstantExpression(); } else { EnterExpressionEvaluationContext Unevaluated(Actions, Sema::ConstantEvaluated); NumElements = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); } } else { if (StaticLoc.isValid()) { Diag(StaticLoc, diag::err_unspecified_size_with_static); StaticLoc = SourceLocation(); // Drop the static. } } // If there was an error parsing the assignment-expression, recover. if (NumElements.isInvalid()) { D.setInvalidType(true); // If the expression was invalid, skip it. SkipUntil(tok::r_square, StopAtSemi); return; } T.consumeClose(); ParsedAttributes attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); // HLSL Change: comment only - MaybeParseHLSLAttributes would go here if allowed at this point // HLSL Change Starts if (getLangOpts().HLSL) { if (StaticLoc.isValid()) { Diag(StaticLoc, diag::err_hlsl_unsupported_construct) << "static keyword on array derivation"; } if (isStar) { Diag(T.getOpenLocation(), diag::err_hlsl_unsupported_construct) << "variable-length array"; } } // HLSL Change Ends // Remember that we parsed a array type, and remember its features. D.AddTypeInfo(DeclaratorChunk::getArray(DS.getTypeQualifiers(), StaticLoc.isValid(), isStar, NumElements.get(), T.getOpenLocation(), T.getCloseLocation()), attrs, T.getCloseLocation()); } /// Diagnose brackets before an identifier. void Parser::ParseMisplacedBracketDeclarator(Declarator &D) { assert(Tok.is(tok::l_square) && "Missing opening bracket"); assert(!D.mayOmitIdentifier() && "Declarator cannot omit identifier"); SourceLocation StartBracketLoc = Tok.getLocation(); Declarator TempDeclarator(D.getDeclSpec(), D.getContext()); while (Tok.is(tok::l_square)) { ParseBracketDeclarator(TempDeclarator); } // Stuff the location of the start of the brackets into the Declarator. // The diagnostics from ParseDirectDeclarator will make more sense if // they use this location instead. if (Tok.is(tok::semi)) D.getName().EndLocation = StartBracketLoc; SourceLocation SuggestParenLoc = Tok.getLocation(); // Now that the brackets are removed, try parsing the declarator again. ParseDeclaratorInternal(D, &Parser::ParseDirectDeclarator); // Something went wrong parsing the brackets, in which case, // ParseBracketDeclarator has emitted an error, and we don't need to emit // one here. if (TempDeclarator.getNumTypeObjects() == 0) return; // Determine if parens will need to be suggested in the diagnostic. bool NeedParens = false; if (D.getNumTypeObjects() != 0) { switch (D.getTypeObject(D.getNumTypeObjects() - 1).Kind) { case DeclaratorChunk::Pointer: case DeclaratorChunk::Reference: case DeclaratorChunk::BlockPointer: case DeclaratorChunk::MemberPointer: NeedParens = true; break; case DeclaratorChunk::Array: case DeclaratorChunk::Function: case DeclaratorChunk::Paren: break; } } if (NeedParens) { // Create a DeclaratorChunk for the inserted parens. ParsedAttributes attrs(AttrFactory); SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd()); D.AddTypeInfo(DeclaratorChunk::getParen(SuggestParenLoc, EndLoc), attrs, SourceLocation()); } // Adding back the bracket info to the end of the Declarator. for (unsigned i = 0, e = TempDeclarator.getNumTypeObjects(); i < e; ++i) { const DeclaratorChunk &Chunk = TempDeclarator.getTypeObject(i); ParsedAttributes attrs(AttrFactory); attrs.set(Chunk.Common.AttrList); D.AddTypeInfo(Chunk, attrs, SourceLocation()); } // The missing identifier would have been diagnosed in ParseDirectDeclarator. // If parentheses are required, always suggest them. if (!D.getIdentifier() && !NeedParens) return; SourceLocation EndBracketLoc = TempDeclarator.getLocEnd(); // Generate the move bracket error message. SourceRange BracketRange(StartBracketLoc, EndBracketLoc); SourceLocation EndLoc = PP.getLocForEndOfToken(D.getLocEnd()); if (NeedParens) { Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) << getLangOpts().CPlusPlus << FixItHint::CreateInsertion(SuggestParenLoc, "(") << FixItHint::CreateInsertion(EndLoc, ")") << FixItHint::CreateInsertionFromRange( EndLoc, CharSourceRange(BracketRange, true)) << FixItHint::CreateRemoval(BracketRange); } else { Diag(EndLoc, diag::err_brackets_go_after_unqualified_id) << getLangOpts().CPlusPlus << FixItHint::CreateInsertionFromRange( EndLoc, CharSourceRange(BracketRange, true)) << FixItHint::CreateRemoval(BracketRange); } } /// [GNU] typeof-specifier: /// typeof ( expressions ) /// typeof ( type-name ) /// [GNU/C++] typeof unary-expression /// void Parser::ParseTypeofSpecifier(DeclSpec &DS) { assert(Tok.is(tok::kw_typeof) && "Not a typeof specifier"); Token OpTok = Tok; SourceLocation StartLoc = ConsumeToken(); const bool hasParens = Tok.is(tok::l_paren); EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, Sema::ReuseLambdaContextDecl); bool isCastExpr; ParsedType CastTy; SourceRange CastRange; ExprResult Operand = Actions.CorrectDelayedTyposInExpr( ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange)); if (hasParens) DS.setTypeofParensRange(CastRange); if (CastRange.getEnd().isInvalid()) // FIXME: Not accurate, the range gets one token more than it should. DS.SetRangeEnd(Tok.getLocation()); else DS.SetRangeEnd(CastRange.getEnd()); if (isCastExpr) { if (!CastTy) { DS.SetTypeSpecError(); return; } const char *PrevSpec = nullptr; unsigned DiagID; // Check for duplicate type specifiers (e.g. "int typeof(int)"). if (DS.SetTypeSpecType(DeclSpec::TST_typeofType, StartLoc, PrevSpec, DiagID, CastTy, Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; return; } // If we get here, the operand to the typeof was an expresion. if (Operand.isInvalid()) { DS.SetTypeSpecError(); return; } // We might need to transform the operand if it is potentially evaluated. Operand = Actions.HandleExprEvaluationContextForTypeof(Operand.get()); if (Operand.isInvalid()) { DS.SetTypeSpecError(); return; } const char *PrevSpec = nullptr; unsigned DiagID; // Check for duplicate type specifiers (e.g. "int typeof(int)"). if (DS.SetTypeSpecType(DeclSpec::TST_typeofExpr, StartLoc, PrevSpec, DiagID, Operand.get(), Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; } /// [C11] atomic-specifier: /// _Atomic ( type-name ) /// void Parser::ParseAtomicSpecifier(DeclSpec &DS) { assert(!getLangOpts().HLSL && "HLSL does not parse atomics"); // HLSL Change assert(Tok.is(tok::kw__Atomic) && NextToken().is(tok::l_paren) && "Not an atomic specifier"); SourceLocation StartLoc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.consumeOpen()) return; TypeResult Result = ParseTypeName(); if (Result.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return; } // Match the ')' T.consumeClose(); if (T.getCloseLocation().isInvalid()) return; DS.setTypeofParensRange(T.getRange()); DS.SetRangeEnd(T.getCloseLocation()); const char *PrevSpec = nullptr; unsigned DiagID; if (DS.SetTypeSpecType(DeclSpec::TST_atomic, StartLoc, PrevSpec, DiagID, Result.get(), Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; } /// TryAltiVecVectorTokenOutOfLine - Out of line body that should only be called /// from TryAltiVecVectorToken. bool Parser::TryAltiVecVectorTokenOutOfLine() { assert(!getLangOpts().HLSL && "HLSL does not parse AltiVec vectors"); // HLSL Change Token Next = NextToken(); switch (Next.getKind()) { default: return false; case tok::kw_short: case tok::kw_long: case tok::kw_signed: case tok::kw_unsigned: case tok::kw_void: case tok::kw_char: case tok::kw_int: case tok::kw_float: case tok::kw_double: case tok::kw_bool: case tok::kw___bool: case tok::kw___pixel: Tok.setKind(tok::kw___vector); return true; case tok::identifier: if (Next.getIdentifierInfo() == Ident_pixel) { Tok.setKind(tok::kw___vector); return true; } if (Next.getIdentifierInfo() == Ident_bool) { Tok.setKind(tok::kw___vector); return true; } return false; } } bool Parser::TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { assert(!getLangOpts().HLSL && "HLSL does not parse AltiVec vectors"); // HLSL Change const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); if (Tok.getIdentifierInfo() == Ident_vector) { Token Next = NextToken(); switch (Next.getKind()) { case tok::kw_short: case tok::kw_long: case tok::kw_signed: case tok::kw_unsigned: case tok::kw_void: case tok::kw_char: case tok::kw_int: case tok::kw_float: case tok::kw_double: case tok::kw_bool: case tok::kw___bool: case tok::kw___pixel: isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID, Policy); return true; case tok::identifier: if (Next.getIdentifierInfo() == Ident_pixel) { isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); return true; } if (Next.getIdentifierInfo() == Ident_bool) { isInvalid = DS.SetTypeAltiVecVector(true, Loc, PrevSpec, DiagID,Policy); return true; } break; default: break; } } else if ((Tok.getIdentifierInfo() == Ident_pixel) && DS.isTypeAltiVecVector()) { isInvalid = DS.SetTypeAltiVecPixel(true, Loc, PrevSpec, DiagID, Policy); return true; } else if ((Tok.getIdentifierInfo() == Ident_bool) && DS.isTypeAltiVecVector()) { isInvalid = DS.SetTypeAltiVecBool(true, Loc, PrevSpec, DiagID, Policy); return true; } return false; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseExpr.cpp
//===--- ParseExpr.cpp - Expression Parsing -------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Provides the Expression parsing implementation. /// /// Expressions in C99 basically consist of a bunch of binary operators with /// unary operators and other random stuff at the leaves. /// /// In the C99 grammar, these unary operators bind tightest and are represented /// as the 'cast-expression' production. Everything else is either a binary /// operator (e.g. '/') or a ternary operator ("?:"). The unary leaves are /// handled by ParseCastExpression, the higher level pieces are handled by /// ParseBinaryExpression. /// //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "RAIIObjectsForParser.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/PrettyStackTrace.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/Scope.h" #include "clang/Sema/TypoCorrection.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" using namespace clang; /// \brief Simple precedence-based parser for binary/ternary operators. /// /// Note: we diverge from the C99 grammar when parsing the assignment-expression /// production. C99 specifies that the LHS of an assignment operator should be /// parsed as a unary-expression, but consistency dictates that it be a /// conditional-expession. In practice, the important thing here is that the /// LHS of an assignment has to be an l-value, which productions between /// unary-expression and conditional-expression don't produce. Because we want /// consistency, we parse the LHS as a conditional-expression, then check for /// l-value-ness in semantic analysis stages. /// /// \verbatim /// pm-expression: [C++ 5.5] /// cast-expression /// pm-expression '.*' cast-expression /// pm-expression '->*' cast-expression /// /// multiplicative-expression: [C99 6.5.5] /// Note: in C++, apply pm-expression instead of cast-expression /// cast-expression /// multiplicative-expression '*' cast-expression /// multiplicative-expression '/' cast-expression /// multiplicative-expression '%' cast-expression /// /// additive-expression: [C99 6.5.6] /// multiplicative-expression /// additive-expression '+' multiplicative-expression /// additive-expression '-' multiplicative-expression /// /// shift-expression: [C99 6.5.7] /// additive-expression /// shift-expression '<<' additive-expression /// shift-expression '>>' additive-expression /// /// relational-expression: [C99 6.5.8] /// shift-expression /// relational-expression '<' shift-expression /// relational-expression '>' shift-expression /// relational-expression '<=' shift-expression /// relational-expression '>=' shift-expression /// /// equality-expression: [C99 6.5.9] /// relational-expression /// equality-expression '==' relational-expression /// equality-expression '!=' relational-expression /// /// AND-expression: [C99 6.5.10] /// equality-expression /// AND-expression '&' equality-expression /// /// exclusive-OR-expression: [C99 6.5.11] /// AND-expression /// exclusive-OR-expression '^' AND-expression /// /// inclusive-OR-expression: [C99 6.5.12] /// exclusive-OR-expression /// inclusive-OR-expression '|' exclusive-OR-expression /// /// logical-AND-expression: [C99 6.5.13] /// inclusive-OR-expression /// logical-AND-expression '&&' inclusive-OR-expression /// /// logical-OR-expression: [C99 6.5.14] /// logical-AND-expression /// logical-OR-expression '||' logical-AND-expression /// /// conditional-expression: [C99 6.5.15] /// logical-OR-expression /// logical-OR-expression '?' expression ':' conditional-expression /// [GNU] logical-OR-expression '?' ':' conditional-expression /// [C++] the third operand is an assignment-expression /// /// assignment-expression: [C99 6.5.16] /// conditional-expression /// unary-expression assignment-operator assignment-expression /// [C++] throw-expression [C++ 15] /// /// assignment-operator: one of /// = *= /= %= += -= <<= >>= &= ^= |= /// /// expression: [C99 6.5.17] /// assignment-expression ...[opt] /// expression ',' assignment-expression ...[opt] /// \endverbatim ExprResult Parser::ParseExpression(TypeCastState isTypeCast) { ExprResult LHS(ParseAssignmentExpression(isTypeCast)); return ParseRHSOfBinaryExpression(LHS, prec::Comma); } /// This routine is called when the '@' is seen and consumed. /// Current token is an Identifier and is not a 'try'. This /// routine is necessary to disambiguate \@try-statement from, /// for example, \@encode-expression. /// ExprResult Parser::ParseExpressionWithLeadingAt(SourceLocation AtLoc) { assert(!getLangOpts().HLSL && "@ for obj-c is unsupported in HLSL"); // HLSL Change ExprResult LHS(ParseObjCAtExpression(AtLoc)); return ParseRHSOfBinaryExpression(LHS, prec::Comma); } /// This routine is called when a leading '__extension__' is seen and /// consumed. This is necessary because the token gets consumed in the /// process of disambiguating between an expression and a declaration. ExprResult Parser::ParseExpressionWithLeadingExtension(SourceLocation ExtLoc) { ExprResult LHS(true); { // Silence extension warnings in the sub-expression ExtensionRAIIObject O(Diags); LHS = ParseCastExpression(false); } if (!LHS.isInvalid()) LHS = Actions.ActOnUnaryOp(getCurScope(), ExtLoc, tok::kw___extension__, LHS.get()); return ParseRHSOfBinaryExpression(LHS, prec::Comma); } /// \brief Parse an expr that doesn't include (top-level) commas. ExprResult Parser::ParseAssignmentExpression(TypeCastState isTypeCast) { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); cutOffParsing(); return ExprError(); } if (Tok.is(tok::kw_throw)) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); return ExprError(); } // HLSL Change Ends return ParseThrowExpression(); } ExprResult LHS = ParseCastExpression(/*isUnaryExpression=*/false, /*isAddressOfOperand=*/false, isTypeCast); return ParseRHSOfBinaryExpression(LHS, prec::Assignment); } /// \brief Parse an assignment expression where part of an Objective-C message /// send has already been parsed. /// /// In this case \p LBracLoc indicates the location of the '[' of the message /// send, and either \p ReceiverName or \p ReceiverExpr is non-null indicating /// the receiver of the message. /// /// Since this handles full assignment-expression's, it handles postfix /// expressions and other binary operators for these expressions as well. ExprResult Parser::ParseAssignmentExprWithObjCMessageExprStart(SourceLocation LBracLoc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr) { assert(!getLangOpts().HLSL && "obj-c constructs unsupported in HLSL"); // HLSL Change ExprResult R = ParseObjCMessageExpressionBody(LBracLoc, SuperLoc, ReceiverType, ReceiverExpr); R = ParsePostfixExpressionSuffix(R); return ParseRHSOfBinaryExpression(R, prec::Assignment); } ExprResult Parser::ParseConstantExpression(TypeCastState isTypeCast) { // C++03 [basic.def.odr]p2: // An expression is potentially evaluated unless it appears where an // integral constant expression is required (see 5.19) [...]. // C++98 and C++11 have no such rule, but this is only a defect in C++98. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::ConstantEvaluated); ExprResult LHS(ParseCastExpression(false, false, isTypeCast)); ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::Conditional)); return Actions.ActOnConstantExpression(Res); } /// \brief Parse a constraint-expression. /// /// \verbatim /// constraint-expression: [Concepts TS temp.constr.decl p1] /// logical-or-expression /// \endverbatim ExprResult Parser::ParseConstraintExpression() { // FIXME: this may erroneously consume a function-body as the braced // initializer list of a compound literal // // FIXME: this may erroneously consume a parenthesized rvalue reference // declarator as a parenthesized address-of-label expression ExprResult LHS(ParseCastExpression(/*isUnaryExpression=*/false)); ExprResult Res(ParseRHSOfBinaryExpression(LHS, prec::LogicalOr)); return Res; } bool Parser::isNotExpressionStart() { tok::TokenKind K = Tok.getKind(); if (K == tok::l_brace || K == tok::r_brace || K == tok::kw_for || K == tok::kw_while || K == tok::kw_if || K == tok::kw_else || K == tok::kw_goto || K == tok::kw_try) return true; // If this is a decl-specifier, we can't be at the start of an expression. return isKnownToBeDeclarationSpecifier(); } static bool isFoldOperator(prec::Level Level) { return Level > prec::Unknown && Level != prec::Conditional; } static bool isFoldOperator(tok::TokenKind Kind) { return isFoldOperator(getBinOpPrecedence(Kind, false, true)); } /// \brief Parse a binary expression that starts with \p LHS and has a /// precedence of at least \p MinPrec. ExprResult Parser::ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec) { prec::Level NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, getLangOpts().CPlusPlus11); SourceLocation ColonLoc; while (1) { // If this token has a lower precedence than we are allowed to parse (e.g. // because we are called recursively, or because the token is not a binop), // then we are done! if (NextTokPrec < MinPrec) return LHS; // Consume the operator, saving the operator token for error reporting. Token OpToken = Tok; ConsumeToken(); // Bail out when encountering a comma followed by a token which can't // possibly be the start of an expression. For instance: // int f() { return 1, } // We can't do this before consuming the comma, because // isNotExpressionStart() looks at the token stream. if (OpToken.is(tok::comma) && isNotExpressionStart()) { PP.EnterToken(Tok); Tok = OpToken; return LHS; } // If the next token is an ellipsis, then this is a fold-expression. Leave // it alone so we can handle it in the paren expression. if (isFoldOperator(NextTokPrec) && Tok.is(tok::ellipsis)) { // FIXME: We can't check this via lookahead before we consume the token // because that tickles a lexer bug. PP.EnterToken(Tok); Tok = OpToken; return LHS; } // Special case handling for the ternary operator. ExprResult TernaryMiddle(true); if (NextTokPrec == prec::Conditional) { if (Tok.isNot(tok::colon)) { // Don't parse FOO:BAR as if it were a typo for FOO::BAR. ColonProtectionRAIIObject X(*this); // Handle this production specially: // logical-OR-expression '?' expression ':' conditional-expression // In particular, the RHS of the '?' is 'expression', not // 'logical-OR-expression' as we might expect. TernaryMiddle = ParseExpression(); if (TernaryMiddle.isInvalid()) { Actions.CorrectDelayedTyposInExpr(LHS); LHS = ExprError(); TernaryMiddle = nullptr; } } else { // Special case handling of "X ? Y : Z" where Y is empty: // logical-OR-expression '?' ':' conditional-expression [GNU] TernaryMiddle = nullptr; // HLSL Change Starts - provide an alternate message if (getLangOpts().HLSL) Diag(Tok, diag::err_hlsl_unsupported_construct) << "use of GNU ?: conditional expression extension, omitting middle operand"; else Diag(Tok, diag::ext_gnu_conditional_expr); // HLSL Change Ends } if (!TryConsumeToken(tok::colon, ColonLoc)) { // Otherwise, we're missing a ':'. Assume that this was a typo that // the user forgot. If we're not in a macro expansion, we can suggest // a fixit hint. If there were two spaces before the current token, // suggest inserting the colon in between them, otherwise insert ": ". SourceLocation FILoc = Tok.getLocation(); const char *FIText = ": "; const SourceManager &SM = PP.getSourceManager(); if (FILoc.isFileID() || PP.isAtStartOfMacroExpansion(FILoc, &FILoc)) { assert(FILoc.isFileID()); bool IsInvalid = false; const char *SourcePtr = SM.getCharacterData(FILoc.getLocWithOffset(-1), &IsInvalid); if (!IsInvalid && *SourcePtr == ' ') { SourcePtr = SM.getCharacterData(FILoc.getLocWithOffset(-2), &IsInvalid); if (!IsInvalid && *SourcePtr == ' ') { FILoc = FILoc.getLocWithOffset(-1); FIText = ":"; } } } Diag(Tok, diag::err_expected) << tok::colon << FixItHint::CreateInsertion(FILoc, FIText); Diag(OpToken, diag::note_matching) << tok::question; ColonLoc = Tok.getLocation(); } } // Code completion for the right-hand side of an assignment expression // goes through a special hook that takes the left-hand side into account. if (Tok.is(tok::code_completion) && NextTokPrec == prec::Assignment) { Actions.CodeCompleteAssignmentRHS(getCurScope(), LHS.get()); cutOffParsing(); return ExprError(); } // Parse another leaf here for the RHS of the operator. // ParseCastExpression works here because all RHS expressions in C have it // as a prefix, at least. However, in C++, an assignment-expression could // be a throw-expression, which is not a valid cast-expression. // Therefore we need some special-casing here. // Also note that the third operand of the conditional operator is // an assignment-expression in C++, and in C++11, we can have a // braced-init-list on the RHS of an assignment. For better diagnostics, // parse as if we were allowed braced-init-lists everywhere, and check that // they only appear on the RHS of assignments later. ExprResult RHS; bool RHSIsInitList = false; if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { RHS = ParseBraceInitializer(); RHSIsInitList = true; } else if (getLangOpts().CPlusPlus && NextTokPrec <= prec::Conditional) RHS = ParseAssignmentExpression(); else RHS = ParseCastExpression(false); if (RHS.isInvalid()) { // FIXME: Errors generated by the delayed typo correction should be // printed before errors from parsing the RHS, not after. Actions.CorrectDelayedTyposInExpr(LHS); if (TernaryMiddle.isUsable()) TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle); LHS = ExprError(); } // Remember the precedence of this operator and get the precedence of the // operator immediately to the right of the RHS. prec::Level ThisPrec = NextTokPrec; NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, getLangOpts().CPlusPlus11); // Assignment and conditional expressions are right-associative. bool isRightAssoc = ThisPrec == prec::Conditional || ThisPrec == prec::Assignment; // Get the precedence of the operator to the right of the RHS. If it binds // more tightly with RHS than we do, evaluate it completely first. if (ThisPrec < NextTokPrec || (ThisPrec == NextTokPrec && isRightAssoc)) { if (!RHS.isInvalid() && RHSIsInitList) { Diag(Tok, diag::err_init_list_bin_op) << /*LHS*/0 << PP.getSpelling(Tok) << Actions.getExprRange(RHS.get()); RHS = ExprError(); } // If this is left-associative, only parse things on the RHS that bind // more tightly than the current operator. If it is left-associative, it // is okay, to bind exactly as tightly. For example, compile A=B=C=D as // A=(B=(C=D)), where each paren is a level of recursion here. // The function takes ownership of the RHS. RHS = ParseRHSOfBinaryExpression(RHS, static_cast<prec::Level>(ThisPrec + !isRightAssoc)); RHSIsInitList = false; if (RHS.isInvalid()) { // FIXME: Errors generated by the delayed typo correction should be // printed before errors from ParseRHSOfBinaryExpression, not after. Actions.CorrectDelayedTyposInExpr(LHS); if (TernaryMiddle.isUsable()) TernaryMiddle = Actions.CorrectDelayedTyposInExpr(TernaryMiddle); LHS = ExprError(); } NextTokPrec = getBinOpPrecedence(Tok.getKind(), GreaterThanIsOperator, getLangOpts().CPlusPlus11); } if (!RHS.isInvalid() && RHSIsInitList) { if (ThisPrec == prec::Assignment) { Diag(OpToken, diag::warn_cxx98_compat_generalized_initializer_lists) << Actions.getExprRange(RHS.get()); } else { Diag(OpToken, diag::err_init_list_bin_op) << /*RHS*/1 << PP.getSpelling(OpToken) << Actions.getExprRange(RHS.get()); LHS = ExprError(); } } if (!LHS.isInvalid()) { // Combine the LHS and RHS into the LHS (e.g. build AST). if (TernaryMiddle.isInvalid()) { // If we're using '>>' as an operator within a template // argument list (in C++98), suggest the addition of // parentheses so that the code remains well-formed in C++0x. if (!GreaterThanIsOperator && OpToken.is(tok::greatergreater)) SuggestParentheses(OpToken.getLocation(), diag::warn_cxx11_right_shift_in_template_arg, SourceRange(Actions.getExprRange(LHS.get()).getBegin(), Actions.getExprRange(RHS.get()).getEnd())); LHS = Actions.ActOnBinOp(getCurScope(), OpToken.getLocation(), OpToken.getKind(), LHS.get(), RHS.get()); } else { LHS = Actions.ActOnConditionalOp(OpToken.getLocation(), ColonLoc, LHS.get(), TernaryMiddle.get(), RHS.get()); } // HLSL Change Begin - Take care TernaryMiddle. } else { // Ensure potential typos in the RHS aren't left undiagnosed. Actions.CorrectDelayedTyposInExpr(RHS); } Actions.CorrectDelayedTyposInExpr(TernaryMiddle); // HLSL Change End. } } /// \brief Parse a cast-expression, or, if \p isUnaryExpression is true, /// parse a unary-expression. /// /// \p isAddressOfOperand exists because an id-expression that is the /// operand of address-of gets special treatment due to member pointers. /// ExprResult Parser::ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand, TypeCastState isTypeCast) { bool NotCastExpr; ExprResult Res = ParseCastExpression(isUnaryExpression, isAddressOfOperand, NotCastExpr, isTypeCast); if (NotCastExpr) Diag(Tok, diag::err_expected_expression); return Res; } namespace { class CastExpressionIdValidator : public CorrectionCandidateCallback { public: CastExpressionIdValidator(Token Next, bool AllowTypes, bool AllowNonTypes) : NextToken(Next), AllowNonTypes(AllowNonTypes) { WantTypeSpecifiers = WantFunctionLikeCasts = AllowTypes; } bool ValidateCandidate(const TypoCorrection &candidate) override { NamedDecl *ND = candidate.getCorrectionDecl(); if (!ND) return candidate.isKeyword(); if (isa<TypeDecl>(ND)) return WantTypeSpecifiers; if (!AllowNonTypes || !CorrectionCandidateCallback::ValidateCandidate(candidate)) return false; if (!NextToken.isOneOf(tok::equal, tok::arrow, tok::period)) return true; for (auto *C : candidate) { NamedDecl *ND = C->getUnderlyingDecl(); if (isa<ValueDecl>(ND) && !isa<FunctionDecl>(ND)) return true; } return false; } private: Token NextToken; bool AllowNonTypes; }; } /// \brief Parse a cast-expression, or, if \pisUnaryExpression is true, parse /// a unary-expression. /// /// \p isAddressOfOperand exists because an id-expression that is the operand /// of address-of gets special treatment due to member pointers. NotCastExpr /// is set to true if the token is not the start of a cast-expression, and no /// diagnostic is emitted in this case. /// /// \verbatim /// cast-expression: [C99 6.5.4] /// unary-expression /// '(' type-name ')' cast-expression /// /// unary-expression: [C99 6.5.3] /// postfix-expression /// '++' unary-expression /// '--' unary-expression /// unary-operator cast-expression /// 'sizeof' unary-expression /// 'sizeof' '(' type-name ')' /// [C++11] 'sizeof' '...' '(' identifier ')' /// [GNU] '__alignof' unary-expression /// [GNU] '__alignof' '(' type-name ')' /// [C11] '_Alignof' '(' type-name ')' /// [C++11] 'alignof' '(' type-id ')' /// [GNU] '&&' identifier /// [C++11] 'noexcept' '(' expression ')' [C++11 5.3.7] /// [C++] new-expression /// [C++] delete-expression /// /// unary-operator: one of /// '&' '*' '+' '-' '~' '!' /// [GNU] '__extension__' '__real' '__imag' /// /// primary-expression: [C99 6.5.1] /// [C99] identifier /// [C++] id-expression /// constant /// string-literal /// [C++] boolean-literal [C++ 2.13.5] /// [C++11] 'nullptr' [C++11 2.14.7] /// [C++11] user-defined-literal /// '(' expression ')' /// [C11] generic-selection /// '__func__' [C99 6.4.2.2] /// [GNU] '__FUNCTION__' /// [MS] '__FUNCDNAME__' /// [MS] 'L__FUNCTION__' /// [GNU] '__PRETTY_FUNCTION__' /// [GNU] '(' compound-statement ')' /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' /// assign-expr ')' /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' /// [GNU] '__null' /// [OBJC] '[' objc-message-expr ']' /// [OBJC] '\@selector' '(' objc-selector-arg ')' /// [OBJC] '\@protocol' '(' identifier ')' /// [OBJC] '\@encode' '(' type-name ')' /// [OBJC] objc-string-literal /// [C++] simple-type-specifier '(' expression-list[opt] ')' [C++ 5.2.3] /// [C++11] simple-type-specifier braced-init-list [C++11 5.2.3] /// [C++] typename-specifier '(' expression-list[opt] ')' [C++ 5.2.3] /// [C++11] typename-specifier braced-init-list [C++11 5.2.3] /// [C++] 'const_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] /// [C++] 'dynamic_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] /// [C++] 'reinterpret_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] /// [C++] 'static_cast' '<' type-name '>' '(' expression ')' [C++ 5.2p1] /// [C++] 'typeid' '(' expression ')' [C++ 5.2p1] /// [C++] 'typeid' '(' type-id ')' [C++ 5.2p1] /// [C++] 'this' [C++ 9.3.2] /// [G++] unary-type-trait '(' type-id ')' /// [G++] binary-type-trait '(' type-id ',' type-id ')' [TODO] /// [EMBT] array-type-trait '(' type-id ',' integer ')' /// [clang] '^' block-literal /// /// constant: [C99 6.4.4] /// integer-constant /// floating-constant /// enumeration-constant -> identifier /// character-constant /// /// id-expression: [C++ 5.1] /// unqualified-id /// qualified-id /// /// unqualified-id: [C++ 5.1] /// identifier /// operator-function-id /// conversion-function-id /// '~' class-name /// template-id /// /// new-expression: [C++ 5.3.4] /// '::'[opt] 'new' new-placement[opt] new-type-id /// new-initializer[opt] /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' /// new-initializer[opt] /// /// delete-expression: [C++ 5.3.5] /// '::'[opt] 'delete' cast-expression /// '::'[opt] 'delete' '[' ']' cast-expression /// /// [GNU/Embarcadero] unary-type-trait: /// '__is_arithmetic' /// '__is_floating_point' /// '__is_integral' /// '__is_lvalue_expr' /// '__is_rvalue_expr' /// '__is_complete_type' /// '__is_void' /// '__is_array' /// '__is_function' /// '__is_reference' /// '__is_lvalue_reference' /// '__is_rvalue_reference' /// '__is_fundamental' /// '__is_object' /// '__is_scalar' /// '__is_compound' /// '__is_pointer' /// '__is_member_object_pointer' /// '__is_member_function_pointer' /// '__is_member_pointer' /// '__is_const' /// '__is_volatile' /// '__is_trivial' /// '__is_standard_layout' /// '__is_signed' /// '__is_unsigned' /// /// [GNU] unary-type-trait: /// '__has_nothrow_assign' /// '__has_nothrow_copy' /// '__has_nothrow_constructor' /// '__has_trivial_assign' [TODO] /// '__has_trivial_copy' [TODO] /// '__has_trivial_constructor' /// '__has_trivial_destructor' /// '__has_virtual_destructor' /// '__is_abstract' [TODO] /// '__is_class' /// '__is_empty' [TODO] /// '__is_enum' /// '__is_final' /// '__is_pod' /// '__is_polymorphic' /// '__is_sealed' [MS] /// '__is_trivial' /// '__is_union' /// /// [Clang] unary-type-trait: /// '__trivially_copyable' /// /// binary-type-trait: /// [GNU] '__is_base_of' /// [MS] '__is_convertible_to' /// '__is_convertible' /// '__is_same' /// /// [Embarcadero] array-type-trait: /// '__array_rank' /// '__array_extent' /// /// [Embarcadero] expression-trait: /// '__is_lvalue_expr' /// '__is_rvalue_expr' /// \endverbatim /// ExprResult Parser::ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast) { ExprResult Res; tok::TokenKind SavedKind = Tok.getKind(); NotCastExpr = false; // This handles all of cast-expression, unary-expression, postfix-expression, // and primary-expression. We handle them together like this for efficiency // and to simplify handling of an expression starting with a '(' token: which // may be one of a parenthesized expression, cast-expression, compound literal // expression, or statement expression. // // If the parsed tokens consist of a primary-expression, the cases below // break out of the switch; at the end we call ParsePostfixExpressionSuffix // to handle the postfix expression suffixes. Cases that cannot be followed // by postfix exprs should return without invoking // ParsePostfixExpressionSuffix. switch (SavedKind) { case tok::l_paren: { // If this expression is limited to being a unary-expression, the parent can // not start a cast expression. ParenParseOption ParenExprType = (isUnaryExpression && !getLangOpts().CPlusPlus) ? CompoundLiteral : CastExpr; ParsedType CastTy; SourceLocation RParenLoc; Res = ParseParenExpression(ParenExprType, false/*stopIfCastExr*/, isTypeCast == IsTypeCast, CastTy, RParenLoc); switch (ParenExprType) { case SimpleExpr: break; // Nothing else to do. case CompoundStmt: break; // Nothing else to do. case CompoundLiteral: // We parsed '(' type-name ')' '{' ... '}'. If any suffixes of // postfix-expression exist, parse them now. break; case CastExpr: // We have parsed the cast-expression and no postfix-expr pieces are // following. return Res; } break; } // primary-expression case tok::numeric_constant: // constant: integer-constant // constant: floating-constant Res = Actions.ActOnNumericConstant(Tok, /*UDLScope*/getCurScope()); ConsumeToken(); break; case tok::kw_true: case tok::kw_false: return ParseCXXBoolLiteral(); case tok::kw___objc_yes: case tok::kw___objc_no: // HLSL Change Starts HLSLReservedKeyword: if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); return ExprError(); } // HLSL Change Ends return ParseObjCBoolLiteral(); case tok::kw_nullptr: // HLSL Change Starts assert(!getLangOpts().HLSL && "nullptr is not a keyword in HLSL"); if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change Ends Diag(Tok, diag::warn_cxx98_compat_nullptr); return Actions.ActOnCXXNullPtrLiteral(ConsumeToken()); case tok::annot_primary_expr: assert(Res.get() == nullptr && "Stray primary-expression annotation?"); Res = getExprAnnotation(Tok); ConsumeToken(); break; case tok::kw___super: case tok::kw_decltype: // HLSL Change Starts assert(!getLangOpts().HLSL && "decltype is not a keyword in HLSL"); if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change Ends // Annotate the token and tail recurse. if (TryAnnotateTypeOrScopeToken()) return ExprError(); assert(Tok.isNot(tok::kw_decltype) && Tok.isNot(tok::kw___super)); return ParseCastExpression(isUnaryExpression, isAddressOfOperand); // HLSL Change Starts case tok::kw_precise: case tok::kw_sample: case tok::kw_globallycoherent: case tok::kw_center: case tok::kw_indices: case tok::kw_vertices: case tok::kw_primitives: case tok::kw_payload: // Back-compat: 'precise', 'globallycoherent', 'center' and 'sample' are keywords when used as an interpolation // modifiers, but in FXC they can also be used an identifiers. No interpolation modifiers are expected here // so we need to change the token type to tok::identifier and fall through to the next case. // Similarly 'indices', 'vertices', 'primitives' and 'payload' are keywords when used // as a type qualifer in mesh shader, but may still be used as a variable name. Tok.setKind(tok::identifier); LLVM_FALLTHROUGH; // HLSL Change Ends case tok::identifier: { // primary-expression: identifier // unqualified-id: identifier // constant: enumeration-constant // Turn a potentially qualified name into a annot_typename or // annot_cxxscope if it would be valid. This handles things like x::y, etc. if (getLangOpts().CPlusPlus) { // Avoid the unnecessary parse-time lookup in the common case // where the syntax forbids a type. const Token &Next = NextToken(); // If this identifier was reverted from a token ID, and the next token // is a parenthesis, this is likely to be a use of a type trait. Check // those tokens. if (Next.is(tok::l_paren) && !getLangOpts().HLSL && // HLSL Change - no type trait support in HLSL Tok.is(tok::identifier) && Tok.getIdentifierInfo()->hasRevertedTokenIDToIdentifier()) { IdentifierInfo *II = Tok.getIdentifierInfo(); // Build up the mapping of revertible type traits, for future use. if (RevertibleTypeTraits.empty()) { #define RTT_JOIN(X,Y) X##Y #define REVERTIBLE_TYPE_TRAIT(Name) \ RevertibleTypeTraits[PP.getIdentifierInfo(#Name)] \ = RTT_JOIN(tok::kw_,Name) REVERTIBLE_TYPE_TRAIT(__is_abstract); REVERTIBLE_TYPE_TRAIT(__is_arithmetic); REVERTIBLE_TYPE_TRAIT(__is_array); REVERTIBLE_TYPE_TRAIT(__is_base_of); REVERTIBLE_TYPE_TRAIT(__is_class); REVERTIBLE_TYPE_TRAIT(__is_complete_type); REVERTIBLE_TYPE_TRAIT(__is_compound); REVERTIBLE_TYPE_TRAIT(__is_const); REVERTIBLE_TYPE_TRAIT(__is_constructible); REVERTIBLE_TYPE_TRAIT(__is_convertible); REVERTIBLE_TYPE_TRAIT(__is_convertible_to); REVERTIBLE_TYPE_TRAIT(__is_destructible); REVERTIBLE_TYPE_TRAIT(__is_empty); REVERTIBLE_TYPE_TRAIT(__is_enum); REVERTIBLE_TYPE_TRAIT(__is_floating_point); REVERTIBLE_TYPE_TRAIT(__is_final); REVERTIBLE_TYPE_TRAIT(__is_function); REVERTIBLE_TYPE_TRAIT(__is_fundamental); REVERTIBLE_TYPE_TRAIT(__is_integral); REVERTIBLE_TYPE_TRAIT(__is_interface_class); REVERTIBLE_TYPE_TRAIT(__is_literal); REVERTIBLE_TYPE_TRAIT(__is_lvalue_expr); REVERTIBLE_TYPE_TRAIT(__is_lvalue_reference); REVERTIBLE_TYPE_TRAIT(__is_member_function_pointer); REVERTIBLE_TYPE_TRAIT(__is_member_object_pointer); REVERTIBLE_TYPE_TRAIT(__is_member_pointer); REVERTIBLE_TYPE_TRAIT(__is_nothrow_assignable); REVERTIBLE_TYPE_TRAIT(__is_nothrow_constructible); REVERTIBLE_TYPE_TRAIT(__is_nothrow_destructible); REVERTIBLE_TYPE_TRAIT(__is_object); REVERTIBLE_TYPE_TRAIT(__is_pod); REVERTIBLE_TYPE_TRAIT(__is_pointer); REVERTIBLE_TYPE_TRAIT(__is_polymorphic); REVERTIBLE_TYPE_TRAIT(__is_reference); REVERTIBLE_TYPE_TRAIT(__is_rvalue_expr); REVERTIBLE_TYPE_TRAIT(__is_rvalue_reference); REVERTIBLE_TYPE_TRAIT(__is_same); REVERTIBLE_TYPE_TRAIT(__is_scalar); REVERTIBLE_TYPE_TRAIT(__is_sealed); REVERTIBLE_TYPE_TRAIT(__is_signed); REVERTIBLE_TYPE_TRAIT(__is_standard_layout); REVERTIBLE_TYPE_TRAIT(__is_trivial); REVERTIBLE_TYPE_TRAIT(__is_trivially_assignable); REVERTIBLE_TYPE_TRAIT(__is_trivially_constructible); REVERTIBLE_TYPE_TRAIT(__is_trivially_copyable); REVERTIBLE_TYPE_TRAIT(__is_union); REVERTIBLE_TYPE_TRAIT(__is_unsigned); REVERTIBLE_TYPE_TRAIT(__is_void); REVERTIBLE_TYPE_TRAIT(__is_volatile); #undef REVERTIBLE_TYPE_TRAIT #undef RTT_JOIN } // If we find that this is in fact the name of a type trait, // update the token kind in place and parse again to treat it as // the appropriate kind of type trait. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind>::iterator Known = RevertibleTypeTraits.find(II); if (Known != RevertibleTypeTraits.end()) { Tok.setKind(Known->second); return ParseCastExpression(isUnaryExpression, isAddressOfOperand, NotCastExpr, isTypeCast); } } if ((!ColonIsSacred && Next.is(tok::colon)) || Next.isOneOf(tok::coloncolon, tok::less, tok::l_paren, tok::l_brace)) { // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. if (TryAnnotateTypeOrScopeToken()) return ExprError(); if (!Tok.is(tok::identifier)) return ParseCastExpression(isUnaryExpression, isAddressOfOperand); } } // Consume the identifier so that we can see if it is followed by a '(' or // '.'. IdentifierInfo &II = *Tok.getIdentifierInfo(); SourceLocation ILoc = ConsumeToken(); // Support 'Class.property' and 'super.property' notation. if (getLangOpts().ObjC1 && Tok.is(tok::period) && (Actions.getTypeName(II, ILoc, getCurScope()) || // Allow the base to be 'super' if in an objc-method. (&II == Ident_super && getCurScope()->isInObjcMethodScope()))) { ConsumeToken(); // Allow either an identifier or the keyword 'class' (in C++). if (Tok.isNot(tok::identifier) && !(getLangOpts().CPlusPlus && Tok.is(tok::kw_class))) { Diag(Tok, diag::err_expected_property_name); return ExprError(); } IdentifierInfo &PropertyName = *Tok.getIdentifierInfo(); SourceLocation PropertyLoc = ConsumeToken(); Res = Actions.ActOnClassPropertyRefExpr(II, PropertyName, ILoc, PropertyLoc); break; } // In an Objective-C method, if we have "super" followed by an identifier, // the token sequence is ill-formed. However, if there's a ':' or ']' after // that identifier, this is probably a message send with a missing open // bracket. Treat it as such. if (getLangOpts().ObjC1 && &II == Ident_super && !InMessageExpression && getCurScope()->isInObjcMethodScope() && ((Tok.is(tok::identifier) && (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) || Tok.is(tok::code_completion))) { Res = ParseObjCMessageExpressionBody(SourceLocation(), ILoc, ParsedType(), nullptr); break; } // If we have an Objective-C class name followed by an identifier // and either ':' or ']', this is an Objective-C class message // send that's missing the opening '['. Recovery // appropriately. Also take this path if we're performing code // completion after an Objective-C class name. if (getLangOpts().ObjC1 && ((Tok.is(tok::identifier) && !InMessageExpression) || Tok.is(tok::code_completion))) { const Token& Next = NextToken(); if (Tok.is(tok::code_completion) || Next.is(tok::colon) || Next.is(tok::r_square)) if (ParsedType Typ = Actions.getTypeName(II, ILoc, getCurScope())) if (Typ.get()->isObjCObjectOrInterfaceType()) { // Fake up a Declarator to use with ActOnTypeName. DeclSpec DS(AttrFactory); DS.SetRangeStart(ILoc); DS.SetRangeEnd(ILoc); const char *PrevSpec = nullptr; unsigned DiagID; DS.SetTypeSpecType(TST_typename, ILoc, PrevSpec, DiagID, Typ, Actions.getASTContext().getPrintingPolicy()); Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); if (Ty.isInvalid()) break; Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), Ty.get(), nullptr); break; } } // Make sure to pass down the right value for isAddressOfOperand. if (isAddressOfOperand && isPostfixExpressionSuffixStart()) isAddressOfOperand = false; // Function designators are allowed to be undeclared (C99 6.5.1p2), so we // need to know whether or not this identifier is a function designator or // not. UnqualifiedId Name; CXXScopeSpec ScopeSpec; SourceLocation TemplateKWLoc; Token Replacement; auto Validator = llvm::make_unique<CastExpressionIdValidator>( Tok, isTypeCast != NotTypeCast, isTypeCast != IsTypeCast); Validator->IsAddressOfOperand = isAddressOfOperand; if (Tok.isOneOf(tok::periodstar, tok::arrowstar)) { Validator->WantExpressionKeywords = false; Validator->WantRemainingKeywords = false; } else { Validator->WantRemainingKeywords = Tok.isNot(tok::r_paren); } Name.setIdentifier(&II, ILoc); Res = Actions.ActOnIdExpression( getCurScope(), ScopeSpec, TemplateKWLoc, Name, Tok.is(tok::l_paren), isAddressOfOperand, std::move(Validator), /*IsInlineAsmIdentifier=*/false, Tok.is(tok::r_paren) ? nullptr : &Replacement); if (!Res.isInvalid() && !Res.get()) { UnconsumeToken(Replacement); return ParseCastExpression(isUnaryExpression, isAddressOfOperand, NotCastExpr, isTypeCast); } break; } case tok::char_constant: // constant: character-constant case tok::wide_char_constant: case tok::utf8_char_constant: case tok::utf16_char_constant: case tok::utf32_char_constant: // HLSL Change Starts // Character constants become 32-bit unsigned ints. That will happen in Sema. if (getLangOpts().HLSL && Tok.getKind() != tok::char_constant) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "non-ASCII/multiple-char character constant"; return ExprError(); } // HLSL Change Ends Res = Actions.ActOnCharacterConstant(Tok, /*UDLScope*/getCurScope()); ConsumeToken(); break; case tok::kw___func__: // primary-expression: __func__ [C99 6.4.2.2] case tok::kw___FUNCTION__: // primary-expression: __FUNCTION__ [GNU] case tok::kw___FUNCDNAME__: // primary-expression: __FUNCDNAME__ [MS] case tok::kw___FUNCSIG__: // primary-expression: __FUNCSIG__ [MS] case tok::kw_L__FUNCTION__: // primary-expression: L__FUNCTION__ [MS] case tok::kw___PRETTY_FUNCTION__: // primary-expression: __P..Y_F..N__ [GNU] // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); return ExprError(); } // HLSL Change Ends Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind); ConsumeToken(); break; case tok::string_literal: // primary-expression: string-literal case tok::wide_string_literal: case tok::utf8_string_literal: case tok::utf16_string_literal: case tok::utf32_string_literal: // HLSL Change Starts if (getLangOpts().HLSL && Tok.getKind() != tok::string_literal) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "non-ASCII string constant"; return ExprError(); } // HLSL Change Ends Res = ParseStringLiteralExpression(true); break; case tok::kw__Generic: // primary-expression: generic-selection [C11 6.5.1] // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); return ExprError(); } // HLSL Change Ends Res = ParseGenericSelectionExpression(); break; case tok::kw___builtin_va_arg: case tok::kw___builtin_offsetof: case tok::kw___builtin_choose_expr: case tok::kw___builtin_astype: // primary-expression: [OCL] as_type() case tok::kw___builtin_convertvector: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - not supported return ParseBuiltinPrimaryExpression(); case tok::kw___null: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - not supported return Actions.ActOnGNUNullExpr(ConsumeToken()); case tok::plusplus: // unary-expression: '++' unary-expression [C99] case tok::minusminus: { // unary-expression: '--' unary-expression [C99] // C++ [expr.unary] has: // unary-expression: // ++ cast-expression // -- cast-expression SourceLocation SavedLoc = ConsumeToken(); // One special case is implicitly handled here: if the preceding tokens are // an ambiguous cast expression, such as "(T())++", then we recurse to // determine whether the '++' is prefix or postfix. Res = ParseCastExpression(!getLangOpts().CPlusPlus, /*isAddressOfOperand*/false, NotCastExpr, NotTypeCast); if (!Res.isInvalid()) Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); return Res; } case tok::amp: { // unary-expression: '&' cast-expression // Special treatment because of member pointers SourceLocation SavedLoc = ConsumeToken(); Res = ParseCastExpression(false, true); if (!Res.isInvalid()) Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); return Res; } case tok::star: // unary-expression: '*' cast-expression case tok::plus: // unary-expression: '+' cast-expression case tok::minus: // unary-expression: '-' cast-expression case tok::tilde: // unary-expression: '~' cast-expression case tok::exclaim: // unary-expression: '!' cast-expression case tok::kw___real: // unary-expression: '__real' cast-expression [GNU] case tok::kw___imag: { // unary-expression: '__imag' cast-expression [GNU] // HLSL Change Starts if (getLangOpts().HLSL && (SavedKind == tok::kw___real || SavedKind == tok::kw___imag)) { goto HLSLReservedKeyword; } // HLSL Change Ends SourceLocation SavedLoc = ConsumeToken(); Res = ParseCastExpression(false); if (!Res.isInvalid()) Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); return Res; } case tok::kw___extension__:{//unary-expression:'__extension__' cast-expr [GNU] // __extension__ silences extension warnings in the subexpression. ExtensionRAIIObject O(Diags); // Use RAII to do this. SourceLocation SavedLoc = ConsumeToken(); Res = ParseCastExpression(false); if (!Res.isInvalid()) Res = Actions.ActOnUnaryOp(getCurScope(), SavedLoc, SavedKind, Res.get()); return Res; } case tok::kw__Alignof: // unary-expression: '_Alignof' '(' type-name ')' if (!getLangOpts().C11) Diag(Tok, diag::ext_c11_alignment) << Tok.getName(); LLVM_FALLTHROUGH; // HLSL Change case tok::kw_alignof: // unary-expression: 'alignof' '(' type-id ')' case tok::kw___alignof: // unary-expression: '__alignof' unary-expression // unary-expression: '__alignof' '(' type-name ')' case tok::kw_sizeof: // unary-expression: 'sizeof' unary-expression // unary-expression: 'sizeof' '(' type-name ')' case tok::kw_vec_step: // unary-expression: OpenCL 'vec_step' expression // unary-expression: '__builtin_omp_required_simd_align' '(' type-name ')' case tok::kw___builtin_omp_required_simd_align: if (getLangOpts().HLSL && Tok.getKind() != tok::kw_sizeof) { goto HLSLReservedKeyword; } // HLSL Change - not supported return ParseUnaryExprOrTypeTraitExpression(); case tok::ampamp: { // unary-expression: '&&' identifier // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "address of label"; return ExprError(); } // HLSL Change Ends SourceLocation AmpAmpLoc = ConsumeToken(); if (Tok.isNot(tok::identifier)) return ExprError(Diag(Tok, diag::err_expected) << tok::identifier); if (getCurScope()->getFnParent() == nullptr) return ExprError(Diag(Tok, diag::err_address_of_label_outside_fn)); Diag(AmpAmpLoc, diag::ext_gnu_address_of_label); LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), Tok.getLocation()); Res = Actions.ActOnAddrLabel(AmpAmpLoc, Tok.getLocation(), LD); ConsumeToken(); return Res; } case tok::kw_const_cast: case tok::kw_dynamic_cast: case tok::kw_reinterpret_cast: case tok::kw_static_cast: // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "C++-style cast"; return ExprError(); } // HLSL Change Ends Res = ParseCXXCasts(); break; case tok::kw_typeid: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - not supported Res = ParseCXXTypeid(); break; case tok::kw___uuidof: // HLSL Change Starts assert(!getLangOpts().HLSL && "__uuidof is not a keyword in HLSL"); if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change Ends Res = ParseCXXUuidof(); break; case tok::kw_this: Res = ParseCXXThis(); break; case tok::annot_typename: if (isStartOfObjCClassMessageMissingOpenBracket()) { ParsedType Type = getTypeAnnotation(Tok); // Fake up a Declarator to use with ActOnTypeName. DeclSpec DS(AttrFactory); DS.SetRangeStart(Tok.getLocation()); DS.SetRangeEnd(Tok.getLastLoc()); const char *PrevSpec = nullptr; unsigned DiagID; DS.SetTypeSpecType(TST_typename, Tok.getAnnotationEndLoc(), PrevSpec, DiagID, Type, Actions.getASTContext().getPrintingPolicy()); Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); if (Ty.isInvalid()) break; ConsumeToken(); Res = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), Ty.get(), nullptr); break; } LLVM_FALLTHROUGH; // HLSL Change case tok::annot_decltype: case tok::kw_char: case tok::kw_wchar_t: case tok::kw_char16_t: case tok::kw_char32_t: case tok::kw_bool: case tok::kw_short: case tok::kw_int: case tok::kw_long: case tok::kw___int64: case tok::kw___int128: case tok::kw_signed: case tok::kw_unsigned: case tok::kw_half: case tok::kw_float: case tok::kw_double: case tok::kw_void: case tok::kw_typename: case tok::kw_typeof: case tok::kw___vector: { // HLSL Change Starts if (getLangOpts().HLSL && (SavedKind == tok::kw_wchar_t || SavedKind == tok::kw_char || SavedKind == tok::kw_char16_t || SavedKind == tok::kw_char32_t || SavedKind == tok::kw_short || SavedKind == tok::kw_long || SavedKind == tok::kw___int64 || SavedKind == tok::kw___int128 || (SavedKind == tok::kw_typename && getLangOpts().HLSLVersion < hlsl::LangStd::v2021) || SavedKind == tok::kw_typeof)) { // the vector/image/sampler/event keywords aren't returned by the lexer for HLSL goto HLSLReservedKeyword; } // HLSL Change Ends if (!getLangOpts().CPlusPlus) { Diag(Tok, diag::err_expected_expression); return ExprError(); } if (SavedKind == tok::kw_typename) { // postfix-expression: typename-specifier '(' expression-list[opt] ')' // typename-specifier braced-init-list if (TryAnnotateTypeOrScopeToken()) return ExprError(); if (!Actions.isSimpleTypeSpecifier(Tok.getKind())) // We are trying to parse a simple-type-specifier but might not get such // a token after error recovery. return ExprError(); } // postfix-expression: simple-type-specifier '(' expression-list[opt] ')' // simple-type-specifier braced-init-list // DeclSpec DS(AttrFactory); ParseCXXSimpleTypeSpecifier(DS); if (Tok.isNot(tok::l_paren) && (!getLangOpts().CPlusPlus11 || Tok.isNot(tok::l_brace))) return ExprError(Diag(Tok, diag::err_expected_lparen_after_type) << DS.getSourceRange()); if (Tok.is(tok::l_brace)) Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); Res = ParseCXXTypeConstructExpression(DS); break; } // HLSL Change Starts case tok::kw_column_major: case tok::kw_row_major: case tok::kw_snorm: case tok::kw_unorm: goto tok_default_case; // HLSL Change Ends case tok::annot_cxxscope: { // [C++] id-expression: qualified-id // If TryAnnotateTypeOrScopeToken annotates the token, tail recurse. // (We can end up in this situation after tentative parsing.) if (TryAnnotateTypeOrScopeToken()) return ExprError(); if (!Tok.is(tok::annot_cxxscope)) return ParseCastExpression(isUnaryExpression, isAddressOfOperand, NotCastExpr, isTypeCast); Token Next = NextToken(); if (Next.is(tok::annot_template_id)) { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Next); if (TemplateId->Kind == TNK_Type_template) { // We have a qualified template-id that we know refers to a // type, translate it into a type and continue parsing as a // cast expression. CXXScopeSpec SS; ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); AnnotateTemplateIdTokenAsType(); return ParseCastExpression(isUnaryExpression, isAddressOfOperand, NotCastExpr, isTypeCast); } } // Parse as an id-expression. Res = ParseCXXIdExpression(isAddressOfOperand); break; } case tok::annot_template_id: { // [C++] template-id TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); if (TemplateId->Kind == TNK_Type_template) { // We have a template-id that we know refers to a type, // translate it into a type and continue parsing as a cast // expression. AnnotateTemplateIdTokenAsType(); return ParseCastExpression(isUnaryExpression, isAddressOfOperand, NotCastExpr, isTypeCast); } // Fall through to treat the template-id as an id-expression. LLVM_FALLTHROUGH; // HLSL Change } case tok::kw_operator: // [C++] id-expression: operator/conversion-function-id if (getLangOpts().HLSL && getLangOpts().HLSLVersion < hlsl::LangStd::v2021 && SavedKind == tok::kw_operator) { goto HLSLReservedKeyword; // HLSL Change - 'operator' is reserved } Res = ParseCXXIdExpression(isAddressOfOperand); break; case tok::coloncolon: { // ::foo::bar -> global qualified name etc. If TryAnnotateTypeOrScopeToken // annotates the token, tail recurse. if (TryAnnotateTypeOrScopeToken()) return ExprError(); if (!Tok.is(tok::coloncolon)) return ParseCastExpression(isUnaryExpression, isAddressOfOperand); // ::new -> [C++] new-expression // ::delete -> [C++] delete-expression SourceLocation CCLoc = ConsumeToken(); if (Tok.is(tok::kw_new)) { if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'new' is reserved return ParseCXXNewExpression(true, CCLoc); } if (Tok.is(tok::kw_delete)) { if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'delete' is reserved return ParseCXXDeleteExpression(true, CCLoc); } // This is not a type name or scope specifier, it is an invalid expression. Diag(CCLoc, diag::err_expected_expression); return ExprError(); } case tok::kw_new: // [C++] new-expression if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'new' is reserved return ParseCXXNewExpression(false, Tok.getLocation()); case tok::kw_delete: // [C++] delete-expression if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - 'delete' is reserved return ParseCXXDeleteExpression(false, Tok.getLocation()); case tok::kw_noexcept: { // [C++0x] 'noexcept' '(' expression ')' if (getLangOpts().HLSL) goto HLSLReservedKeyword; // HLSL Change - reserved keyword Diag(Tok, diag::warn_cxx98_compat_noexcept_expr); SourceLocation KeyLoc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.expectAndConsume(diag::err_expected_lparen_after, "noexcept")) return ExprError(); // C++11 [expr.unary.noexcept]p1: // The noexcept operator determines whether the evaluation of its operand, // which is an unevaluated operand, can throw an exception. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); ExprResult Result = ParseExpression(); T.consumeClose(); if (!Result.isInvalid()) Result = Actions.ActOnNoexceptExpr(KeyLoc, T.getOpenLocation(), Result.get(), T.getCloseLocation()); return Result; } #define TYPE_TRAIT(N,Spelling,K) \ case tok::kw_##Spelling: #include "clang/Basic/TokenKinds.def" return ParseTypeTrait(); case tok::kw___array_rank: case tok::kw___array_extent: return ParseArrayTypeTrait(); case tok::kw___is_lvalue_expr: case tok::kw___is_rvalue_expr: return ParseExpressionTrait(); case tok::at: { // HLSL Change Starts assert(!getLangOpts().HLSL && "HLSL does not recognize '@' as a token"); if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change Ends SourceLocation AtLoc = ConsumeToken(); return ParseObjCAtExpression(AtLoc); } case tok::caret: // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "block"; return ExprError(); } // HLSL Change Ends Res = ParseBlockLiteralExpression(); break; case tok::code_completion: { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); cutOffParsing(); return ExprError(); } case tok::l_square: if (getLangOpts().CPlusPlus11) { if (getLangOpts().ObjC1) { // C++11 lambda expressions and Objective-C message sends both start with a // square bracket. There are three possibilities here: // we have a valid lambda expression, we have an invalid lambda // expression, or we have something that doesn't appear to be a lambda. // If we're in the last case, we fall back to ParseObjCMessageExpression. Res = TryParseLambdaExpression(); if (!Res.isInvalid() && !Res.get()) Res = ParseObjCMessageExpression(); break; } Res = ParseLambdaExpression(); break; } if (getLangOpts().ObjC1) { Res = ParseObjCMessageExpression(); break; } LLVM_FALLTHROUGH; // HLSL Change default: tok_default_case: // HLSL Change - add to target cases dead-code'd by HLSL NotCastExpr = true; return ExprError(); } // These can be followed by postfix-expr pieces. return ParsePostfixExpressionSuffix(Res); } /// \brief Once the leading part of a postfix-expression is parsed, this /// method parses any suffixes that apply. /// /// \verbatim /// postfix-expression: [C99 6.5.2] /// primary-expression /// postfix-expression '[' expression ']' /// postfix-expression '[' braced-init-list ']' /// postfix-expression '(' argument-expression-list[opt] ')' /// postfix-expression '.' identifier /// postfix-expression '->' identifier /// postfix-expression '++' /// postfix-expression '--' /// '(' type-name ')' '{' initializer-list '}' /// '(' type-name ')' '{' initializer-list ',' '}' /// /// argument-expression-list: [C99 6.5.2] /// argument-expression ...[opt] /// argument-expression-list ',' assignment-expression ...[opt] /// \endverbatim ExprResult Parser::ParsePostfixExpressionSuffix(ExprResult LHS) { // Now that the primary-expression piece of the postfix-expression has been // parsed, see if there are any postfix-expression pieces here. SourceLocation Loc; while (1) { switch (Tok.getKind()) { case tok::code_completion: if (InMessageExpression) return LHS; Actions.CodeCompletePostfixExpression(getCurScope(), LHS); cutOffParsing(); return ExprError(); case tok::identifier: // If we see identifier: after an expression, and we're not already in a // message send, then this is probably a message send with a missing // opening bracket '['. if (getLangOpts().ObjC1 && !InMessageExpression && (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { LHS = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), ParsedType(), LHS.get()); break; } // Fall through; this isn't a message send. LLVM_FALLTHROUGH; // HLSL Change default: // Not a postfix-expression suffix. return LHS; case tok::l_square: { // postfix-expression: p-e '[' expression ']' // If we have a array postfix expression that starts on a new line and // Objective-C is enabled, it is highly likely that the user forgot a // semicolon after the base expression and that the array postfix-expr is // actually another message send. In this case, do some look-ahead to see // if the contents of the square brackets are obviously not a valid // expression and recover by pretending there is no suffix. if (getLangOpts().ObjC1 && Tok.isAtStartOfLine() && isSimpleObjCMessageExpression()) return LHS; // Reject array indices starting with a lambda-expression. '[[' is // reserved for attributes. if (CheckProhibitedCXX11Attribute()) return ExprError(); BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); Loc = T.getOpenLocation(); ExprResult Idx; if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); Idx = ParseBraceInitializer(); } else Idx = ParseExpression(); SourceLocation RLoc = Tok.getLocation(); if (!LHS.isInvalid() && !Idx.isInvalid() && Tok.is(tok::r_square)) { LHS = Actions.ActOnArraySubscriptExpr(getCurScope(), LHS.get(), Loc, Idx.get(), RLoc); } else { (void)Actions.CorrectDelayedTyposInExpr(LHS); (void)Actions.CorrectDelayedTyposInExpr(Idx); LHS = ExprError(); Idx = ExprError(); } // Match the ']'. T.consumeClose(); break; } case tok::l_paren: // p-e: p-e '(' argument-expression-list[opt] ')' case tok::lesslessless: { // p-e: p-e '<<<' argument-expression-list '>>>' // '(' argument-expression-list[opt] ')' tok::TokenKind OpKind = Tok.getKind(); InMessageExpressionRAIIObject InMessage(*this, false); Expr *ExecConfig = nullptr; BalancedDelimiterTracker PT(*this, tok::l_paren); if (getLangOpts().HLSL && OpKind == tok::lesslessless) { // HLSL Change: <<< is not supported in HLSL ExprVector ExecConfigExprs; CommaLocsTy ExecConfigCommaLocs; SourceLocation OpenLoc = ConsumeToken(); if (ParseSimpleExpressionList(ExecConfigExprs, ExecConfigCommaLocs)) { (void)Actions.CorrectDelayedTyposInExpr(LHS); LHS = ExprError(); } SourceLocation CloseLoc; if (TryConsumeToken(tok::greatergreatergreater, CloseLoc)) { } else if (LHS.isInvalid()) { SkipUntil(tok::greatergreatergreater, StopAtSemi); } else { // There was an error closing the brackets Diag(Tok, diag::err_expected) << tok::greatergreatergreater; Diag(OpenLoc, diag::note_matching) << tok::lesslessless; SkipUntil(tok::greatergreatergreater, StopAtSemi); LHS = ExprError(); } if (!LHS.isInvalid()) { if (ExpectAndConsume(tok::l_paren)) LHS = ExprError(); else Loc = PrevTokLocation; } if (!LHS.isInvalid()) { ExprResult ECResult = Actions.ActOnCUDAExecConfigExpr(getCurScope(), OpenLoc, ExecConfigExprs, CloseLoc); if (ECResult.isInvalid()) LHS = ExprError(); else ExecConfig = ECResult.get(); } } else { PT.consumeOpen(); Loc = PT.getOpenLocation(); } ExprVector ArgExprs; CommaLocsTy CommaLocs; if (Tok.is(tok::code_completion)) { Actions.CodeCompleteCall(getCurScope(), LHS.get(), None); cutOffParsing(); return ExprError(); } if (OpKind == tok::l_paren || !LHS.isInvalid()) { if (Tok.isNot(tok::r_paren)) { if (ParseExpressionList(ArgExprs, CommaLocs, [&] { Actions.CodeCompleteCall(getCurScope(), LHS.get(), ArgExprs); })) { (void)Actions.CorrectDelayedTyposInExpr(LHS); LHS = ExprError(); } else if (LHS.isInvalid()) { for (auto &E : ArgExprs) Actions.CorrectDelayedTyposInExpr(E); } } } // Match the ')'. if (LHS.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); } else if (Tok.isNot(tok::r_paren)) { bool HadDelayedTypo = false; if (Actions.CorrectDelayedTyposInExpr(LHS).get() != LHS.get()) HadDelayedTypo = true; for (auto &E : ArgExprs) if (Actions.CorrectDelayedTyposInExpr(E).get() != E) HadDelayedTypo = true; // If there were delayed typos in the LHS or ArgExprs, call SkipUntil // instead of PT.consumeClose() to avoid emitting extra diagnostics for // the unmatched l_paren. if (HadDelayedTypo) SkipUntil(tok::r_paren, StopAtSemi); else PT.consumeClose(); LHS = ExprError(); } else { assert((ArgExprs.size() == 0 || ArgExprs.size()-1 == CommaLocs.size())&& "Unexpected number of commas!"); LHS = Actions.ActOnCallExpr(getCurScope(), LHS.get(), Loc, ArgExprs, Tok.getLocation(), ExecConfig); PT.consumeClose(); } break; } case tok::arrow: case tok::period: { // postfix-expression: p-e '->' template[opt] id-expression // postfix-expression: p-e '.' template[opt] id-expression tok::TokenKind OpKind = Tok.getKind(); SourceLocation OpLoc = ConsumeToken(); // Eat the "." or "->" token. CXXScopeSpec SS; ParsedType ObjectType; bool MayBePseudoDestructor = false; if (getLangOpts().CPlusPlus && !LHS.isInvalid()) { Expr *Base = LHS.get(); const Type* BaseType = Base->getType().getTypePtrOrNull(); if (BaseType && Tok.is(tok::l_paren) && (BaseType->isFunctionType() || BaseType->isSpecificPlaceholderType(BuiltinType::BoundMember))) { Diag(OpLoc, diag::err_function_is_not_record) << OpKind << Base->getSourceRange() << FixItHint::CreateRemoval(OpLoc); return ParsePostfixExpressionSuffix(Base); } LHS = Actions.ActOnStartCXXMemberReference(getCurScope(), Base, OpLoc, OpKind, ObjectType, MayBePseudoDestructor); if (LHS.isInvalid()) break; ParseOptionalCXXScopeSpecifier(SS, ObjectType, /*EnteringContext=*/false, &MayBePseudoDestructor); if (SS.isNotEmpty()) ObjectType = ParsedType(); } // HLSL Change Starts // At this point, if we have an arrow, a diagnostic has been emitted, and // we recover parsing by treating this as a period. if (getLangOpts().HLSL) { OpKind = tok::period; } // HLSL Change Ends if (Tok.is(tok::code_completion)) { // Code completion for a member access expression. Actions.CodeCompleteMemberReferenceExpr(getCurScope(), LHS.get(), OpLoc, OpKind == tok::arrow); cutOffParsing(); return ExprError(); } if (MayBePseudoDestructor && !LHS.isInvalid()) { LHS = ParseCXXPseudoDestructor(LHS.get(), OpLoc, OpKind, SS, ObjectType); break; } // HLSL Change Starts // 'sample' and others are keywords when used as modifiers, but they are // also built-in field of some types. By the time we're considering a // field access, update the token if necessary to reflect this. if (getLangOpts().HLSL) { switch (auto tk = Tok.getKind()) { case tok::kw_center: case tok::kw_globallycoherent: case tok::kw_precise: case tok::kw_sample: case tok::kw_indices: case tok::kw_vertices: case tok::kw_primitives: case tok::kw_payload: Tok.setKind(tok::identifier); Tok.setIdentifierInfo(PP.getIdentifierInfo(getKeywordSpelling(tk))); break; default: break; } } // HLSL Change Ends // Either the action has told us that this cannot be a // pseudo-destructor expression (based on the type of base // expression), or we didn't see a '~' in the right place. We // can still parse a destructor name here, but in that case it // names a real destructor. // Allow explicit constructor calls in Microsoft mode. // FIXME: Add support for explicit call of template constructor. SourceLocation TemplateKWLoc; UnqualifiedId Name; if (getLangOpts().ObjC2 && OpKind == tok::period && Tok.is(tok::kw_class)) { // Objective-C++: // After a '.' in a member access expression, treat the keyword // 'class' as if it were an identifier. // // This hack allows property access to the 'class' method because it is // such a common method name. For other C++ keywords that are // Objective-C method names, one must use the message send syntax. IdentifierInfo *Id = Tok.getIdentifierInfo(); SourceLocation Loc = ConsumeToken(); Name.setIdentifier(Id, Loc); } else if (ParseUnqualifiedId(SS, /*EnteringContext=*/false, /*AllowDestructorName=*/true, /*AllowConstructorName=*/ getLangOpts().MicrosoftExt, ObjectType, TemplateKWLoc, Name)) { (void)Actions.CorrectDelayedTyposInExpr(LHS); LHS = ExprError(); } if (!LHS.isInvalid()) LHS = Actions.ActOnMemberAccessExpr(getCurScope(), LHS.get(), OpLoc, OpKind, SS, TemplateKWLoc, Name, CurParsedObjCImpl ? CurParsedObjCImpl->Dcl : nullptr); break; } case tok::plusplus: // postfix-expression: postfix-expression '++' case tok::minusminus: // postfix-expression: postfix-expression '--' if (!LHS.isInvalid()) { LHS = Actions.ActOnPostfixUnaryOp(getCurScope(), Tok.getLocation(), Tok.getKind(), LHS.get()); } ConsumeToken(); break; } } } /// ParseExprAfterUnaryExprOrTypeTrait - We parsed a typeof/sizeof/alignof/ /// vec_step and we are at the start of an expression or a parenthesized /// type-id. OpTok is the operand token (typeof/sizeof/alignof). Returns the /// expression (isCastExpr == false) or the type (isCastExpr == true). /// /// \verbatim /// unary-expression: [C99 6.5.3] /// 'sizeof' unary-expression /// 'sizeof' '(' type-name ')' /// [GNU] '__alignof' unary-expression /// [GNU] '__alignof' '(' type-name ')' /// [C11] '_Alignof' '(' type-name ')' /// [C++0x] 'alignof' '(' type-id ')' /// /// [GNU] typeof-specifier: /// typeof ( expressions ) /// typeof ( type-name ) /// [GNU/C++] typeof unary-expression /// /// [OpenCL 1.1 6.11.12] vec_step built-in function: /// vec_step ( expressions ) /// vec_step ( type-name ) /// \endverbatim ExprResult Parser::ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange) { // HLSL Change Begin assert((!getLangOpts().HLSL || OpTok.getKind() == tok::kw_sizeof) && "not supported for HLSL - unreachable"); // HLSL Change End assert(OpTok.isOneOf(tok::kw_typeof, tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step, tok::kw___builtin_omp_required_simd_align) && "Not a typeof/sizeof/alignof/vec_step expression!"); ExprResult Operand; // If the operand doesn't start with an '(', it must be an expression. if (Tok.isNot(tok::l_paren)) { // If construct allows a form without parenthesis, user may forget to put // pathenthesis around type name. if (OpTok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof, tok::kw__Alignof)) { if (isTypeIdUnambiguously()) { DeclSpec DS(AttrFactory); ParseSpecifierQualifierList(DS); Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); ParseDeclarator(DeclaratorInfo); SourceLocation LParenLoc = PP.getLocForEndOfToken(OpTok.getLocation()); SourceLocation RParenLoc = PP.getLocForEndOfToken(PrevTokLocation); Diag(LParenLoc, diag::err_expected_parentheses_around_typename) << OpTok.getName() << FixItHint::CreateInsertion(LParenLoc, "(") << FixItHint::CreateInsertion(RParenLoc, ")"); isCastExpr = true; return ExprEmpty(); } } isCastExpr = false; if (OpTok.is(tok::kw_typeof) && !getLangOpts().CPlusPlus) { Diag(Tok, diag::err_expected_after) << OpTok.getIdentifierInfo() << tok::l_paren; return ExprError(); } Operand = ParseCastExpression(true/*isUnaryExpression*/); } else { // If it starts with a '(', we know that it is either a parenthesized // type-name, or it is a unary-expression that starts with a compound // literal, or starts with a primary-expression that is a parenthesized // expression. ParenParseOption ExprType = CastExpr; SourceLocation LParenLoc = Tok.getLocation(), RParenLoc; Operand = ParseParenExpression(ExprType, true/*stopIfCastExpr*/, false, CastTy, RParenLoc); CastRange = SourceRange(LParenLoc, RParenLoc); // If ParseParenExpression parsed a '(typename)' sequence only, then this is // a type. if (ExprType == CastExpr) { isCastExpr = true; return ExprEmpty(); } if (getLangOpts().CPlusPlus || OpTok.isNot(tok::kw_typeof)) { // GNU typeof in C requires the expression to be parenthesized. Not so for // sizeof/alignof or in C++. Therefore, the parenthesized expression is // the start of a unary-expression, but doesn't include any postfix // pieces. Parse these now if present. if (!Operand.isInvalid()) Operand = ParsePostfixExpressionSuffix(Operand.get()); } } // If we get here, the operand to the typeof/sizeof/alignof was an expresion. isCastExpr = false; return Operand; } /// \brief Parse a sizeof or alignof expression. /// /// \verbatim /// unary-expression: [C99 6.5.3] /// 'sizeof' unary-expression /// 'sizeof' '(' type-name ')' /// [C++11] 'sizeof' '...' '(' identifier ')' /// [GNU] '__alignof' unary-expression /// [GNU] '__alignof' '(' type-name ')' /// [C11] '_Alignof' '(' type-name ')' /// [C++11] 'alignof' '(' type-id ')' /// \endverbatim ExprResult Parser::ParseUnaryExprOrTypeTraitExpression() { // HLSL Change Begin assert((!getLangOpts().HLSL || Tok.getKind() == tok::kw_sizeof) && "not supported for HLSL - unreachable"); // HLSL Change End assert(Tok.isOneOf(tok::kw_sizeof, tok::kw___alignof, tok::kw_alignof, tok::kw__Alignof, tok::kw_vec_step, tok::kw___builtin_omp_required_simd_align) && "Not a sizeof/alignof/vec_step expression!"); Token OpTok = Tok; ConsumeToken(); // [C++11] 'sizeof' '...' '(' identifier ')' if (Tok.is(tok::ellipsis) && OpTok.is(tok::kw_sizeof) && !getLangOpts().HLSL) { // HLSL Change SourceLocation EllipsisLoc = ConsumeToken(); SourceLocation LParenLoc, RParenLoc; IdentifierInfo *Name = nullptr; SourceLocation NameLoc; if (Tok.is(tok::l_paren)) { BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); LParenLoc = T.getOpenLocation(); if (Tok.is(tok::identifier)) { Name = Tok.getIdentifierInfo(); NameLoc = ConsumeToken(); T.consumeClose(); RParenLoc = T.getCloseLocation(); if (RParenLoc.isInvalid()) RParenLoc = PP.getLocForEndOfToken(NameLoc); } else { Diag(Tok, diag::err_expected_parameter_pack); SkipUntil(tok::r_paren, StopAtSemi); } } else if (Tok.is(tok::identifier)) { Name = Tok.getIdentifierInfo(); NameLoc = ConsumeToken(); LParenLoc = PP.getLocForEndOfToken(EllipsisLoc); RParenLoc = PP.getLocForEndOfToken(NameLoc); Diag(LParenLoc, diag::err_paren_sizeof_parameter_pack) << Name << FixItHint::CreateInsertion(LParenLoc, "(") << FixItHint::CreateInsertion(RParenLoc, ")"); } else { Diag(Tok, diag::err_sizeof_parameter_pack); } if (!Name) return ExprError(); EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, Sema::ReuseLambdaContextDecl); return Actions.ActOnSizeofParameterPackExpr(getCurScope(), OpTok.getLocation(), *Name, NameLoc, RParenLoc); } if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof)) Diag(OpTok, diag::warn_cxx98_compat_alignof); EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, Sema::ReuseLambdaContextDecl); bool isCastExpr; ParsedType CastTy; SourceRange CastRange; ExprResult Operand = ParseExprAfterUnaryExprOrTypeTrait(OpTok, isCastExpr, CastTy, CastRange); UnaryExprOrTypeTrait ExprKind = UETT_SizeOf; if (OpTok.isOneOf(tok::kw_alignof, tok::kw___alignof, tok::kw__Alignof)) ExprKind = UETT_AlignOf; else if (OpTok.is(tok::kw_vec_step)) ExprKind = UETT_VecStep; else if (OpTok.is(tok::kw___builtin_omp_required_simd_align)) ExprKind = UETT_OpenMPRequiredSimdAlign; if (isCastExpr) return Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), ExprKind, /*isType=*/true, CastTy.getAsOpaquePtr(), CastRange); if (OpTok.isOneOf(tok::kw_alignof, tok::kw__Alignof)) Diag(OpTok, diag::ext_alignof_expr) << OpTok.getIdentifierInfo(); // If we get here, the operand to the sizeof/alignof was an expresion. if (!Operand.isInvalid()) Operand = Actions.ActOnUnaryExprOrTypeTraitExpr(OpTok.getLocation(), ExprKind, /*isType=*/false, Operand.get(), CastRange); return Operand; } /// ParseBuiltinPrimaryExpression /// /// \verbatim /// primary-expression: [C99 6.5.1] /// [GNU] '__builtin_va_arg' '(' assignment-expression ',' type-name ')' /// [GNU] '__builtin_offsetof' '(' type-name ',' offsetof-member-designator')' /// [GNU] '__builtin_choose_expr' '(' assign-expr ',' assign-expr ',' /// assign-expr ')' /// [GNU] '__builtin_types_compatible_p' '(' type-name ',' type-name ')' /// [OCL] '__builtin_astype' '(' assignment-expression ',' type-name ')' /// /// [GNU] offsetof-member-designator: /// [GNU] identifier /// [GNU] offsetof-member-designator '.' identifier /// [GNU] offsetof-member-designator '[' expression ']' /// \endverbatim ExprResult Parser::ParseBuiltinPrimaryExpression() { assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change ExprResult Res; const IdentifierInfo *BuiltinII = Tok.getIdentifierInfo(); tok::TokenKind T = Tok.getKind(); SourceLocation StartLoc = ConsumeToken(); // Eat the builtin identifier. // All of these start with an open paren. if (Tok.isNot(tok::l_paren)) return ExprError(Diag(Tok, diag::err_expected_after) << BuiltinII << tok::l_paren); BalancedDelimiterTracker PT(*this, tok::l_paren); PT.consumeOpen(); // TODO: Build AST. switch (T) { default: llvm_unreachable("Not a builtin primary expression!"); case tok::kw___builtin_va_arg: { ExprResult Expr(ParseAssignmentExpression()); if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::r_paren, StopAtSemi); Expr = ExprError(); } TypeResult Ty = ParseTypeName(); if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected) << tok::r_paren; Expr = ExprError(); } if (Expr.isInvalid() || Ty.isInvalid()) Res = ExprError(); else Res = Actions.ActOnVAArg(StartLoc, Expr.get(), Ty.get(), ConsumeParen()); break; } case tok::kw___builtin_offsetof: { SourceLocation TypeLoc = Tok.getLocation(); TypeResult Ty = ParseTypeName(); if (Ty.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } // We must have at least one identifier here. if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } // Keep track of the various subcomponents we see. SmallVector<Sema::OffsetOfComponent, 4> Comps; Comps.push_back(Sema::OffsetOfComponent()); Comps.back().isBrackets = false; Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); Comps.back().LocStart = Comps.back().LocEnd = ConsumeToken(); // FIXME: This loop leaks the index expressions on error. while (1) { if (Tok.is(tok::period)) { // offsetof-member-designator: offsetof-member-designator '.' identifier Comps.push_back(Sema::OffsetOfComponent()); Comps.back().isBrackets = false; Comps.back().LocStart = ConsumeToken(); if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } Comps.back().U.IdentInfo = Tok.getIdentifierInfo(); Comps.back().LocEnd = ConsumeToken(); } else if (Tok.is(tok::l_square)) { if (CheckProhibitedCXX11Attribute()) return ExprError(); // offsetof-member-designator: offsetof-member-design '[' expression ']' Comps.push_back(Sema::OffsetOfComponent()); Comps.back().isBrackets = true; BalancedDelimiterTracker ST(*this, tok::l_square); ST.consumeOpen(); Comps.back().LocStart = ST.getOpenLocation(); Res = ParseExpression(); if (Res.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return Res; } Comps.back().U.E = Res.get(); ST.consumeClose(); Comps.back().LocEnd = ST.getCloseLocation(); } else { if (Tok.isNot(tok::r_paren)) { PT.consumeClose(); Res = ExprError(); } else if (Ty.isInvalid()) { Res = ExprError(); } else { PT.consumeClose(); Res = Actions.ActOnBuiltinOffsetOf(getCurScope(), StartLoc, TypeLoc, Ty.get(), &Comps[0], Comps.size(), PT.getCloseLocation()); } break; } } break; } case tok::kw___builtin_choose_expr: { ExprResult Cond(ParseAssignmentExpression()); if (Cond.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return Cond; } if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } ExprResult Expr1(ParseAssignmentExpression()); if (Expr1.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return Expr1; } if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } ExprResult Expr2(ParseAssignmentExpression()); if (Expr2.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return Expr2; } if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected) << tok::r_paren; return ExprError(); } Res = Actions.ActOnChooseExpr(StartLoc, Cond.get(), Expr1.get(), Expr2.get(), ConsumeParen()); break; } case tok::kw___builtin_astype: { // The first argument is an expression to be converted, followed by a comma. ExprResult Expr(ParseAssignmentExpression()); if (Expr.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } // Second argument is the type to bitcast to. TypeResult DestTy = ParseTypeName(); if (DestTy.isInvalid()) return ExprError(); // Attempt to consume the r-paren. if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected) << tok::r_paren; SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } Res = Actions.ActOnAsTypeExpr(Expr.get(), DestTy.get(), StartLoc, ConsumeParen()); break; } case tok::kw___builtin_convertvector: { // The first argument is an expression to be converted, followed by a comma. ExprResult Expr(ParseAssignmentExpression()); if (Expr.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } // Second argument is the type to bitcast to. TypeResult DestTy = ParseTypeName(); if (DestTy.isInvalid()) return ExprError(); // Attempt to consume the r-paren. if (Tok.isNot(tok::r_paren)) { Diag(Tok, diag::err_expected) << tok::r_paren; SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } Res = Actions.ActOnConvertVectorExpr(Expr.get(), DestTy.get(), StartLoc, ConsumeParen()); break; } } if (Res.isInvalid()) return ExprError(); // These can be followed by postfix-expr pieces because they are // primary-expressions. return ParsePostfixExpressionSuffix(Res.get()); } /// ParseParenExpression - This parses the unit that starts with a '(' token, /// based on what is allowed by ExprType. The actual thing parsed is returned /// in ExprType. If stopIfCastExpr is true, it will only return the parsed type, /// not the parsed cast-expression. /// /// \verbatim /// primary-expression: [C99 6.5.1] /// '(' expression ')' /// [GNU] '(' compound-statement ')' (if !ParenExprOnly) /// postfix-expression: [C99 6.5.2] /// '(' type-name ')' '{' initializer-list '}' /// '(' type-name ')' '{' initializer-list ',' '}' /// cast-expression: [C99 6.5.4] /// '(' type-name ')' cast-expression /// [ARC] bridged-cast-expression /// [ARC] bridged-cast-expression: /// (__bridge type-name) cast-expression /// (__bridge_transfer type-name) cast-expression /// (__bridge_retained type-name) cast-expression /// fold-expression: [C++1z] /// '(' cast-expression fold-operator '...' ')' /// '(' '...' fold-operator cast-expression ')' /// '(' cast-expression fold-operator '...' /// fold-operator cast-expression ')' /// \endverbatim ExprResult Parser::ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc) { assert(Tok.is(tok::l_paren) && "Not a paren expr!"); ColonProtectionRAIIObject ColonProtection(*this, false); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.consumeOpen()) return ExprError(); SourceLocation OpenLoc = T.getOpenLocation(); ExprResult Result(true); bool isAmbiguousTypeId; CastTy = ParsedType(); if (Tok.is(tok::code_completion)) { Actions.CodeCompleteOrdinaryName(getCurScope(), ExprType >= CompoundLiteral? Sema::PCC_ParenthesizedExpression : Sema::PCC_Expression); cutOffParsing(); return ExprError(); } // Diagnose use of bridge casts in non-arc mode. bool BridgeCast = (getLangOpts().ObjC2 && Tok.isOneOf(tok::kw___bridge, tok::kw___bridge_transfer, tok::kw___bridge_retained, tok::kw___bridge_retain)); if (BridgeCast && !getLangOpts().ObjCAutoRefCount) { if (!TryConsumeToken(tok::kw___bridge)) { StringRef BridgeCastName = Tok.getName(); SourceLocation BridgeKeywordLoc = ConsumeToken(); if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc)) Diag(BridgeKeywordLoc, diag::warn_arc_bridge_cast_nonarc) << BridgeCastName << FixItHint::CreateReplacement(BridgeKeywordLoc, ""); } BridgeCast = false; } // None of these cases should fall through with an invalid Result // unless they've already reported an error. if (ExprType >= CompoundStmt && Tok.is(tok::l_brace)) { Diag(Tok, diag::ext_gnu_statement_expr); if (!getCurScope()->getFnParent() && !getCurScope()->getBlockParent()) { Result = ExprError(Diag(OpenLoc, diag::err_stmtexpr_file_scope)); } else { // Find the nearest non-record decl context. Variables declared in a // statement expression behave as if they were declared in the enclosing // function, block, or other code construct. DeclContext *CodeDC = Actions.CurContext; while (CodeDC->isRecord() || isa<EnumDecl>(CodeDC)) { CodeDC = CodeDC->getParent(); assert(CodeDC && !CodeDC->isFileContext() && "statement expr not in code context"); } Sema::ContextRAII SavedContext(Actions, CodeDC, /*NewThisContext=*/false); Actions.ActOnStartStmtExpr(); StmtResult Stmt(ParseCompoundStatement(true)); ExprType = CompoundStmt; // If the substmt parsed correctly, build the AST node. if (!Stmt.isInvalid()) { Result = Actions.ActOnStmtExpr(OpenLoc, Stmt.get(), Tok.getLocation()); } else { Actions.ActOnStmtExprError(); } } } else if (ExprType >= CompoundLiteral && BridgeCast) { tok::TokenKind tokenKind = Tok.getKind(); SourceLocation BridgeKeywordLoc = ConsumeToken(); // Parse an Objective-C ARC ownership cast expression. ObjCBridgeCastKind Kind; if (tokenKind == tok::kw___bridge) Kind = OBC_Bridge; else if (tokenKind == tok::kw___bridge_transfer) Kind = OBC_BridgeTransfer; else if (tokenKind == tok::kw___bridge_retained) Kind = OBC_BridgeRetained; else { // As a hopefully temporary workaround, allow __bridge_retain as // a synonym for __bridge_retained, but only in system headers. assert(tokenKind == tok::kw___bridge_retain); Kind = OBC_BridgeRetained; if (!PP.getSourceManager().isInSystemHeader(BridgeKeywordLoc)) Diag(BridgeKeywordLoc, diag::err_arc_bridge_retain) << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained"); } TypeResult Ty = ParseTypeName(); T.consumeClose(); ColonProtection.restore(); RParenLoc = T.getCloseLocation(); ExprResult SubExpr = ParseCastExpression(/*isUnaryExpression=*/false); if (Ty.isInvalid() || SubExpr.isInvalid()) return ExprError(); return Actions.ActOnObjCBridgedCast(getCurScope(), OpenLoc, Kind, BridgeKeywordLoc, Ty.get(), RParenLoc, SubExpr.get()); } else if (ExprType >= CompoundLiteral && isTypeIdInParens(isAmbiguousTypeId)) { // Otherwise, this is a compound literal expression or cast expression. // In C++, if the type-id is ambiguous we disambiguate based on context. // If stopIfCastExpr is true the context is a typeof/sizeof/alignof // in which case we should treat it as type-id. // if stopIfCastExpr is false, we need to determine the context past the // parens, so we defer to ParseCXXAmbiguousParenExpression for that. if (isAmbiguousTypeId && !stopIfCastExpr) { ExprResult res = ParseCXXAmbiguousParenExpression(ExprType, CastTy, T, ColonProtection); RParenLoc = T.getCloseLocation(); return res; } // Parse the type declarator. DeclSpec DS(AttrFactory); ParseSpecifierQualifierList(DS); Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); ParseDeclarator(DeclaratorInfo); // If our type is followed by an identifier and either ':' or ']', then // this is probably an Objective-C message send where the leading '[' is // missing. Recover as if that were the case. if (!DeclaratorInfo.isInvalidType() && Tok.is(tok::identifier) && !InMessageExpression && getLangOpts().ObjC1 && (NextToken().is(tok::colon) || NextToken().is(tok::r_square))) { TypeResult Ty; { InMessageExpressionRAIIObject InMessage(*this, false); Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); } Result = ParseObjCMessageExpressionBody(SourceLocation(), SourceLocation(), Ty.get(), nullptr); } else { // Match the ')'. T.consumeClose(); ColonProtection.restore(); RParenLoc = T.getCloseLocation(); if (Tok.is(tok::l_brace)) { // HLSL Change Starts if (getLangOpts().HLSL) { // (type-name) { initializer-list } Diag(Tok, diag::err_hlsl_unsupported_construct) << "compound literal"; return ExprError(); } // HLSL Change Ends ExprType = CompoundLiteral; TypeResult Ty; { InMessageExpressionRAIIObject InMessage(*this, false); Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); } return ParseCompoundLiteralExpression(Ty.get(), OpenLoc, RParenLoc); } if (ExprType == CastExpr) { // We parsed '(' type-name ')' and the thing after it wasn't a '{'. if (DeclaratorInfo.isInvalidType()) return ExprError(); // Note that this doesn't parse the subsequent cast-expression, it just // returns the parsed type to the callee. if (stopIfCastExpr) { TypeResult Ty; { InMessageExpressionRAIIObject InMessage(*this, false); Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); } CastTy = Ty.get(); return ExprResult(); } // Reject the cast of super idiom in ObjC. if (Tok.is(tok::identifier) && getLangOpts().ObjC1 && Tok.getIdentifierInfo() == Ident_super && getCurScope()->isInObjcMethodScope() && GetLookAheadToken(1).isNot(tok::period)) { Diag(Tok.getLocation(), diag::err_illegal_super_cast) << SourceRange(OpenLoc, RParenLoc); return ExprError(); } // Parse the cast-expression that follows it next. // TODO: For cast expression with CastTy. Result = ParseCastExpression(/*isUnaryExpression=*/false, /*isAddressOfOperand=*/false, /*isTypeCast=*/IsTypeCast); if (!Result.isInvalid()) { Result = Actions.ActOnCastExpr(getCurScope(), OpenLoc, DeclaratorInfo, CastTy, RParenLoc, Result.get()); } return Result; } Diag(Tok, diag::err_expected_lbrace_in_compound_literal); return ExprError(); } } else if (Tok.is(tok::ellipsis) && isFoldOperator(NextToken().getKind())) { return ParseFoldExpression(ExprResult(), T); } else if (isTypeCast) { // Parse the expression-list. InMessageExpressionRAIIObject InMessage(*this, false); ExprVector ArgExprs; CommaLocsTy CommaLocs; if (!ParseSimpleExpressionList(ArgExprs, CommaLocs)) { // FIXME: If we ever support comma expressions as operands to // fold-expressions, we'll need to allow multiple ArgExprs here. if (ArgExprs.size() == 1 && isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) return ParseFoldExpression(Result, T); ExprType = SimpleExpr; Result = Actions.ActOnParenListExpr(OpenLoc, Tok.getLocation(), ArgExprs); } } else { InMessageExpressionRAIIObject InMessage(*this, false); Result = ParseExpression(MaybeTypeCast); if (!getLangOpts().CPlusPlus && MaybeTypeCast && Result.isUsable()) { // Correct typos in non-C++ code earlier so that implicit-cast-like // expressions are parsed correctly. Result = Actions.CorrectDelayedTyposInExpr(Result); } ExprType = SimpleExpr; if (isFoldOperator(Tok.getKind()) && NextToken().is(tok::ellipsis)) return ParseFoldExpression(Result, T); // Don't build a paren expression unless we actually match a ')'. if (!Result.isInvalid() && Tok.is(tok::r_paren)) Result = Actions.ActOnParenExpr(OpenLoc, Tok.getLocation(), Result.get()); } // Match the ')'. if (Result.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } T.consumeClose(); RParenLoc = T.getCloseLocation(); return Result; } /// ParseCompoundLiteralExpression - We have parsed the parenthesized type-name /// and we are at the left brace. /// /// \verbatim /// postfix-expression: [C99 6.5.2] /// '(' type-name ')' '{' initializer-list '}' /// '(' type-name ')' '{' initializer-list ',' '}' /// \endverbatim ExprResult Parser::ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc) { assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::l_brace) && "Not a compound literal!"); if (!getLangOpts().C99) // Compound literals don't exist in C90. Diag(LParenLoc, diag::ext_c99_compound_literal); ExprResult Result = ParseInitializer(); if (!Result.isInvalid() && Ty) return Actions.ActOnCompoundLiteral(LParenLoc, Ty, RParenLoc, Result.get()); return Result; } /// ParseStringLiteralExpression - This handles the various token types that /// form string literals, and also handles string concatenation [C99 5.1.1.2, /// translation phase #6]. /// /// \verbatim /// primary-expression: [C99 6.5.1] /// string-literal /// \verbatim ExprResult Parser::ParseStringLiteralExpression(bool AllowUserDefinedLiteral) { assert(isTokenStringLiteral() && "Not a string literal!"); // String concat. Note that keywords like __func__ and __FUNCTION__ are not // considered to be strings for concatenation purposes. SmallVector<Token, 4> StringToks; do { StringToks.push_back(Tok); ConsumeStringToken(); } while (isTokenStringLiteral()); // Pass the set of string tokens, ready for concatenation, to the actions. return Actions.ActOnStringLiteral(StringToks, AllowUserDefinedLiteral ? getCurScope() : nullptr); } /// ParseGenericSelectionExpression - Parse a C11 generic-selection /// [C11 6.5.1.1]. /// /// \verbatim /// generic-selection: /// _Generic ( assignment-expression , generic-assoc-list ) /// generic-assoc-list: /// generic-association /// generic-assoc-list , generic-association /// generic-association: /// type-name : assignment-expression /// default : assignment-expression /// \endverbatim ExprResult Parser::ParseGenericSelectionExpression() { assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::kw__Generic) && "_Generic keyword expected"); SourceLocation KeyLoc = ConsumeToken(); if (!getLangOpts().C11) Diag(KeyLoc, diag::ext_c11_generic_selection); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.expectAndConsume()) return ExprError(); ExprResult ControllingExpr; { // C11 6.5.1.1p3 "The controlling expression of a generic selection is // not evaluated." EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); ControllingExpr = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); if (ControllingExpr.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } } if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } SourceLocation DefaultLoc; TypeVector Types; ExprVector Exprs; do { ParsedType Ty; if (Tok.is(tok::kw_default)) { // C11 6.5.1.1p2 "A generic selection shall have no more than one default // generic association." if (!DefaultLoc.isInvalid()) { Diag(Tok, diag::err_duplicate_default_assoc); Diag(DefaultLoc, diag::note_previous_default_assoc); SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } DefaultLoc = ConsumeToken(); Ty = ParsedType(); } else { ColonProtectionRAIIObject X(*this); TypeResult TR = ParseTypeName(); if (TR.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } Ty = TR.get(); } Types.push_back(Ty); if (ExpectAndConsume(tok::colon)) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } // FIXME: These expressions should be parsed in a potentially potentially // evaluated context. ExprResult ER( Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression())); if (ER.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } Exprs.push_back(ER.get()); } while (TryConsumeToken(tok::comma)); T.consumeClose(); if (T.getCloseLocation().isInvalid()) return ExprError(); return Actions.ActOnGenericSelectionExpr(KeyLoc, DefaultLoc, T.getCloseLocation(), ControllingExpr.get(), Types, Exprs); } /// \brief Parse A C++1z fold-expression after the opening paren and optional /// left-hand-side expression. /// /// \verbatim /// fold-expression: /// ( cast-expression fold-operator ... ) /// ( ... fold-operator cast-expression ) /// ( cast-expression fold-operator ... fold-operator cast-expression ) ExprResult Parser::ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T) { if (LHS.isInvalid()) { T.skipToEnd(); return true; } tok::TokenKind Kind = tok::unknown; SourceLocation FirstOpLoc; if (LHS.isUsable()) { Kind = Tok.getKind(); assert(isFoldOperator(Kind) && "missing fold-operator"); FirstOpLoc = ConsumeToken(); } assert(Tok.is(tok::ellipsis) && "not a fold-expression"); SourceLocation EllipsisLoc = ConsumeToken(); ExprResult RHS; if (Tok.isNot(tok::r_paren)) { if (!isFoldOperator(Tok.getKind())) return Diag(Tok.getLocation(), diag::err_expected_fold_operator); if (Kind != tok::unknown && Tok.getKind() != Kind) Diag(Tok.getLocation(), diag::err_fold_operator_mismatch) << SourceRange(FirstOpLoc); Kind = Tok.getKind(); ConsumeToken(); RHS = ParseExpression(); if (RHS.isInvalid()) { T.skipToEnd(); return true; } } Diag(EllipsisLoc, getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_fold_expression : diag::ext_fold_expression); T.consumeClose(); return Actions.ActOnCXXFoldExpr(T.getOpenLocation(), LHS.get(), Kind, EllipsisLoc, RHS.get(), T.getCloseLocation()); } /// ParseExpressionList - Used for C/C++ (argument-)expression-list. /// /// \verbatim /// argument-expression-list: /// assignment-expression /// argument-expression-list , assignment-expression /// /// [C++] expression-list: /// [C++] assignment-expression /// [C++] expression-list , assignment-expression /// /// [C++0x] expression-list: /// [C++0x] initializer-list /// /// [C++0x] initializer-list /// [C++0x] initializer-clause ...[opt] /// [C++0x] initializer-list , initializer-clause ...[opt] /// /// [C++0x] initializer-clause: /// [C++0x] assignment-expression /// [C++0x] braced-init-list /// \endverbatim bool Parser::ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, std::function<void()> Completer) { bool SawError = false; while (1) { if (Tok.is(tok::code_completion)) { if (Completer) Completer(); else Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Expression); cutOffParsing(); return true; } ExprResult Expr; if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); Expr = ParseBraceInitializer(); } else Expr = ParseAssignmentExpression(); if (Tok.is(tok::ellipsis)) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_variadic_templates); SkipUntil(tok::r_paren, StopBeforeMatch); Actions.CorrectDelayedTyposInExpr(Expr); Expr = ExprError(); SawError = true; break; } // HLSL Change Ends Expr = Actions.ActOnPackExpansion(Expr.get(), ConsumeToken()); } if (Expr.isInvalid()) { SkipUntil(tok::comma, tok::r_paren, StopBeforeMatch); SawError = true; } else { Exprs.push_back(Expr.get()); } if (Tok.isNot(tok::comma)) break; // Move to the next argument, remember where the comma was. CommaLocs.push_back(ConsumeToken()); } if (SawError) { // Ensure typos get diagnosed when errors were encountered while parsing the // expression list. for (auto &E : Exprs) { ExprResult Expr = Actions.CorrectDelayedTyposInExpr(E); if (Expr.isUsable()) E = Expr.get(); } } return SawError; } /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. /// /// \verbatim /// simple-expression-list: /// assignment-expression /// simple-expression-list , assignment-expression /// \endverbatim bool Parser::ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs) { while (1) { ExprResult Expr = ParseAssignmentExpression(); if (Expr.isInvalid()) return true; Exprs.push_back(Expr.get()); if (Tok.isNot(tok::comma)) return false; // Move to the next argument, remember where the comma was. CommaLocs.push_back(ConsumeToken()); } } /// ParseBlockId - Parse a block-id, which roughly looks like int (int x). /// /// \verbatim /// [clang] block-id: /// [clang] specifier-qualifier-list block-declarator /// \endverbatim void Parser::ParseBlockId(SourceLocation CaretLoc) { assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change if (Tok.is(tok::code_completion)) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Type); return cutOffParsing(); } // Parse the specifier-qualifier-list piece. DeclSpec DS(AttrFactory); ParseSpecifierQualifierList(DS); // Parse the block-declarator. Declarator DeclaratorInfo(DS, Declarator::BlockLiteralContext); ParseDeclarator(DeclaratorInfo); MaybeParseGNUAttributes(DeclaratorInfo); // Inform sema that we are starting a block. Actions.ActOnBlockArguments(CaretLoc, DeclaratorInfo, getCurScope()); } /// ParseBlockLiteralExpression - Parse a block literal, which roughly looks /// like ^(int x){ return x+1; } /// /// \verbatim /// block-literal: /// [clang] '^' block-args[opt] compound-statement /// [clang] '^' block-id compound-statement /// [clang] block-args: /// [clang] '(' parameter-list ')' /// \endverbatim ExprResult Parser::ParseBlockLiteralExpression() { assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::caret) && "block literal starts with ^"); SourceLocation CaretLoc = ConsumeToken(); PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), CaretLoc, "block literal parsing"); // Enter a scope to hold everything within the block. This includes the // argument decls, decls within the compound expression, etc. This also // allows determining whether a variable reference inside the block is // within or outside of the block. ParseScope BlockScope(this, Scope::BlockScope | Scope::FnScope | Scope::DeclScope); // Inform sema that we are starting a block. Actions.ActOnBlockStart(CaretLoc, getCurScope()); // Parse the return type if present. DeclSpec DS(AttrFactory); Declarator ParamInfo(DS, Declarator::BlockLiteralContext); // FIXME: Since the return type isn't actually parsed, it can't be used to // fill ParamInfo with an initial valid range, so do it manually. ParamInfo.SetSourceRange(SourceRange(Tok.getLocation(), Tok.getLocation())); // If this block has arguments, parse them. There is no ambiguity here with // the expression case, because the expression case requires a parameter list. if (Tok.is(tok::l_paren)) { ParseParenDeclarator(ParamInfo); // Parse the pieces after the identifier as if we had "int(...)". // SetIdentifier sets the source range end, but in this case we're past // that location. SourceLocation Tmp = ParamInfo.getSourceRange().getEnd(); ParamInfo.SetIdentifier(nullptr, CaretLoc); ParamInfo.SetRangeEnd(Tmp); if (ParamInfo.isInvalidType()) { // If there was an error parsing the arguments, they may have // tried to use ^(x+y) which requires an argument list. Just // skip the whole block literal. Actions.ActOnBlockError(CaretLoc, getCurScope()); return ExprError(); } MaybeParseGNUAttributes(ParamInfo); // Inform sema that we are starting a block. Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope()); } else if (!Tok.is(tok::l_brace)) { ParseBlockId(CaretLoc); } else { // Otherwise, pretend we saw (void). ParsedAttributes attrs(AttrFactory); SourceLocation NoLoc; ParamInfo.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/true, /*IsAmbiguous=*/false, /*RParenLoc=*/NoLoc, /*ArgInfo=*/nullptr, /*NumArgs=*/0, /*EllipsisLoc=*/NoLoc, /*RParenLoc=*/NoLoc, /*TypeQuals=*/0, /*RefQualifierIsLvalueRef=*/true, /*RefQualifierLoc=*/NoLoc, /*ConstQualifierLoc=*/NoLoc, /*VolatileQualifierLoc=*/NoLoc, /*RestrictQualifierLoc=*/NoLoc, /*MutableLoc=*/NoLoc, EST_None, /*ESpecLoc=*/NoLoc, /*Exceptions=*/nullptr, /*ExceptionRanges=*/nullptr, /*NumExceptions=*/0, /*NoexceptExpr=*/nullptr, /*ExceptionSpecTokens=*/nullptr, CaretLoc, CaretLoc, ParamInfo), attrs, CaretLoc); MaybeParseGNUAttributes(ParamInfo); // Inform sema that we are starting a block. Actions.ActOnBlockArguments(CaretLoc, ParamInfo, getCurScope()); } ExprResult Result(true); if (!Tok.is(tok::l_brace)) { // Saw something like: ^expr Diag(Tok, diag::err_expected_expression); Actions.ActOnBlockError(CaretLoc, getCurScope()); return ExprError(); } StmtResult Stmt(ParseCompoundStatementBody()); BlockScope.Exit(); if (!Stmt.isInvalid()) Result = Actions.ActOnBlockStmtExpr(CaretLoc, Stmt.get(), getCurScope()); else Actions.ActOnBlockError(CaretLoc, getCurScope()); return Result; } /// ParseObjCBoolLiteral - This handles the objective-c Boolean literals. /// /// '__objc_yes' /// '__objc_no' ExprResult Parser::ParseObjCBoolLiteral() { assert(!getLangOpts().HLSL && "not supported for HLSL - unreachable"); // HLSL Change tok::TokenKind Kind = Tok.getKind(); return Actions.ActOnObjCBoolLiteral(ConsumeToken(), Kind); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseCXXInlineMethods.cpp
//===--- ParseCXXInlineMethods.cpp - C++ class inline methods parsing------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements parsing for C++ class inline methods. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "RAIIObjectsForParser.h" #include "clang/AST/DeclTemplate.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Scope.h" using namespace clang; /// ParseCXXInlineMethodDef - We parsed and verified that the specified /// Declarator is a well formed C++ inline method definition. Now lex its body /// and store its tokens for parsing after the C++ class is complete. NamedDecl *Parser::ParseCXXInlineMethodDef(AccessSpecifier AS, AttributeList *AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers& VS, SourceLocation PureSpecLoc) { assert(D.isFunctionDeclarator() && "This isn't a function declarator!"); assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try, tok::equal) && "Current token not a '{', ':', '=', or 'try'!"); MultiTemplateParamsArg TemplateParams( TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->data() : nullptr, TemplateInfo.TemplateParams ? TemplateInfo.TemplateParams->size() : 0); NamedDecl *FnD; if (D.getDeclSpec().isFriendSpecified()) FnD = Actions.ActOnFriendFunctionDecl(getCurScope(), D, TemplateParams); else { FnD = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, D, TemplateParams, nullptr, VS, ICIS_NoInit); if (FnD) { Actions.ProcessDeclAttributeList(getCurScope(), FnD, AccessAttrs); if (PureSpecLoc.isValid()) Actions.ActOnPureSpecifier(FnD, PureSpecLoc); } } HandleMemberFunctionDeclDelays(D, FnD); D.complete(FnD); if (TryConsumeToken(tok::equal)) { if (!FnD) { SkipUntil(tok::semi); return nullptr; } // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "function deletion and defaulting"; SkipUntil(tok::semi); return FnD; } // HLSL Change Ends bool Delete = false; SourceLocation KWLoc; SourceLocation KWEndLoc = Tok.getEndLoc().getLocWithOffset(-1); if (TryConsumeToken(tok::kw_delete, KWLoc)) { Diag(KWLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_deleted_function : diag::ext_deleted_function); Actions.SetDeclDeleted(FnD, KWLoc); Delete = true; if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) { DeclAsFunction->setRangeEnd(KWEndLoc); } } else if (TryConsumeToken(tok::kw_default, KWLoc)) { Diag(KWLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_defaulted_function : diag::ext_defaulted_function); Actions.SetDeclDefaulted(FnD, KWLoc); if (auto *DeclAsFunction = dyn_cast<FunctionDecl>(FnD)) { DeclAsFunction->setRangeEnd(KWEndLoc); } } else { llvm_unreachable("function definition after = not 'delete' or 'default'"); } if (Tok.is(tok::comma)) { Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) << Delete; SkipUntil(tok::semi); } else if (ExpectAndConsume(tok::semi, diag::err_expected_after, Delete ? "delete" : "default")) { SkipUntil(tok::semi); } return FnD; } // In delayed template parsing mode, if we are within a class template // or if we are about to parse function member template then consume // the tokens and store them for parsing at the end of the translation unit. if (getLangOpts().DelayedTemplateParsing && D.getFunctionDefinitionKind() == FDK_Definition && !D.getDeclSpec().isConstexprSpecified() && !(FnD && FnD->getAsFunction() && FnD->getAsFunction()->getReturnType()->getContainedAutoType()) && ((Actions.CurContext->isDependentContext() || (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && TemplateInfo.Kind != ParsedTemplateInfo::ExplicitSpecialization)) && !Actions.IsInsideALocalClassWithinATemplateFunction())) { CachedTokens Toks; LexTemplateFunctionForLateParsing(Toks); if (FnD) { FunctionDecl *FD = FnD->getAsFunction(); Actions.CheckForFunctionRedefinition(FD); Actions.MarkAsLateParsedTemplate(FD, FnD, Toks); } return FnD; } // Consume the tokens and store them for later parsing. LexedMethod* LM = new LexedMethod(this, FnD); getCurrentClass().LateParsedDeclarations.push_back(LM); LM->TemplateScope = getCurScope()->isTemplateParamScope(); CachedTokens &Toks = LM->Toks; tok::TokenKind kind = Tok.getKind(); // Consume everything up to (and including) the left brace of the // function body. if (ConsumeAndStoreFunctionPrologue(Toks)) { // We didn't find the left-brace we expected after the // constructor initializer; we already printed an error, and it's likely // impossible to recover, so don't try to parse this method later. // Skip over the rest of the decl and back to somewhere that looks // reasonable. SkipMalformedDecl(); delete getCurrentClass().LateParsedDeclarations.back(); getCurrentClass().LateParsedDeclarations.pop_back(); return FnD; } else { // Consume everything up to (and including) the matching right brace. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); } // If we're in a function-try-block, we need to store all the catch blocks. if (kind == tok::kw_try) { while (Tok.is(tok::kw_catch)) { ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); } } if (FnD) { // If this is a friend function, mark that it's late-parsed so that // it's still known to be a definition even before we attach the // parsed body. Sema needs to treat friend function definitions // differently during template instantiation, and it's possible for // the containing class to be instantiated before all its member // function definitions are parsed. // // If you remove this, you can remove the code that clears the flag // after parsing the member. if (D.getDeclSpec().isFriendSpecified()) { FunctionDecl *FD = FnD->getAsFunction(); Actions.CheckForFunctionRedefinition(FD); FD->setLateTemplateParsed(true); } } else { // If semantic analysis could not build a function declaration, // just throw away the late-parsed declaration. delete getCurrentClass().LateParsedDeclarations.back(); getCurrentClass().LateParsedDeclarations.pop_back(); } return FnD; } /// ParseCXXNonStaticMemberInitializer - We parsed and verified that the /// specified Declarator is a well formed C++ non-static data member /// declaration. Now lex its initializer and store its tokens for parsing /// after the class is complete. void Parser::ParseCXXNonStaticMemberInitializer(Decl *VarD) { assert(Tok.isOneOf(tok::l_brace, tok::equal) && "Current token not a '{' or '='!"); LateParsedMemberInitializer *MI = new LateParsedMemberInitializer(this, VarD); getCurrentClass().LateParsedDeclarations.push_back(MI); CachedTokens &Toks = MI->Toks; tok::TokenKind kind = Tok.getKind(); if (kind == tok::equal) { Toks.push_back(Tok); ConsumeToken(); } if (kind == tok::l_brace) { // Begin by storing the '{' token. Toks.push_back(Tok); ConsumeBrace(); // Consume everything up to (and including) the matching right brace. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/true); } else { // Consume everything up to (but excluding) the comma or semicolon. ConsumeAndStoreInitializer(Toks, CIK_DefaultInitializer); } // Store an artificial EOF token to ensure that we don't run off the end of // the initializer when we come to parse it. Token Eof; Eof.startToken(); Eof.setKind(tok::eof); Eof.setLocation(Tok.getLocation()); Eof.setEofData(VarD); Toks.push_back(Eof); } Parser::LateParsedDeclaration::~LateParsedDeclaration() {} void Parser::LateParsedDeclaration::ParseLexedMethodDeclarations() {} void Parser::LateParsedDeclaration::ParseLexedMemberInitializers() {} void Parser::LateParsedDeclaration::ParseLexedMethodDefs() {} Parser::LateParsedClass::LateParsedClass(Parser *P, ParsingClass *C) : Self(P), Class(C) {} Parser::LateParsedClass::~LateParsedClass() { Self->DeallocateParsedClasses(Class); } void Parser::LateParsedClass::ParseLexedMethodDeclarations() { Self->ParseLexedMethodDeclarations(*Class); } void Parser::LateParsedClass::ParseLexedMemberInitializers() { Self->ParseLexedMemberInitializers(*Class); } void Parser::LateParsedClass::ParseLexedMethodDefs() { Self->ParseLexedMethodDefs(*Class); } void Parser::LateParsedMethodDeclaration::ParseLexedMethodDeclarations() { Self->ParseLexedMethodDeclaration(*this); } void Parser::LexedMethod::ParseLexedMethodDefs() { Self->ParseLexedMethodDef(*this); } void Parser::LateParsedMemberInitializer::ParseLexedMemberInitializers() { Self->ParseLexedMemberInitializer(*this); } /// ParseLexedMethodDeclarations - We finished parsing the member /// specification of a top (non-nested) C++ class. Now go over the /// stack of method declarations with some parts for which parsing was /// delayed (such as default arguments) and parse them. void Parser::ParseLexedMethodDeclarations(ParsingClass &Class) { bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope); TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); if (HasTemplateScope) { Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); ++CurTemplateDepthTracker; } // The current scope is still active if we're the top-level class. // Otherwise we'll need to push and enter a new scope. bool HasClassScope = !Class.TopLevelClass; ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope, HasClassScope); if (HasClassScope) Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) { Class.LateParsedDeclarations[i]->ParseLexedMethodDeclarations(); } if (HasClassScope) Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); } void Parser::ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM) { // If this is a member template, introduce the template parameter scope. ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope); TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); if (LM.TemplateScope) { Actions.ActOnReenterTemplateScope(getCurScope(), LM.Method); ++CurTemplateDepthTracker; } // Start the delayed C++ method declaration Actions.ActOnStartDelayedCXXMethodDeclaration(getCurScope(), LM.Method); // Introduce the parameters into scope and parse their default // arguments. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | Scope::FunctionDeclarationScope | Scope::DeclScope); for (unsigned I = 0, N = LM.DefaultArgs.size(); I != N; ++I) { auto Param = cast<ParmVarDecl>(LM.DefaultArgs[I].Param); // Introduce the parameter into scope. bool HasUnparsed = Param->hasUnparsedDefaultArg(); Actions.ActOnDelayedCXXMethodParameter(getCurScope(), Param); if (CachedTokens *Toks = LM.DefaultArgs[I].Toks) { // Mark the end of the default argument so that we know when to stop when // we parse it later on. Token LastDefaultArgToken = Toks->back(); Token DefArgEnd; DefArgEnd.startToken(); DefArgEnd.setKind(tok::eof); DefArgEnd.setLocation(LastDefaultArgToken.getEndLoc()); DefArgEnd.setEofData(Param); Toks->push_back(DefArgEnd); // Parse the default argument from its saved token stream. Toks->push_back(Tok); // So that the current token doesn't get lost PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false); // Consume the previously-pushed token. ConsumeAnyToken(); // Consume the '='. assert(Tok.is(tok::equal) && "Default argument not starting with '='"); SourceLocation EqualLoc = ConsumeToken(); // The argument isn't actually potentially evaluated unless it is // used. EnterExpressionEvaluationContext Eval(Actions, Sema::PotentiallyEvaluatedIfUsed, Param); ExprResult DefArgResult; if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); DefArgResult = ParseBraceInitializer(); } else DefArgResult = ParseAssignmentExpression(); DefArgResult = Actions.CorrectDelayedTyposInExpr(DefArgResult); if (DefArgResult.isInvalid()) { Actions.ActOnParamDefaultArgumentError(Param, EqualLoc); } else { if (Tok.isNot(tok::eof) || Tok.getEofData() != Param) { // The last two tokens are the terminator and the saved value of // Tok; the last token in the default argument is the one before // those. assert(Toks->size() >= 3 && "expected a token in default arg"); Diag(Tok.getLocation(), diag::err_default_arg_unparsed) << SourceRange(Tok.getLocation(), (*Toks)[Toks->size() - 3].getLocation()); } Actions.ActOnParamDefaultArgument(Param, EqualLoc, DefArgResult.get()); } // There could be leftover tokens (e.g. because of an error). // Skip through until we reach the 'end of default argument' token. while (Tok.isNot(tok::eof)) ConsumeAnyToken(); if (Tok.is(tok::eof) && Tok.getEofData() == Param) ConsumeAnyToken(); delete Toks; LM.DefaultArgs[I].Toks = nullptr; } else if (HasUnparsed) { assert(Param->hasInheritedDefaultArg()); FunctionDecl *Old = cast<FunctionDecl>(LM.Method)->getPreviousDecl(); ParmVarDecl *OldParam = Old->getParamDecl(I); assert (!OldParam->hasUnparsedDefaultArg()); if (OldParam->hasUninstantiatedDefaultArg()) Param->setUninstantiatedDefaultArg( Param->getUninstantiatedDefaultArg()); else Param->setDefaultArg(OldParam->getInit()); } } // Parse a delayed exception-specification, if there is one. if (CachedTokens *Toks = LM.ExceptionSpecTokens) { // Add the 'stop' token. Token LastExceptionSpecToken = Toks->back(); Token ExceptionSpecEnd; ExceptionSpecEnd.startToken(); ExceptionSpecEnd.setKind(tok::eof); ExceptionSpecEnd.setLocation(LastExceptionSpecToken.getEndLoc()); ExceptionSpecEnd.setEofData(LM.Method); Toks->push_back(ExceptionSpecEnd); // Parse the default argument from its saved token stream. Toks->push_back(Tok); // So that the current token doesn't get lost PP.EnterTokenStream(&Toks->front(), Toks->size(), true, false); // Consume the previously-pushed token. ConsumeAnyToken(); // C++11 [expr.prim.general]p3: // If a declaration declares a member function or member function // template of a class X, the expression this is a prvalue of type // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq // and the end of the function-definition, member-declarator, or // declarator. CXXMethodDecl *Method; if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(LM.Method)) Method = cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); else Method = cast<CXXMethodDecl>(LM.Method); Sema::CXXThisScopeRAII ThisScope(Actions, Method->getParent(), Method->getTypeQualifiers(), getLangOpts().CPlusPlus11); // Parse the exception-specification. SourceRange SpecificationRange; SmallVector<ParsedType, 4> DynamicExceptions; SmallVector<SourceRange, 4> DynamicExceptionRanges; ExprResult NoexceptExpr; CachedTokens *ExceptionSpecTokens; ExceptionSpecificationType EST = tryParseExceptionSpecification(/*Delayed=*/false, SpecificationRange, DynamicExceptions, DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens); if (Tok.isNot(tok::eof) || Tok.getEofData() != LM.Method) Diag(Tok.getLocation(), diag::err_except_spec_unparsed); // Attach the exception-specification to the method. Actions.actOnDelayedExceptionSpecification(LM.Method, EST, SpecificationRange, DynamicExceptions, DynamicExceptionRanges, NoexceptExpr.isUsable()? NoexceptExpr.get() : nullptr); // There could be leftover tokens (e.g. because of an error). // Skip through until we reach the original token position. while (Tok.isNot(tok::eof)) ConsumeAnyToken(); // Clean up the remaining EOF token. if (Tok.is(tok::eof) && Tok.getEofData() == LM.Method) ConsumeAnyToken(); delete Toks; LM.ExceptionSpecTokens = nullptr; } PrototypeScope.Exit(); // Finish the delayed C++ method declaration. Actions.ActOnFinishDelayedCXXMethodDeclaration(getCurScope(), LM.Method); } /// ParseLexedMethodDefs - We finished parsing the member specification of a top /// (non-nested) C++ class. Now go over the stack of lexed methods that were /// collected during its parsing and parse them all. void Parser::ParseLexedMethodDefs(ParsingClass &Class) { bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope); TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); if (HasTemplateScope) { Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); ++CurTemplateDepthTracker; } bool HasClassScope = !Class.TopLevelClass; ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope, HasClassScope); for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) { Class.LateParsedDeclarations[i]->ParseLexedMethodDefs(); } } void Parser::ParseLexedMethodDef(LexedMethod &LM) { // If this is a member template, introduce the template parameter scope. ParseScope TemplateScope(this, Scope::TemplateParamScope, LM.TemplateScope); TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); if (LM.TemplateScope) { Actions.ActOnReenterTemplateScope(getCurScope(), LM.D); ++CurTemplateDepthTracker; } assert(!LM.Toks.empty() && "Empty body!"); Token LastBodyToken = LM.Toks.back(); Token BodyEnd; BodyEnd.startToken(); BodyEnd.setKind(tok::eof); BodyEnd.setLocation(LastBodyToken.getEndLoc()); BodyEnd.setEofData(LM.D); LM.Toks.push_back(BodyEnd); // Append the current token at the end of the new token stream so that it // doesn't get lost. LM.Toks.push_back(Tok); PP.EnterTokenStream(LM.Toks.data(), LM.Toks.size(), true, false); // Consume the previously pushed token. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) && "Inline method not starting with '{', ':' or 'try'"); // Parse the method body. Function body parsing code is similar enough // to be re-used for method bodies as well. ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope); Actions.ActOnStartOfFunctionDef(getCurScope(), LM.D); if (Tok.is(tok::kw_try)) { // HLSL Change Starts - remove support for function try if (getLangOpts().HLSL) { Diag(Tok, diag::err_expected_fn_body); FnScope.Exit(); Actions.ActOnFinishFunctionBody(LM.D, nullptr); while (Tok.isNot(tok::eof)) ConsumeAnyToken(); if (Tok.is(tok::eof) && Tok.getEofData() == LM.D) ConsumeAnyToken(); return; } // HLSL Change Ends ParseFunctionTryBlock(LM.D, FnScope); while (Tok.isNot(tok::eof)) ConsumeAnyToken(); if (Tok.is(tok::eof) && Tok.getEofData() == LM.D) ConsumeAnyToken(); return; } if (Tok.is(tok::colon)) { ParseConstructorInitializer(LM.D); // Error recovery. if (!Tok.is(tok::l_brace) || getLangOpts().HLSL) { // HLSL Change FnScope.Exit(); Actions.ActOnFinishFunctionBody(LM.D, nullptr); while (Tok.isNot(tok::eof)) ConsumeAnyToken(); if (Tok.is(tok::eof) && Tok.getEofData() == LM.D) ConsumeAnyToken(); return; } } else Actions.ActOnDefaultCtorInitializers(LM.D); assert((Actions.getDiagnostics().hasErrorOccurred() || !isa<FunctionTemplateDecl>(LM.D) || cast<FunctionTemplateDecl>(LM.D)->getTemplateParameters()->getDepth() < TemplateParameterDepth) && "TemplateParameterDepth should be greater than the depth of " "current template being instantiated!"); ParseFunctionStatementBody(LM.D, FnScope); // Clear the late-template-parsed bit if we set it before. if (LM.D) LM.D->getAsFunction()->setLateTemplateParsed(false); while (Tok.isNot(tok::eof)) ConsumeAnyToken(); if (Tok.is(tok::eof) && Tok.getEofData() == LM.D) ConsumeAnyToken(); if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(LM.D)) Actions.ActOnFinishInlineMethodDef(MD); } /// ParseLexedMemberInitializers - We finished parsing the member specification /// of a top (non-nested) C++ class. Now go over the stack of lexed data member /// initializers that were collected during its parsing and parse them all. void Parser::ParseLexedMemberInitializers(ParsingClass &Class) { bool HasTemplateScope = !Class.TopLevelClass && Class.TemplateScope; ParseScope ClassTemplateScope(this, Scope::TemplateParamScope, HasTemplateScope); TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); if (HasTemplateScope) { Actions.ActOnReenterTemplateScope(getCurScope(), Class.TagOrTemplate); ++CurTemplateDepthTracker; } // Set or update the scope flags. bool AlreadyHasClassScope = Class.TopLevelClass; unsigned ScopeFlags = Scope::ClassScope|Scope::DeclScope; ParseScope ClassScope(this, ScopeFlags, !AlreadyHasClassScope); ParseScopeFlags ClassScopeFlags(this, ScopeFlags, AlreadyHasClassScope); if (!AlreadyHasClassScope) Actions.ActOnStartDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); if (!Class.LateParsedDeclarations.empty()) { // C++11 [expr.prim.general]p4: // Otherwise, if a member-declarator declares a non-static data member // (9.2) of a class X, the expression this is a prvalue of type "pointer // to X" within the optional brace-or-equal-initializer. It shall not // appear elsewhere in the member-declarator. Sema::CXXThisScopeRAII ThisScope(Actions, Class.TagOrTemplate, /*TypeQuals=*/(unsigned)0); for (size_t i = 0; i < Class.LateParsedDeclarations.size(); ++i) { Class.LateParsedDeclarations[i]->ParseLexedMemberInitializers(); } } if (!AlreadyHasClassScope) Actions.ActOnFinishDelayedMemberDeclarations(getCurScope(), Class.TagOrTemplate); Actions.ActOnFinishDelayedMemberInitializers(Class.TagOrTemplate); } void Parser::ParseLexedMemberInitializer(LateParsedMemberInitializer &MI) { if (!MI.Field || MI.Field->isInvalidDecl()) return; // Append the current token at the end of the new token stream so that it // doesn't get lost. MI.Toks.push_back(Tok); PP.EnterTokenStream(MI.Toks.data(), MI.Toks.size(), true, false); // Consume the previously pushed token. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); SourceLocation EqualLoc; Actions.ActOnStartCXXInClassMemberInitializer(); ExprResult Init = ParseCXXMemberInitializer(MI.Field, /*IsFunction=*/false, EqualLoc); Actions.ActOnFinishCXXInClassMemberInitializer(MI.Field, EqualLoc, Init.get()); // The next token should be our artificial terminating EOF token. if (Tok.isNot(tok::eof)) { if (!Init.isInvalid()) { SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation); if (!EndLoc.isValid()) EndLoc = Tok.getLocation(); // No fixit; we can't recover as if there were a semicolon here. Diag(EndLoc, diag::err_expected_semi_decl_list); } // Consume tokens until we hit the artificial EOF. while (Tok.isNot(tok::eof)) ConsumeAnyToken(); } // Make sure this is *our* artificial EOF token. if (Tok.getEofData() == MI.Field) ConsumeAnyToken(); } /// ConsumeAndStoreUntil - Consume and store the token at the passed token /// container until the token 'T' is reached (which gets /// consumed/stored too, if ConsumeFinalToken). /// If StopAtSemi is true, then we will stop early at a ';' character. /// Returns true if token 'T1' or 'T2' was found. /// NOTE: This is a specialized version of Parser::SkipUntil. bool Parser::ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi, bool ConsumeFinalToken) { // We always want this function to consume at least one token if the first // token isn't T and if not at EOF. bool isFirstTokenConsumed = true; while (1) { // If we found one of the tokens, stop and return true. if (Tok.is(T1) || Tok.is(T2)) { if (ConsumeFinalToken) { Toks.push_back(Tok); ConsumeAnyToken(); } return true; } switch (Tok.getKind()) { case tok::eof: case tok::annot_module_begin: case tok::annot_module_end: case tok::annot_module_include: // Ran out of tokens. return false; case tok::l_paren: // Recursively consume properly-nested parens. Toks.push_back(Tok); ConsumeParen(); ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); break; case tok::l_square: // Recursively consume properly-nested square brackets. Toks.push_back(Tok); ConsumeBracket(); ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false); break; case tok::l_brace: // Recursively consume properly-nested braces. Toks.push_back(Tok); ConsumeBrace(); ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); break; // Okay, we found a ']' or '}' or ')', which we think should be balanced. // Since the user wasn't looking for this token (if they were, it would // already be handled), this isn't balanced. If there is a LHS token at a // higher level, we will assume that this matches the unbalanced token // and return it. Otherwise, this is a spurious RHS token, which we skip. case tok::r_paren: if (ParenCount && !isFirstTokenConsumed) return false; // Matches something. Toks.push_back(Tok); ConsumeParen(); break; case tok::r_square: if (BracketCount && !isFirstTokenConsumed) return false; // Matches something. Toks.push_back(Tok); ConsumeBracket(); break; case tok::r_brace: if (BraceCount && !isFirstTokenConsumed) return false; // Matches something. Toks.push_back(Tok); ConsumeBrace(); break; case tok::code_completion: Toks.push_back(Tok); ConsumeCodeCompletionToken(); break; case tok::string_literal: case tok::wide_string_literal: case tok::utf8_string_literal: case tok::utf16_string_literal: case tok::utf32_string_literal: Toks.push_back(Tok); ConsumeStringToken(); break; case tok::semi: if (StopAtSemi) return false; LLVM_FALLTHROUGH; // HLSL CHANGE. default: // consume this token. Toks.push_back(Tok); ConsumeToken(); break; } isFirstTokenConsumed = false; } } /// \brief Consume tokens and store them in the passed token container until /// we've passed the try keyword and constructor initializers and have consumed /// the opening brace of the function body. The opening brace will be consumed /// if and only if there was no error. /// /// \return True on error. bool Parser::ConsumeAndStoreFunctionPrologue(CachedTokens &Toks) { if (Tok.is(tok::kw_try)) { Toks.push_back(Tok); ConsumeToken(); } if (Tok.isNot(tok::colon)) { // Easy case, just a function body. // Grab any remaining garbage to be diagnosed later. We stop when we reach a // brace: an opening one is the function body, while a closing one probably // means we've reached the end of the class. ConsumeAndStoreUntil(tok::l_brace, tok::r_brace, Toks, /*StopAtSemi=*/true, /*ConsumeFinalToken=*/false); if (Tok.isNot(tok::l_brace)) return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace; Toks.push_back(Tok); ConsumeBrace(); return false; } Toks.push_back(Tok); ConsumeToken(); // We can't reliably skip over a mem-initializer-id, because it could be // a template-id involving not-yet-declared names. Given: // // S ( ) : a < b < c > ( e ) // // 'e' might be an initializer or part of a template argument, depending // on whether 'b' is a template. // Track whether we might be inside a template argument. We can give // significantly better diagnostics if we know that we're not. bool MightBeTemplateArgument = false; while (true) { // Skip over the mem-initializer-id, if possible. if (Tok.is(tok::kw_decltype)) { Toks.push_back(Tok); SourceLocation OpenLoc = ConsumeToken(); if (Tok.isNot(tok::l_paren)) return Diag(Tok.getLocation(), diag::err_expected_lparen_after) << "decltype"; Toks.push_back(Tok); ConsumeParen(); if (!ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/true)) { Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren; Diag(OpenLoc, diag::note_matching) << tok::l_paren; return true; } } do { // Walk over a component of a nested-name-specifier. if (Tok.is(tok::coloncolon)) { Toks.push_back(Tok); ConsumeToken(); if (Tok.is(tok::kw_template)) { Toks.push_back(Tok); ConsumeToken(); } } if (Tok.isOneOf(tok::identifier, tok::kw_template)) { Toks.push_back(Tok); ConsumeToken(); } else if (Tok.is(tok::code_completion)) { Toks.push_back(Tok); ConsumeCodeCompletionToken(); // Consume the rest of the initializers permissively. // FIXME: We should be able to perform code-completion here even if // there isn't a subsequent '{' token. MightBeTemplateArgument = true; break; } else { break; } } while (Tok.is(tok::coloncolon)); if (Tok.is(tok::less)) MightBeTemplateArgument = true; if (MightBeTemplateArgument) { // We may be inside a template argument list. Grab up to the start of the // next parenthesized initializer or braced-init-list. This *might* be the // initializer, or it might be a subexpression in the template argument // list. // FIXME: Count angle brackets, and clear MightBeTemplateArgument // if all angles are closed. if (!ConsumeAndStoreUntil(tok::l_paren, tok::l_brace, Toks, /*StopAtSemi=*/true, /*ConsumeFinalToken=*/false)) { // We're not just missing the initializer, we're also missing the // function body! return Diag(Tok.getLocation(), diag::err_expected) << tok::l_brace; } } else if (Tok.isNot(tok::l_paren) && Tok.isNot(tok::l_brace)) { // We found something weird in a mem-initializer-id. if (getLangOpts().CPlusPlus11) return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_paren << tok::l_brace; else return Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren; } tok::TokenKind kind = Tok.getKind(); Toks.push_back(Tok); bool IsLParen = (kind == tok::l_paren); SourceLocation OpenLoc = Tok.getLocation(); if (IsLParen) { ConsumeParen(); } else { assert(kind == tok::l_brace && "Must be left paren or brace here."); ConsumeBrace(); // In C++03, this has to be the start of the function body, which // means the initializer is malformed; we'll diagnose it later. if (!getLangOpts().CPlusPlus11) return false; } // Grab the initializer (or the subexpression of the template argument). // FIXME: If we support lambdas here, we'll need to set StopAtSemi to false // if we might be inside the braces of a lambda-expression. tok::TokenKind CloseKind = IsLParen ? tok::r_paren : tok::r_brace; if (!ConsumeAndStoreUntil(CloseKind, Toks, /*StopAtSemi=*/true)) { Diag(Tok, diag::err_expected) << CloseKind; Diag(OpenLoc, diag::note_matching) << kind; return true; } // Grab pack ellipsis, if present. if (Tok.is(tok::ellipsis)) { Toks.push_back(Tok); ConsumeToken(); } // If we know we just consumed a mem-initializer, we must have ',' or '{' // next. if (Tok.is(tok::comma)) { Toks.push_back(Tok); ConsumeToken(); } else if (Tok.is(tok::l_brace)) { // This is the function body if the ')' or '}' is immediately followed by // a '{'. That cannot happen within a template argument, apart from the // case where a template argument contains a compound literal: // // S ( ) : a < b < c > ( d ) { } // // End of declaration, or still inside the template argument? // // ... and the case where the template argument contains a lambda: // // S ( ) : a < 0 && b < c > ( d ) + [ ] ( ) { return 0; } // ( ) > ( ) { } // // FIXME: Disambiguate these cases. Note that the latter case is probably // going to be made ill-formed by core issue 1607. Toks.push_back(Tok); ConsumeBrace(); return false; } else if (!MightBeTemplateArgument) { return Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace << tok::comma; } } } /// \brief Consume and store tokens from the '?' to the ':' in a conditional /// expression. bool Parser::ConsumeAndStoreConditional(CachedTokens &Toks) { // Consume '?'. assert(Tok.is(tok::question)); Toks.push_back(Tok); ConsumeToken(); while (Tok.isNot(tok::colon)) { if (!ConsumeAndStoreUntil(tok::question, tok::colon, Toks, /*StopAtSemi=*/true, /*ConsumeFinalToken=*/false)) return false; // If we found a nested conditional, consume it. if (Tok.is(tok::question) && !ConsumeAndStoreConditional(Toks)) return false; } // Consume ':'. Toks.push_back(Tok); ConsumeToken(); return true; } /// \brief A tentative parsing action that can also revert token annotations. class Parser::UnannotatedTentativeParsingAction : public TentativeParsingAction { public: explicit UnannotatedTentativeParsingAction(Parser &Self, tok::TokenKind EndKind) : TentativeParsingAction(Self), Self(Self), EndKind(EndKind) { // Stash away the old token stream, so we can restore it once the // tentative parse is complete. TentativeParsingAction Inner(Self); Self.ConsumeAndStoreUntil(EndKind, Toks, true, /*ConsumeFinalToken*/false); Inner.Revert(); } void RevertAnnotations() { Revert(); // Put back the original tokens. Self.SkipUntil(EndKind, StopAtSemi | StopBeforeMatch); if (Toks.size()) { Token *Buffer = new Token[Toks.size()]; std::copy(Toks.begin() + 1, Toks.end(), Buffer); Buffer[Toks.size() - 1] = Self.Tok; Self.PP.EnterTokenStream(Buffer, Toks.size(), true, /*Owned*/true); Self.Tok = Toks.front(); } } private: Parser &Self; CachedTokens Toks; tok::TokenKind EndKind; }; /// ConsumeAndStoreInitializer - Consume and store the token at the passed token /// container until the end of the current initializer expression (either a /// default argument or an in-class initializer for a non-static data member). /// /// Returns \c true if we reached the end of something initializer-shaped, /// \c false if we bailed out. bool Parser::ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK) { // We always want this function to consume at least one token if not at EOF. bool IsFirstToken = true; // Number of possible unclosed <s we've seen so far. These might be templates, // and might not, but if there were none of them (or we know for sure that // we're within a template), we can avoid a tentative parse. unsigned AngleCount = 0; unsigned KnownTemplateCount = 0; while (1) { switch (Tok.getKind()) { case tok::comma: // If we might be in a template, perform a tentative parse to check. if (!AngleCount) // Not a template argument: this is the end of the initializer. return true; if (KnownTemplateCount) goto consume_token; // We hit a comma inside angle brackets. This is the hard case. The // rule we follow is: // * For a default argument, if the tokens after the comma form a // syntactically-valid parameter-declaration-clause, in which each // parameter has an initializer, then this comma ends the default // argument. // * For a default initializer, if the tokens after the comma form a // syntactically-valid init-declarator-list, then this comma ends // the default initializer. { UnannotatedTentativeParsingAction PA(*this, CIK == CIK_DefaultInitializer ? tok::semi : tok::r_paren); Sema::TentativeAnalysisScope Scope(Actions); TPResult Result = TPResult::Error; ConsumeToken(); switch (CIK) { case CIK_DefaultInitializer: Result = TryParseInitDeclaratorList(); // If we parsed a complete, ambiguous init-declarator-list, this // is only syntactically-valid if it's followed by a semicolon. if (Result == TPResult::Ambiguous && Tok.isNot(tok::semi)) Result = TPResult::False; break; case CIK_DefaultArgument: bool InvalidAsDeclaration = false; Result = TryParseParameterDeclarationClause( &InvalidAsDeclaration, /*VersusTemplateArgument=*/true); // If this is an expression or a declaration with a missing // 'typename', assume it's not a declaration. if (Result == TPResult::Ambiguous && InvalidAsDeclaration) Result = TPResult::False; break; } // If what follows could be a declaration, it is a declaration. if (Result != TPResult::False && Result != TPResult::Error) { PA.Revert(); return true; } // In the uncommon case that we decide the following tokens are part // of a template argument, revert any annotations we've performed in // those tokens. We're not going to look them up until we've parsed // the rest of the class, and that might add more declarations. PA.RevertAnnotations(); } // Keep going. We know we're inside a template argument list now. ++KnownTemplateCount; goto consume_token; case tok::eof: case tok::annot_module_begin: case tok::annot_module_end: case tok::annot_module_include: // Ran out of tokens. return false; case tok::less: // FIXME: A '<' can only start a template-id if it's preceded by an // identifier, an operator-function-id, or a literal-operator-id. ++AngleCount; goto consume_token; case tok::question: // In 'a ? b : c', 'b' can contain an unparenthesized comma. If it does, // that is *never* the end of the initializer. Skip to the ':'. if (!ConsumeAndStoreConditional(Toks)) return false; break; case tok::greatergreatergreater: // HLSL Change - refactor to satisfy GCC and clang fallthrough detects if (getLangOpts().CPlusPlus11) { if (AngleCount) AngleCount -= 3; if (KnownTemplateCount){ KnownTemplateCount -= 3;} } goto consume_token; case tok::greatergreater: if (getLangOpts().CPlusPlus11) { if (AngleCount) AngleCount-= 2; if (KnownTemplateCount){ KnownTemplateCount -= 2;} } goto consume_token; // End HLSL Change case tok::greater: if (AngleCount) --AngleCount; if (KnownTemplateCount) --KnownTemplateCount; goto consume_token; case tok::kw_template: // 'template' identifier '<' is known to start a template argument list, // and can be used to disambiguate the parse. // FIXME: Support all forms of 'template' unqualified-id '<'. Toks.push_back(Tok); ConsumeToken(); if (Tok.is(tok::identifier)) { Toks.push_back(Tok); ConsumeToken(); if (Tok.is(tok::less)) { ++AngleCount; ++KnownTemplateCount; Toks.push_back(Tok); ConsumeToken(); } } break; case tok::kw_operator: // If 'operator' precedes other punctuation, that punctuation loses // its special behavior. Toks.push_back(Tok); ConsumeToken(); switch (Tok.getKind()) { case tok::comma: case tok::greatergreatergreater: case tok::greatergreater: case tok::greater: case tok::less: Toks.push_back(Tok); ConsumeToken(); break; default: break; } break; case tok::l_paren: // Recursively consume properly-nested parens. Toks.push_back(Tok); ConsumeParen(); ConsumeAndStoreUntil(tok::r_paren, Toks, /*StopAtSemi=*/false); break; case tok::l_square: // Recursively consume properly-nested square brackets. Toks.push_back(Tok); ConsumeBracket(); ConsumeAndStoreUntil(tok::r_square, Toks, /*StopAtSemi=*/false); break; case tok::l_brace: // Recursively consume properly-nested braces. Toks.push_back(Tok); ConsumeBrace(); ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); break; // Okay, we found a ']' or '}' or ')', which we think should be balanced. // Since the user wasn't looking for this token (if they were, it would // already be handled), this isn't balanced. If there is a LHS token at a // higher level, we will assume that this matches the unbalanced token // and return it. Otherwise, this is a spurious RHS token, which we // consume and pass on to downstream code to diagnose. case tok::r_paren: if (CIK == CIK_DefaultArgument) return true; // End of the default argument. if (ParenCount && !IsFirstToken) return false; Toks.push_back(Tok); ConsumeParen(); continue; case tok::r_square: if (BracketCount && !IsFirstToken) return false; Toks.push_back(Tok); ConsumeBracket(); continue; case tok::r_brace: if (BraceCount && !IsFirstToken) return false; Toks.push_back(Tok); ConsumeBrace(); continue; case tok::code_completion: Toks.push_back(Tok); ConsumeCodeCompletionToken(); break; case tok::string_literal: case tok::wide_string_literal: case tok::utf8_string_literal: case tok::utf16_string_literal: case tok::utf32_string_literal: Toks.push_back(Tok); ConsumeStringToken(); break; case tok::semi: if (CIK == CIK_DefaultInitializer) return true; // End of the default initializer. LLVM_FALLTHROUGH; // HLSL CHANGE. default: consume_token: Toks.push_back(Tok); ConsumeToken(); break; } IsFirstToken = false; } }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/HLSLRootSignature.h
//===--- HLSLRootSignature.h ---- HLSL root signature parsing -------------===// /////////////////////////////////////////////////////////////////////////////// // // // HLSLRootSignature.h // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // /////////////////////////////////////////////////////////////////////////////// #pragma once #include "dxc/DXIL/DXIL.h" #include "dxc/DxilRootSignature/DxilRootSignature.h" #include "dxc/Support/WinIncludes.h" namespace llvm { class raw_ostream; } namespace hlsl { class RootSignatureTokenizer { public: class Token { public: enum Type { Unknown, EOL, Comma, LParen, RParen, OR, EQ, NumberI32, NumberU32, NumberFloat, TReg, SReg, UReg, BReg, numDescriptors, unbounded, space, offset, // OffsetInDescriptorsFromTableStart DESCRIPTOR_RANGE_OFFSET_APPEND, RootConstants, num32BitConstants, Sampler, StaticSampler, CBV, SRV, UAV, DescriptorTable, flags, DESCRIPTORS_VOLATILE, DATA_VOLATILE, DATA_STATIC, DATA_STATIC_WHILE_SET_AT_EXECUTE, DESCRIPTORS_STATIC_KEEPING_BUFFER_BOUNDS_CHECKS, // Visibility visibility, SHADER_VISIBILITY_ALL, SHADER_VISIBILITY_VERTEX, SHADER_VISIBILITY_HULL, SHADER_VISIBILITY_DOMAIN, SHADER_VISIBILITY_GEOMETRY, SHADER_VISIBILITY_PIXEL, SHADER_VISIBILITY_AMPLIFICATION, SHADER_VISIBILITY_MESH, // Root signature flags RootFlags, ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, DENY_VERTEX_SHADER_ROOT_ACCESS, DENY_HULL_SHADER_ROOT_ACCESS, DENY_DOMAIN_SHADER_ROOT_ACCESS, DENY_GEOMETRY_SHADER_ROOT_ACCESS, DENY_PIXEL_SHADER_ROOT_ACCESS, DENY_AMPLIFICATION_SHADER_ROOT_ACCESS, DENY_MESH_SHADER_ROOT_ACCESS, ALLOW_STREAM_OUTPUT, LOCAL_ROOT_SIGNATURE, CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED, SAMPLER_HEAP_DIRECTLY_INDEXED, // Filter filter, FILTER_MIN_MAG_MIP_POINT, FILTER_MIN_MAG_POINT_MIP_LINEAR, FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT, FILTER_MIN_POINT_MAG_MIP_LINEAR, FILTER_MIN_LINEAR_MAG_MIP_POINT, FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR, FILTER_MIN_MAG_LINEAR_MIP_POINT, FILTER_MIN_MAG_MIP_LINEAR, FILTER_ANISOTROPIC, FILTER_COMPARISON_MIN_MAG_MIP_POINT, FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR, FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT, FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR, FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT, FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR, FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT, FILTER_COMPARISON_MIN_MAG_MIP_LINEAR, FILTER_COMPARISON_ANISOTROPIC, FILTER_MINIMUM_MIN_MAG_MIP_POINT, FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR, FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT, FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR, FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT, FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR, FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT, FILTER_MINIMUM_MIN_MAG_MIP_LINEAR, FILTER_MINIMUM_ANISOTROPIC, FILTER_MAXIMUM_MIN_MAG_MIP_POINT, FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR, FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT, FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR, FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT, FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR, FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT, FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR, FILTER_MAXIMUM_ANISOTROPIC, // Texture address mode addressU, addressV, addressW, TEXTURE_ADDRESS_WRAP, TEXTURE_ADDRESS_MIRROR, TEXTURE_ADDRESS_CLAMP, TEXTURE_ADDRESS_BORDER, TEXTURE_ADDRESS_MIRROR_ONCE, mipLODBias, maxAnisotropy, // Comparison function comparisonFunc, COMPARISON_NEVER, COMPARISON_LESS, COMPARISON_EQUAL, COMPARISON_LESS_EQUAL, COMPARISON_GREATER, COMPARISON_NOT_EQUAL, COMPARISON_GREATER_EQUAL, COMPARISON_ALWAYS, // Static border color borderColor, STATIC_BORDER_COLOR_TRANSPARENT_BLACK, STATIC_BORDER_COLOR_OPAQUE_BLACK, STATIC_BORDER_COLOR_OPAQUE_WHITE, STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT, STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT, minLOD, maxLOD, }; private: Type m_Type; const char *m_pStr; union { int m_I32Value; uint32_t m_U32Value; float m_FloatValue; }; public: Token() : m_Type(Unknown), m_pStr(NULL), m_I32Value(0) {} Token(enum Type t, const char *pStr, uint32_t n = 0) : m_Type(t), m_pStr(pStr), m_U32Value(n) {} Token(enum Type t, const char *pStr, float f) : m_Type(t), m_pStr(pStr), m_FloatValue(f) {} Token(const Token &o) : m_Type(o.m_Type), m_pStr(o.m_pStr), m_U32Value(o.m_U32Value) {} Token &operator=(const Token &o) { if (this != &o) { m_Type = o.m_Type; m_pStr = o.m_pStr; m_U32Value = o.m_U32Value; } return *this; } enum Type GetType() const { return m_Type; } const char *GetStr() const { return m_pStr; } uint32_t GetU32Value() const { return m_U32Value; } int GetI32Value() const { return m_I32Value; } float GetFloatValue() const { return m_FloatValue; } bool IsEOL() const { return m_Type == Type::EOL; } }; public: RootSignatureTokenizer(const char *pStr); RootSignatureTokenizer(const char *pStr, size_t len); Token GetToken(); Token PeekToken(); private: const char *m_pStrPos; const char *m_pEndPos; const static uint32_t kMaxTokenLength = 127; const static uint32_t kNumBuffers = 2; Token m_Tokens[kNumBuffers]; char m_TokenStrings[kNumBuffers][kMaxTokenLength + 1]; uint32_t m_TokenBufferIdx; void ReadNextToken(uint32_t BufferIdx); bool IsDone() const; void EatSpace(); bool ToI32(const char *pBuf, int &n); bool ToU32(const char *pBuf, uint32_t &n); bool ToFloat(const char *pBuf, float &n); bool ToRegister(const char *pBuf, Token &T); bool ToKeyword(const char *pBuf, Token &T, const char *pKeyWord, Token::Type Type); bool IsSeparator(char c) const; bool IsDigit(char c) const; bool IsAlpha(char c) const; }; class RootSignatureParser { public: RootSignatureParser(RootSignatureTokenizer *pTokenizer, DxilRootSignatureVersion DefaultVersion, DxilRootSignatureCompilationFlags Flags, llvm::raw_ostream &OS); HRESULT Parse(DxilVersionedRootSignatureDesc **ppRootSignature); private: typedef RootSignatureTokenizer::Token TokenType; RootSignatureTokenizer *m_pTokenizer; DxilRootSignatureVersion m_Version; DxilRootSignatureCompilationFlags m_CompilationFlags; llvm::raw_ostream &m_OS; HRESULT GetAndMatchToken(TokenType &Token, TokenType::Type Type); HRESULT Error(uint32_t uErrorNum, const char *pError, ...); HRESULT ParseRootSignature(DxilVersionedRootSignatureDesc **ppRootSignature); HRESULT ParseRootSignatureFlags(DxilRootSignatureFlags &Flags); HRESULT ParseRootConstants(DxilRootParameter1 &P); HRESULT ParseRootShaderResource(TokenType::Type TokType, TokenType::Type RegType, DxilRootParameterType ResType, DxilRootParameter1 &P); HRESULT ParseRootDescriptorTable(DxilRootParameter1 &P); HRESULT ParseStaticSampler(DxilStaticSamplerDesc &P); HRESULT ParseDescTableResource(TokenType::Type TokType, TokenType::Type RegType, DxilDescriptorRangeType RangeType, DxilDescriptorRange1 &R); HRESULT ParseRegister(TokenType::Type RegType, uint32_t &Reg); HRESULT ParseSpace(uint32_t &Space); HRESULT ParseNumDescriptors(uint32_t &NumDescriptors); HRESULT ParseRootDescFlags(DxilRootDescriptorFlags &Flags); HRESULT ParseDescRangeFlags(DxilDescriptorRangeType RangeType, DxilDescriptorRangeFlags &Flags); HRESULT ParseOffset(uint32_t &Offset); HRESULT ParseVisibility(DxilShaderVisibility &Vis); HRESULT ParseNum32BitConstants(uint32_t &NumConst); HRESULT ParseFilter(DxilFilter &Filter); HRESULT ParseTextureAddressMode(DxilTextureAddressMode &AddressMode); HRESULT ParseMipLODBias(float &MipLODBias); HRESULT ParseMaxAnisotropy(uint32_t &MaxAnisotropy); HRESULT ParseComparisonFunction(DxilComparisonFunc &ComparisonFunc); HRESULT ParseBorderColor(DxilStaticBorderColor &BorderColor); HRESULT ParseMinLOD(float &MinLOD); HRESULT ParseMaxLOD(float &MaxLOD); HRESULT ParseFloat(float &v); HRESULT MarkParameter(bool &bSeen, const char *pName); }; } // namespace hlsl
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/CMakeLists.txt
set(LLVM_LINK_COMPONENTS # MC # HLSL Change # MCParser # HLSL Change Support ) add_clang_library(clangParse ParseAST.cpp ParseCXXInlineMethods.cpp ParseDecl.cpp ParseDeclCXX.cpp ParseExpr.cpp ParseExprCXX.cpp ParseInit.cpp ParseObjc.cpp ParseOpenMP.cpp ParsePragma.cpp ParseStmt.cpp ParseStmtAsm.cpp ParseTemplate.cpp ParseTentative.cpp Parser.cpp ParseHLSL.cpp # HLSL Change HLSLRootSignature.cpp # HLSL Change LINK_LIBS clangAST clangBasic clangLex clangSema )
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/HLSLRootSignature.cpp
//===--- HLSLRootSignature.cpp -- HLSL root signature parsing -------------===// /////////////////////////////////////////////////////////////////////////////// // // // HLSLRootSignature.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // This file implements the parser for the root signature mini-language. // // // /////////////////////////////////////////////////////////////////////////////// #include "HLSLRootSignature.h" #include "dxc/Support/Global.h" #include "dxc/Support/WinFunctions.h" #include "dxc/Support/WinIncludes.h" #include "clang/Basic/Diagnostic.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Parse/ParseHLSL.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/raw_ostream.h" #include <float.h> using namespace llvm; using namespace hlsl; // Error codes. These could be useful for localization at some point. #define ERR_RS_UNEXPECTED_TOKEN 4612 #define ERR_RS_ROOTFLAGS_MORE_THAN_ONCE 4613 #define ERR_RS_CREATION_FAILED 4614 #define ERR_RS_BAD_SM 4615 #define ERR_RS_UNDEFINED_REGISTER 4616 #define ERR_RS_INCORRECT_REGISTER_TYPE 4617 #define ERR_RS_NOT_ALLOWED_FOR_HS_PATCH_CONST 4618 #define ERR_RS_WRONG_ROOT_DESC_FLAG 4619 #define ERR_RS_WRONG_DESC_RANGE_FLAG 4620 #define ERR_RS_LOCAL_FLAG_ON_GLOBAL 4621 #define ERR_RS_BAD_FLOAT 5000 // Non-throwing new #define NEW new (std::nothrow) DEFINE_ENUM_FLAG_OPERATORS(DxilRootSignatureFlags) DEFINE_ENUM_FLAG_OPERATORS(DxilRootDescriptorFlags) DEFINE_ENUM_FLAG_OPERATORS(DxilDescriptorRangeFlags) DEFINE_ENUM_FLAG_OPERATORS(DxilRootSignatureCompilationFlags) RootSignatureTokenizer::RootSignatureTokenizer(const char *pStr, size_t len) : m_pStrPos(pStr), m_pEndPos(pStr + len) { m_TokenBufferIdx = 0; ReadNextToken(m_TokenBufferIdx); } RootSignatureTokenizer::RootSignatureTokenizer(const char *pStr) : m_pStrPos(pStr), m_pEndPos(pStr + strlen(pStr)) { m_TokenBufferIdx = 0; ReadNextToken(m_TokenBufferIdx); } RootSignatureTokenizer::Token RootSignatureTokenizer::GetToken() { uint32_t CurBufferIdx = m_TokenBufferIdx; m_TokenBufferIdx = (m_TokenBufferIdx + 1) % kNumBuffers; ReadNextToken(m_TokenBufferIdx); return m_Tokens[CurBufferIdx]; } RootSignatureTokenizer::Token RootSignatureTokenizer::PeekToken() { return m_Tokens[m_TokenBufferIdx]; } bool RootSignatureTokenizer::IsDone() const { return m_pStrPos == m_pEndPos; } void RootSignatureTokenizer::ReadNextToken(uint32_t BufferIdx) { char *pBuffer = m_TokenStrings[BufferIdx]; Token &T = m_Tokens[BufferIdx]; bool bFloat = false; bool bKW = false; char c = 0; EatSpace(); // Identify token uint32_t TokLen = 0; char ch; // Any time m_pStrPos moves, update ch; no null termination assumptions made. // Test ch, not m_StrPos[0], which may be at end. #define STRPOS_MOVED() ch = m_pStrPos == m_pEndPos ? '\0' : m_pStrPos[0]; STRPOS_MOVED(); if (IsSeparator(ch)) { pBuffer[TokLen++] = *m_pStrPos++; } else if (IsDigit(ch) || ch == '+' || ch == '-' || ch == '.') { if (ch == '+' || ch == '-') { pBuffer[TokLen++] = *m_pStrPos++; STRPOS_MOVED(); } bool bSeenDigit = false; while (IsDigit(ch) && TokLen < kMaxTokenLength) { pBuffer[TokLen++] = *m_pStrPos++; STRPOS_MOVED(); bSeenDigit = true; } if (ch == '.') { bFloat = true; pBuffer[TokLen++] = *m_pStrPos++; STRPOS_MOVED(); if (!bSeenDigit && !IsDigit(ch)) { goto lUnknownToken; } while (IsDigit(ch) && TokLen < kMaxTokenLength) { pBuffer[TokLen++] = *m_pStrPos++; STRPOS_MOVED(); bSeenDigit = true; } } if (!bSeenDigit) { goto lUnknownToken; } if (ch == 'e' || ch == 'E') { bFloat = true; pBuffer[TokLen++] = *m_pStrPos++; STRPOS_MOVED() if (ch == '+' || ch == '-') { pBuffer[TokLen++] = *m_pStrPos++; STRPOS_MOVED(); } if (!IsDigit(ch)) { goto lUnknownToken; } while (IsDigit(ch) && TokLen < kMaxTokenLength) { pBuffer[TokLen++] = *m_pStrPos++; STRPOS_MOVED(); } } if (ch == 'f' || ch == 'F') { bFloat = true; pBuffer[TokLen++] = *m_pStrPos++; STRPOS_MOVED(); } } else if (IsAlpha(ch) || ch == '_') { while ((IsAlpha(ch) || ch == '_' || IsDigit(ch)) && TokLen < kMaxTokenLength) { pBuffer[TokLen++] = *m_pStrPos++; STRPOS_MOVED(); } } else { while (m_pStrPos < m_pEndPos && TokLen < kMaxTokenLength) { pBuffer[TokLen++] = *m_pStrPos++; STRPOS_MOVED(); // not really needed, but good for consistency } } pBuffer[TokLen] = '\0'; #undef STRPOS_MOVED // // Classify token // c = pBuffer[0]; // Delimiters switch (c) { case '\0': T = Token(Token::Type::EOL, pBuffer); return; case ',': T = Token(Token::Type::Comma, pBuffer); return; case '(': T = Token(Token::Type::LParen, pBuffer); return; case ')': T = Token(Token::Type::RParen, pBuffer); return; case '=': T = Token(Token::Type::EQ, pBuffer); return; case '|': T = Token(Token::Type::OR, pBuffer); return; } // Number if (IsDigit(c) || c == '+' || c == '-' || c == '.') { if (bFloat) { float v = 0.f; if (ToFloat(pBuffer, v)) { T = Token(Token::Type::NumberFloat, pBuffer, v); return; } } else { if (c == '-') { int n = 0; if (ToI32(pBuffer, n)) { T = Token(Token::Type::NumberI32, pBuffer, (uint32_t)n); return; } } else { uint32_t n = 0; if (ToU32(pBuffer, n)) { T = Token(Token::Type::NumberU32, pBuffer, n); return; } } } goto lUnknownToken; } // Register if (IsDigit(pBuffer[1]) && (c == 't' || c == 's' || c == 'u' || c == 'b')) { if (ToRegister(pBuffer, T)) return; } // Keyword #define KW(__name) ToKeyword(pBuffer, T, #__name, Token::Type::__name) // Case-incensitive switch (toupper(c)) { case 'A': bKW = KW(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT) || KW(ALLOW_STREAM_OUTPUT) || KW(addressU) || KW(addressV) || KW(addressW); break; case 'B': bKW = KW(borderColor); break; case 'C': bKW = KW(CBV) || KW(comparisonFunc) || KW(COMPARISON_NEVER) || KW(COMPARISON_LESS) || KW(COMPARISON_EQUAL) || KW(COMPARISON_LESS_EQUAL) || KW(COMPARISON_GREATER) || KW(COMPARISON_NOT_EQUAL) || KW(COMPARISON_GREATER_EQUAL) || KW(COMPARISON_ALWAYS) || KW(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED); break; case 'D': bKW = KW(DescriptorTable) || KW(DESCRIPTOR_RANGE_OFFSET_APPEND) || KW(DENY_VERTEX_SHADER_ROOT_ACCESS) || KW(DENY_HULL_SHADER_ROOT_ACCESS) || KW(DENY_DOMAIN_SHADER_ROOT_ACCESS) || KW(DENY_GEOMETRY_SHADER_ROOT_ACCESS) || KW(DENY_PIXEL_SHADER_ROOT_ACCESS) || KW(DENY_AMPLIFICATION_SHADER_ROOT_ACCESS) || KW(DENY_MESH_SHADER_ROOT_ACCESS) || KW(DESCRIPTORS_VOLATILE) || KW(DATA_VOLATILE) || KW(DATA_STATIC) || KW(DATA_STATIC_WHILE_SET_AT_EXECUTE) || KW(DESCRIPTORS_STATIC_KEEPING_BUFFER_BOUNDS_CHECKS); break; case 'F': bKW = KW(flags) || KW(filter) || KW(FILTER_MIN_MAG_MIP_POINT) || KW(FILTER_MIN_MAG_POINT_MIP_LINEAR) || KW(FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT) || KW(FILTER_MIN_POINT_MAG_MIP_LINEAR) || KW(FILTER_MIN_LINEAR_MAG_MIP_POINT) || KW(FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR) || KW(FILTER_MIN_MAG_LINEAR_MIP_POINT) || KW(FILTER_MIN_MAG_MIP_LINEAR) || KW(FILTER_ANISOTROPIC) || KW(FILTER_COMPARISON_MIN_MAG_MIP_POINT) || KW(FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR) || KW(FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT) || KW(FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR) || KW(FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT) || KW(FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR) || KW(FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT) || KW(FILTER_COMPARISON_MIN_MAG_MIP_LINEAR) || KW(FILTER_COMPARISON_ANISOTROPIC) || KW(FILTER_MINIMUM_MIN_MAG_MIP_POINT) || KW(FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR) || KW(FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT) || KW(FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR) || KW(FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT) || KW(FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR) || KW(FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT) || KW(FILTER_MINIMUM_MIN_MAG_MIP_LINEAR) || KW(FILTER_MINIMUM_ANISOTROPIC) || KW(FILTER_MAXIMUM_MIN_MAG_MIP_POINT) || KW(FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR) || KW(FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT) || KW(FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR) || KW(FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT) || KW(FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR) || KW(FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT) || KW(FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR) || KW(FILTER_MAXIMUM_ANISOTROPIC); break; case 'L': bKW = KW(LOCAL_ROOT_SIGNATURE); break; case 'M': bKW = KW(maxAnisotropy) || KW(mipLODBias) || KW(minLOD) || KW(maxLOD); break; case 'N': bKW = KW(numDescriptors) || KW(num32BitConstants); break; case 'O': bKW = KW(offset); break; case 'R': bKW = KW(RootFlags) || KW(RootConstants); break; case 'S': bKW = KW(space) || KW(Sampler) || KW(StaticSampler) || KW(SRV) || KW(SAMPLER_HEAP_DIRECTLY_INDEXED) || KW(SHADER_VISIBILITY_ALL) || KW(SHADER_VISIBILITY_VERTEX) || KW(SHADER_VISIBILITY_HULL) || KW(SHADER_VISIBILITY_DOMAIN) || KW(SHADER_VISIBILITY_GEOMETRY) || KW(SHADER_VISIBILITY_PIXEL) || KW(SHADER_VISIBILITY_AMPLIFICATION) || KW(SHADER_VISIBILITY_MESH) || KW(STATIC_BORDER_COLOR_TRANSPARENT_BLACK) || KW(STATIC_BORDER_COLOR_OPAQUE_BLACK) || KW(STATIC_BORDER_COLOR_OPAQUE_WHITE) || KW(STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT) || KW(STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT) || KW(SAMPLER_HEAP_DIRECTLY_INDEXED); break; case 'T': bKW = KW(TEXTURE_ADDRESS_WRAP) || KW(TEXTURE_ADDRESS_MIRROR) || KW(TEXTURE_ADDRESS_CLAMP) || KW(TEXTURE_ADDRESS_BORDER) || KW(TEXTURE_ADDRESS_MIRROR_ONCE); break; case 'U': bKW = KW(unbounded) || KW(UAV); break; case 'V': bKW = KW(visibility); break; } #undef KW if (!bKW) goto lUnknownToken; return; lUnknownToken: T = Token(Token::Type::Unknown, pBuffer); } void RootSignatureTokenizer::EatSpace() { while (m_pStrPos < m_pEndPos && *m_pStrPos == ' ') m_pStrPos++; } bool RootSignatureTokenizer::ToI32(LPCSTR pBuf, int &n) { if (pBuf[0] == '\0') return false; long long N = _atoi64(pBuf); if (N > INT_MAX || N < INT_MIN) return false; n = static_cast<int>(N); return true; } bool RootSignatureTokenizer::ToU32(LPCSTR pBuf, uint32_t &n) { if (pBuf[0] == '\0') return false; long long N = _atoi64(pBuf); if (N > UINT32_MAX || N < 0) return false; n = static_cast<uint32_t>(N); return true; } bool RootSignatureTokenizer::ToFloat(LPCSTR pBuf, float &n) { if (pBuf[0] == '\0') return false; errno = 0; double N = strtod(pBuf, NULL); if (errno == ERANGE || (N > FLT_MAX || N < -FLT_MAX)) { return false; } n = static_cast<float>(N); return true; } bool RootSignatureTokenizer::ToRegister(LPCSTR pBuf, Token &T) { uint32_t n; if (ToU32(&pBuf[1], n)) { switch (pBuf[0]) { case 't': T = Token(Token::Type::TReg, pBuf, n); return true; case 's': T = Token(Token::Type::SReg, pBuf, n); return true; case 'u': T = Token(Token::Type::UReg, pBuf, n); return true; case 'b': T = Token(Token::Type::BReg, pBuf, n); return true; } } return false; } bool RootSignatureTokenizer::ToKeyword(LPCSTR pBuf, Token &T, const char *pKeyword, Token::Type Type) { // Tokens are case-insencitive to allow more flexibility for programmers if (_stricmp(pBuf, pKeyword) == 0) { T = Token(Type, pBuf); return true; } else { T = Token(Token::Type::Unknown, pBuf); return false; } } bool RootSignatureTokenizer::IsSeparator(char c) const { return (c == ',' || c == '=' || c == '|' || c == '(' || c == ')' || c == ' ' || c == '\t' || c == '\n'); } bool RootSignatureTokenizer::IsDigit(char c) const { return isdigit(c) > 0; } bool RootSignatureTokenizer::IsAlpha(char c) const { return isalpha(c) > 0; } RootSignatureParser::RootSignatureParser( RootSignatureTokenizer *pTokenizer, DxilRootSignatureVersion DefaultVersion, DxilRootSignatureCompilationFlags CompilationFlags, llvm::raw_ostream &OS) : m_pTokenizer(pTokenizer), m_Version(DefaultVersion), m_CompilationFlags(CompilationFlags), m_OS(OS) {} HRESULT RootSignatureParser::Parse(DxilVersionedRootSignatureDesc **ppRootSignature) { HRESULT hr = S_OK; DxilVersionedRootSignatureDesc *pRS = NULL; DXASSERT(!((bool)(m_CompilationFlags & DxilRootSignatureCompilationFlags::GlobalRootSignature) && (bool)(m_CompilationFlags & DxilRootSignatureCompilationFlags::LocalRootSignature)), "global and local cannot be both set"); if (ppRootSignature != NULL) { IFC(ParseRootSignature(&pRS)); *ppRootSignature = pRS; } Cleanup: return hr; } HRESULT RootSignatureParser::GetAndMatchToken(TokenType &Token, TokenType::Type Type) { HRESULT hr = S_OK; Token = m_pTokenizer->GetToken(); if (Token.GetType() != Type) IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); Cleanup: return hr; } HRESULT RootSignatureParser::Error(uint32_t uErrorNum, LPCSTR pError, ...) { va_list Args; char msg[512]; va_start(Args, pError); vsnprintf_s(msg, _countof(msg), pError, Args); va_end(Args); try { m_OS << msg; } CATCH_CPP_RETURN_HRESULT(); return E_FAIL; } HRESULT RootSignatureParser::ParseRootSignature( DxilVersionedRootSignatureDesc **ppRootSignature) { HRESULT hr = S_OK; TokenType Token; bool bSeenFlags = false; SmallVector<DxilRootParameter1, 8> RSParameters; DxilRootParameter1 *pRSParams = NULL; SmallVector<DxilStaticSamplerDesc, 8> StaticSamplers; DxilStaticSamplerDesc *pStaticSamplers = NULL; DxilVersionedRootSignatureDesc *pRS = NULL; *ppRootSignature = NULL; IFCOOM(pRS = NEW DxilVersionedRootSignatureDesc); // Always parse root signature string to the latest version. pRS->Version = DxilRootSignatureVersion::Version_1_1; memset(&pRS->Desc_1_1, 0, sizeof(pRS->Desc_1_1)); Token = m_pTokenizer->PeekToken(); while (Token.GetType() != TokenType::EOL) { switch (Token.GetType()) { case TokenType::RootFlags: if (!bSeenFlags) { IFC(ParseRootSignatureFlags(pRS->Desc_1_1.Flags)); bSeenFlags = true; } else { IFC(Error(ERR_RS_ROOTFLAGS_MORE_THAN_ONCE, "RootFlags cannot be specified more than once")); } break; case TokenType::RootConstants: { DxilRootParameter1 P; IFC(ParseRootConstants(P)); RSParameters.push_back(P); break; } case TokenType::CBV: { DxilRootParameter1 P; IFC(ParseRootShaderResource(Token.GetType(), TokenType::BReg, DxilRootParameterType::CBV, P)); RSParameters.push_back(P); break; } case TokenType::SRV: { DxilRootParameter1 P; IFC(ParseRootShaderResource(Token.GetType(), TokenType::TReg, DxilRootParameterType::SRV, P)); RSParameters.push_back(P); break; } case TokenType::UAV: { DxilRootParameter1 P; IFC(ParseRootShaderResource(Token.GetType(), TokenType::UReg, DxilRootParameterType::UAV, P)); RSParameters.push_back(P); break; } case TokenType::DescriptorTable: { DxilRootParameter1 P; IFC(ParseRootDescriptorTable(P)); RSParameters.push_back(P); break; } case TokenType::StaticSampler: { DxilStaticSamplerDesc P; IFC(ParseStaticSampler(P)); StaticSamplers.push_back(P); break; } default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s' when parsing root signature", Token.GetStr())); } Token = m_pTokenizer->GetToken(); if (Token.GetType() == TokenType::EOL) break; // Consume ',' if (Token.GetType() != TokenType::Comma) IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Expected ',', found: '%s'", Token.GetStr())); Token = m_pTokenizer->PeekToken(); } if (RSParameters.size() > 0) { IFCOOM(pRSParams = NEW DxilRootParameter1[RSParameters.size()]); pRS->Desc_1_1.NumParameters = RSParameters.size(); memcpy(pRSParams, RSParameters.data(), pRS->Desc_1_1.NumParameters * sizeof(DxilRootParameter1)); pRS->Desc_1_1.pParameters = pRSParams; } if (StaticSamplers.size() > 0) { IFCOOM(pStaticSamplers = NEW DxilStaticSamplerDesc[StaticSamplers.size()]); pRS->Desc_1_1.NumStaticSamplers = StaticSamplers.size(); memcpy(pStaticSamplers, StaticSamplers.data(), pRS->Desc_1_1.NumStaticSamplers * sizeof(DxilStaticSamplerDesc)); pRS->Desc_1_1.pStaticSamplers = pStaticSamplers; } // Set local signature flag if not already on if ((bool)(m_CompilationFlags & DxilRootSignatureCompilationFlags::LocalRootSignature)) pRS->Desc_1_1.Flags |= DxilRootSignatureFlags::LocalRootSignature; // Down-convert root signature to the right version, if needed. if (pRS->Version != m_Version) { DxilVersionedRootSignatureDesc *pRS1 = NULL; try { hlsl::ConvertRootSignature( pRS, m_Version, const_cast<const DxilVersionedRootSignatureDesc **>(&pRS1)); } CATCH_CPP_ASSIGN_HRESULT(); IFC(hr); hlsl::DeleteRootSignature(pRS); pRS = pRS1; } *ppRootSignature = pRS; Cleanup: if (FAILED(hr)) { hlsl::DeleteRootSignature(pRS); } return hr; } HRESULT RootSignatureParser::ParseRootSignatureFlags(DxilRootSignatureFlags &Flags) { // RootFlags(ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT | // DENY_VERTEX_SHADER_ROOT_ACCESS) // ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT // DENY_VERTEX_SHADER_ROOT_ACCESS // DENY_HULL_SHADER_ROOT_ACCESS // DENY_DOMAIN_SHADER_ROOT_ACCESS // DENY_GEOMETRY_SHADER_ROOT_ACCESS // DENY_PIXEL_SHADER_ROOT_ACCESS // DENY_AMPLIFICATION_SHADER_ROOT_ACCESS // DENY_MESH_SHADER_ROOT_ACCESS // ALLOW_STREAM_OUTPUT // LOCAL_ROOT_SIGNATURE HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::RootFlags)); IFC(GetAndMatchToken(Token, TokenType::LParen)); Flags = DxilRootSignatureFlags::None; Token = m_pTokenizer->PeekToken(); if (Token.GetType() == TokenType::NumberU32) { IFC(GetAndMatchToken(Token, TokenType::NumberU32)); uint32_t n = Token.GetU32Value(); if (n != 0) { IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Root signature flag values can only be 0 or flag enum values, " "found: '%s'", Token.GetStr())); } } else { for (;;) { Token = m_pTokenizer->GetToken(); switch (Token.GetType()) { case TokenType::ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT: Flags |= DxilRootSignatureFlags::AllowInputAssemblerInputLayout; break; case TokenType::DENY_VERTEX_SHADER_ROOT_ACCESS: Flags |= DxilRootSignatureFlags::DenyVertexShaderRootAccess; break; case TokenType::DENY_HULL_SHADER_ROOT_ACCESS: Flags |= DxilRootSignatureFlags::DenyHullShaderRootAccess; break; case TokenType::DENY_DOMAIN_SHADER_ROOT_ACCESS: Flags |= DxilRootSignatureFlags::DenyDomainShaderRootAccess; break; case TokenType::DENY_GEOMETRY_SHADER_ROOT_ACCESS: Flags |= DxilRootSignatureFlags::DenyGeometryShaderRootAccess; break; case TokenType::DENY_PIXEL_SHADER_ROOT_ACCESS: Flags |= DxilRootSignatureFlags::DenyPixelShaderRootAccess; break; case TokenType::DENY_AMPLIFICATION_SHADER_ROOT_ACCESS: Flags |= DxilRootSignatureFlags::DenyAmplificationShaderRootAccess; break; case TokenType::DENY_MESH_SHADER_ROOT_ACCESS: Flags |= DxilRootSignatureFlags::DenyMeshShaderRootAccess; break; case TokenType::ALLOW_STREAM_OUTPUT: Flags |= DxilRootSignatureFlags::AllowStreamOutput; break; case TokenType::LOCAL_ROOT_SIGNATURE: if ((bool)(m_CompilationFlags & DxilRootSignatureCompilationFlags::GlobalRootSignature)) IFC(Error(ERR_RS_LOCAL_FLAG_ON_GLOBAL, "LOCAL_ROOT_SIGNATURE flag used in global root signature")); Flags |= DxilRootSignatureFlags::LocalRootSignature; break; case TokenType::CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED: Flags |= DxilRootSignatureFlags::CBVSRVUAVHeapDirectlyIndexed; break; case TokenType::SAMPLER_HEAP_DIRECTLY_INDEXED: Flags |= DxilRootSignatureFlags::SamplerHeapDirectlyIndexed; break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Expected a root signature flag value, found: '%s'", Token.GetStr())); } Token = m_pTokenizer->PeekToken(); if (Token.GetType() == TokenType::RParen) break; IFC(GetAndMatchToken(Token, TokenType::OR)); } } IFC(GetAndMatchToken(Token, TokenType::RParen)); Cleanup: return hr; } HRESULT RootSignatureParser::ParseRootConstants(DxilRootParameter1 &P) { //"RootConstants(num32BitConstants=3, b2 [, space=1, //visibility=SHADER_VISIBILITY_ALL ] ), " HRESULT hr = S_OK; TokenType Token; memset(&P, 0, sizeof(P)); DXASSERT(P.ShaderVisibility == DxilShaderVisibility::All, "else default isn't zero"); P.ParameterType = DxilRootParameterType::Constants32Bit; bool bSeenNum32BitConstants = false; bool bSeenBReg = false; bool bSeenSpace = false; bool bSeenVisibility = false; IFC(GetAndMatchToken(Token, TokenType::RootConstants)); IFC(GetAndMatchToken(Token, TokenType::LParen)); for (;;) { Token = m_pTokenizer->PeekToken(); switch (Token.GetType()) { case TokenType::num32BitConstants: IFC(MarkParameter(bSeenNum32BitConstants, "num32BitConstants")); IFC(ParseNum32BitConstants(P.Constants.Num32BitValues)); break; case TokenType::BReg: IFC(MarkParameter(bSeenBReg, "cbuffer register b#")); IFC(ParseRegister(TokenType::BReg, P.Constants.ShaderRegister)); break; case TokenType::space: IFC(MarkParameter(bSeenSpace, "space")); IFC(ParseSpace(P.Constants.RegisterSpace)); break; case TokenType::visibility: IFC(MarkParameter(bSeenVisibility, "visibility")); IFC(ParseVisibility(P.ShaderVisibility)); break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); break; } Token = m_pTokenizer->GetToken(); if (Token.GetType() == TokenType::RParen) break; else if (Token.GetType() != TokenType::Comma) IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); } if (!bSeenNum32BitConstants) { IFC(Error(ERR_RS_UNDEFINED_REGISTER, "num32BitConstants must be defined for each RootConstants")); } if (!bSeenBReg) { IFC(Error( ERR_RS_UNDEFINED_REGISTER, "Constant buffer register b# must be defined for each RootConstants")); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseRootShaderResource( TokenType::Type TokType, TokenType::Type RegType, DxilRootParameterType ResType, DxilRootParameter1 &P) { // CBV(b0 [, space=3, flags=0, visibility=VISIBILITY_ALL] ) HRESULT hr = S_OK; TokenType Token; P.ParameterType = ResType; P.ShaderVisibility = DxilShaderVisibility::All; P.Descriptor.ShaderRegister = 0; P.Descriptor.RegisterSpace = 0; P.Descriptor.Flags = DxilRootDescriptorFlags::None; bool bSeenReg = false; bool bSeenFlags = false; bool bSeenSpace = false; bool bSeenVisibility = false; IFC(GetAndMatchToken(Token, TokType)); IFC(GetAndMatchToken(Token, TokenType::LParen)); for (;;) { Token = m_pTokenizer->PeekToken(); switch (Token.GetType()) { case TokenType::BReg: case TokenType::TReg: case TokenType::UReg: IFC(MarkParameter(bSeenReg, "shader register")); IFC(ParseRegister(RegType, P.Descriptor.ShaderRegister)); break; case TokenType::flags: IFC(MarkParameter(bSeenFlags, "flags")); IFC(ParseRootDescFlags(P.Descriptor.Flags)); break; case TokenType::space: IFC(MarkParameter(bSeenSpace, "space")); IFC(ParseSpace(P.Descriptor.RegisterSpace)); break; case TokenType::visibility: IFC(MarkParameter(bSeenVisibility, "visibility")); IFC(ParseVisibility(P.ShaderVisibility)); break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); break; } Token = m_pTokenizer->GetToken(); if (Token.GetType() == TokenType::RParen) break; else if (Token.GetType() != TokenType::Comma) IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); } if (!bSeenReg) { IFC(Error(ERR_RS_UNDEFINED_REGISTER, "shader register must be defined for each CBV/SRV/UAV")); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseRootDescriptorTable(DxilRootParameter1 &P) { // DescriptorTable( SRV(t2, numDescriptors = 6), UAV(u0, numDescriptors = 4) // [, visibility = SHADER_VISIBILITY_ALL ] ) HRESULT hr = S_OK; TokenType Token; memset(&P, 0, sizeof(P)); DXASSERT(P.ShaderVisibility == DxilShaderVisibility::All, "else default isn't zero"); P.ParameterType = DxilRootParameterType::DescriptorTable; bool bSeenVisibility = false; DxilDescriptorRange1 *pDescs = NULL; SmallVector<DxilDescriptorRange1, 4> Ranges; IFC(GetAndMatchToken(Token, TokenType::DescriptorTable)); IFC(GetAndMatchToken(Token, TokenType::LParen)); for (;;) { Token = m_pTokenizer->PeekToken(); switch (Token.GetType()) { case TokenType::CBV: { DxilDescriptorRange1 R; IFC(ParseDescTableResource(Token.GetType(), TokenType::BReg, DxilDescriptorRangeType::CBV, R)); Ranges.push_back(R); break; } case TokenType::SRV: { DxilDescriptorRange1 R; IFC(ParseDescTableResource(Token.GetType(), TokenType::TReg, DxilDescriptorRangeType::SRV, R)); Ranges.push_back(R); break; } case TokenType::UAV: { DxilDescriptorRange1 R; IFC(ParseDescTableResource(Token.GetType(), TokenType::UReg, DxilDescriptorRangeType::UAV, R)); Ranges.push_back(R); break; } case TokenType::Sampler: { DxilDescriptorRange1 R; IFC(ParseDescTableResource(Token.GetType(), TokenType::SReg, DxilDescriptorRangeType::Sampler, R)); Ranges.push_back(R); break; } case TokenType::visibility: IFC(MarkParameter(bSeenVisibility, "visibility")); IFC(ParseVisibility(P.ShaderVisibility)); break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); break; } Token = m_pTokenizer->GetToken(); if (Token.GetType() == TokenType::RParen) break; else if (Token.GetType() != TokenType::Comma) IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); } if (Ranges.size() > 0) { IFCOOM(pDescs = NEW DxilDescriptorRange1[Ranges.size()]); for (uint32_t i = 0; i < Ranges.size(); i++) { pDescs[i] = Ranges[i]; } P.DescriptorTable.pDescriptorRanges = pDescs; P.DescriptorTable.NumDescriptorRanges = Ranges.size(); } Cleanup: if (FAILED(hr)) { delete[] pDescs; } return hr; } HRESULT RootSignatureParser::ParseDescTableResource( TokenType::Type TokType, TokenType::Type RegType, DxilDescriptorRangeType RangeType, DxilDescriptorRange1 &R) { HRESULT hr = S_OK; TokenType Token; // CBV(b0 [, numDescriptors = 1, space=0, flags=0, offset = // DESCRIPTOR_RANGE_OFFSET_APPEND] ) R.RangeType = RangeType; R.NumDescriptors = 1; R.BaseShaderRegister = 0; R.RegisterSpace = 0; R.Flags = DxilDescriptorRangeFlags::None; R.OffsetInDescriptorsFromTableStart = DxilDescriptorRangeOffsetAppend; bool bSeenReg = false; bool bSeenNumDescriptors = false; bool bSeenSpace = false; bool bSeenFlags = false; bool bSeenOffset = false; IFC(GetAndMatchToken(Token, TokType)); IFC(GetAndMatchToken(Token, TokenType::LParen)); for (;;) { Token = m_pTokenizer->PeekToken(); switch (Token.GetType()) { case TokenType::BReg: case TokenType::TReg: case TokenType::UReg: case TokenType::SReg: IFC(MarkParameter(bSeenReg, "shader register")); IFC(ParseRegister(RegType, R.BaseShaderRegister)); break; case TokenType::numDescriptors: IFC(MarkParameter(bSeenNumDescriptors, "numDescriptors")); IFC(ParseNumDescriptors(R.NumDescriptors)); break; case TokenType::space: IFC(MarkParameter(bSeenSpace, "space")); IFC(ParseSpace(R.RegisterSpace)); break; case TokenType::flags: IFC(MarkParameter(bSeenFlags, "flags")); IFC(ParseDescRangeFlags(RangeType, R.Flags)); break; case TokenType::offset: IFC(MarkParameter(bSeenOffset, "offset")); IFC(ParseOffset(R.OffsetInDescriptorsFromTableStart)); break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); break; } Token = m_pTokenizer->GetToken(); if (Token.GetType() == TokenType::RParen) break; else if (Token.GetType() != TokenType::Comma) IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); } if (!bSeenReg) { IFC(Error(ERR_RS_UNDEFINED_REGISTER, "shader register must be defined for each CBV/SRV/UAV")); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseRegister(TokenType::Type RegType, uint32_t &Reg) { HRESULT hr = S_OK; TokenType Token = m_pTokenizer->PeekToken(); switch (Token.GetType()) { case TokenType::BReg: IFC(GetAndMatchToken(Token, TokenType::BReg)); break; case TokenType::TReg: IFC(GetAndMatchToken(Token, TokenType::TReg)); break; case TokenType::UReg: IFC(GetAndMatchToken(Token, TokenType::UReg)); break; case TokenType::SReg: IFC(GetAndMatchToken(Token, TokenType::SReg)); break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Expected a register token (CBV, SRV, UAV, Sampler), found: '%s'", Token.GetStr())); } if (Token.GetType() != RegType) { switch (RegType) { case TokenType::BReg: IFC(Error(ERR_RS_INCORRECT_REGISTER_TYPE, "Incorrect register type '%s' in CBV (expected b#)", Token.GetStr())); break; case TokenType::TReg: IFC(Error(ERR_RS_INCORRECT_REGISTER_TYPE, "Incorrect register type '%s' in SRV (expected t#)", Token.GetStr())); break; case TokenType::UReg: IFC(Error(ERR_RS_INCORRECT_REGISTER_TYPE, "Incorrect register type '%s' in UAV (expected u#)", Token.GetStr())); break; case TokenType::SReg: IFC(Error( ERR_RS_INCORRECT_REGISTER_TYPE, "Incorrect register type '%s' in Sampler/StaticSampler (expected s#)", Token.GetStr())); break; default: // Only Register types are relevant. break; } } Reg = Token.GetU32Value(); Cleanup: return hr; } HRESULT RootSignatureParser::ParseSpace(uint32_t &Space) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::space)); IFC(GetAndMatchToken(Token, TokenType::EQ)); IFC(GetAndMatchToken(Token, TokenType::NumberU32)); Space = Token.GetU32Value(); Cleanup: return hr; } HRESULT RootSignatureParser::ParseNumDescriptors(uint32_t &NumDescriptors) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::numDescriptors)); IFC(GetAndMatchToken(Token, TokenType::EQ)); Token = m_pTokenizer->PeekToken(); if (Token.GetType() == TokenType::unbounded) { IFC(GetAndMatchToken(Token, TokenType::unbounded)); NumDescriptors = UINT32_MAX; } else { IFC(GetAndMatchToken(Token, TokenType::NumberU32)); NumDescriptors = Token.GetU32Value(); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseRootDescFlags(DxilRootDescriptorFlags &Flags) { // flags=DATA_VOLATILE | DATA_STATIC | DATA_STATIC_WHILE_SET_AT_EXECUTE HRESULT hr = S_OK; TokenType Token; if (m_Version == DxilRootSignatureVersion::Version_1_0) { IFC(Error(ERR_RS_WRONG_ROOT_DESC_FLAG, "Root descriptor flags cannot be specified for root_sig_1_0")); } IFC(GetAndMatchToken(Token, TokenType::flags)); IFC(GetAndMatchToken(Token, TokenType::EQ)); Flags = DxilRootDescriptorFlags::None; Token = m_pTokenizer->PeekToken(); if (Token.GetType() == TokenType::NumberU32) { IFC(GetAndMatchToken(Token, TokenType::NumberU32)); uint32_t n = Token.GetU32Value(); if (n != 0) { IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Root descriptor flag values can only be 0 or flag enum " "values, found: '%s'", Token.GetStr())); } } else { for (;;) { Token = m_pTokenizer->GetToken(); switch (Token.GetType()) { case TokenType::DATA_VOLATILE: Flags |= DxilRootDescriptorFlags::DataVolatile; break; case TokenType::DATA_STATIC: Flags |= DxilRootDescriptorFlags::DataStatic; break; case TokenType::DATA_STATIC_WHILE_SET_AT_EXECUTE: Flags |= DxilRootDescriptorFlags::DataStaticWhileSetAtExecute; break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Expected a root descriptor flag value, found: '%s'", Token.GetStr())); } Token = m_pTokenizer->PeekToken(); if (Token.GetType() == TokenType::RParen || Token.GetType() == TokenType::Comma) break; IFC(GetAndMatchToken(Token, TokenType::OR)); } } Cleanup: return hr; } HRESULT RootSignatureParser::ParseDescRangeFlags(DxilDescriptorRangeType, DxilDescriptorRangeFlags &Flags) { // flags=DESCRIPTORS_VOLATILE | DATA_VOLATILE | DATA_STATIC | // DATA_STATIC_WHILE_SET_AT_EXECUTE | // DESCRIPTORS_STATIC_KEEPING_BUFFER_BOUNDS_CHECKS HRESULT hr = S_OK; TokenType Token; if (m_Version == DxilRootSignatureVersion::Version_1_0) { IFC(Error(ERR_RS_WRONG_DESC_RANGE_FLAG, "Descriptor range flags cannot be specified for root_sig_1_0")); } IFC(GetAndMatchToken(Token, TokenType::flags)); IFC(GetAndMatchToken(Token, TokenType::EQ)); Flags = DxilDescriptorRangeFlags::None; Token = m_pTokenizer->PeekToken(); if (Token.GetType() == TokenType::NumberU32) { IFC(GetAndMatchToken(Token, TokenType::NumberU32)); uint32_t n = Token.GetU32Value(); if (n != 0) { IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Descriptor range flag values can only be 0 or flag enum " "values, found: '%s'", Token.GetStr())); } } else { for (;;) { Token = m_pTokenizer->GetToken(); switch (Token.GetType()) { case TokenType::DESCRIPTORS_VOLATILE: Flags |= DxilDescriptorRangeFlags::DescriptorsVolatile; break; case TokenType::DATA_VOLATILE: Flags |= DxilDescriptorRangeFlags::DataVolatile; break; case TokenType::DATA_STATIC: Flags |= DxilDescriptorRangeFlags::DataStatic; break; case TokenType::DATA_STATIC_WHILE_SET_AT_EXECUTE: Flags |= DxilDescriptorRangeFlags::DataStaticWhileSetAtExecute; break; case TokenType::DESCRIPTORS_STATIC_KEEPING_BUFFER_BOUNDS_CHECKS: Flags |= DxilDescriptorRangeFlags:: DescriptorsStaticKeepingBufferBoundsChecks; break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Expected a descriptor range flag value, found: '%s'", Token.GetStr())); } Token = m_pTokenizer->PeekToken(); if (Token.GetType() == TokenType::RParen || Token.GetType() == TokenType::Comma) break; IFC(GetAndMatchToken(Token, TokenType::OR)); } } Cleanup: return hr; } HRESULT RootSignatureParser::ParseOffset(uint32_t &Offset) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::offset)); IFC(GetAndMatchToken(Token, TokenType::EQ)); Token = m_pTokenizer->PeekToken(); if (Token.GetType() == TokenType::DESCRIPTOR_RANGE_OFFSET_APPEND) { IFC(GetAndMatchToken(Token, TokenType::DESCRIPTOR_RANGE_OFFSET_APPEND)); Offset = DxilDescriptorRangeOffsetAppend; } else { IFC(GetAndMatchToken(Token, TokenType::NumberU32)); Offset = Token.GetU32Value(); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseVisibility(DxilShaderVisibility &Vis) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::visibility)); IFC(GetAndMatchToken(Token, TokenType::EQ)); Token = m_pTokenizer->GetToken(); switch (Token.GetType()) { case TokenType::SHADER_VISIBILITY_ALL: Vis = DxilShaderVisibility::All; break; case TokenType::SHADER_VISIBILITY_VERTEX: Vis = DxilShaderVisibility::Vertex; break; case TokenType::SHADER_VISIBILITY_HULL: Vis = DxilShaderVisibility::Hull; break; case TokenType::SHADER_VISIBILITY_DOMAIN: Vis = DxilShaderVisibility::Domain; break; case TokenType::SHADER_VISIBILITY_GEOMETRY: Vis = DxilShaderVisibility::Geometry; break; case TokenType::SHADER_VISIBILITY_PIXEL: Vis = DxilShaderVisibility::Pixel; break; case TokenType::SHADER_VISIBILITY_AMPLIFICATION: Vis = DxilShaderVisibility::Amplification; break; case TokenType::SHADER_VISIBILITY_MESH: Vis = DxilShaderVisibility::Mesh; break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected visibility value: '%s'.", Token.GetStr())); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseNum32BitConstants(uint32_t &NumConst) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::num32BitConstants)); IFC(GetAndMatchToken(Token, TokenType::EQ)); IFC(GetAndMatchToken(Token, TokenType::NumberU32)); NumConst = Token.GetU32Value(); Cleanup: return hr; } HRESULT RootSignatureParser::ParseStaticSampler(DxilStaticSamplerDesc &P) { // StaticSampler( s0, // [ Filter = FILTER_ANISOTROPIC, // AddressU = TEXTURE_ADDRESS_WRAP, // AddressV = TEXTURE_ADDRESS_WRAP, // AddressW = TEXTURE_ADDRESS_WRAP, // MipLODBias = 0, // MaxAnisotropy = 16, // ComparisonFunc = COMPARISON_LESS_EQUAL, // BorderColor = STATIC_BORDER_COLOR_OPAQUE_WHITE, // MinLOD = 0.f, // MaxLOD = 3.402823466e+38f // space = 0, // visibility = SHADER_VISIBILITY_ALL ] ) HRESULT hr = S_OK; TokenType Token; memset(&P, 0, sizeof(P)); P.Filter = DxilFilter::ANISOTROPIC; P.AddressU = P.AddressV = P.AddressW = DxilTextureAddressMode::Wrap; P.MaxAnisotropy = 16; P.ComparisonFunc = DxilComparisonFunc::LessEqual; P.BorderColor = DxilStaticBorderColor::OpaqueWhite; P.MaxLOD = DxilFloat32Max; bool bSeenFilter = false; bool bSeenAddressU = false; bool bSeenAddressV = false; bool bSeenAddressW = false; bool bSeenMipLODBias = false; bool bSeenMaxAnisotropy = false; bool bSeenComparisonFunc = false; bool bSeenBorderColor = false; bool bSeenMinLOD = false; bool bSeenMaxLOD = false; bool bSeenSReg = false; bool bSeenSpace = false; bool bSeenVisibility = false; IFC(GetAndMatchToken(Token, TokenType::StaticSampler)); IFC(GetAndMatchToken(Token, TokenType::LParen)); for (;;) { Token = m_pTokenizer->PeekToken(); switch (Token.GetType()) { case TokenType::filter: IFC(MarkParameter(bSeenFilter, "filter")); IFC(ParseFilter(P.Filter)); break; case TokenType::addressU: IFC(MarkParameter(bSeenAddressU, "addressU")); IFC(ParseTextureAddressMode(P.AddressU)); break; case TokenType::addressV: IFC(MarkParameter(bSeenAddressV, "addressV")); IFC(ParseTextureAddressMode(P.AddressV)); break; case TokenType::addressW: IFC(MarkParameter(bSeenAddressW, "addressW")); IFC(ParseTextureAddressMode(P.AddressW)); break; case TokenType::mipLODBias: IFC(MarkParameter(bSeenMipLODBias, "mipLODBias")); IFC(ParseMipLODBias(P.MipLODBias)); break; case TokenType::maxAnisotropy: IFC(MarkParameter(bSeenMaxAnisotropy, "maxAnisotropy")); IFC(ParseMaxAnisotropy(P.MaxAnisotropy)); break; case TokenType::comparisonFunc: IFC(MarkParameter(bSeenComparisonFunc, "comparisonFunc")); IFC(ParseComparisonFunction(P.ComparisonFunc)); break; case TokenType::borderColor: IFC(MarkParameter(bSeenBorderColor, "borderColor")); IFC(ParseBorderColor(P.BorderColor)); break; case TokenType::minLOD: IFC(MarkParameter(bSeenMinLOD, "minLOD")); IFC(ParseMinLOD(P.MinLOD)); break; case TokenType::maxLOD: IFC(MarkParameter(bSeenMaxLOD, "maxLOD")); IFC(ParseMaxLOD(P.MaxLOD)); break; case TokenType::SReg: IFC(MarkParameter(bSeenSReg, "sampler register s#")); IFC(ParseRegister(TokenType::SReg, P.ShaderRegister)); break; case TokenType::space: IFC(MarkParameter(bSeenSpace, "space")); IFC(ParseSpace(P.RegisterSpace)); break; case TokenType::visibility: IFC(MarkParameter(bSeenVisibility, "visibility")); IFC(ParseVisibility(P.ShaderVisibility)); break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); break; } Token = m_pTokenizer->GetToken(); if (Token.GetType() == TokenType::RParen) break; else if (Token.GetType() != TokenType::Comma) IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected token '%s'", Token.GetStr())); } if (!bSeenSReg) { IFC(Error(ERR_RS_UNDEFINED_REGISTER, "Sampler register s# must be defined for each static sampler")); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseFilter(DxilFilter &Filter) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::filter)); IFC(GetAndMatchToken(Token, TokenType::EQ)); Token = m_pTokenizer->GetToken(); switch (Token.GetType()) { case TokenType::FILTER_MIN_MAG_MIP_POINT: Filter = DxilFilter::MIN_MAG_MIP_POINT; break; case TokenType::FILTER_MIN_MAG_POINT_MIP_LINEAR: Filter = DxilFilter::MIN_MAG_POINT_MIP_LINEAR; break; case TokenType::FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT: Filter = DxilFilter::MIN_POINT_MAG_LINEAR_MIP_POINT; break; case TokenType::FILTER_MIN_POINT_MAG_MIP_LINEAR: Filter = DxilFilter::MIN_POINT_MAG_MIP_LINEAR; break; case TokenType::FILTER_MIN_LINEAR_MAG_MIP_POINT: Filter = DxilFilter::MIN_LINEAR_MAG_MIP_POINT; break; case TokenType::FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR: Filter = DxilFilter::MIN_LINEAR_MAG_POINT_MIP_LINEAR; break; case TokenType::FILTER_MIN_MAG_LINEAR_MIP_POINT: Filter = DxilFilter::MIN_MAG_LINEAR_MIP_POINT; break; case TokenType::FILTER_MIN_MAG_MIP_LINEAR: Filter = DxilFilter::MIN_MAG_MIP_LINEAR; break; case TokenType::FILTER_ANISOTROPIC: Filter = DxilFilter::ANISOTROPIC; break; case TokenType::FILTER_COMPARISON_MIN_MAG_MIP_POINT: Filter = DxilFilter::COMPARISON_MIN_MAG_MIP_POINT; break; case TokenType::FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR: Filter = DxilFilter::COMPARISON_MIN_MAG_POINT_MIP_LINEAR; break; case TokenType::FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT: Filter = DxilFilter::COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT; break; case TokenType::FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR: Filter = DxilFilter::COMPARISON_MIN_POINT_MAG_MIP_LINEAR; break; case TokenType::FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT: Filter = DxilFilter::COMPARISON_MIN_LINEAR_MAG_MIP_POINT; break; case TokenType::FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR: Filter = DxilFilter::COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR; break; case TokenType::FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT: Filter = DxilFilter::COMPARISON_MIN_MAG_LINEAR_MIP_POINT; break; case TokenType::FILTER_COMPARISON_MIN_MAG_MIP_LINEAR: Filter = DxilFilter::COMPARISON_MIN_MAG_MIP_LINEAR; break; case TokenType::FILTER_COMPARISON_ANISOTROPIC: Filter = DxilFilter::COMPARISON_ANISOTROPIC; break; case TokenType::FILTER_MINIMUM_MIN_MAG_MIP_POINT: Filter = DxilFilter::MINIMUM_MIN_MAG_MIP_POINT; break; case TokenType::FILTER_MINIMUM_MIN_MAG_POINT_MIP_LINEAR: Filter = DxilFilter::MINIMUM_MIN_MAG_POINT_MIP_LINEAR; break; case TokenType::FILTER_MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT: Filter = DxilFilter::MINIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT; break; case TokenType::FILTER_MINIMUM_MIN_POINT_MAG_MIP_LINEAR: Filter = DxilFilter::MINIMUM_MIN_POINT_MAG_MIP_LINEAR; break; case TokenType::FILTER_MINIMUM_MIN_LINEAR_MAG_MIP_POINT: Filter = DxilFilter::MINIMUM_MIN_LINEAR_MAG_MIP_POINT; break; case TokenType::FILTER_MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR: Filter = DxilFilter::MINIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR; break; case TokenType::FILTER_MINIMUM_MIN_MAG_LINEAR_MIP_POINT: Filter = DxilFilter::MINIMUM_MIN_MAG_LINEAR_MIP_POINT; break; case TokenType::FILTER_MINIMUM_MIN_MAG_MIP_LINEAR: Filter = DxilFilter::MINIMUM_MIN_MAG_MIP_LINEAR; break; case TokenType::FILTER_MINIMUM_ANISOTROPIC: Filter = DxilFilter::MINIMUM_ANISOTROPIC; break; case TokenType::FILTER_MAXIMUM_MIN_MAG_MIP_POINT: Filter = DxilFilter::MAXIMUM_MIN_MAG_MIP_POINT; break; case TokenType::FILTER_MAXIMUM_MIN_MAG_POINT_MIP_LINEAR: Filter = DxilFilter::MAXIMUM_MIN_MAG_POINT_MIP_LINEAR; break; case TokenType::FILTER_MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT: Filter = DxilFilter::MAXIMUM_MIN_POINT_MAG_LINEAR_MIP_POINT; break; case TokenType::FILTER_MAXIMUM_MIN_POINT_MAG_MIP_LINEAR: Filter = DxilFilter::MAXIMUM_MIN_POINT_MAG_MIP_LINEAR; break; case TokenType::FILTER_MAXIMUM_MIN_LINEAR_MAG_MIP_POINT: Filter = DxilFilter::MAXIMUM_MIN_LINEAR_MAG_MIP_POINT; break; case TokenType::FILTER_MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR: Filter = DxilFilter::MAXIMUM_MIN_LINEAR_MAG_POINT_MIP_LINEAR; break; case TokenType::FILTER_MAXIMUM_MIN_MAG_LINEAR_MIP_POINT: Filter = DxilFilter::MAXIMUM_MIN_MAG_LINEAR_MIP_POINT; break; case TokenType::FILTER_MAXIMUM_MIN_MAG_MIP_LINEAR: Filter = DxilFilter::MAXIMUM_MIN_MAG_MIP_LINEAR; break; case TokenType::FILTER_MAXIMUM_ANISOTROPIC: Filter = DxilFilter::MAXIMUM_ANISOTROPIC; break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected filter value: '%s'.", Token.GetStr())); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseTextureAddressMode( DxilTextureAddressMode &AddressMode) { HRESULT hr = S_OK; TokenType Token = m_pTokenizer->GetToken(); DXASSERT_NOMSG(Token.GetType() == TokenType::addressU || Token.GetType() == TokenType::addressV || Token.GetType() == TokenType::addressW); IFC(GetAndMatchToken(Token, TokenType::EQ)); Token = m_pTokenizer->GetToken(); switch (Token.GetType()) { case TokenType::TEXTURE_ADDRESS_WRAP: AddressMode = DxilTextureAddressMode::Wrap; break; case TokenType::TEXTURE_ADDRESS_MIRROR: AddressMode = DxilTextureAddressMode::Mirror; break; case TokenType::TEXTURE_ADDRESS_CLAMP: AddressMode = DxilTextureAddressMode::Clamp; break; case TokenType::TEXTURE_ADDRESS_BORDER: AddressMode = DxilTextureAddressMode::Border; break; case TokenType::TEXTURE_ADDRESS_MIRROR_ONCE: AddressMode = DxilTextureAddressMode::MirrorOnce; break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected texture address mode value: '%s'.", Token.GetStr())); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseMipLODBias(float &MipLODBias) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::mipLODBias)); IFC(GetAndMatchToken(Token, TokenType::EQ)); IFC(ParseFloat(MipLODBias)); Cleanup: return hr; } HRESULT RootSignatureParser::ParseMaxAnisotropy(uint32_t &MaxAnisotropy) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::maxAnisotropy)); IFC(GetAndMatchToken(Token, TokenType::EQ)); IFC(GetAndMatchToken(Token, TokenType::NumberU32)); MaxAnisotropy = Token.GetU32Value(); Cleanup: return hr; } HRESULT RootSignatureParser::ParseComparisonFunction( DxilComparisonFunc &ComparisonFunc) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::comparisonFunc)); IFC(GetAndMatchToken(Token, TokenType::EQ)); Token = m_pTokenizer->GetToken(); switch (Token.GetType()) { case TokenType::COMPARISON_NEVER: ComparisonFunc = DxilComparisonFunc::Never; break; case TokenType::COMPARISON_LESS: ComparisonFunc = DxilComparisonFunc::Less; break; case TokenType::COMPARISON_EQUAL: ComparisonFunc = DxilComparisonFunc::Equal; break; case TokenType::COMPARISON_LESS_EQUAL: ComparisonFunc = DxilComparisonFunc::LessEqual; break; case TokenType::COMPARISON_GREATER: ComparisonFunc = DxilComparisonFunc::Greater; break; case TokenType::COMPARISON_NOT_EQUAL: ComparisonFunc = DxilComparisonFunc::NotEqual; break; case TokenType::COMPARISON_GREATER_EQUAL: ComparisonFunc = DxilComparisonFunc::GreaterEqual; break; case TokenType::COMPARISON_ALWAYS: ComparisonFunc = DxilComparisonFunc::Always; break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected texture address mode value: '%s'.", Token.GetStr())); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseBorderColor(DxilStaticBorderColor &BorderColor) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::borderColor)); IFC(GetAndMatchToken(Token, TokenType::EQ)); Token = m_pTokenizer->GetToken(); switch (Token.GetType()) { case TokenType::STATIC_BORDER_COLOR_TRANSPARENT_BLACK: BorderColor = DxilStaticBorderColor::TransparentBlack; break; case TokenType::STATIC_BORDER_COLOR_OPAQUE_BLACK: BorderColor = DxilStaticBorderColor::OpaqueBlack; break; case TokenType::STATIC_BORDER_COLOR_OPAQUE_WHITE: BorderColor = DxilStaticBorderColor::OpaqueWhite; break; case TokenType::STATIC_BORDER_COLOR_OPAQUE_BLACK_UINT: BorderColor = DxilStaticBorderColor::OpaqueBlackUint; break; case TokenType::STATIC_BORDER_COLOR_OPAQUE_WHITE_UINT: BorderColor = DxilStaticBorderColor::OpaqueWhiteUint; break; default: IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Unexpected texture address mode value: '%s'.", Token.GetStr())); } Cleanup: return hr; } HRESULT RootSignatureParser::ParseMinLOD(float &MinLOD) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::minLOD)); IFC(GetAndMatchToken(Token, TokenType::EQ)); IFC(ParseFloat(MinLOD)); Cleanup: return hr; } HRESULT RootSignatureParser::ParseMaxLOD(float &MaxLOD) { HRESULT hr = S_OK; TokenType Token; IFC(GetAndMatchToken(Token, TokenType::maxLOD)); IFC(GetAndMatchToken(Token, TokenType::EQ)); IFC(ParseFloat(MaxLOD)); Cleanup: return hr; } HRESULT RootSignatureParser::ParseFloat(float &v) { HRESULT hr = S_OK; TokenType Token = m_pTokenizer->GetToken(); if (Token.GetType() == TokenType::NumberU32) { v = (float)Token.GetU32Value(); } else if (Token.GetType() == TokenType::NumberI32) { v = (float)Token.GetI32Value(); } else if (Token.GetType() == TokenType::NumberFloat) { v = Token.GetFloatValue(); } else { IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Expected float, found token '%s'", Token.GetStr())); } Cleanup: return hr; } HRESULT RootSignatureParser::MarkParameter(bool &bSeen, LPCSTR pName) { HRESULT hr = S_OK; if (bSeen) { IFC(Error(ERR_RS_UNEXPECTED_TOKEN, "Parameter '%s' can be specified only once", pName)); } bSeen = true; Cleanup: return hr; } bool clang::ParseHLSLRootSignature( const char *pData, unsigned Len, hlsl::DxilRootSignatureVersion Ver, hlsl::DxilRootSignatureCompilationFlags Flags, hlsl::DxilVersionedRootSignatureDesc **ppDesc, SourceLocation Loc, clang::DiagnosticsEngine &Diags) { *ppDesc = nullptr; std::string OSStr; llvm::raw_string_ostream OS(OSStr); hlsl::RootSignatureTokenizer RST(pData, Len); hlsl::RootSignatureParser RSP(&RST, Ver, Flags, OS); hlsl::DxilVersionedRootSignatureDesc *D = nullptr; if (SUCCEEDED(RSP.Parse(&D))) { *ppDesc = D; return true; } else { // Create diagnostic error message. OS.flush(); if (OSStr.empty()) { Diags.Report(Loc, clang::diag::err_hlsl_rootsig) << "unexpected"; } else { Diags.Report(Loc, clang::diag::err_hlsl_rootsig) << OSStr.c_str(); } return false; } } void clang::ReportHLSLRootSigError(clang::DiagnosticsEngine &Diags, clang::SourceLocation Loc, const char *pData, unsigned Len) { Diags.Report(Loc, clang::diag::err_hlsl_rootsig) << StringRef(pData, Len); return; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseStmtAsm.cpp
//===---- ParseStmtAsm.cpp - Assembly Statement Parser --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements parsing for GCC and Microsoft inline assembly. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "RAIIObjectsForParser.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/SmallString.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCParser/MCAsmParser.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MCTargetAsmParser.h" #include "llvm/MC/MCTargetOptions.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" using namespace clang; #if 0 // HLSL Change - disable this block to avoid having to build/link llvmMC namespace { class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback { Parser &TheParser; SourceLocation AsmLoc; StringRef AsmString; /// The tokens we streamed into AsmString and handed off to MC. ArrayRef<Token> AsmToks; /// The offset of each token in AsmToks within AsmString. ArrayRef<unsigned> AsmTokOffsets; public: ClangAsmParserCallback(Parser &P, SourceLocation Loc, StringRef AsmString, ArrayRef<Token> Toks, ArrayRef<unsigned> Offsets) : TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks), AsmTokOffsets(Offsets) { assert(AsmToks.size() == AsmTokOffsets.size()); } void *LookupInlineAsmIdentifier(StringRef &LineBuf, llvm::InlineAsmIdentifierInfo &Info, bool IsUnevaluatedContext) override { // Collect the desired tokens. SmallVector<Token, 16> LineToks; const Token *FirstOrigToken = nullptr; findTokensForString(LineBuf, LineToks, FirstOrigToken); unsigned NumConsumedToks; ExprResult Result = TheParser.ParseMSAsmIdentifier( LineToks, NumConsumedToks, &Info, IsUnevaluatedContext); // If we consumed the entire line, tell MC that. // Also do this if we consumed nothing as a way of reporting failure. if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) { // By not modifying LineBuf, we're implicitly consuming it all. // Otherwise, consume up to the original tokens. } else { assert(FirstOrigToken && "not using original tokens?"); // Since we're using original tokens, apply that offset. assert(FirstOrigToken[NumConsumedToks].getLocation() == LineToks[NumConsumedToks].getLocation()); unsigned FirstIndex = FirstOrigToken - AsmToks.begin(); unsigned LastIndex = FirstIndex + NumConsumedToks - 1; // The total length we've consumed is the relative offset // of the last token we consumed plus its length. unsigned TotalOffset = (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() - AsmTokOffsets[FirstIndex]); LineBuf = LineBuf.substr(0, TotalOffset); } // Initialize the "decl" with the lookup result. Info.OpDecl = static_cast<void *>(Result.get()); return Info.OpDecl; } StringRef LookupInlineAsmLabel(StringRef Identifier, llvm::SourceMgr &LSM, llvm::SMLoc Location, bool Create) override { SourceLocation Loc = translateLocation(LSM, Location); LabelDecl *Label = TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create); return Label->getMSAsmLabel(); } bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset) override { return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset, AsmLoc); } static void DiagHandlerCallback(const llvm::SMDiagnostic &D, void *Context) { ((ClangAsmParserCallback *)Context)->handleDiagnostic(D); } private: /// Collect the appropriate tokens for the given string. void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks, const Token *&FirstOrigToken) const { // For now, assert that the string we're working with is a substring // of what we gave to MC. This lets us use the original tokens. assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) && !std::less<const char *>()(AsmString.end(), Str.end())); // Try to find a token whose offset matches the first token. unsigned FirstCharOffset = Str.begin() - AsmString.begin(); const unsigned *FirstTokOffset = std::lower_bound( AsmTokOffsets.begin(), AsmTokOffsets.end(), FirstCharOffset); // For now, assert that the start of the string exactly // corresponds to the start of a token. assert(*FirstTokOffset == FirstCharOffset); // Use all the original tokens for this line. (We assume the // end of the line corresponds cleanly to a token break.) unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin(); FirstOrigToken = &AsmToks[FirstTokIndex]; unsigned LastCharOffset = Str.end() - AsmString.begin(); for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) { if (AsmTokOffsets[i] >= LastCharOffset) break; TempToks.push_back(AsmToks[i]); } } SourceLocation translateLocation(const llvm::SourceMgr &LSM, llvm::SMLoc SMLoc) { // Compute an offset into the inline asm buffer. // FIXME: This isn't right if .macro is involved (but hopefully, no // real-world code does that). const llvm::MemoryBuffer *LBuf = LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc)); unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart(); // Figure out which token that offset points into. const unsigned *TokOffsetPtr = std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset); unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin(); unsigned TokOffset = *TokOffsetPtr; // If we come up with an answer which seems sane, use it; otherwise, // just point at the __asm keyword. // FIXME: Assert the answer is sane once we handle .macro correctly. SourceLocation Loc = AsmLoc; if (TokIndex < AsmToks.size()) { const Token &Tok = AsmToks[TokIndex]; Loc = Tok.getLocation(); Loc = Loc.getLocWithOffset(Offset - TokOffset); } return Loc; } void handleDiagnostic(const llvm::SMDiagnostic &D) { const llvm::SourceMgr &LSM = *D.getSourceMgr(); SourceLocation Loc = translateLocation(LSM, D.getLoc()); TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage(); } }; } #endif // HLSL Change - disable this block to avoid having to build/link llvmMC /// Parse an identifier in an MS-style inline assembly block. /// /// \param CastInfo - a void* so that we don't have to teach Parser.h /// about the actual type. ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, void *CastInfo, bool IsUnevaluatedContext) { assert(!getLangOpts().HLSL && "no MS assembly support in HLSL"); // HLSL Change llvm::InlineAsmIdentifierInfo &Info = *(llvm::InlineAsmIdentifierInfo *)CastInfo; // Push a fake token on the end so that we don't overrun the token // stream. We use ';' because it expression-parsing should never // overrun it. const tok::TokenKind EndOfStream = tok::semi; Token EndOfStreamTok; EndOfStreamTok.startToken(); EndOfStreamTok.setKind(EndOfStream); LineToks.push_back(EndOfStreamTok); // Also copy the current token over. LineToks.push_back(Tok); PP.EnterTokenStream(LineToks.begin(), LineToks.size(), /*disable macros*/ true, /*owns tokens*/ false); // Clear the current token and advance to the first token in LineToks. ConsumeAnyToken(); // Parse an optional scope-specifier if we're in C++. CXXScopeSpec SS; if (getLangOpts().CPlusPlus) { ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); } // Require an identifier here. SourceLocation TemplateKWLoc; UnqualifiedId Id; bool Invalid = ParseUnqualifiedId(SS, /*EnteringContext=*/false, /*AllowDestructorName=*/false, /*AllowConstructorName=*/false, /*ObjectType=*/ParsedType(), TemplateKWLoc, Id); // Figure out how many tokens we are into LineToks. unsigned LineIndex = 0; if (Tok.is(EndOfStream)) { LineIndex = LineToks.size() - 2; } else { while (LineToks[LineIndex].getLocation() != Tok.getLocation()) { LineIndex++; assert(LineIndex < LineToks.size() - 2); // we added two extra tokens } } // If we've run into the poison token we inserted before, or there // was a parsing error, then claim the entire line. if (Invalid || Tok.is(EndOfStream)) { NumLineToksConsumed = LineToks.size() - 2; } else { // Otherwise, claim up to the start of the next token. NumLineToksConsumed = LineIndex; } // Finally, restore the old parsing state by consuming all the tokens we // staged before, implicitly killing off the token-lexer we pushed. for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) { ConsumeAnyToken(); } assert(Tok.is(EndOfStream)); ConsumeToken(); // Leave LineToks in its original state. LineToks.pop_back(); LineToks.pop_back(); // Perform the lookup. return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info, IsUnevaluatedContext); } #if 0 // HLSL Change Start - disable this block to avoid having to build/link llvmMC /// Turn a sequence of our tokens back into a string that we can hand /// to the MC asm parser. static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc, ArrayRef<Token> AsmToks, SmallVectorImpl<unsigned> &TokOffsets, SmallString<512> &Asm) { assert(!AsmToks.empty() && "Didn't expect an empty AsmToks!"); // Is this the start of a new assembly statement? bool isNewStatement = true; for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) { const Token &Tok = AsmToks[i]; // Start each new statement with a newline and a tab. if (!isNewStatement && (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) { Asm += "\n\t"; isNewStatement = true; } // Preserve the existence of leading whitespace except at the // start of a statement. if (!isNewStatement && Tok.hasLeadingSpace()) Asm += ' '; // Remember the offset of this token. TokOffsets.push_back(Asm.size()); // Don't actually write '__asm' into the assembly stream. if (Tok.is(tok::kw_asm)) { // Complain about __asm at the end of the stream. if (i + 1 == e) { PP.Diag(AsmLoc, diag::err_asm_empty); return true; } continue; } // Append the spelling of the token. SmallString<32> SpellingBuffer; bool SpellingInvalid = false; Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid); assert(!SpellingInvalid && "spelling was invalid after correct parse?"); // We are no longer at the start of a statement. isNewStatement = false; } // Ensure that the buffer is null-terminated. Asm.push_back('\0'); Asm.pop_back(); assert(TokOffsets.size() == AsmToks.size()); return false; } #endif // HLSL Change End - disable this block to avoid having to build/link llvmMC /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled, /// this routine is called to collect the tokens for an MS asm statement. /// /// [MS] ms-asm-statement: /// ms-asm-block /// ms-asm-block ms-asm-statement /// /// [MS] ms-asm-block: /// '__asm' ms-asm-line '\n' /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt] /// /// [MS] ms-asm-instruction-block /// ms-asm-line /// ms-asm-line '\n' ms-asm-instruction-block /// StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) { assert(!getLangOpts().HLSL && "no MS assembly support in HLSL"); // HLSL Change #if 1 // HLSL Change - disable this block to avoid having to build/link llvmMC return StmtResult(); #else SourceManager &SrcMgr = PP.getSourceManager(); SourceLocation EndLoc = AsmLoc; SmallVector<Token, 4> AsmToks; bool SingleLineMode = true; unsigned BraceNesting = 0; unsigned short savedBraceCount = BraceCount; bool InAsmComment = false; FileID FID; unsigned LineNo = 0; unsigned NumTokensRead = 0; SmallVector<SourceLocation, 4> LBraceLocs; bool SkippedStartOfLine = false; if (Tok.is(tok::l_brace)) { // Braced inline asm: consume the opening brace. SingleLineMode = false; BraceNesting = 1; EndLoc = ConsumeBrace(); LBraceLocs.push_back(EndLoc); ++NumTokensRead; } else { // Single-line inline asm; compute which line it is on. std::pair<FileID, unsigned> ExpAsmLoc = SrcMgr.getDecomposedExpansionLoc(EndLoc); FID = ExpAsmLoc.first; LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second); LBraceLocs.push_back(SourceLocation()); } SourceLocation TokLoc = Tok.getLocation(); do { // If we hit EOF, we're done, period. if (isEofOrEom()) break; if (!InAsmComment && Tok.is(tok::l_brace)) { // Consume the opening brace. SkippedStartOfLine = Tok.isAtStartOfLine(); EndLoc = ConsumeBrace(); BraceNesting++; LBraceLocs.push_back(EndLoc); TokLoc = Tok.getLocation(); ++NumTokensRead; continue; } else if (!InAsmComment && Tok.is(tok::semi)) { // A semicolon in an asm is the start of a comment. InAsmComment = true; if (!SingleLineMode) { // Compute which line the comment is on. std::pair<FileID, unsigned> ExpSemiLoc = SrcMgr.getDecomposedExpansionLoc(TokLoc); FID = ExpSemiLoc.first; LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second); } } else if (SingleLineMode || InAsmComment) { // If end-of-line is significant, check whether this token is on a // new line. std::pair<FileID, unsigned> ExpLoc = SrcMgr.getDecomposedExpansionLoc(TokLoc); if (ExpLoc.first != FID || SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) { // If this is a single-line __asm, we're done, except if the next // line begins with an __asm too, in which case we finish a comment // if needed and then keep processing the next line as a single // line __asm. bool isAsm = Tok.is(tok::kw_asm); if (SingleLineMode && !isAsm) break; // We're no longer in a comment. InAsmComment = false; if (isAsm) { LineNo = SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second); SkippedStartOfLine = Tok.isAtStartOfLine(); } } else if (!InAsmComment && Tok.is(tok::r_brace)) { // In MSVC mode, braces only participate in brace matching and // separating the asm statements. This is an intentional // departure from the Apple gcc behavior. if (!BraceNesting) break; } } if (!InAsmComment && BraceNesting && Tok.is(tok::r_brace) && BraceCount == (savedBraceCount + BraceNesting)) { // Consume the closing brace. SkippedStartOfLine = Tok.isAtStartOfLine(); EndLoc = ConsumeBrace(); BraceNesting--; // Finish if all of the opened braces in the inline asm section were // consumed. if (BraceNesting == 0 && !SingleLineMode) break; else { LBraceLocs.pop_back(); TokLoc = Tok.getLocation(); ++NumTokensRead; continue; } } // Consume the next token; make sure we don't modify the brace count etc. // if we are in a comment. EndLoc = TokLoc; if (InAsmComment) PP.Lex(Tok); else { // Set the token as the start of line if we skipped the original start // of line token in case it was a nested brace. if (SkippedStartOfLine) Tok.setFlag(Token::StartOfLine); AsmToks.push_back(Tok); ConsumeAnyToken(); } TokLoc = Tok.getLocation(); ++NumTokensRead; SkippedStartOfLine = false; } while (1); if (BraceNesting && BraceCount != savedBraceCount) { // __asm without closing brace (this can happen at EOF). for (unsigned i = 0; i < BraceNesting; ++i) { Diag(Tok, diag::err_expected) << tok::r_brace; Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace; LBraceLocs.pop_back(); } return StmtError(); } else if (NumTokensRead == 0) { // Empty __asm. Diag(Tok, diag::err_expected) << tok::l_brace; return StmtError(); } // Okay, prepare to use MC to parse the assembly. SmallVector<StringRef, 4> ConstraintRefs; SmallVector<Expr *, 4> Exprs; SmallVector<StringRef, 4> ClobberRefs; // We need an actual supported target. const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple(); llvm::Triple::ArchType ArchTy = TheTriple.getArch(); const std::string &TT = TheTriple.getTriple(); const llvm::Target *TheTarget = nullptr; bool UnsupportedArch = (ArchTy != llvm::Triple::x86 && ArchTy != llvm::Triple::x86_64); if (UnsupportedArch) { Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName(); } else { std::string Error; TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error); if (!TheTarget) Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error; } assert(!LBraceLocs.empty() && "Should have at least one location here"); // If we don't support assembly, or the assembly is empty, we don't // need to instantiate the AsmParser, etc. if (!TheTarget || AsmToks.empty()) { return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, StringRef(), /*NumOutputs*/ 0, /*NumInputs*/ 0, ConstraintRefs, ClobberRefs, Exprs, EndLoc); } // Expand the tokens into a string buffer. SmallString<512> AsmString; SmallVector<unsigned, 8> TokOffsets; if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString)) return StmtError(); std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT)); std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT)); // Get the instruction descriptor. std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo()); std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo()); std::unique_ptr<llvm::MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(TT, "", "")); llvm::SourceMgr TempSrcMgr; llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr); MOFI->InitMCObjectFileInfo(TheTriple, llvm::Reloc::Default, llvm::CodeModel::Default, Ctx); std::unique_ptr<llvm::MemoryBuffer> Buffer = llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>"); // Tell SrcMgr about this buffer, which is what the parser will pick up. TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc()); std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx)); std::unique_ptr<llvm::MCAsmParser> Parser( createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI)); // FIXME: init MCOptions from sanitizer flags here. llvm::MCTargetOptions MCOptions; std::unique_ptr<llvm::MCTargetAsmParser> TargetParser( TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions)); std::unique_ptr<llvm::MCInstPrinter> IP( TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI)); // Change to the Intel dialect. Parser->setAssemblerDialect(1); Parser->setTargetParser(*TargetParser.get()); Parser->setParsingInlineAsm(true); TargetParser->setParsingInlineAsm(true); ClangAsmParserCallback Callback(*this, AsmLoc, AsmString, AsmToks, TokOffsets); TargetParser->setSemaCallback(&Callback); TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback, &Callback); unsigned NumOutputs; unsigned NumInputs; std::string AsmStringIR; SmallVector<std::pair<void *, bool>, 4> OpExprs; SmallVector<std::string, 4> Constraints; SmallVector<std::string, 4> Clobbers; if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR, NumOutputs, NumInputs, OpExprs, Constraints, Clobbers, MII.get(), IP.get(), Callback)) return StmtError(); // Filter out "fpsw". Clang doesn't accept it, and it always lists flags and // fpsr as clobbers. auto End = std::remove(Clobbers.begin(), Clobbers.end(), "fpsw"); Clobbers.erase(End, Clobbers.end()); // Build the vector of clobber StringRefs. ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end()); // Recast the void pointers and build the vector of constraint StringRefs. unsigned NumExprs = NumOutputs + NumInputs; ConstraintRefs.resize(NumExprs); Exprs.resize(NumExprs); for (unsigned i = 0, e = NumExprs; i != e; ++i) { Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first); if (!OpExpr) return StmtError(); // Need address of variable. if (OpExprs[i].second) OpExpr = Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr).get(); ConstraintRefs[i] = StringRef(Constraints[i]); Exprs[i] = OpExpr; } // FIXME: We should be passing source locations for better diagnostics. return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR, NumOutputs, NumInputs, ConstraintRefs, ClobberRefs, Exprs, EndLoc); #endif // HLSL Change } /// ParseAsmStatement - Parse a GNU extended asm statement. /// asm-statement: /// gnu-asm-statement /// ms-asm-statement /// /// [GNU] gnu-asm-statement: /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';' /// /// [GNU] asm-argument: /// asm-string-literal /// asm-string-literal ':' asm-operands[opt] /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt] /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt] /// ':' asm-clobbers /// /// [GNU] asm-clobbers: /// asm-string-literal /// asm-clobbers ',' asm-string-literal /// StmtResult Parser::ParseAsmStatement(bool &msAsm) { assert(!getLangOpts().HLSL && "no GNU assembly support in HLSL"); // HLSL Change assert(Tok.is(tok::kw_asm) && "Not an asm stmt"); SourceLocation AsmLoc = ConsumeToken(); if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) && !isTypeQualifier()) { msAsm = true; return ParseMicrosoftAsmStatement(AsmLoc); } DeclSpec DS(AttrFactory); SourceLocation Loc = Tok.getLocation(); ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed); // GNU asms accept, but warn, about type-qualifiers other than volatile. if (DS.getTypeQualifiers() & DeclSpec::TQ_const) Diag(Loc, diag::w_asm_qualifier_ignored) << "const"; if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict"; // FIXME: Once GCC supports _Atomic, check whether it permits it here. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic"; // Remember if this was a volatile asm. bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile; if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen_after) << "asm"; SkipUntil(tok::r_paren, StopAtSemi); return StmtError(); } BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); ExprResult AsmString(ParseAsmStringLiteral()); // Check if GNU-style InlineAsm is disabled. // Error on anything other than empty string. if (!(getLangOpts().GNUAsm || AsmString.isInvalid())) { const auto *SL = cast<StringLiteral>(AsmString.get()); if (!SL->getString().trim().empty()) Diag(Loc, diag::err_gnu_inline_asm_disabled); } if (AsmString.isInvalid()) { // Consume up to and including the closing paren. T.skipToEnd(); return StmtError(); } SmallVector<IdentifierInfo *, 4> Names; ExprVector Constraints; ExprVector Exprs; ExprVector Clobbers; if (Tok.is(tok::r_paren)) { // We have a simple asm expression like 'asm("foo")'. T.consumeClose(); return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile, /*NumOutputs*/ 0, /*NumInputs*/ 0, nullptr, Constraints, Exprs, AsmString.get(), Clobbers, T.getCloseLocation()); } // Parse Outputs, if present. bool AteExtraColon = false; if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) { // In C++ mode, parse "::" like ": :". AteExtraColon = Tok.is(tok::coloncolon); ConsumeToken(); if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs)) return StmtError(); } unsigned NumOutputs = Names.size(); // Parse Inputs, if present. if (AteExtraColon || Tok.is(tok::colon) || Tok.is(tok::coloncolon)) { // In C++ mode, parse "::" like ": :". if (AteExtraColon) AteExtraColon = false; else { AteExtraColon = Tok.is(tok::coloncolon); ConsumeToken(); } if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs)) return StmtError(); } assert(Names.size() == Constraints.size() && Constraints.size() == Exprs.size() && "Input operand size mismatch!"); unsigned NumInputs = Names.size() - NumOutputs; // Parse the clobbers, if present. if (AteExtraColon || Tok.is(tok::colon)) { if (!AteExtraColon) ConsumeToken(); // Parse the asm-string list for clobbers if present. if (Tok.isNot(tok::r_paren)) { while (1) { ExprResult Clobber(ParseAsmStringLiteral()); if (Clobber.isInvalid()) break; Clobbers.push_back(Clobber.get()); if (!TryConsumeToken(tok::comma)) break; } } } T.consumeClose(); return Actions.ActOnGCCAsmStmt( AsmLoc, false, isVolatile, NumOutputs, NumInputs, Names.data(), Constraints, Exprs, AsmString.get(), Clobbers, T.getCloseLocation()); } /// ParseAsmOperands - Parse the asm-operands production as used by /// asm-statement, assuming the leading ':' token was eaten. /// /// [GNU] asm-operands: /// asm-operand /// asm-operands ',' asm-operand /// /// [GNU] asm-operand: /// asm-string-literal '(' expression ')' /// '[' identifier ']' asm-string-literal '(' expression ')' /// // // FIXME: Avoid unnecessary std::string trashing. bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs) { assert(!getLangOpts().HLSL && "no assembly support in HLSL"); // HLSL Change // 'asm-operands' isn't present? if (!isTokenStringLiteral() && Tok.isNot(tok::l_square)) return false; while (1) { // Read the [id] if present. if (Tok.is(tok::l_square)) { BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; SkipUntil(tok::r_paren, StopAtSemi); return true; } IdentifierInfo *II = Tok.getIdentifierInfo(); ConsumeToken(); Names.push_back(II); T.consumeClose(); } else Names.push_back(nullptr); ExprResult Constraint(ParseAsmStringLiteral()); if (Constraint.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return true; } Constraints.push_back(Constraint.get()); if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen_after) << "asm operand"; SkipUntil(tok::r_paren, StopAtSemi); return true; } // Read the parenthesized expression. BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression()); T.consumeClose(); if (Res.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return true; } Exprs.push_back(Res.get()); // Eat the comma and continue parsing if it exists. if (!TryConsumeToken(tok::comma)) return false; } }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParsePragma.cpp
//===--- ParsePragma.cpp - Language specific pragma parsing ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the language specific #pragma handlers. // //===----------------------------------------------------------------------===// #include "RAIIObjectsForParser.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Sema/LoopHint.h" #include "clang/Sema/Scope.h" #include "llvm/ADT/StringSwitch.h" using namespace clang; namespace { struct PragmaAlignHandler : public PragmaHandler { explicit PragmaAlignHandler() : PragmaHandler("align") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaGCCVisibilityHandler : public PragmaHandler { explicit PragmaGCCVisibilityHandler() : PragmaHandler("visibility") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaOptionsHandler : public PragmaHandler { explicit PragmaOptionsHandler() : PragmaHandler("options") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaPackHandler : public PragmaHandler { explicit PragmaPackHandler() : PragmaHandler("pack") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaMSStructHandler : public PragmaHandler { explicit PragmaMSStructHandler() : PragmaHandler("ms_struct") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaUnusedHandler : public PragmaHandler { PragmaUnusedHandler() : PragmaHandler("unused") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaWeakHandler : public PragmaHandler { explicit PragmaWeakHandler() : PragmaHandler("weak") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaRedefineExtnameHandler : public PragmaHandler { explicit PragmaRedefineExtnameHandler() : PragmaHandler("redefine_extname") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaOpenCLExtensionHandler : public PragmaHandler { PragmaOpenCLExtensionHandler() : PragmaHandler("EXTENSION") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaFPContractHandler : public PragmaHandler { PragmaFPContractHandler() : PragmaHandler("FP_CONTRACT") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaNoOpenMPHandler : public PragmaHandler { PragmaNoOpenMPHandler() : PragmaHandler("omp") { } void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaOpenMPHandler : public PragmaHandler { PragmaOpenMPHandler() : PragmaHandler("omp") { } void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; /// PragmaCommentHandler - "\#pragma comment ...". struct PragmaCommentHandler : public PragmaHandler { PragmaCommentHandler(Sema &Actions) : PragmaHandler("comment"), Actions(Actions) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; private: Sema &Actions; }; struct PragmaDetectMismatchHandler : public PragmaHandler { PragmaDetectMismatchHandler(Sema &Actions) : PragmaHandler("detect_mismatch"), Actions(Actions) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; private: Sema &Actions; }; struct PragmaMSPointersToMembers : public PragmaHandler { explicit PragmaMSPointersToMembers() : PragmaHandler("pointers_to_members") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaMSVtorDisp : public PragmaHandler { explicit PragmaMSVtorDisp() : PragmaHandler("vtordisp") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaMSPragma : public PragmaHandler { explicit PragmaMSPragma(const char *name) : PragmaHandler(name) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; /// PragmaOptimizeHandler - "\#pragma clang optimize on/off". struct PragmaOptimizeHandler : public PragmaHandler { PragmaOptimizeHandler(Sema &S) : PragmaHandler("optimize"), Actions(S) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; private: Sema &Actions; }; struct PragmaLoopHintHandler : public PragmaHandler { PragmaLoopHintHandler() : PragmaHandler("loop") {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaUnrollHintHandler : public PragmaHandler { PragmaUnrollHintHandler(const char *name) : PragmaHandler(name) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; }; struct PragmaPackMatrixHandler : public PragmaHandler { PragmaPackMatrixHandler(Sema &S) : PragmaHandler("pack_matrix"), Actions(S) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override; private: Sema &Actions; }; } // end namespace void Parser::initializePragmaHandlers() { if (!getLangOpts().HLSL) { // HLSL Change // HLSL Note - Considering adding alignment support AlignHandler.reset(new PragmaAlignHandler()); PP.AddPragmaHandler(AlignHandler.get()); GCCVisibilityHandler.reset(new PragmaGCCVisibilityHandler()); PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get()); OptionsHandler.reset(new PragmaOptionsHandler()); PP.AddPragmaHandler(OptionsHandler.get()); PackHandler.reset(new PragmaPackHandler()); PP.AddPragmaHandler(PackHandler.get()); MSStructHandler.reset(new PragmaMSStructHandler()); PP.AddPragmaHandler(MSStructHandler.get()); UnusedHandler.reset(new PragmaUnusedHandler()); PP.AddPragmaHandler(UnusedHandler.get()); WeakHandler.reset(new PragmaWeakHandler()); PP.AddPragmaHandler(WeakHandler.get()); RedefineExtnameHandler.reset(new PragmaRedefineExtnameHandler()); PP.AddPragmaHandler(RedefineExtnameHandler.get()); FPContractHandler.reset(new PragmaFPContractHandler()); PP.AddPragmaHandler("STDC", FPContractHandler.get()); if (getLangOpts().OpenCL) { OpenCLExtensionHandler.reset(new PragmaOpenCLExtensionHandler()); PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get()); PP.AddPragmaHandler("OPENCL", FPContractHandler.get()); } if (getLangOpts().OpenMP) OpenMPHandler.reset(new PragmaOpenMPHandler()); else OpenMPHandler.reset(new PragmaNoOpenMPHandler()); PP.AddPragmaHandler(OpenMPHandler.get()); if (getLangOpts().MicrosoftExt || getTargetInfo().getTriple().isPS4()) { MSCommentHandler.reset(new PragmaCommentHandler(Actions)); PP.AddPragmaHandler(MSCommentHandler.get()); } if (getLangOpts().MicrosoftExt) { MSDetectMismatchHandler.reset(new PragmaDetectMismatchHandler(Actions)); PP.AddPragmaHandler(MSDetectMismatchHandler.get()); MSPointersToMembers.reset(new PragmaMSPointersToMembers()); PP.AddPragmaHandler(MSPointersToMembers.get()); MSVtorDisp.reset(new PragmaMSVtorDisp()); PP.AddPragmaHandler(MSVtorDisp.get()); MSInitSeg.reset(new PragmaMSPragma("init_seg")); PP.AddPragmaHandler(MSInitSeg.get()); MSDataSeg.reset(new PragmaMSPragma("data_seg")); PP.AddPragmaHandler(MSDataSeg.get()); MSBSSSeg.reset(new PragmaMSPragma("bss_seg")); PP.AddPragmaHandler(MSBSSSeg.get()); MSConstSeg.reset(new PragmaMSPragma("const_seg")); PP.AddPragmaHandler(MSConstSeg.get()); MSCodeSeg.reset(new PragmaMSPragma("code_seg")); PP.AddPragmaHandler(MSCodeSeg.get()); MSSection.reset(new PragmaMSPragma("section")); PP.AddPragmaHandler(MSSection.get()); } // HLSL Note - Considering adding alignment support OptimizeHandler.reset(new PragmaOptimizeHandler(Actions)); PP.AddPragmaHandler("clang", OptimizeHandler.get()); // HLSL Note - Considering adding alignment support LoopHintHandler.reset(new PragmaLoopHintHandler()); PP.AddPragmaHandler("clang", LoopHintHandler.get()); UnrollHintHandler.reset(new PragmaUnrollHintHandler("unroll")); PP.AddPragmaHandler(UnrollHintHandler.get()); NoUnrollHintHandler.reset(new PragmaUnrollHintHandler("nounroll")); PP.AddPragmaHandler(NoUnrollHintHandler.get()); } // HLSL Change, matching HLSL check to remove pragma processing else { // HLSL Change Begin - packmatrix. // The pointer ownership goes to PP as soon as we do the call, // which deletes it in its destructor unless it is removed & deleted via resetPragmaHandlers pPackMatrixHandler = new PragmaPackMatrixHandler(Actions); PP.AddPragmaHandler(pPackMatrixHandler); // HLSL Change End. } } void Parser::resetPragmaHandlers() { if (!getLangOpts().HLSL) { // HLSL Change - open conditional for skipping pragmas // Remove the pragma handlers we installed. PP.RemovePragmaHandler(AlignHandler.get()); AlignHandler.reset(); PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get()); GCCVisibilityHandler.reset(); PP.RemovePragmaHandler(OptionsHandler.get()); OptionsHandler.reset(); PP.RemovePragmaHandler(PackHandler.get()); PackHandler.reset(); PP.RemovePragmaHandler(MSStructHandler.get()); MSStructHandler.reset(); PP.RemovePragmaHandler(UnusedHandler.get()); UnusedHandler.reset(); PP.RemovePragmaHandler(WeakHandler.get()); WeakHandler.reset(); PP.RemovePragmaHandler(RedefineExtnameHandler.get()); RedefineExtnameHandler.reset(); if (getLangOpts().OpenCL) { PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get()); OpenCLExtensionHandler.reset(); PP.RemovePragmaHandler("OPENCL", FPContractHandler.get()); } PP.RemovePragmaHandler(OpenMPHandler.get()); OpenMPHandler.reset(); if (getLangOpts().MicrosoftExt || getTargetInfo().getTriple().isPS4()) { PP.RemovePragmaHandler(MSCommentHandler.get()); MSCommentHandler.reset(); } if (getLangOpts().MicrosoftExt) { PP.RemovePragmaHandler(MSDetectMismatchHandler.get()); MSDetectMismatchHandler.reset(); PP.RemovePragmaHandler(MSPointersToMembers.get()); MSPointersToMembers.reset(); PP.RemovePragmaHandler(MSVtorDisp.get()); MSVtorDisp.reset(); PP.RemovePragmaHandler(MSInitSeg.get()); MSInitSeg.reset(); PP.RemovePragmaHandler(MSDataSeg.get()); MSDataSeg.reset(); PP.RemovePragmaHandler(MSBSSSeg.get()); MSBSSSeg.reset(); PP.RemovePragmaHandler(MSConstSeg.get()); MSConstSeg.reset(); PP.RemovePragmaHandler(MSCodeSeg.get()); MSCodeSeg.reset(); PP.RemovePragmaHandler(MSSection.get()); MSSection.reset(); } PP.RemovePragmaHandler("STDC", FPContractHandler.get()); FPContractHandler.reset(); PP.RemovePragmaHandler("clang", OptimizeHandler.get()); OptimizeHandler.reset(); PP.RemovePragmaHandler("clang", LoopHintHandler.get()); LoopHintHandler.reset(); PP.RemovePragmaHandler(UnrollHintHandler.get()); UnrollHintHandler.reset(); PP.RemovePragmaHandler(NoUnrollHintHandler.get()); NoUnrollHintHandler.reset(); } // HLSL Change - close conditional for skipping pragmas else { // HLSL Change Begin - packmatrix. PP.RemovePragmaHandler(pPackMatrixHandler); delete pPackMatrixHandler; pPackMatrixHandler = nullptr; // HLSL Change End. } } /// \brief Handle the annotation token produced for #pragma unused(...) /// /// Each annot_pragma_unused is followed by the argument token so e.g. /// "#pragma unused(x,y)" becomes: /// annot_pragma_unused 'x' annot_pragma_unused 'y' void Parser::HandlePragmaUnused() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_unused)); SourceLocation UnusedLoc = ConsumeToken(); Actions.ActOnPragmaUnused(Tok, getCurScope(), UnusedLoc); ConsumeToken(); // The argument token. } void Parser::HandlePragmaVisibility() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_vis)); const IdentifierInfo *VisType = static_cast<IdentifierInfo *>(Tok.getAnnotationValue()); SourceLocation VisLoc = ConsumeToken(); Actions.ActOnPragmaVisibility(VisType, VisLoc); } struct PragmaPackInfo { Sema::PragmaPackKind Kind; IdentifierInfo *Name; Token Alignment; SourceLocation LParenLoc; SourceLocation RParenLoc; }; void Parser::HandlePragmaPack() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_pack)); PragmaPackInfo *Info = static_cast<PragmaPackInfo *>(Tok.getAnnotationValue()); SourceLocation PragmaLoc = ConsumeToken(); ExprResult Alignment; if (Info->Alignment.is(tok::numeric_constant)) { Alignment = Actions.ActOnNumericConstant(Info->Alignment); if (Alignment.isInvalid()) return; } Actions.ActOnPragmaPack(Info->Kind, Info->Name, Alignment.get(), PragmaLoc, Info->LParenLoc, Info->RParenLoc); } void Parser::HandlePragmaMSStruct() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_msstruct)); Sema::PragmaMSStructKind Kind = static_cast<Sema::PragmaMSStructKind>( reinterpret_cast<uintptr_t>(Tok.getAnnotationValue())); Actions.ActOnPragmaMSStruct(Kind); ConsumeToken(); // The annotation token. } void Parser::HandlePragmaAlign() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_align)); Sema::PragmaOptionsAlignKind Kind = static_cast<Sema::PragmaOptionsAlignKind>( reinterpret_cast<uintptr_t>(Tok.getAnnotationValue())); SourceLocation PragmaLoc = ConsumeToken(); Actions.ActOnPragmaOptionsAlign(Kind, PragmaLoc); } void Parser::HandlePragmaWeak() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_weak)); SourceLocation PragmaLoc = ConsumeToken(); Actions.ActOnPragmaWeakID(Tok.getIdentifierInfo(), PragmaLoc, Tok.getLocation()); ConsumeToken(); // The weak name. } void Parser::HandlePragmaWeakAlias() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_weakalias)); SourceLocation PragmaLoc = ConsumeToken(); IdentifierInfo *WeakName = Tok.getIdentifierInfo(); SourceLocation WeakNameLoc = Tok.getLocation(); ConsumeToken(); IdentifierInfo *AliasName = Tok.getIdentifierInfo(); SourceLocation AliasNameLoc = Tok.getLocation(); ConsumeToken(); Actions.ActOnPragmaWeakAlias(WeakName, AliasName, PragmaLoc, WeakNameLoc, AliasNameLoc); } void Parser::HandlePragmaRedefineExtname() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_redefine_extname)); SourceLocation RedefLoc = ConsumeToken(); IdentifierInfo *RedefName = Tok.getIdentifierInfo(); SourceLocation RedefNameLoc = Tok.getLocation(); ConsumeToken(); IdentifierInfo *AliasName = Tok.getIdentifierInfo(); SourceLocation AliasNameLoc = Tok.getLocation(); ConsumeToken(); Actions.ActOnPragmaRedefineExtname(RedefName, AliasName, RedefLoc, RedefNameLoc, AliasNameLoc); } void Parser::HandlePragmaFPContract() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_fp_contract)); tok::OnOffSwitch OOS = static_cast<tok::OnOffSwitch>( reinterpret_cast<uintptr_t>(Tok.getAnnotationValue())); Actions.ActOnPragmaFPContract(OOS); ConsumeToken(); // The annotation token. } StmtResult Parser::HandlePragmaCaptured() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_captured)); ConsumeToken(); if (Tok.isNot(tok::l_brace)) { PP.Diag(Tok, diag::err_expected) << tok::l_brace; return StmtError(); } SourceLocation Loc = Tok.getLocation(); ParseScope CapturedRegionScope(this, Scope::FnScope | Scope::DeclScope); Actions.ActOnCapturedRegionStart(Loc, getCurScope(), CR_Default, /*NumParams=*/1); StmtResult R = ParseCompoundStatement(); CapturedRegionScope.Exit(); if (R.isInvalid()) { Actions.ActOnCapturedRegionError(); return StmtError(); } return Actions.ActOnCapturedRegionEnd(R.get()); } namespace { typedef llvm::PointerIntPair<IdentifierInfo *, 1, bool> OpenCLExtData; } void Parser::HandlePragmaOpenCLExtension() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_opencl_extension)); OpenCLExtData data = OpenCLExtData::getFromOpaqueValue(Tok.getAnnotationValue()); unsigned state = data.getInt(); IdentifierInfo *ename = data.getPointer(); SourceLocation NameLoc = Tok.getLocation(); ConsumeToken(); // The annotation token. OpenCLOptions &f = Actions.getOpenCLOptions(); // OpenCL 1.1 9.1: "The all variant sets the behavior for all extensions, // overriding all previously issued extension directives, but only if the // behavior is set to disable." if (state == 0 && ename->isStr("all")) { #define OPENCLEXT(nm) f.nm = 0; #include "clang/Basic/OpenCLExtensions.def" } #define OPENCLEXT(nm) else if (ename->isStr(#nm)) { f.nm = state; } #include "clang/Basic/OpenCLExtensions.def" else { PP.Diag(NameLoc, diag::warn_pragma_unknown_extension) << ename; return; } } void Parser::HandlePragmaMSPointersToMembers() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_ms_pointers_to_members)); LangOptions::PragmaMSPointersToMembersKind RepresentationMethod = static_cast<LangOptions::PragmaMSPointersToMembersKind>( reinterpret_cast<uintptr_t>(Tok.getAnnotationValue())); SourceLocation PragmaLoc = ConsumeToken(); // The annotation token. Actions.ActOnPragmaMSPointersToMembers(RepresentationMethod, PragmaLoc); } void Parser::HandlePragmaMSVtorDisp() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_ms_vtordisp)); uintptr_t Value = reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()); Sema::PragmaVtorDispKind Kind = static_cast<Sema::PragmaVtorDispKind>((Value >> 16) & 0xFFFF); MSVtorDispAttr::Mode Mode = MSVtorDispAttr::Mode(Value & 0xFFFF); SourceLocation PragmaLoc = ConsumeToken(); // The annotation token. Actions.ActOnPragmaMSVtorDisp(Kind, PragmaLoc, Mode); } void Parser::HandlePragmaMSPragma() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_ms_pragma)); // Grab the tokens out of the annotation and enter them into the stream. auto TheTokens = (std::pair<Token*, size_t> *)Tok.getAnnotationValue(); PP.EnterTokenStream(TheTokens->first, TheTokens->second, true, true); SourceLocation PragmaLocation = ConsumeToken(); // The annotation token. assert(Tok.isAnyIdentifier()); StringRef PragmaName = Tok.getIdentifierInfo()->getName(); PP.Lex(Tok); // pragma kind // Figure out which #pragma we're dealing with. The switch has no default // because lex shouldn't emit the annotation token for unrecognized pragmas. typedef bool (Parser::*PragmaHandler)(StringRef, SourceLocation); PragmaHandler Handler = llvm::StringSwitch<PragmaHandler>(PragmaName) .Case("data_seg", &Parser::HandlePragmaMSSegment) .Case("bss_seg", &Parser::HandlePragmaMSSegment) .Case("const_seg", &Parser::HandlePragmaMSSegment) .Case("code_seg", &Parser::HandlePragmaMSSegment) .Case("section", &Parser::HandlePragmaMSSection) .Case("init_seg", &Parser::HandlePragmaMSInitSeg); if (!(this->*Handler)(PragmaName, PragmaLocation)) { // Pragma handling failed, and has been diagnosed. Slurp up the tokens // until eof (really end of line) to prevent follow-on errors. while (Tok.isNot(tok::eof)) PP.Lex(Tok); PP.Lex(Tok); } } bool Parser::HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change if (Tok.isNot(tok::l_paren)) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName; return false; } PP.Lex(Tok); // ( // Parsing code for pragma section if (Tok.isNot(tok::string_literal)) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_section_name) << PragmaName; return false; } ExprResult StringResult = ParseStringLiteralExpression(); if (StringResult.isInvalid()) return false; // Already diagnosed. StringLiteral *SegmentName = cast<StringLiteral>(StringResult.get()); if (SegmentName->getCharByteWidth() != 1) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string) << PragmaName; return false; } int SectionFlags = ASTContext::PSF_Read; bool SectionFlagsAreDefault = true; while (Tok.is(tok::comma)) { PP.Lex(Tok); // , // Ignore "long" and "short". // They are undocumented, but widely used, section attributes which appear // to do nothing. if (Tok.is(tok::kw_long) || Tok.is(tok::kw_short)) { PP.Lex(Tok); // long/short continue; } if (!Tok.isAnyIdentifier()) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_action_or_r_paren) << PragmaName; return false; } ASTContext::PragmaSectionFlag Flag = llvm::StringSwitch<ASTContext::PragmaSectionFlag>( Tok.getIdentifierInfo()->getName()) .Case("read", ASTContext::PSF_Read) .Case("write", ASTContext::PSF_Write) .Case("execute", ASTContext::PSF_Execute) .Case("shared", ASTContext::PSF_Invalid) .Case("nopage", ASTContext::PSF_Invalid) .Case("nocache", ASTContext::PSF_Invalid) .Case("discard", ASTContext::PSF_Invalid) .Case("remove", ASTContext::PSF_Invalid) .Default(ASTContext::PSF_None); if (Flag == ASTContext::PSF_None || Flag == ASTContext::PSF_Invalid) { PP.Diag(PragmaLocation, Flag == ASTContext::PSF_None ? diag::warn_pragma_invalid_specific_action : diag::warn_pragma_unsupported_action) << PragmaName << Tok.getIdentifierInfo()->getName(); return false; } SectionFlags |= Flag; SectionFlagsAreDefault = false; PP.Lex(Tok); // Identifier } // If no section attributes are specified, the section will be marked as // read/write. if (SectionFlagsAreDefault) SectionFlags |= ASTContext::PSF_Write; if (Tok.isNot(tok::r_paren)) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName; return false; } PP.Lex(Tok); // ) if (Tok.isNot(tok::eof)) { PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol) << PragmaName; return false; } PP.Lex(Tok); // eof Actions.ActOnPragmaMSSection(PragmaLocation, SectionFlags, SegmentName); return true; } bool Parser::HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change if (Tok.isNot(tok::l_paren)) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName; return false; } PP.Lex(Tok); // ( Sema::PragmaMsStackAction Action = Sema::PSK_Reset; StringRef SlotLabel; if (Tok.isAnyIdentifier()) { StringRef PushPop = Tok.getIdentifierInfo()->getName(); if (PushPop == "push") Action = Sema::PSK_Push; else if (PushPop == "pop") Action = Sema::PSK_Pop; else { PP.Diag(PragmaLocation, diag::warn_pragma_expected_section_push_pop_or_name) << PragmaName; return false; } if (Action != Sema::PSK_Reset) { PP.Lex(Tok); // push | pop if (Tok.is(tok::comma)) { PP.Lex(Tok); // , // If we've got a comma, we either need a label or a string. if (Tok.isAnyIdentifier()) { SlotLabel = Tok.getIdentifierInfo()->getName(); PP.Lex(Tok); // identifier if (Tok.is(tok::comma)) PP.Lex(Tok); else if (Tok.isNot(tok::r_paren)) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc) << PragmaName; return false; } } } else if (Tok.isNot(tok::r_paren)) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc) << PragmaName; return false; } } } // Grab the string literal for our section name. StringLiteral *SegmentName = nullptr; if (Tok.isNot(tok::r_paren)) { if (Tok.isNot(tok::string_literal)) { unsigned DiagID = Action != Sema::PSK_Reset ? !SlotLabel.empty() ? diag::warn_pragma_expected_section_name : diag::warn_pragma_expected_section_label_or_name : diag::warn_pragma_expected_section_push_pop_or_name; PP.Diag(PragmaLocation, DiagID) << PragmaName; return false; } ExprResult StringResult = ParseStringLiteralExpression(); if (StringResult.isInvalid()) return false; // Already diagnosed. SegmentName = cast<StringLiteral>(StringResult.get()); if (SegmentName->getCharByteWidth() != 1) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string) << PragmaName; return false; } // Setting section "" has no effect if (SegmentName->getLength()) Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set); } if (Tok.isNot(tok::r_paren)) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName; return false; } PP.Lex(Tok); // ) if (Tok.isNot(tok::eof)) { PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol) << PragmaName; return false; } PP.Lex(Tok); // eof Actions.ActOnPragmaMSSeg(PragmaLocation, Action, SlotLabel, SegmentName, PragmaName); return true; } // #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} ) bool Parser::HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change if (getTargetInfo().getTriple().getEnvironment() != llvm::Triple::MSVC) { PP.Diag(PragmaLocation, diag::warn_pragma_init_seg_unsupported_target); return false; } if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen, PragmaName)) return false; // Parse either the known section names or the string section name. StringLiteral *SegmentName = nullptr; if (Tok.isAnyIdentifier()) { auto *II = Tok.getIdentifierInfo(); StringRef Section = llvm::StringSwitch<StringRef>(II->getName()) .Case("compiler", "\".CRT$XCC\"") .Case("lib", "\".CRT$XCL\"") .Case("user", "\".CRT$XCU\"") .Default(""); if (!Section.empty()) { // Pretend the user wrote the appropriate string literal here. Token Toks[1]; Toks[0].startToken(); Toks[0].setKind(tok::string_literal); Toks[0].setLocation(Tok.getLocation()); Toks[0].setLiteralData(Section.data()); Toks[0].setLength(Section.size()); SegmentName = cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get()); PP.Lex(Tok); } } else if (Tok.is(tok::string_literal)) { ExprResult StringResult = ParseStringLiteralExpression(); if (StringResult.isInvalid()) return false; SegmentName = cast<StringLiteral>(StringResult.get()); if (SegmentName->getCharByteWidth() != 1) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string) << PragmaName; return false; } // FIXME: Add support for the '[, func-name]' part of the pragma. } if (!SegmentName) { PP.Diag(PragmaLocation, diag::warn_pragma_expected_init_seg) << PragmaName; return false; } if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen, PragmaName) || ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol, PragmaName)) return false; Actions.ActOnPragmaMSInitSeg(PragmaLocation, SegmentName); return true; } struct PragmaLoopHintInfo { Token PragmaName; Token Option; Token *Toks; size_t TokSize; PragmaLoopHintInfo() : Toks(nullptr), TokSize(0) {} }; static std::string PragmaLoopHintString(Token PragmaName, Token Option) { std::string PragmaString; if (PragmaName.getIdentifierInfo()->getName() == "loop") { PragmaString = "clang loop "; PragmaString += Option.getIdentifierInfo()->getName(); } else { assert(PragmaName.getIdentifierInfo()->getName() == "unroll" && "Unexpected pragma name"); PragmaString = "unroll"; } return PragmaString; } bool Parser::HandlePragmaLoopHint(LoopHint &Hint) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::annot_pragma_loop_hint)); PragmaLoopHintInfo *Info = static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue()); IdentifierInfo *PragmaNameInfo = Info->PragmaName.getIdentifierInfo(); Hint.PragmaNameLoc = IdentifierLoc::create( Actions.Context, Info->PragmaName.getLocation(), PragmaNameInfo); // It is possible that the loop hint has no option identifier, such as // #pragma unroll(4). IdentifierInfo *OptionInfo = Info->Option.is(tok::identifier) ? Info->Option.getIdentifierInfo() : nullptr; Hint.OptionLoc = IdentifierLoc::create( Actions.Context, Info->Option.getLocation(), OptionInfo); Token *Toks = Info->Toks; size_t TokSize = Info->TokSize; // Return a valid hint if pragma unroll or nounroll were specified // without an argument. bool PragmaUnroll = PragmaNameInfo->getName() == "unroll"; bool PragmaNoUnroll = PragmaNameInfo->getName() == "nounroll"; if (TokSize == 0 && (PragmaUnroll || PragmaNoUnroll)) { ConsumeToken(); // The annotation token. Hint.Range = Info->PragmaName.getLocation(); return true; } // The constant expression is always followed by an eof token, which increases // the TokSize by 1. assert(TokSize > 0 && "PragmaLoopHintInfo::Toks must contain at least one token."); // If no option is specified the argument is assumed to be a constant expr. bool OptionUnroll = false; bool StateOption = false; if (OptionInfo) { // Pragma Unroll does not specify an option. OptionUnroll = OptionInfo->isStr("unroll"); StateOption = llvm::StringSwitch<bool>(OptionInfo->getName()) .Case("vectorize", true) .Case("interleave", true) .Case("unroll", true) .Default(false); } // Verify loop hint has an argument. if (Toks[0].is(tok::eof)) { ConsumeToken(); // The annotation token. Diag(Toks[0].getLocation(), diag::err_pragma_loop_missing_argument) << /*StateArgument=*/StateOption << /*FullKeyword=*/OptionUnroll; return false; } // Validate the argument. if (StateOption) { ConsumeToken(); // The annotation token. SourceLocation StateLoc = Toks[0].getLocation(); IdentifierInfo *StateInfo = Toks[0].getIdentifierInfo(); if (!StateInfo || ((OptionUnroll ? !StateInfo->isStr("full") : !StateInfo->isStr("enable") && !StateInfo->isStr("assume_safety")) && !StateInfo->isStr("disable"))) { Diag(Toks[0].getLocation(), diag::err_pragma_invalid_keyword) << /*FullKeyword=*/OptionUnroll; return false; } if (TokSize > 2) Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << PragmaLoopHintString(Info->PragmaName, Info->Option); Hint.StateLoc = IdentifierLoc::create(Actions.Context, StateLoc, StateInfo); } else { // Enter constant expression including eof terminator into token stream. PP.EnterTokenStream(Toks, TokSize, /*DisableMacroExpansion=*/false, /*OwnsTokens=*/false); ConsumeToken(); // The annotation token. ExprResult R = ParseConstantExpression(); // Tokens following an error in an ill-formed constant expression will // remain in the token stream and must be removed. if (Tok.isNot(tok::eof)) { Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << PragmaLoopHintString(Info->PragmaName, Info->Option); while (Tok.isNot(tok::eof)) ConsumeAnyToken(); } ConsumeToken(); // Consume the constant expression eof terminator. if (R.isInvalid() || Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation())) return false; // Argument is a constant expression with an integer type. Hint.ValueExpr = R.get(); } Hint.Range = SourceRange(Info->PragmaName.getLocation(), Info->Toks[TokSize - 1].getLocation()); return true; } // #pragma GCC visibility comes in two variants: // 'push' '(' [visibility] ')' // 'pop' void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &VisTok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change SourceLocation VisLoc = VisTok.getLocation(); Token Tok; PP.LexUnexpandedToken(Tok); const IdentifierInfo *PushPop = Tok.getIdentifierInfo(); const IdentifierInfo *VisType; if (PushPop && PushPop->isStr("pop")) { VisType = nullptr; } else if (PushPop && PushPop->isStr("push")) { PP.LexUnexpandedToken(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "visibility"; return; } PP.LexUnexpandedToken(Tok); VisType = Tok.getIdentifierInfo(); if (!VisType) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "visibility"; return; } PP.LexUnexpandedToken(Tok); if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "visibility"; return; } } else { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "visibility"; return; } SourceLocation EndLoc = Tok.getLocation(); PP.LexUnexpandedToken(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "visibility"; return; } Token *Toks = new Token[1]; Toks[0].startToken(); Toks[0].setKind(tok::annot_pragma_vis); Toks[0].setLocation(VisLoc); Toks[0].setAnnotationEndLoc(EndLoc); Toks[0].setAnnotationValue( const_cast<void*>(static_cast<const void*>(VisType))); PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true, /*OwnsTokens=*/true); } // #pragma pack(...) comes in the following delicious flavors: // pack '(' [integer] ')' // pack '(' 'show' ')' // pack '(' ('push' | 'pop') [',' identifier] [, integer] ')' void PragmaPackHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &PackTok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change SourceLocation PackLoc = PackTok.getLocation(); Token Tok; PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "pack"; return; } Sema::PragmaPackKind Kind = Sema::PPK_Default; IdentifierInfo *Name = nullptr; Token Alignment; Alignment.startToken(); SourceLocation LParenLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.is(tok::numeric_constant)) { Alignment = Tok; PP.Lex(Tok); // In MSVC/gcc, #pragma pack(4) sets the alignment without affecting // the push/pop stack. // In Apple gcc, #pragma pack(4) is equivalent to #pragma pack(push, 4) if (PP.getLangOpts().ApplePragmaPack) Kind = Sema::PPK_Push; } else if (Tok.is(tok::identifier)) { const IdentifierInfo *II = Tok.getIdentifierInfo(); if (II->isStr("show")) { Kind = Sema::PPK_Show; PP.Lex(Tok); } else { if (II->isStr("push")) { Kind = Sema::PPK_Push; } else if (II->isStr("pop")) { Kind = Sema::PPK_Pop; } else { PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action) << "pack"; return; } PP.Lex(Tok); if (Tok.is(tok::comma)) { PP.Lex(Tok); if (Tok.is(tok::numeric_constant)) { Alignment = Tok; PP.Lex(Tok); } else if (Tok.is(tok::identifier)) { Name = Tok.getIdentifierInfo(); PP.Lex(Tok); if (Tok.is(tok::comma)) { PP.Lex(Tok); if (Tok.isNot(tok::numeric_constant)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed); return; } Alignment = Tok; PP.Lex(Tok); } } else { PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed); return; } } } } else if (PP.getLangOpts().ApplePragmaPack) { // In MSVC/gcc, #pragma pack() resets the alignment without affecting // the push/pop stack. // In Apple gcc #pragma pack() is equivalent to #pragma pack(pop). Kind = Sema::PPK_Pop; } if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "pack"; return; } SourceLocation RParenLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "pack"; return; } PragmaPackInfo *Info = (PragmaPackInfo*) PP.getPreprocessorAllocator().Allocate( sizeof(PragmaPackInfo), llvm::alignOf<PragmaPackInfo>()); new (Info) PragmaPackInfo(); Info->Kind = Kind; Info->Name = Name; Info->Alignment = Alignment; Info->LParenLoc = LParenLoc; Info->RParenLoc = RParenLoc; Token *Toks = (Token*) PP.getPreprocessorAllocator().Allocate( sizeof(Token) * 1, llvm::alignOf<Token>()); new (Toks) Token(); Toks[0].startToken(); Toks[0].setKind(tok::annot_pragma_pack); Toks[0].setLocation(PackLoc); Toks[0].setAnnotationEndLoc(RParenLoc); Toks[0].setAnnotationValue(static_cast<void*>(Info)); PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false); } // #pragma ms_struct on // #pragma ms_struct off void PragmaMSStructHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &MSStructTok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change Sema::PragmaMSStructKind Kind = Sema::PMSST_OFF; Token Tok; PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct); return; } SourceLocation EndLoc = Tok.getLocation(); const IdentifierInfo *II = Tok.getIdentifierInfo(); if (II->isStr("on")) { Kind = Sema::PMSST_ON; PP.Lex(Tok); } else if (II->isStr("off") || II->isStr("reset")) PP.Lex(Tok); else { PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct); return; } if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "ms_struct"; return; } Token *Toks = (Token*) PP.getPreprocessorAllocator().Allocate( sizeof(Token) * 1, llvm::alignOf<Token>()); new (Toks) Token(); Toks[0].startToken(); Toks[0].setKind(tok::annot_pragma_msstruct); Toks[0].setLocation(MSStructTok.getLocation()); Toks[0].setAnnotationEndLoc(EndLoc); Toks[0].setAnnotationValue(reinterpret_cast<void*>( static_cast<uintptr_t>(Kind))); PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false); } // #pragma 'align' '=' {'native','natural','mac68k','power','reset'} // #pragma 'options 'align' '=' {'native','natural','mac68k','power','reset'} static void ParseAlignPragma(Preprocessor &PP, Token &FirstTok, bool IsOptions) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change Token Tok; if (IsOptions) { PP.Lex(Tok); if (Tok.isNot(tok::identifier) || !Tok.getIdentifierInfo()->isStr("align")) { PP.Diag(Tok.getLocation(), diag::warn_pragma_options_expected_align); return; } } PP.Lex(Tok); if (Tok.isNot(tok::equal)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_align_expected_equal) << IsOptions; return; } PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << (IsOptions ? "options" : "align"); return; } Sema::PragmaOptionsAlignKind Kind = Sema::POAK_Natural; const IdentifierInfo *II = Tok.getIdentifierInfo(); if (II->isStr("native")) Kind = Sema::POAK_Native; else if (II->isStr("natural")) Kind = Sema::POAK_Natural; else if (II->isStr("packed")) Kind = Sema::POAK_Packed; else if (II->isStr("power")) Kind = Sema::POAK_Power; else if (II->isStr("mac68k")) Kind = Sema::POAK_Mac68k; else if (II->isStr("reset")) Kind = Sema::POAK_Reset; else { PP.Diag(Tok.getLocation(), diag::warn_pragma_align_invalid_option) << IsOptions; return; } SourceLocation EndLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << (IsOptions ? "options" : "align"); return; } Token *Toks = (Token*) PP.getPreprocessorAllocator().Allocate( sizeof(Token) * 1, llvm::alignOf<Token>()); new (Toks) Token(); Toks[0].startToken(); Toks[0].setKind(tok::annot_pragma_align); Toks[0].setLocation(FirstTok.getLocation()); Toks[0].setAnnotationEndLoc(EndLoc); Toks[0].setAnnotationValue(reinterpret_cast<void*>( static_cast<uintptr_t>(Kind))); PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false); } void PragmaAlignHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &AlignTok) { ParseAlignPragma(PP, AlignTok, /*IsOptions=*/false); } void PragmaOptionsHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &OptionsTok) { ParseAlignPragma(PP, OptionsTok, /*IsOptions=*/true); } // #pragma unused(identifier) void PragmaUnusedHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &UnusedTok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change // FIXME: Should we be expanding macros here? My guess is no. SourceLocation UnusedLoc = UnusedTok.getLocation(); // Lex the left '('. Token Tok; PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "unused"; return; } // Lex the declaration reference(s). SmallVector<Token, 5> Identifiers; SourceLocation RParenLoc; bool LexID = true; while (true) { PP.Lex(Tok); if (LexID) { if (Tok.is(tok::identifier)) { Identifiers.push_back(Tok); LexID = false; continue; } // Illegal token! PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_var); return; } // We are execting a ')' or a ','. if (Tok.is(tok::comma)) { LexID = true; continue; } if (Tok.is(tok::r_paren)) { RParenLoc = Tok.getLocation(); break; } // Illegal token! PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_punc) << "unused"; return; } PP.Lex(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "unused"; return; } // Verify that we have a location for the right parenthesis. assert(RParenLoc.isValid() && "Valid '#pragma unused' must have ')'"); assert(!Identifiers.empty() && "Valid '#pragma unused' must have arguments"); // For each identifier token, insert into the token stream a // annot_pragma_unused token followed by the identifier token. // This allows us to cache a "#pragma unused" that occurs inside an inline // C++ member function. Token *Toks = (Token*) PP.getPreprocessorAllocator().Allocate( sizeof(Token) * 2 * Identifiers.size(), llvm::alignOf<Token>()); for (unsigned i=0; i != Identifiers.size(); i++) { Token &pragmaUnusedTok = Toks[2*i], &idTok = Toks[2*i+1]; pragmaUnusedTok.startToken(); pragmaUnusedTok.setKind(tok::annot_pragma_unused); pragmaUnusedTok.setLocation(UnusedLoc); idTok = Identifiers[i]; } PP.EnterTokenStream(Toks, 2*Identifiers.size(), /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false); } // #pragma weak identifier // #pragma weak identifier '=' identifier void PragmaWeakHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &WeakTok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change SourceLocation WeakLoc = WeakTok.getLocation(); Token Tok; PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "weak"; return; } Token WeakName = Tok; bool HasAlias = false; Token AliasName; PP.Lex(Tok); if (Tok.is(tok::equal)) { HasAlias = true; PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "weak"; return; } AliasName = Tok; PP.Lex(Tok); } if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "weak"; return; } if (HasAlias) { Token *Toks = (Token*) PP.getPreprocessorAllocator().Allocate( sizeof(Token) * 3, llvm::alignOf<Token>()); Token &pragmaUnusedTok = Toks[0]; pragmaUnusedTok.startToken(); pragmaUnusedTok.setKind(tok::annot_pragma_weakalias); pragmaUnusedTok.setLocation(WeakLoc); pragmaUnusedTok.setAnnotationEndLoc(AliasName.getLocation()); Toks[1] = WeakName; Toks[2] = AliasName; PP.EnterTokenStream(Toks, 3, /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false); } else { Token *Toks = (Token*) PP.getPreprocessorAllocator().Allocate( sizeof(Token) * 2, llvm::alignOf<Token>()); Token &pragmaUnusedTok = Toks[0]; pragmaUnusedTok.startToken(); pragmaUnusedTok.setKind(tok::annot_pragma_weak); pragmaUnusedTok.setLocation(WeakLoc); pragmaUnusedTok.setAnnotationEndLoc(WeakLoc); Toks[1] = WeakName; PP.EnterTokenStream(Toks, 2, /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false); } } // #pragma redefine_extname identifier identifier void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &RedefToken) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change SourceLocation RedefLoc = RedefToken.getLocation(); Token Tok; PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "redefine_extname"; return; } Token RedefName = Tok; PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "redefine_extname"; return; } Token AliasName = Tok; PP.Lex(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "redefine_extname"; return; } Token *Toks = (Token*) PP.getPreprocessorAllocator().Allocate( sizeof(Token) * 3, llvm::alignOf<Token>()); Token &pragmaRedefTok = Toks[0]; pragmaRedefTok.startToken(); pragmaRedefTok.setKind(tok::annot_pragma_redefine_extname); pragmaRedefTok.setLocation(RedefLoc); pragmaRedefTok.setAnnotationEndLoc(AliasName.getLocation()); Toks[1] = RedefName; Toks[2] = AliasName; PP.EnterTokenStream(Toks, 3, /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false); } void PragmaFPContractHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change tok::OnOffSwitch OOS; if (PP.LexOnOffSwitch(OOS)) return; Token *Toks = (Token*) PP.getPreprocessorAllocator().Allocate( sizeof(Token) * 1, llvm::alignOf<Token>()); new (Toks) Token(); Toks[0].startToken(); Toks[0].setKind(tok::annot_pragma_fp_contract); Toks[0].setLocation(Tok.getLocation()); Toks[0].setAnnotationEndLoc(Tok.getLocation()); Toks[0].setAnnotationValue(reinterpret_cast<void*>( static_cast<uintptr_t>(OOS))); PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false); } void PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change PP.LexUnexpandedToken(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "OPENCL"; return; } IdentifierInfo *ename = Tok.getIdentifierInfo(); SourceLocation NameLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.isNot(tok::colon)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_colon) << ename; return; } PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_enable_disable); return; } IdentifierInfo *op = Tok.getIdentifierInfo(); unsigned state; if (op->isStr("enable")) { state = 1; } else if (op->isStr("disable")) { state = 0; } else { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_enable_disable); return; } SourceLocation StateLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "OPENCL EXTENSION"; return; } OpenCLExtData data(ename, state); Token *Toks = (Token*) PP.getPreprocessorAllocator().Allocate( sizeof(Token) * 1, llvm::alignOf<Token>()); new (Toks) Token(); Toks[0].startToken(); Toks[0].setKind(tok::annot_pragma_opencl_extension); Toks[0].setLocation(NameLoc); Toks[0].setAnnotationValue(data.getOpaqueValue()); Toks[0].setAnnotationEndLoc(StateLoc); PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true, /*OwnsTokens=*/false); if (PP.getPPCallbacks()) PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, ename, StateLoc, state); } /// \brief Handle '#pragma omp ...' when OpenMP is disabled. /// void PragmaNoOpenMPHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstTok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change if (!PP.getDiagnostics().isIgnored(diag::warn_pragma_omp_ignored, FirstTok.getLocation())) { PP.Diag(FirstTok, diag::warn_pragma_omp_ignored); PP.getDiagnostics().setSeverity(diag::warn_pragma_omp_ignored, diag::Severity::Ignored, SourceLocation()); } PP.DiscardUntilEndOfDirective(); } /// \brief Handle '#pragma omp ...' when OpenMP is enabled. /// void PragmaOpenMPHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstTok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change SmallVector<Token, 16> Pragma; Token Tok; Tok.startToken(); Tok.setKind(tok::annot_pragma_openmp); Tok.setLocation(FirstTok.getLocation()); while (Tok.isNot(tok::eod)) { Pragma.push_back(Tok); PP.Lex(Tok); } SourceLocation EodLoc = Tok.getLocation(); Tok.startToken(); Tok.setKind(tok::annot_pragma_openmp_end); Tok.setLocation(EodLoc); Pragma.push_back(Tok); Token *Toks = new Token[Pragma.size()]; std::copy(Pragma.begin(), Pragma.end(), Toks); PP.EnterTokenStream(Toks, Pragma.size(), /*DisableMacroExpansion=*/false, /*OwnsTokens=*/true); } /// \brief Handle '#pragma pointers_to_members' // The grammar for this pragma is as follows: // // <inheritance model> ::= ('single' | 'multiple' | 'virtual') '_inheritance' // // #pragma pointers_to_members '(' 'best_case' ')' // #pragma pointers_to_members '(' 'full_generality' [',' inheritance-model] ')' // #pragma pointers_to_members '(' inheritance-model ')' void PragmaMSPointersToMembers::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change SourceLocation PointersToMembersLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(PointersToMembersLoc, diag::warn_pragma_expected_lparen) << "pointers_to_members"; return; } PP.Lex(Tok); const IdentifierInfo *Arg = Tok.getIdentifierInfo(); if (!Arg) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "pointers_to_members"; return; } PP.Lex(Tok); LangOptions::PragmaMSPointersToMembersKind RepresentationMethod; if (Arg->isStr("best_case")) { RepresentationMethod = LangOptions::PPTMK_BestCase; } else { if (Arg->isStr("full_generality")) { if (Tok.is(tok::comma)) { PP.Lex(Tok); Arg = Tok.getIdentifierInfo(); if (!Arg) { PP.Diag(Tok.getLocation(), diag::err_pragma_pointers_to_members_unknown_kind) << Tok.getKind() << /*OnlyInheritanceModels*/ 0; return; } PP.Lex(Tok); } else if (Tok.is(tok::r_paren)) { // #pragma pointers_to_members(full_generality) implicitly specifies // virtual_inheritance. Arg = nullptr; RepresentationMethod = LangOptions::PPTMK_FullGeneralityVirtualInheritance; } else { PP.Diag(Tok.getLocation(), diag::err_expected_punc) << "full_generality"; return; } } if (Arg) { if (Arg->isStr("single_inheritance")) { RepresentationMethod = LangOptions::PPTMK_FullGeneralitySingleInheritance; } else if (Arg->isStr("multiple_inheritance")) { RepresentationMethod = LangOptions::PPTMK_FullGeneralityMultipleInheritance; } else if (Arg->isStr("virtual_inheritance")) { RepresentationMethod = LangOptions::PPTMK_FullGeneralityVirtualInheritance; } else { PP.Diag(Tok.getLocation(), diag::err_pragma_pointers_to_members_unknown_kind) << Arg << /*HasPointerDeclaration*/ 1; return; } } } if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok.getLocation(), diag::err_expected_rparen_after) << (Arg ? Arg->getName() : "full_generality"); return; } SourceLocation EndLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "pointers_to_members"; return; } Token AnnotTok; AnnotTok.startToken(); AnnotTok.setKind(tok::annot_pragma_ms_pointers_to_members); AnnotTok.setLocation(PointersToMembersLoc); AnnotTok.setAnnotationEndLoc(EndLoc); AnnotTok.setAnnotationValue( reinterpret_cast<void *>(static_cast<uintptr_t>(RepresentationMethod))); PP.EnterToken(AnnotTok); } /// \brief Handle '#pragma vtordisp' // The grammar for this pragma is as follows: // // <vtordisp-mode> ::= ('off' | 'on' | '0' | '1' | '2' ) // // #pragma vtordisp '(' ['push' ','] vtordisp-mode ')' // #pragma vtordisp '(' 'pop' ')' // #pragma vtordisp '(' ')' void PragmaMSVtorDisp::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change SourceLocation VtorDispLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(VtorDispLoc, diag::warn_pragma_expected_lparen) << "vtordisp"; return; } PP.Lex(Tok); Sema::PragmaVtorDispKind Kind = Sema::PVDK_Set; const IdentifierInfo *II = Tok.getIdentifierInfo(); if (II) { if (II->isStr("push")) { // #pragma vtordisp(push, mode) PP.Lex(Tok); if (Tok.isNot(tok::comma)) { PP.Diag(VtorDispLoc, diag::warn_pragma_expected_punc) << "vtordisp"; return; } PP.Lex(Tok); Kind = Sema::PVDK_Push; // not push, could be on/off } else if (II->isStr("pop")) { // #pragma vtordisp(pop) PP.Lex(Tok); Kind = Sema::PVDK_Pop; } // not push or pop, could be on/off } else { if (Tok.is(tok::r_paren)) { // #pragma vtordisp() Kind = Sema::PVDK_Reset; } } uint64_t Value = 0; if (Kind == Sema::PVDK_Push || Kind == Sema::PVDK_Set) { const IdentifierInfo *II = Tok.getIdentifierInfo(); if (II && II->isStr("off")) { PP.Lex(Tok); Value = 0; } else if (II && II->isStr("on")) { PP.Lex(Tok); Value = 1; } else if (Tok.is(tok::numeric_constant) && PP.parseSimpleIntegerLiteral(Tok, Value)) { if (Value > 2) { PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_integer) << 0 << 2 << "vtordisp"; return; } } else { PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action) << "vtordisp"; return; } } // Finish the pragma: ')' $ if (Tok.isNot(tok::r_paren)) { PP.Diag(VtorDispLoc, diag::warn_pragma_expected_rparen) << "vtordisp"; return; } SourceLocation EndLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "vtordisp"; return; } // Enter the annotation. Token AnnotTok; AnnotTok.startToken(); AnnotTok.setKind(tok::annot_pragma_ms_vtordisp); AnnotTok.setLocation(VtorDispLoc); AnnotTok.setAnnotationEndLoc(EndLoc); // OACR error 6297 #pragma prefast(disable: __WARNING_RESULTOFSHIFTCASTTOLARGERSIZE, "valid Kind values will not overflow") AnnotTok.setAnnotationValue(reinterpret_cast<void *>( static_cast<uintptr_t>((Kind << 16) | (Value & 0xFFFF)))); PP.EnterToken(AnnotTok); } /// \brief Handle all MS pragmas. Simply forwards the tokens after inserting /// an annotation token. void PragmaMSPragma::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change Token EoF, AnnotTok; EoF.startToken(); EoF.setKind(tok::eof); AnnotTok.startToken(); AnnotTok.setKind(tok::annot_pragma_ms_pragma); AnnotTok.setLocation(Tok.getLocation()); AnnotTok.setAnnotationEndLoc(Tok.getLocation()); SmallVector<Token, 8> TokenVector; // Suck up all of the tokens before the eod. for (; Tok.isNot(tok::eod); PP.Lex(Tok)) { TokenVector.push_back(Tok); AnnotTok.setAnnotationEndLoc(Tok.getLocation()); } // Add a sentinal EoF token to the end of the list. TokenVector.push_back(EoF); // We must allocate this array with new because EnterTokenStream is going to // delete it later. Token *TokenArray = new Token[TokenVector.size()]; std::copy(TokenVector.begin(), TokenVector.end(), TokenArray); auto Value = new (PP.getPreprocessorAllocator()) std::pair<Token*, size_t>(std::make_pair(TokenArray, TokenVector.size())); AnnotTok.setAnnotationValue(Value); PP.EnterToken(AnnotTok); } /// \brief Handle the Microsoft \#pragma detect_mismatch extension. /// /// The syntax is: /// \code /// #pragma detect_mismatch("name", "value") /// \endcode /// Where 'name' and 'value' are quoted strings. The values are embedded in /// the object file and passed along to the linker. If the linker detects a /// mismatch in the object file's values for the given name, a LNK2038 error /// is emitted. See MSDN for more details. void PragmaDetectMismatchHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change SourceLocation CommentLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(CommentLoc, diag::err_expected) << tok::l_paren; return; } // Read the name to embed, which must be a string literal. std::string NameString; if (!PP.LexStringLiteral(Tok, NameString, "pragma detect_mismatch", /*MacroExpansion=*/true)) return; // Read the comma followed by a second string literal. std::string ValueString; if (Tok.isNot(tok::comma)) { PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed); return; } if (!PP.LexStringLiteral(Tok, ValueString, "pragma detect_mismatch", /*MacroExpansion=*/true)) return; if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren; return; } PP.Lex(Tok); // Eat the r_paren. if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed); return; } // If the pragma is lexically sound, notify any interested PPCallbacks. if (PP.getPPCallbacks()) PP.getPPCallbacks()->PragmaDetectMismatch(CommentLoc, NameString, ValueString); Actions.ActOnPragmaDetectMismatch(NameString, ValueString); } /// \brief Handle the microsoft \#pragma comment extension. /// /// The syntax is: /// \code /// #pragma comment(linker, "foo") /// \endcode /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user. /// "foo" is a string, which is fully macro expanded, and permits string /// concatenation, embedded escape characters etc. See MSDN for more details. void PragmaCommentHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change SourceLocation CommentLoc = Tok.getLocation(); PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(CommentLoc, diag::err_pragma_comment_malformed); return; } // Read the identifier. PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(CommentLoc, diag::err_pragma_comment_malformed); return; } // Verify that this is one of the 5 whitelisted options. IdentifierInfo *II = Tok.getIdentifierInfo(); Sema::PragmaMSCommentKind Kind = llvm::StringSwitch<Sema::PragmaMSCommentKind>(II->getName()) .Case("linker", Sema::PCK_Linker) .Case("lib", Sema::PCK_Lib) .Case("compiler", Sema::PCK_Compiler) .Case("exestr", Sema::PCK_ExeStr) .Case("user", Sema::PCK_User) .Default(Sema::PCK_Unknown); if (Kind == Sema::PCK_Unknown) { PP.Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind); return; } // On PS4, issue a warning about any pragma comments other than // #pragma comment lib. if (PP.getTargetInfo().getTriple().isPS4() && Kind != Sema::PCK_Lib) { PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored) << II->getName(); return; } // Read the optional string if present. PP.Lex(Tok); std::string ArgumentString; if (Tok.is(tok::comma) && !PP.LexStringLiteral(Tok, ArgumentString, "pragma comment", /*MacroExpansion=*/true)) return; // FIXME: warn that 'exestr' is deprecated. // FIXME: If the kind is "compiler" warn if the string is present (it is // ignored). // The MSDN docs say that "lib" and "linker" require a string and have a short // whitelist of linker options they support, but in practice MSVC doesn't // issue a diagnostic. Therefore neither does clang. if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed); return; } PP.Lex(Tok); // eat the r_paren. if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed); return; } // If the pragma is lexically sound, notify any interested PPCallbacks. if (PP.getPPCallbacks()) PP.getPPCallbacks()->PragmaComment(CommentLoc, II, ArgumentString); Actions.ActOnPragmaMSComment(Kind, ArgumentString); } // #pragma clang optimize off // #pragma clang optimize on void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change Token Tok; PP.Lex(Tok); if (Tok.is(tok::eod)) { PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument) << "clang optimize" << /*Expected=*/true << "'on' or 'off'"; return; } if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument) << PP.getSpelling(Tok); return; } const IdentifierInfo *II = Tok.getIdentifierInfo(); // The only accepted values are 'on' or 'off'. bool IsOn = false; if (II->isStr("on")) { IsOn = true; } else if (!II->isStr("off")) { PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument) << PP.getSpelling(Tok); return; } PP.Lex(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_extra_argument) << PP.getSpelling(Tok); return; } Actions.ActOnPragmaOptimize(IsOn, FirstToken.getLocation()); } /// \brief Parses loop or unroll pragma hint value and fills in Info. static bool ParseLoopHintValue(Preprocessor &PP, Token &Tok, Token PragmaName, Token Option, bool ValueInParens, PragmaLoopHintInfo &Info) { SmallVector<Token, 1> ValueList; int OpenParens = ValueInParens ? 1 : 0; // Read constant expression. while (Tok.isNot(tok::eod)) { if (Tok.is(tok::l_paren)) OpenParens++; else if (Tok.is(tok::r_paren)) { OpenParens--; if (OpenParens == 0 && ValueInParens) break; } ValueList.push_back(Tok); PP.Lex(Tok); } if (ValueInParens) { // Read ')' if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren; return true; } PP.Lex(Tok); } Token EOFTok; EOFTok.startToken(); EOFTok.setKind(tok::eof); EOFTok.setLocation(Tok.getLocation()); ValueList.push_back(EOFTok); // Terminates expression for parsing. Token *TokenArray = (Token *)PP.getPreprocessorAllocator().Allocate( ValueList.size() * sizeof(Token), llvm::alignOf<Token>()); std::copy(ValueList.begin(), ValueList.end(), TokenArray); Info.Toks = TokenArray; Info.TokSize = ValueList.size(); Info.PragmaName = PragmaName; Info.Option = Option; return false; } /// \brief Handle the \#pragma clang loop directive. /// #pragma clang 'loop' loop-hints /// /// loop-hints: /// loop-hint loop-hints[opt] /// /// loop-hint: /// 'vectorize' '(' loop-hint-keyword ')' /// 'interleave' '(' loop-hint-keyword ')' /// 'unroll' '(' unroll-hint-keyword ')' /// 'vectorize_width' '(' loop-hint-value ')' /// 'interleave_count' '(' loop-hint-value ')' /// 'unroll_count' '(' loop-hint-value ')' /// /// loop-hint-keyword: /// 'enable' /// 'disable' /// 'assume_safety' /// /// unroll-hint-keyword: /// 'full' /// 'disable' /// /// loop-hint-value: /// constant-expression /// /// Specifying vectorize(enable) or vectorize_width(_value_) instructs llvm to /// try vectorizing the instructions of the loop it precedes. Specifying /// interleave(enable) or interleave_count(_value_) instructs llvm to try /// interleaving multiple iterations of the loop it precedes. The width of the /// vector instructions is specified by vectorize_width() and the number of /// interleaved loop iterations is specified by interleave_count(). Specifying a /// value of 1 effectively disables vectorization/interleaving, even if it is /// possible and profitable, and 0 is invalid. The loop vectorizer currently /// only works on inner loops. /// /// The unroll and unroll_count directives control the concatenation /// unroller. Specifying unroll(full) instructs llvm to try to /// unroll the loop completely, and unroll(disable) disables unrolling /// for the loop. Specifying unroll_count(_value_) instructs llvm to /// try to unroll the loop the number of times indicated by the value. void PragmaLoopHintHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change // Incoming token is "loop" from "#pragma clang loop". Token PragmaName = Tok; SmallVector<Token, 1> TokenList; // Lex the optimization option and verify it is an identifier. PP.Lex(Tok); if (Tok.isNot(tok::identifier)) { PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option) << /*MissingOption=*/true << ""; return; } while (Tok.is(tok::identifier)) { Token Option = Tok; IdentifierInfo *OptionInfo = Tok.getIdentifierInfo(); bool OptionValid = llvm::StringSwitch<bool>(OptionInfo->getName()) .Case("vectorize", true) .Case("interleave", true) .Case("unroll", true) .Case("vectorize_width", true) .Case("interleave_count", true) .Case("unroll_count", true) .Default(false); if (!OptionValid) { PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option) << /*MissingOption=*/false << OptionInfo; return; } PP.Lex(Tok); // Read '(' if (Tok.isNot(tok::l_paren)) { PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren; return; } PP.Lex(Tok); auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo; if (ParseLoopHintValue(PP, Tok, PragmaName, Option, /*ValueInParens=*/true, *Info)) return; // Generate the loop hint token. Token LoopHintTok; LoopHintTok.startToken(); LoopHintTok.setKind(tok::annot_pragma_loop_hint); LoopHintTok.setLocation(PragmaName.getLocation()); LoopHintTok.setAnnotationEndLoc(PragmaName.getLocation()); LoopHintTok.setAnnotationValue(static_cast<void *>(Info)); TokenList.push_back(LoopHintTok); } if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "clang loop"; return; } Token *TokenArray = new Token[TokenList.size()]; std::copy(TokenList.begin(), TokenList.end(), TokenArray); PP.EnterTokenStream(TokenArray, TokenList.size(), /*DisableMacroExpansion=*/false, /*OwnsTokens=*/true); } /// \brief Handle the loop unroll optimization pragmas. /// #pragma unroll /// #pragma unroll unroll-hint-value /// #pragma unroll '(' unroll-hint-value ')' /// #pragma nounroll /// /// unroll-hint-value: /// constant-expression /// /// Loop unrolling hints can be specified with '#pragma unroll' or /// '#pragma nounroll'. '#pragma unroll' can take a numeric argument optionally /// contained in parentheses. With no argument the directive instructs llvm to /// try to unroll the loop completely. A positive integer argument can be /// specified to indicate the number of times the loop should be unrolled. To /// maximize compatibility with other compilers the unroll count argument can be /// specified with or without parentheses. Specifying, '#pragma nounroll' /// disables unrolling of the loop. void PragmaUnrollHintHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { assert(!PP.getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change // Incoming token is "unroll" for "#pragma unroll", or "nounroll" for // "#pragma nounroll". Token PragmaName = Tok; PP.Lex(Tok); auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo; if (Tok.is(tok::eod)) { // nounroll or unroll pragma without an argument. Info->PragmaName = PragmaName; Info->Option.startToken(); } else if (PragmaName.getIdentifierInfo()->getName() == "nounroll") { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "nounroll"; return; } else { // Unroll pragma with an argument: "#pragma unroll N" or // "#pragma unroll(N)". // Read '(' if it exists. bool ValueInParens = Tok.is(tok::l_paren); if (ValueInParens) PP.Lex(Tok); Token Option; Option.startToken(); if (ParseLoopHintValue(PP, Tok, PragmaName, Option, ValueInParens, *Info)) return; // In CUDA, the argument to '#pragma unroll' should not be contained in // parentheses. if (PP.getLangOpts().CUDA && ValueInParens) PP.Diag(Info->Toks[0].getLocation(), diag::warn_pragma_unroll_cuda_value_in_parens); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "unroll"; return; } } // Generate the hint token. Token *TokenArray = new Token[1]; TokenArray[0].startToken(); TokenArray[0].setKind(tok::annot_pragma_loop_hint); TokenArray[0].setLocation(PragmaName.getLocation()); TokenArray[0].setAnnotationEndLoc(PragmaName.getLocation()); TokenArray[0].setAnnotationValue(static_cast<void *>(Info)); PP.EnterTokenStream(TokenArray, 1, /*DisableMacroExpansion=*/false, /*OwnsTokens=*/true); } // HLSL Change Begin - pack_matrix /// \brief Handle the pack_matrix pragmas. /// #pragma pack_matrix(row_major) /// #pragma pack_matrix(column_major) /// void PragmaPackMatrixHandler::HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &Tok) { assert(PP.getLangOpts().HLSL && "only supported in HLSL"); PP.Lex(Tok); if (!Tok.is(tok::l_paren)) { PP.Diag(Tok, diag::err_expected) << tok::l_brace; return; } PP.Lex(Tok); Token PragmaArg = Tok; bool bRowMajor = false; if (Tok.is(tok::kw_row_major)) { bRowMajor = true; } else if (Tok.isNot(tok::kw_column_major)) { PP.Diag(Tok.getLocation(), diag::err_pragma_invalid_keyword); return; } // Make sure pragma finish correctly. PP.Lex(Tok); if (Tok.isNot(tok::r_paren)) { PP.Diag(Tok, diag::err_expected) << tok::r_brace; return; } PP.Lex(Tok); if (Tok.isNot(tok::eod)) { PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol); return; } // Note: to make things easy, pack_matrix will modify ast type directly in // Sema::TransferUnusualAttributes. // Another solution is create ast node for pack_matrix, and take care it at // clang codegen. Actions.ActOnPragmaPackMatrix(bRowMajor, PragmaArg.getLocation()); } // HLSL Change End.
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseDeclCXX.cpp
//===--- ParseDeclCXX.cpp - C++ Declaration Parsing -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the C++ Declaration portions of the Parser interfaces. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "RAIIObjectsForParser.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclTemplate.h" #include "clang/Basic/Attributes.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/OperatorKinds.h" #include "clang/Basic/TargetInfo.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/PrettyDeclStackTrace.h" #include "clang/Sema/Scope.h" #include "clang/Sema/SemaDiagnostic.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/TimeProfiler.h" // HLSL Change using namespace clang; /// ParseNamespace - We know that the current token is a namespace keyword. This /// may either be a top level namespace or a block-level namespace alias. If /// there was an inline keyword, it has already been parsed. /// /// namespace-definition: [C++ 7.3: basic.namespace] /// named-namespace-definition /// unnamed-namespace-definition /// /// unnamed-namespace-definition: /// 'inline'[opt] 'namespace' attributes[opt] '{' namespace-body '}' /// /// named-namespace-definition: /// original-namespace-definition /// extension-namespace-definition /// /// original-namespace-definition: /// 'inline'[opt] 'namespace' identifier attributes[opt] /// '{' namespace-body '}' /// /// extension-namespace-definition: /// 'inline'[opt] 'namespace' original-namespace-name /// '{' namespace-body '}' /// /// namespace-alias-definition: [C++ 7.3.2: namespace.alias] /// 'namespace' identifier '=' qualified-namespace-specifier ';' /// Decl *Parser::ParseNamespace(unsigned Context, SourceLocation &DeclEnd, SourceLocation InlineLoc) { assert(Tok.is(tok::kw_namespace) && "Not a namespace!"); SourceLocation NamespaceLoc = ConsumeToken(); // eat the 'namespace'. ObjCDeclContextSwitch ObjCDC(*this); if (Tok.is(tok::code_completion)) { Actions.CodeCompleteNamespaceDecl(getCurScope()); cutOffParsing(); return nullptr; } SourceLocation IdentLoc; IdentifierInfo *Ident = nullptr; std::vector<SourceLocation> ExtraIdentLoc; std::vector<IdentifierInfo*> ExtraIdent; std::vector<SourceLocation> ExtraNamespaceLoc; ParsedAttributesWithRange attrs(AttrFactory); SourceLocation attrLoc; if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) { if (!getLangOpts().CPlusPlus1z) Diag(Tok.getLocation(), diag::warn_cxx14_compat_attribute) << 0 /*namespace*/; attrLoc = Tok.getLocation(); ParseCXX11Attributes(attrs); } if (Tok.is(tok::identifier)) { Ident = Tok.getIdentifierInfo(); IdentLoc = ConsumeToken(); // eat the identifier. while (Tok.is(tok::coloncolon) && NextToken().is(tok::identifier)) { ExtraNamespaceLoc.push_back(ConsumeToken()); ExtraIdent.push_back(Tok.getIdentifierInfo()); ExtraIdentLoc.push_back(ConsumeToken()); } } // HLSL Change Starts else if (getLangOpts().HLSL) { Diag(Tok, diag::err_expected) << tok::identifier; } // HLSL Change Ends // A nested namespace definition cannot have attributes. if (!ExtraNamespaceLoc.empty() && attrLoc.isValid()) Diag(attrLoc, diag::err_unexpected_nested_namespace_attribute); // Read label attributes, if present. if (Tok.is(tok::kw___attribute)) { attrLoc = Tok.getLocation(); ParseGNUAttributes(attrs); } if (Tok.is(tok::equal)) { if (!Ident || getLangOpts().HLSL) { // HLSL Change: HLSL disallows namespace aliases Diag(Tok, diag::err_expected) << tok::identifier; // Skip to end of the definition and eat the ';'. SkipUntil(tok::semi); return nullptr; } if (attrLoc.isValid()) Diag(attrLoc, diag::err_unexpected_namespace_attributes_alias); if (InlineLoc.isValid()) Diag(InlineLoc, diag::err_inline_namespace_alias) << FixItHint::CreateRemoval(InlineLoc); return ParseNamespaceAlias(NamespaceLoc, IdentLoc, Ident, DeclEnd); } BalancedDelimiterTracker T(*this, tok::l_brace); if (T.consumeOpen()) { if (Ident) Diag(Tok, diag::err_expected) << tok::l_brace; else Diag(Tok, diag::err_expected_either) << tok::identifier << tok::l_brace; return nullptr; } if (getCurScope()->isClassScope() || getCurScope()->isTemplateParamScope() || getCurScope()->isInObjcMethodScope() || getCurScope()->getBlockParent() || getCurScope()->getFnParent()) { Diag(T.getOpenLocation(), diag::err_namespace_nonnamespace_scope); SkipUntil(tok::r_brace); return nullptr; } if (ExtraIdent.empty()) { // Normal namespace definition, not a nested-namespace-definition. } else if (InlineLoc.isValid()) { Diag(InlineLoc, diag::err_inline_nested_namespace_definition); } else if (getLangOpts().CPlusPlus1z) { Diag(ExtraNamespaceLoc[0], diag::warn_cxx14_compat_nested_namespace_definition); } else { TentativeParsingAction TPA(*this); SkipUntil(tok::r_brace, StopBeforeMatch); Token rBraceToken = Tok; TPA.Revert(); if (!rBraceToken.is(tok::r_brace)) { Diag(ExtraNamespaceLoc[0], getLangOpts().HLSL ? diag::err_hlsl_nested_namespace_definition : // HLSL Change diag::ext_nested_namespace_definition) << SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()); } else { std::string NamespaceFix; for (std::vector<IdentifierInfo*>::iterator I = ExtraIdent.begin(), E = ExtraIdent.end(); I != E; ++I) { NamespaceFix += " { namespace "; NamespaceFix += (*I)->getName(); } std::string RBraces; for (unsigned i = 0, e = ExtraIdent.size(); i != e; ++i) RBraces += "} "; Diag(ExtraNamespaceLoc[0], getLangOpts().HLSL ? diag::err_hlsl_nested_namespace_definition : // HLSL Change diag::ext_nested_namespace_definition) << FixItHint::CreateReplacement(SourceRange(ExtraNamespaceLoc.front(), ExtraIdentLoc.back()), NamespaceFix) << FixItHint::CreateInsertion(rBraceToken.getLocation(), RBraces); } } // If we're still good, complain about inline namespaces in non-C++0x now. if (InlineLoc.isValid()) Diag(InlineLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_inline_namespace : diag::ext_inline_namespace); // Enter a scope for the namespace. ParseScope NamespaceScope(this, Scope::DeclScope); Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(getCurScope(), InlineLoc, NamespaceLoc, IdentLoc, Ident, T.getOpenLocation(), attrs.getList()); PrettyDeclStackTraceEntry CrashInfo(Actions, NamespcDecl, NamespaceLoc, "parsing namespace"); // Parse the contents of the namespace. This includes parsing recovery on // any improperly nested namespaces. ParseInnerNamespace(ExtraIdentLoc, ExtraIdent, ExtraNamespaceLoc, 0, InlineLoc, attrs, T); // Leave the namespace scope. NamespaceScope.Exit(); DeclEnd = T.getCloseLocation(); Actions.ActOnFinishNamespaceDef(NamespcDecl, DeclEnd); return NamespcDecl; } /// ParseInnerNamespace - Parse the contents of a namespace. void Parser::ParseInnerNamespace(std::vector<SourceLocation> &IdentLoc, std::vector<IdentifierInfo *> &Ident, std::vector<SourceLocation> &NamespaceLoc, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker) { if (index == Ident.size()) { while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { ParsedAttributesWithRange attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); MaybeParseMicrosoftAttributes(attrs); ParseExternalDeclaration(attrs); } // The caller is what called check -- we are simply calling // the close for it. Tracker.consumeClose(); return; } // Handle a nested namespace definition. // FIXME: Preserve the source information through to the AST rather than // desugaring it here. ParseScope NamespaceScope(this, Scope::DeclScope); Decl *NamespcDecl = Actions.ActOnStartNamespaceDef(getCurScope(), SourceLocation(), NamespaceLoc[index], IdentLoc[index], Ident[index], Tracker.getOpenLocation(), attrs.getList()); ParseInnerNamespace(IdentLoc, Ident, NamespaceLoc, ++index, InlineLoc, attrs, Tracker); NamespaceScope.Exit(); Actions.ActOnFinishNamespaceDef(NamespcDecl, Tracker.getCloseLocation()); } /// ParseNamespaceAlias - Parse the part after the '=' in a namespace /// alias definition. /// Decl *Parser::ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd) { assert(Tok.is(tok::equal) && "Not equal token"); ConsumeToken(); // eat the '='. if (Tok.is(tok::code_completion)) { Actions.CodeCompleteNamespaceAliasDecl(getCurScope()); cutOffParsing(); return nullptr; } CXXScopeSpec SS; // Parse (optional) nested-name-specifier. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); if (SS.isInvalid() || Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_namespace_name); // Skip to end of the definition and eat the ';'. SkipUntil(tok::semi); return nullptr; } // Parse identifier. IdentifierInfo *Ident = Tok.getIdentifierInfo(); SourceLocation IdentLoc = ConsumeToken(); // Eat the ';'. DeclEnd = Tok.getLocation(); if (ExpectAndConsume(tok::semi, diag::err_expected_semi_after_namespace_name)) SkipUntil(tok::semi); return Actions.ActOnNamespaceAliasDef(getCurScope(), NamespaceLoc, AliasLoc, Alias, SS, IdentLoc, Ident); } /// ParseLinkage - We know that the current token is a string_literal /// and just before that, that extern was seen. /// /// linkage-specification: [C++ 7.5p2: dcl.link] /// 'extern' string-literal '{' declaration-seq[opt] '}' /// 'extern' string-literal declaration /// Decl *Parser::ParseLinkage(ParsingDeclSpec &DS, unsigned Context) { assert(isTokenStringLiteral() && "Not a string literal!"); ExprResult Lang = ParseStringLiteralExpression(false); ParseScope LinkageScope(this, Scope::DeclScope); Decl *LinkageSpec = Lang.isInvalid() ? nullptr : Actions.ActOnStartLinkageSpecification( getCurScope(), DS.getSourceRange().getBegin(), Lang.get(), Tok.is(tok::l_brace) ? Tok.getLocation() : SourceLocation()); ParsedAttributesWithRange attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); MaybeParseHLSLAttributes(attrs); // HLSL Change MaybeParseMicrosoftAttributes(attrs); if (Tok.isNot(tok::l_brace)) { // Reset the source range in DS, as the leading "extern" // does not really belong to the inner declaration ... DS.SetRangeStart(SourceLocation()); DS.SetRangeEnd(SourceLocation()); // ... but anyway remember that such an "extern" was seen. DS.setExternInLinkageSpec(true); ParseExternalDeclaration(attrs, &DS); return LinkageSpec ? Actions.ActOnFinishLinkageSpecification( getCurScope(), LinkageSpec, SourceLocation()) : nullptr; } DS.abort(); ProhibitAttributes(attrs); BalancedDelimiterTracker T(*this, tok::l_brace); T.consumeOpen(); unsigned NestedModules = 0; while (true) { switch (Tok.getKind()) { case tok::annot_module_begin: ++NestedModules; ParseTopLevelDecl(); continue; case tok::annot_module_end: if (!NestedModules) break; --NestedModules; ParseTopLevelDecl(); continue; case tok::annot_module_include: ParseTopLevelDecl(); continue; case tok::eof: break; case tok::r_brace: if (!NestedModules) break; LLVM_FALLTHROUGH; // HLSL Change. default: ParsedAttributesWithRange attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); MaybeParseHLSLAttributes(attrs); // HLSL Change MaybeParseMicrosoftAttributes(attrs); ParseExternalDeclaration(attrs); continue; } break; } T.consumeClose(); return LinkageSpec ? Actions.ActOnFinishLinkageSpecification( getCurScope(), LinkageSpec, T.getCloseLocation()) : nullptr; } /// ParseUsingDirectiveOrDeclaration - Parse C++ using using-declaration or /// using-directive. Assumes that current token is 'using'. Decl *Parser::ParseUsingDirectiveOrDeclaration(unsigned Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, Decl **OwnedType) { assert(Tok.is(tok::kw_using) && "Not using token"); ObjCDeclContextSwitch ObjCDC(*this); // Eat 'using'. SourceLocation UsingLoc = ConsumeToken(); if (Tok.is(tok::code_completion)) { Actions.CodeCompleteUsing(getCurScope()); cutOffParsing(); return nullptr; } // 'using namespace' means this is a using-directive. if (Tok.is(tok::kw_namespace)) { // Template parameters are always an error here. if (TemplateInfo.Kind) { SourceRange R = TemplateInfo.getSourceRange(); Diag(UsingLoc, diag::err_templated_using_directive) << R << FixItHint::CreateRemoval(R); } return ParseUsingDirective(Context, UsingLoc, DeclEnd, attrs); } // Otherwise, it must be a using-declaration or an alias-declaration. // Using declarations can't have attributes. ProhibitAttributes(attrs); return ParseUsingDeclaration(Context, TemplateInfo, UsingLoc, DeclEnd, AS_none, OwnedType); } /// ParseUsingDirective - Parse C++ using-directive, assumes /// that current token is 'namespace' and 'using' was already parsed. /// /// using-directive: [C++ 7.3.p4: namespace.udir] /// 'using' 'namespace' ::[opt] nested-name-specifier[opt] /// namespace-name ; /// [GNU] using-directive: /// 'using' 'namespace' ::[opt] nested-name-specifier[opt] /// namespace-name attributes[opt] ; /// Decl *Parser::ParseUsingDirective(unsigned Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs) { assert(Tok.is(tok::kw_namespace) && "Not 'namespace' token"); // Eat 'namespace'. SourceLocation NamespcLoc = ConsumeToken(); // HLSL change begin -warning ext before HLSL2021. if (getLangOpts().HLSL) { if (getLangOpts().HLSLVersion < hlsl::LangStd::v2021) Diag(UsingLoc, diag::warn_hlsl_new_feature) << "keyword 'using'" << "2021"; } // HLSL change end. if (Tok.is(tok::code_completion)) { Actions.CodeCompleteUsingDirective(getCurScope()); cutOffParsing(); return nullptr; } CXXScopeSpec SS; // Parse (optional) nested-name-specifier. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); IdentifierInfo *NamespcName = nullptr; SourceLocation IdentLoc = SourceLocation(); // Parse namespace-name. if (SS.isInvalid() || Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_namespace_name); // If there was invalid namespace name, skip to end of decl, and eat ';'. SkipUntil(tok::semi); // FIXME: Are there cases, when we would like to call ActOnUsingDirective? return nullptr; } // Parse identifier. NamespcName = Tok.getIdentifierInfo(); IdentLoc = ConsumeToken(); // Parse (optional) attributes (most likely GNU strong-using extension). bool GNUAttr = false; if (Tok.is(tok::kw___attribute)) { GNUAttr = true; ParseGNUAttributes(attrs); } // Eat ';'. DeclEnd = Tok.getLocation(); if (ExpectAndConsume(tok::semi, GNUAttr ? diag::err_expected_semi_after_attribute_list : diag::err_expected_semi_after_namespace_name)) SkipUntil(tok::semi); return Actions.ActOnUsingDirective(getCurScope(), UsingLoc, NamespcLoc, SS, IdentLoc, NamespcName, attrs.getList()); } /// ParseUsingDeclaration - Parse C++ using-declaration or alias-declaration. /// Assumes that 'using' was already seen. /// /// using-declaration: [C++ 7.3.p3: namespace.udecl] /// 'using' 'typename'[opt] ::[opt] nested-name-specifier /// unqualified-id /// 'using' :: unqualified-id /// /// alias-declaration: C++11 [dcl.dcl]p1 /// 'using' identifier attribute-specifier-seq[opt] = type-id ; /// Decl *Parser::ParseUsingDeclaration(unsigned Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS, Decl **OwnedType) { CXXScopeSpec SS; SourceLocation TypenameLoc; bool HasTypenameKeyword = false; // Check for misplaced attributes before the identifier in an // alias-declaration. ParsedAttributesWithRange MisplacedAttrs(AttrFactory); MaybeParseCXX11Attributes(MisplacedAttrs); // Ignore optional 'typename'. // FIXME: This is wrong; we should parse this as a typename-specifier. if (TryConsumeToken(tok::kw_typename, TypenameLoc)) HasTypenameKeyword = true; if (Tok.is(tok::kw___super)) { Diag(Tok.getLocation(), diag::err_super_in_using_declaration); SkipUntil(tok::semi); return nullptr; } // Parse nested-name-specifier. IdentifierInfo *LastII = nullptr; ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false, /*MayBePseudoDtor=*/nullptr, /*IsTypename=*/false, /*LastII=*/&LastII); // Check nested-name specifier. if (SS.isInvalid()) { SkipUntil(tok::semi); return nullptr; } SourceLocation TemplateKWLoc; UnqualifiedId Name; // Parse the unqualified-id. We allow parsing of both constructor and // destructor names and allow the action module to diagnose any semantic // errors. // // C++11 [class.qual]p2: // [...] in a using-declaration that is a member-declaration, if the name // specified after the nested-name-specifier is the same as the identifier // or the simple-template-id's template-name in the last component of the // nested-name-specifier, the name is [...] considered to name the // constructor. if (getLangOpts().CPlusPlus11 && Context == Declarator::MemberContext && Tok.is(tok::identifier) && NextToken().is(tok::semi) && SS.isNotEmpty() && LastII == Tok.getIdentifierInfo() && !SS.getScopeRep()->getAsNamespace() && !SS.getScopeRep()->getAsNamespaceAlias()) { SourceLocation IdLoc = ConsumeToken(); ParsedType Type = Actions.getInheritingConstructorName(SS, IdLoc, *LastII); Name.setConstructorName(Type, IdLoc, IdLoc); } else if (ParseUnqualifiedId( SS, /*EnteringContext=*/false, /*AllowDestructorName=*/true, /*AllowConstructorName=*/NextToken().isNot(tok::equal), ParsedType(), TemplateKWLoc, Name)) { SkipUntil(tok::semi); return nullptr; } ParsedAttributesWithRange Attrs(AttrFactory); MaybeParseGNUAttributes(Attrs); MaybeParseCXX11Attributes(Attrs); // Maybe this is an alias-declaration. TypeResult TypeAlias; bool IsAliasDecl = Tok.is(tok::equal); Decl *DeclFromDeclSpec = nullptr; if (IsAliasDecl) { // If we had any misplaced attributes from earlier, this is where they // should have been written. if (MisplacedAttrs.Range.isValid()) { Diag(MisplacedAttrs.Range.getBegin(), diag::err_attributes_not_allowed) << FixItHint::CreateInsertionFromRange( Tok.getLocation(), CharSourceRange::getTokenRange(MisplacedAttrs.Range)) << FixItHint::CreateRemoval(MisplacedAttrs.Range); Attrs.takeAllFrom(MisplacedAttrs); } ConsumeToken(); // HLSL change begin -warning ext before HLSL2021. if (getLangOpts().HLSL) { if (getLangOpts().HLSLVersion < hlsl::LangStd::v2021) Diag(UsingLoc, diag::warn_hlsl_new_feature) << "keyword 'using'" << "2021"; } else // HLSL change end. Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_alias_declaration : diag::ext_alias_declaration); // Type alias templates cannot be specialized. int SpecKind = -1; if (TemplateInfo.Kind == ParsedTemplateInfo::Template && Name.getKind() == UnqualifiedId::IK_TemplateId) SpecKind = 0; if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization) SpecKind = 1; if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) SpecKind = 2; if (SpecKind != -1) { SourceRange Range; if (SpecKind == 0) Range = SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc); else Range = TemplateInfo.getSourceRange(); Diag(Range.getBegin(), diag::err_alias_declaration_specialization) << SpecKind << Range; SkipUntil(tok::semi); return nullptr; } // Name must be an identifier. if (Name.getKind() != UnqualifiedId::IK_Identifier) { Diag(Name.StartLocation, diag::err_alias_declaration_not_identifier); // No removal fixit: can't recover from this. SkipUntil(tok::semi); return nullptr; } else if (HasTypenameKeyword) Diag(TypenameLoc, diag::err_alias_declaration_not_identifier) << FixItHint::CreateRemoval(SourceRange(TypenameLoc, SS.isNotEmpty() ? SS.getEndLoc() : TypenameLoc)); else if (SS.isNotEmpty()) Diag(SS.getBeginLoc(), diag::err_alias_declaration_not_identifier) << FixItHint::CreateRemoval(SS.getRange()); TypeAlias = ParseTypeName(nullptr, TemplateInfo.Kind ? Declarator::AliasTemplateContext : Declarator::AliasDeclContext, AS, &DeclFromDeclSpec, &Attrs); if (OwnedType) *OwnedType = DeclFromDeclSpec; } else { // C++11 attributes are not allowed on a using-declaration, but GNU ones // are. ProhibitAttributes(MisplacedAttrs); ProhibitAttributes(Attrs); // Parse (optional) attributes (most likely GNU strong-using extension). MaybeParseGNUAttributes(Attrs); } // Eat ';'. DeclEnd = Tok.getLocation(); if (ExpectAndConsume(tok::semi, diag::err_expected_after, !Attrs.empty() ? "attributes list" : IsAliasDecl ? "alias declaration" : "using declaration")) SkipUntil(tok::semi); // Diagnose an attempt to declare a templated using-declaration. // In C++11, alias-declarations can be templates: // template <...> using id = type; if (TemplateInfo.Kind && !IsAliasDecl) { SourceRange R = TemplateInfo.getSourceRange(); Diag(UsingLoc, diag::err_templated_using_declaration) << R << FixItHint::CreateRemoval(R); // Unfortunately, we have to bail out instead of recovering by // ignoring the parameters, just in case the nested name specifier // depends on the parameters. return nullptr; } // "typename" keyword is allowed for identifiers only, // because it may be a type definition. if (HasTypenameKeyword && Name.getKind() != UnqualifiedId::IK_Identifier) { Diag(Name.getSourceRange().getBegin(), diag::err_typename_identifiers_only) << FixItHint::CreateRemoval(SourceRange(TypenameLoc)); // Proceed parsing, but reset the HasTypenameKeyword flag. HasTypenameKeyword = false; } if (IsAliasDecl) { TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; MultiTemplateParamsArg TemplateParamsArg( TemplateParams ? TemplateParams->data() : nullptr, TemplateParams ? TemplateParams->size() : 0); return Actions.ActOnAliasDeclaration(getCurScope(), AS, TemplateParamsArg, UsingLoc, Name, Attrs.getList(), TypeAlias, DeclFromDeclSpec); } return Actions.ActOnUsingDeclaration(getCurScope(), AS, /* HasUsingKeyword */ true, UsingLoc, SS, Name, Attrs.getList(), HasTypenameKeyword, TypenameLoc); } /// ParseStaticAssertDeclaration - Parse C++0x or C11 static_assert-declaration. /// /// [C++0x] static_assert-declaration: /// static_assert ( constant-expression , string-literal ) ; /// /// [C11] static_assert-declaration: /// _Static_assert ( constant-expression , string-literal ) ; /// Decl *Parser::ParseStaticAssertDeclaration(SourceLocation &DeclEnd){ assert(Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert) && "Not a static_assert declaration"); if (Tok.is(tok::kw__Static_assert) && !getLangOpts().C11 && !getLangOpts().HLSL) // HLSL Change - support enabled Diag(Tok, diag::ext_c11_static_assert); if (Tok.is(tok::kw_static_assert) && !getLangOpts().HLSL) // HLSL Change - support enabled Diag(Tok, diag::warn_cxx98_compat_static_assert); SourceLocation StaticAssertLoc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_paren; SkipMalformedDecl(); return nullptr; } ExprResult AssertExpr(ParseConstantExpression()); if (AssertExpr.isInvalid()) { SkipMalformedDecl(); return nullptr; } ExprResult AssertMessage; if (Tok.is(tok::r_paren)) { Diag(Tok, getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_static_assert_no_message : diag::ext_static_assert_no_message) << (getLangOpts().CPlusPlus1z ? FixItHint() : FixItHint::CreateInsertion(Tok.getLocation(), ", \"\"")); } else { if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::semi); return nullptr; } if (!isTokenStringLiteral()) { Diag(Tok, diag::err_expected_string_literal) << /*Source='static_assert'*/1; SkipMalformedDecl(); return nullptr; } AssertMessage = ParseStringLiteralExpression(); if (AssertMessage.isInvalid()) { SkipMalformedDecl(); return nullptr; } } T.consumeClose(); DeclEnd = Tok.getLocation(); ExpectAndConsumeSemi(diag::err_expected_semi_after_static_assert); return Actions.ActOnStaticAssertDeclaration(StaticAssertLoc, AssertExpr.get(), AssertMessage.get(), T.getCloseLocation()); } /// ParseDecltypeSpecifier - Parse a C++11 decltype specifier. /// /// 'decltype' ( expression ) /// 'decltype' ( 'auto' ) [C++1y] /// SourceLocation Parser::ParseDecltypeSpecifier(DeclSpec &DS) { assert(Tok.isOneOf(tok::kw_decltype, tok::annot_decltype) && "Not a decltype specifier"); ExprResult Result; SourceLocation StartLoc = Tok.getLocation(); SourceLocation EndLoc; if (Tok.is(tok::annot_decltype)) { Result = getExprAnnotation(Tok); EndLoc = Tok.getAnnotationEndLoc(); ConsumeToken(); if (Result.isInvalid()) { DS.SetTypeSpecError(); return EndLoc; } } else { if (Tok.getIdentifierInfo()->isStr("decltype")) Diag(Tok, diag::warn_cxx98_compat_decltype); ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.expectAndConsume(diag::err_expected_lparen_after, "decltype", tok::r_paren)) { DS.SetTypeSpecError(); return T.getOpenLocation() == Tok.getLocation() ? StartLoc : T.getOpenLocation(); } // Check for C++1y 'decltype(auto)'. if (Tok.is(tok::kw_auto)) { // No need to disambiguate here: an expression can't start with 'auto', // because the typename-specifier in a function-style cast operation can't // be 'auto'. Diag(Tok.getLocation(), getLangOpts().CPlusPlus14 ? diag::warn_cxx11_compat_decltype_auto_type_specifier : diag::ext_decltype_auto_type_specifier); ConsumeToken(); } else { // Parse the expression // C++11 [dcl.type.simple]p4: // The operand of the decltype specifier is an unevaluated operand. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, nullptr,/*IsDecltype=*/true); Result = Actions.CorrectDelayedTyposInExpr(ParseExpression(), [](Expr *E) { return E->hasPlaceholderType() ? ExprError() : E; }); if (Result.isInvalid()) { DS.SetTypeSpecError(); if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) { EndLoc = ConsumeParen(); } else { if (PP.isBacktrackEnabled() && Tok.is(tok::semi)) { // Backtrack to get the location of the last token before the semi. PP.RevertCachedTokens(2); ConsumeToken(); // the semi. EndLoc = ConsumeAnyToken(); assert(Tok.is(tok::semi)); } else { EndLoc = Tok.getLocation(); } } return EndLoc; } Result = Actions.ActOnDecltypeExpression(Result.get()); } // Match the ')' T.consumeClose(); if (T.getCloseLocation().isInvalid()) { DS.SetTypeSpecError(); // FIXME: this should return the location of the last token // that was consumed (by "consumeClose()") return T.getCloseLocation(); } if (Result.isInvalid()) { DS.SetTypeSpecError(); return T.getCloseLocation(); } EndLoc = T.getCloseLocation(); } assert(!Result.isInvalid()); const char *PrevSpec = nullptr; unsigned DiagID; const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); // Check for duplicate type specifiers (e.g. "int decltype(a)"). if (Result.get() ? DS.SetTypeSpecType(DeclSpec::TST_decltype, StartLoc, PrevSpec, DiagID, Result.get(), Policy) : DS.SetTypeSpecType(DeclSpec::TST_decltype_auto, StartLoc, PrevSpec, DiagID, Policy)) { Diag(StartLoc, DiagID) << PrevSpec; DS.SetTypeSpecError(); } return EndLoc; } void Parser::AnnotateExistingDecltypeSpecifier(const DeclSpec& DS, SourceLocation StartLoc, SourceLocation EndLoc) { // make sure we have a token we can turn into an annotation token if (PP.isBacktrackEnabled()) PP.RevertCachedTokens(1); else PP.EnterToken(Tok); Tok.setKind(tok::annot_decltype); setExprAnnotation(Tok, DS.getTypeSpecType() == TST_decltype ? DS.getRepAsExpr() : DS.getTypeSpecType() == TST_decltype_auto ? ExprResult() : ExprError()); Tok.setAnnotationEndLoc(EndLoc); Tok.setLocation(StartLoc); PP.AnnotateCachedTokens(Tok); } void Parser::ParseUnderlyingTypeSpecifier(DeclSpec &DS) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << Tok.getName(); DS.SetTypeSpecError(); ConsumeToken(); if (Tok.is(tok::l_paren)) { BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); T.skipToEnd(); } return; } // HLSL Change Ends assert(Tok.is(tok::kw___underlying_type) && "Not an underlying type specifier"); SourceLocation StartLoc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.expectAndConsume(diag::err_expected_lparen_after, "__underlying_type", tok::r_paren)) { return; } TypeResult Result = ParseTypeName(); if (Result.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return; } // Match the ')' T.consumeClose(); if (T.getCloseLocation().isInvalid()) return; const char *PrevSpec = nullptr; unsigned DiagID; if (DS.SetTypeSpecType(DeclSpec::TST_underlyingType, StartLoc, PrevSpec, DiagID, Result.get(), Actions.getASTContext().getPrintingPolicy())) Diag(StartLoc, DiagID) << PrevSpec; DS.setTypeofParensRange(T.getRange()); } /// ParseBaseTypeSpecifier - Parse a C++ base-type-specifier which is either a /// class name or decltype-specifier. Note that we only check that the result /// names a type; semantic analysis will need to verify that the type names a /// class. The result is either a type or null, depending on whether a type /// name was found. /// /// base-type-specifier: [C++11 class.derived] /// class-or-decltype /// class-or-decltype: [C++11 class.derived] /// nested-name-specifier[opt] class-name /// decltype-specifier /// class-name: [C++ class.name] /// identifier /// simple-template-id /// /// In C++98, instead of base-type-specifier, we have: /// /// ::[opt] nested-name-specifier[opt] class-name TypeResult Parser::ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation) { // Ignore attempts to use typename if (Tok.is(tok::kw_typename)) { Diag(Tok, diag::err_expected_class_name_not_template) << FixItHint::CreateRemoval(Tok.getLocation()); ConsumeToken(); } // Parse optional nested-name-specifier CXXScopeSpec SS; ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); BaseLoc = Tok.getLocation(); // Parse decltype-specifier // tok == kw_decltype is just error recovery, it can only happen when SS // isn't empty if (Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) { if (SS.isNotEmpty()) Diag(SS.getBeginLoc(), diag::err_unexpected_scope_on_base_decltype) << FixItHint::CreateRemoval(SS.getRange()); // Fake up a Declarator to use with ActOnTypeName. DeclSpec DS(AttrFactory); EndLocation = ParseDecltypeSpecifier(DS); Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); } // Check whether we have a template-id that names a type. if (Tok.is(tok::annot_template_id)) { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); if (TemplateId->Kind == TNK_Type_template || TemplateId->Kind == TNK_Dependent_template_name) { AnnotateTemplateIdTokenAsType(); assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); ParsedType Type = getTypeAnnotation(Tok); EndLocation = Tok.getAnnotationEndLoc(); ConsumeToken(); if (Type) return Type; return true; } // Fall through to produce an error below. } if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected_class_name); return true; } IdentifierInfo *Id = Tok.getIdentifierInfo(); SourceLocation IdLoc = ConsumeToken(); if (Tok.is(tok::less)) { // It looks the user intended to write a template-id here, but the // template-name was wrong. Try to fix that. TemplateNameKind TNK = TNK_Type_template; TemplateTy Template; if (!Actions.DiagnoseUnknownTemplateName(*Id, IdLoc, getCurScope(), &SS, Template, TNK)) { Diag(IdLoc, diag::err_unknown_template_name) << Id; } if (!Template) { TemplateArgList TemplateArgs; SourceLocation LAngleLoc, RAngleLoc; ParseTemplateIdAfterTemplateName(TemplateTy(), IdLoc, SS, true, LAngleLoc, TemplateArgs, RAngleLoc); return true; } // Form the template name UnqualifiedId TemplateName; TemplateName.setIdentifier(Id, IdLoc); // Parse the full template-id, then turn it into a type. if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), TemplateName, true)) return true; if (TNK == TNK_Dependent_template_name) AnnotateTemplateIdTokenAsType(); // If we didn't end up with a typename token, there's nothing more we // can do. if (Tok.isNot(tok::annot_typename)) return true; // Retrieve the type from the annotation token, consume that token, and // return. EndLocation = Tok.getAnnotationEndLoc(); ParsedType Type = getTypeAnnotation(Tok); ConsumeToken(); return Type; } // We have an identifier; check whether it is actually a type. IdentifierInfo *CorrectedII = nullptr; ParsedType Type = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, true, false, ParsedType(), /*IsCtorOrDtorName=*/false, /*NonTrivialTypeSourceInfo=*/true, &CorrectedII); if (!Type) { Diag(IdLoc, diag::err_expected_class_name); return true; } // Consume the identifier. EndLocation = IdLoc; // Fake up a Declarator to use with ActOnTypeName. DeclSpec DS(AttrFactory); DS.SetRangeStart(IdLoc); DS.SetRangeEnd(EndLocation); DS.getTypeSpecScope() = SS; const char *PrevSpec = nullptr; unsigned DiagID; DS.SetTypeSpecType(TST_typename, IdLoc, PrevSpec, DiagID, Type, Actions.getASTContext().getPrintingPolicy()); Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); return Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); } void Parser::ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs) { while (Tok.isOneOf(tok::kw___single_inheritance, tok::kw___multiple_inheritance, tok::kw___virtual_inheritance)) { IdentifierInfo *AttrName = Tok.getIdentifierInfo(); SourceLocation AttrNameLoc = ConsumeToken(); attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0, AttributeList::AS_Keyword); } } /// Determine whether the following tokens are valid after a type-specifier /// which could be a standalone declaration. This will conservatively return /// true if there's any doubt, and is appropriate for insert-';' fixits. bool Parser::isValidAfterTypeSpecifier(bool CouldBeBitfield) { // HLSL Change Starts - abridged version of the table below if (getLangOpts().HLSL) { switch (Tok.getKind()) { case tok::semi: case tok::identifier: return true; case tok::colon: return CouldBeBitfield; default: return false; } } // HLSL Change Ends // This switch enumerates the valid "follow" set for type-specifiers. switch (Tok.getKind()) { default: break; case tok::semi: // struct foo {...} ; case tok::star: // struct foo {...} * P; case tok::amp: // struct foo {...} & R = ... case tok::ampamp: // struct foo {...} && R = ... case tok::identifier: // struct foo {...} V ; case tok::r_paren: //(struct foo {...} ) {4} case tok::annot_cxxscope: // struct foo {...} a:: b; case tok::annot_typename: // struct foo {...} a ::b; case tok::annot_template_id: // struct foo {...} a<int> ::b; case tok::l_paren: // struct foo {...} ( x); case tok::comma: // __builtin_offsetof(struct foo{...} , case tok::kw_operator: // struct foo operator ++() {...} case tok::kw___declspec: // struct foo {...} __declspec(...) case tok::l_square: // void f(struct f [ 3]) case tok::ellipsis: // void f(struct f ... [Ns]) // FIXME: we should emit semantic diagnostic when declaration // attribute is in type attribute position. case tok::kw___attribute: // struct foo __attribute__((used)) x; return true; case tok::colon: return CouldBeBitfield; // enum E { ... } : 2; // Type qualifiers case tok::kw_const: // struct foo {...} const x; case tok::kw_volatile: // struct foo {...} volatile x; case tok::kw_restrict: // struct foo {...} restrict x; case tok::kw__Atomic: // struct foo {...} _Atomic x; case tok::kw___unaligned: // struct foo {...} __unaligned *x; // Function specifiers // Note, no 'explicit'. An explicit function must be either a conversion // operator or a constructor. Either way, it can't have a return type. case tok::kw_inline: // struct foo inline f(); case tok::kw_virtual: // struct foo virtual f(); case tok::kw_friend: // struct foo friend f(); // Storage-class specifiers case tok::kw_static: // struct foo {...} static x; case tok::kw_extern: // struct foo {...} extern x; case tok::kw_typedef: // struct foo {...} typedef x; case tok::kw_register: // struct foo {...} register x; case tok::kw_auto: // struct foo {...} auto x; case tok::kw_mutable: // struct foo {...} mutable x; case tok::kw_thread_local: // struct foo {...} thread_local x; case tok::kw_constexpr: // struct foo {...} constexpr x; // As shown above, type qualifiers and storage class specifiers absolutely // can occur after class specifiers according to the grammar. However, // almost no one actually writes code like this. If we see one of these, // it is much more likely that someone missed a semi colon and the // type/storage class specifier we're seeing is part of the *next* // intended declaration, as in: // // struct foo { ... } // typedef int X; // // We'd really like to emit a missing semicolon error instead of emitting // an error on the 'int' saying that you can't have two type specifiers in // the same declaration of X. Because of this, we look ahead past this // token to see if it's a type specifier. If so, we know the code is // otherwise invalid, so we can produce the expected semi error. if (!isKnownToBeTypeSpecifier(NextToken())) return true; break; case tok::r_brace: // struct bar { struct foo {...} } // Missing ';' at end of struct is accepted as an extension in C mode. if (!getLangOpts().CPlusPlus) return true; break; case tok::greater: // template<class T = class X> return getLangOpts().CPlusPlus; } return false; } /// ParseClassSpecifier - Parse a C++ class-specifier [C++ class] or /// elaborated-type-specifier [C++ dcl.type.elab]; we can't tell which /// until we reach the start of a definition or see a token that /// cannot start a definition. /// /// class-specifier: [C++ class] /// class-head '{' member-specification[opt] '}' /// class-head '{' member-specification[opt] '}' attributes[opt] /// class-head: /// class-key identifier[opt] base-clause[opt] /// class-key nested-name-specifier identifier base-clause[opt] /// class-key nested-name-specifier[opt] simple-template-id /// base-clause[opt] /// [GNU] class-key attributes[opt] identifier[opt] base-clause[opt] /// [GNU] class-key attributes[opt] nested-name-specifier /// identifier base-clause[opt] /// [GNU] class-key attributes[opt] nested-name-specifier[opt] /// simple-template-id base-clause[opt] /// class-key: /// 'class' /// 'struct' /// 'union' /// /// elaborated-type-specifier: [C++ dcl.type.elab] /// class-key ::[opt] nested-name-specifier[opt] identifier /// class-key ::[opt] nested-name-specifier[opt] 'template'[opt] /// simple-template-id /// /// Note that the C++ class-specifier and elaborated-type-specifier, /// together, subsume the C99 struct-or-union-specifier: /// /// struct-or-union-specifier: [C99 6.7.2.1] /// struct-or-union identifier[opt] '{' struct-contents '}' /// struct-or-union identifier /// [GNU] struct-or-union attributes[opt] identifier[opt] '{' struct-contents /// '}' attributes[opt] /// [GNU] struct-or-union attributes[opt] identifier /// struct-or-union: /// 'struct' /// 'union' void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation StartLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes) { DeclSpec::TST TagType; if (TagTokKind == tok::kw_struct) TagType = DeclSpec::TST_struct; else if (TagTokKind == tok::kw___interface || TagTokKind == tok::kw_interface) // HLSL Change - support 'interface' TagType = DeclSpec::TST_interface; else if (TagTokKind == tok::kw_class) TagType = DeclSpec::TST_class; else { assert(TagTokKind == tok::kw_union && "Not a class specifier"); TagType = DeclSpec::TST_union; } if (Tok.is(tok::code_completion)) { // Code completion for a struct, class, or union name. Actions.CodeCompleteTag(getCurScope(), TagType); return cutOffParsing(); } // C++03 [temp.explicit] 14.7.2/8: // The usual access checking rules do not apply to names used to specify // explicit instantiations. // // As an extension we do not perform access checking on the names used to // specify explicit specializations either. This is important to allow // specializing traits classes for private types. // // Note that we don't suppress if this turns out to be an elaborated // type specifier. bool shouldDelayDiagsInTag = (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation || TemplateInfo.Kind == ParsedTemplateInfo::ExplicitSpecialization); SuppressAccessChecks diagsFromTag(*this, shouldDelayDiagsInTag); ParsedAttributesWithRange attrs(AttrFactory); // If attributes exist after tag, parse them. MaybeParseGNUAttributes(attrs); MaybeParseMicrosoftDeclSpecs(attrs); // Parse inheritance specifiers. // HLSL Change Starts - these keywords are only defined for Microsoft Extensions assert(!getLangOpts().HLSL || (!Tok.is(tok::kw___single_inheritance) && !Tok.is(tok::kw___multiple_inheritance) && !Tok.is(tok::kw___virtual_inheritance))); // HLSL Change if (!getLangOpts().HLSL) { // HLSL Change Ends - succeeding block is now conditional if (Tok.isOneOf(tok::kw___single_inheritance, tok::kw___multiple_inheritance, tok::kw___virtual_inheritance)) ParseMicrosoftInheritanceClassAttributes(attrs); } // HLSL Change - close conditional block // If C++0x attributes exist here, parse them. // FIXME: Are we consistent with the ordering of parsing of different // styles of attributes? MaybeParseCXX11Attributes(attrs); MaybeParseHLSLAttributes(attrs); // HLSL Change // Source location used by FIXIT to insert misplaced // C++11 attributes SourceLocation AttrFixitLoc = Tok.getLocation(); if (!getLangOpts().HLSL) { // HLSL Change - skip fixes for GNU libstdc++ - succeeding block is now conditional if (TagType == DeclSpec::TST_struct && Tok.isNot(tok::identifier) && !Tok.isAnnotation() && Tok.getIdentifierInfo() && Tok.isOneOf(tok::kw___is_abstract, tok::kw___is_arithmetic, tok::kw___is_array, tok::kw___is_base_of, tok::kw___is_class, tok::kw___is_complete_type, tok::kw___is_compound, tok::kw___is_const, tok::kw___is_constructible, tok::kw___is_convertible, tok::kw___is_convertible_to, tok::kw___is_destructible, tok::kw___is_empty, tok::kw___is_enum, tok::kw___is_floating_point, tok::kw___is_final, tok::kw___is_function, tok::kw___is_fundamental, tok::kw___is_integral, tok::kw___is_interface_class, tok::kw___is_literal, tok::kw___is_lvalue_expr, tok::kw___is_lvalue_reference, tok::kw___is_member_function_pointer, tok::kw___is_member_object_pointer, tok::kw___is_member_pointer, tok::kw___is_nothrow_assignable, tok::kw___is_nothrow_constructible, tok::kw___is_nothrow_destructible, tok::kw___is_object, tok::kw___is_pod, tok::kw___is_pointer, tok::kw___is_polymorphic, tok::kw___is_reference, tok::kw___is_rvalue_expr, tok::kw___is_rvalue_reference, tok::kw___is_same, tok::kw___is_scalar, tok::kw___is_sealed, tok::kw___is_signed, tok::kw___is_standard_layout, tok::kw___is_trivial, tok::kw___is_trivially_assignable, tok::kw___is_trivially_constructible, tok::kw___is_trivially_copyable, tok::kw___is_union, tok::kw___is_unsigned, tok::kw___is_void, tok::kw___is_volatile)) // GNU libstdc++ 4.2 and libc++ use certain intrinsic names as the // name of struct templates, but some are keywords in GCC >= 4.3 // and Clang. Therefore, when we see the token sequence "struct // X", make X into a normal identifier rather than a keyword, to // allow libstdc++ 4.2 and libc++ to work properly. TryKeywordIdentFallback(true); } // HLSL Change - close conditional block // Parse the (optional) nested-name-specifier. CXXScopeSpec &SS = DS.getTypeSpecScope(); if (getLangOpts().CPlusPlus) { // "FOO : BAR" is not a potential typo for "FOO::BAR". In this context it // is a base-specifier-list. ColonProtectionRAIIObject X(*this); CXXScopeSpec Spec; bool HasValidSpec = true; if (ParseOptionalCXXScopeSpecifier(Spec, ParsedType(), EnteringContext)) { DS.SetTypeSpecError(); HasValidSpec = false; } if (Spec.isSet()) if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) { Diag(Tok, diag::err_expected) << tok::identifier; HasValidSpec = false; } if (HasValidSpec) SS = Spec; } TemplateParameterLists *TemplateParams = TemplateInfo.TemplateParams; // Parse the (optional) class name or simple-template-id. IdentifierInfo *Name = nullptr; SourceLocation NameLoc; TemplateIdAnnotation *TemplateId = nullptr; if (Tok.is(tok::identifier)) { Name = Tok.getIdentifierInfo(); NameLoc = ConsumeToken(); if (Tok.is(tok::less) && getLangOpts().CPlusPlus) { // The name was supposed to refer to a template, but didn't. // Eat the template argument list and try to continue parsing this as // a class (or template thereof). TemplateArgList TemplateArgs; SourceLocation LAngleLoc, RAngleLoc; if (ParseTemplateIdAfterTemplateName(TemplateTy(), NameLoc, SS, true, LAngleLoc, TemplateArgs, RAngleLoc)) { // We couldn't parse the template argument list at all, so don't // try to give any location information for the list. LAngleLoc = RAngleLoc = SourceLocation(); } Diag(NameLoc, diag::err_explicit_spec_non_template) << (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) << TagTokKind << Name << SourceRange(LAngleLoc, RAngleLoc); // Strip off the last template parameter list if it was empty, since // we've removed its template argument list. if (TemplateParams && TemplateInfo.LastParameterListWasEmpty) { if (TemplateParams && TemplateParams->size() > 1) { TemplateParams->pop_back(); } else { TemplateParams = nullptr; const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind = ParsedTemplateInfo::NonTemplate; } } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { // Pretend this is just a forward declaration. TemplateParams = nullptr; const_cast<ParsedTemplateInfo&>(TemplateInfo).Kind = ParsedTemplateInfo::NonTemplate; const_cast<ParsedTemplateInfo&>(TemplateInfo).TemplateLoc = SourceLocation(); const_cast<ParsedTemplateInfo&>(TemplateInfo).ExternLoc = SourceLocation(); } } } else if (Tok.is(tok::annot_template_id)) { TemplateId = takeTemplateIdAnnotation(Tok); NameLoc = ConsumeToken(); if (TemplateId->Kind != TNK_Type_template && TemplateId->Kind != TNK_Dependent_template_name) { // The template-name in the simple-template-id refers to // something other than a class template. Give an appropriate // error message and skip to the ';'. SourceRange Range(NameLoc); if (SS.isNotEmpty()) Range.setBegin(SS.getBeginLoc()); // FIXME: Name may be null here. Diag(TemplateId->LAngleLoc, diag::err_template_spec_syntax_non_template) << TemplateId->Name << static_cast<int>(TemplateId->Kind) << Range; DS.SetTypeSpecError(); SkipUntil(tok::semi, StopBeforeMatch); return; } } // There are four options here. // - If we are in a trailing return type, this is always just a reference, // and we must not try to parse a definition. For instance, // [] () -> struct S { }; // does not define a type. // - If we have 'struct foo {...', 'struct foo :...', // 'struct foo final :' or 'struct foo final {', then this is a definition. // - If we have 'struct foo;', then this is either a forward declaration // or a friend declaration, which have to be treated differently. // - Otherwise we have something like 'struct foo xyz', a reference. // // We also detect these erroneous cases to provide better diagnostic for // C++11 attributes parsing. // - attributes follow class name: // struct foo [[]] {}; // - attributes appear before or after 'final': // struct foo [[]] final [[]] {}; // // However, in type-specifier-seq's, things look like declarations but are // just references, e.g. // new struct s; // or // &T::operator struct s; // For these, DSC is DSC_type_specifier or DSC_alias_declaration. // If there are attributes after class name, parse them. MaybeParseCXX11Attributes(Attributes); MaybeParseHLSLAttributes(Attributes); // HLSL Change const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); Sema::TagUseKind TUK; if (DSC == DSC_trailing) TUK = Sema::TUK_Reference; else if (Tok.is(tok::l_brace) || (getLangOpts().CPlusPlus && Tok.is(tok::colon)) || (isCXX11FinalKeyword() && (NextToken().is(tok::l_brace) || NextToken().is(tok::colon)))) { if (DS.isFriendSpecified()) { // C++ [class.friend]p2: // A class shall not be defined in a friend declaration. Diag(Tok.getLocation(), diag::err_friend_decl_defines_type) << SourceRange(DS.getFriendSpecLoc()); // Skip everything up to the semicolon, so that this looks like a proper // friend class (or template thereof) declaration. SkipUntil(tok::semi, StopBeforeMatch); TUK = Sema::TUK_Friend; } else { // Okay, this is a class definition. TUK = Sema::TUK_Definition; } } else if (isCXX11FinalKeyword() && (NextToken().is(tok::l_square) || NextToken().is(tok::kw_alignas))) { // We can't tell if this is a definition or reference // until we skipped the 'final' and C++11 attribute specifiers. TentativeParsingAction PA(*this); // Skip the 'final' keyword. ConsumeToken(); // Skip C++11 attribute specifiers. while (true) { if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) { ConsumeBracket(); if (!SkipUntil(tok::r_square, StopAtSemi)) break; } else if (Tok.is(tok::kw_alignas) && NextToken().is(tok::l_paren)) { ConsumeToken(); ConsumeParen(); if (!SkipUntil(tok::r_paren, StopAtSemi)) break; } else { break; } } if (Tok.isOneOf(tok::l_brace, tok::colon)) TUK = Sema::TUK_Definition; else TUK = Sema::TUK_Reference; PA.Revert(); } else if (!isTypeSpecifier(DSC) && (Tok.is(tok::semi) || (Tok.isAtStartOfLine() && !isValidAfterTypeSpecifier(false)))) { TUK = DS.isFriendSpecified() ? Sema::TUK_Friend : Sema::TUK_Declaration; if (Tok.isNot(tok::semi)) { const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy(); // A semicolon was missing after this declaration. Diagnose and recover. ExpectAndConsume(tok::semi, diag::err_expected_after, DeclSpec::getSpecifierName(TagType, PPol)); PP.EnterToken(Tok); Tok.setKind(tok::semi); } } else TUK = Sema::TUK_Reference; // Forbid misplaced attributes. In cases of a reference, we pass attributes // to caller to handle. if (TUK != Sema::TUK_Reference) { // If this is not a reference, then the only possible // valid place for C++11 attributes to appear here // is between class-key and class-name. If there are // any attributes after class-name, we try a fixit to move // them to the right place. SourceRange AttrRange = Attributes.Range; if (AttrRange.isValid()) { Diag(AttrRange.getBegin(), diag::err_attributes_not_allowed) << AttrRange << FixItHint::CreateInsertionFromRange(AttrFixitLoc, CharSourceRange(AttrRange, true)) << FixItHint::CreateRemoval(AttrRange); // Recover by adding misplaced attributes to the attribute list // of the class so they can be applied on the class later. attrs.takeAllFrom(Attributes); } } // If this is an elaborated type specifier, and we delayed // diagnostics before, just merge them into the current pool. if (shouldDelayDiagsInTag) { diagsFromTag.done(); if (TUK == Sema::TUK_Reference) diagsFromTag.redelay(); } if (!Name && !TemplateId && (DS.getTypeSpecType() == DeclSpec::TST_error || TUK != Sema::TUK_Definition)) { if (DS.getTypeSpecType() != DeclSpec::TST_error) { // We have a declaration or reference to an anonymous class. Diag(StartLoc, diag::err_anon_type_definition) << DeclSpec::getSpecifierName(TagType, Policy); } // If we are parsing a definition and stop at a base-clause, continue on // until the semicolon. Continuing from the comma will just trick us into // thinking we are seeing a variable declaration. if (TUK == Sema::TUK_Definition && Tok.is(tok::colon)) SkipUntil(tok::semi, StopBeforeMatch); else SkipUntil(tok::comma, StopAtSemi); return; } // Create the tag portion of the class or class template. DeclResult TagOrTempResult = true; // invalid TypeResult TypeResult = true; // invalid bool Owned = false; Sema::SkipBodyInfo SkipBody; if (TemplateId) { // Explicit specialization, class template partial specialization, // or explicit instantiation. ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), TemplateId->NumArgs); if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && TUK == Sema::TUK_Declaration) { // This is an explicit instantiation of a class template. ProhibitAttributes(attrs); TagOrTempResult = Actions.ActOnExplicitInstantiation(getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, TagType, StartLoc, SS, TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc, attrs.getList()); // Friend template-ids are treated as references unless // they have template headers, in which case they're ill-formed // (FIXME: "template <class T> friend class A<T>::B<int>;"). // We diagnose this error in ActOnClassTemplateSpecialization. } else if (TUK == Sema::TUK_Reference || (TUK == Sema::TUK_Friend && TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate)) { ProhibitAttributes(attrs); TypeResult = Actions.ActOnTagTemplateIdType(TUK, TagType, StartLoc, TemplateId->SS, TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc); } else { // This is an explicit specialization or a class template // partial specialization. TemplateParameterLists FakedParamLists; if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { // This looks like an explicit instantiation, because we have // something like // // template class Foo<X> // // but it actually has a definition. Most likely, this was // meant to be an explicit specialization, but the user forgot // the '<>' after 'template'. // It this is friend declaration however, since it cannot have a // template header, it is most likely that the user meant to // remove the 'template' keyword. assert((TUK == Sema::TUK_Definition || TUK == Sema::TUK_Friend) && "Expected a definition here"); if (TUK == Sema::TUK_Friend) { Diag(DS.getFriendSpecLoc(), diag::err_friend_explicit_instantiation); TemplateParams = nullptr; } else { SourceLocation LAngleLoc = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); Diag(TemplateId->TemplateNameLoc, diag::err_explicit_instantiation_with_definition) << SourceRange(TemplateInfo.TemplateLoc) << FixItHint::CreateInsertion(LAngleLoc, "<>"); // Create a fake template parameter list that contains only // "template<>", so that we treat this construct as a class // template specialization. FakedParamLists.push_back(Actions.ActOnTemplateParameterList( 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr, 0, LAngleLoc)); TemplateParams = &FakedParamLists; } } // Build the class template specialization. TagOrTempResult = Actions.ActOnClassTemplateSpecialization( getCurScope(), TagType, TUK, StartLoc, DS.getModulePrivateSpecLoc(), *TemplateId, attrs.getList(), MultiTemplateParamsArg(TemplateParams ? &(*TemplateParams)[0] : nullptr, TemplateParams ? TemplateParams->size() : 0), &SkipBody); } } else if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation && TUK == Sema::TUK_Declaration) { // Explicit instantiation of a member of a class template // specialization, e.g., // // template struct Outer<int>::Inner; // ProhibitAttributes(attrs); TagOrTempResult = Actions.ActOnExplicitInstantiation(getCurScope(), TemplateInfo.ExternLoc, TemplateInfo.TemplateLoc, TagType, StartLoc, SS, Name, NameLoc, attrs.getList()); } else if (TUK == Sema::TUK_Friend && TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) { ProhibitAttributes(attrs); TagOrTempResult = Actions.ActOnTemplatedFriendTag(getCurScope(), DS.getFriendSpecLoc(), TagType, StartLoc, SS, Name, NameLoc, attrs.getList(), MultiTemplateParamsArg( TemplateParams? &(*TemplateParams)[0] : nullptr, TemplateParams? TemplateParams->size() : 0)); } else { if (TUK != Sema::TUK_Declaration && TUK != Sema::TUK_Definition) ProhibitAttributes(attrs); if (TUK == Sema::TUK_Definition && TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { // If the declarator-id is not a template-id, issue a diagnostic and // recover by ignoring the 'template' keyword. Diag(Tok, diag::err_template_defn_explicit_instantiation) << 1 << FixItHint::CreateRemoval(TemplateInfo.TemplateLoc); TemplateParams = nullptr; } bool IsDependent = false; // Don't pass down template parameter lists if this is just a tag // reference. For example, we don't need the template parameters here: // template <class T> class A *makeA(T t); MultiTemplateParamsArg TParams; if (TUK != Sema::TUK_Reference && TemplateParams) TParams = MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size()); handleDeclspecAlignBeforeClassKey(attrs, DS, TUK); // Declaration or definition of a class type TagOrTempResult = Actions.ActOnTag(getCurScope(), TagType, TUK, StartLoc, SS, Name, NameLoc, attrs.getList(), AS, DS.getModulePrivateSpecLoc(), TParams, Owned, IsDependent, SourceLocation(), false, clang::TypeResult(), DSC == DSC_type_specifier, &SkipBody); // If ActOnTag said the type was dependent, try again with the // less common call. if (IsDependent) { assert(TUK == Sema::TUK_Reference || TUK == Sema::TUK_Friend); TypeResult = Actions.ActOnDependentTag(getCurScope(), TagType, TUK, SS, Name, StartLoc, NameLoc); } } // If there is a body, parse it and inform the actions module. if (TUK == Sema::TUK_Definition) { assert(Tok.is(tok::l_brace) || (getLangOpts().CPlusPlus && Tok.is(tok::colon)) || isCXX11FinalKeyword()); if (SkipBody.ShouldSkip) SkipCXXMemberSpecification(StartLoc, AttrFixitLoc, TagType, TagOrTempResult.get()); else if (getLangOpts().CPlusPlus) ParseCXXMemberSpecification(StartLoc, AttrFixitLoc, attrs, TagType, TagOrTempResult.get()); else ParseStructUnionBody(StartLoc, TagType, TagOrTempResult.get()); } const char *PrevSpec = nullptr; unsigned DiagID; bool Result; if (!TypeResult.isInvalid()) { Result = DS.SetTypeSpecType(DeclSpec::TST_typename, StartLoc, NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec, DiagID, TypeResult.get(), Policy); } else if (!TagOrTempResult.isInvalid()) { Result = DS.SetTypeSpecType(TagType, StartLoc, NameLoc.isValid() ? NameLoc : StartLoc, PrevSpec, DiagID, TagOrTempResult.get(), Owned, Policy); } else { DS.SetTypeSpecError(); return; } if (Result) Diag(StartLoc, DiagID) << PrevSpec; // At this point, we've successfully parsed a class-specifier in 'definition' // form (e.g. "struct foo { int x; }". While we could just return here, we're // going to look at what comes after it to improve error recovery. If an // impossible token occurs next, we assume that the programmer forgot a ; at // the end of the declaration and recover that way. // // Also enforce C++ [temp]p3: // In a template-declaration which defines a class, no declarator // is permitted. // // After a type-specifier, we don't expect a semicolon. This only happens in // C, since definitions are not permitted in this context in C++. if (TUK == Sema::TUK_Definition && (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) && (TemplateInfo.Kind || !isValidAfterTypeSpecifier(false))) { if (Tok.isNot(tok::semi)) { const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy(); ExpectAndConsume(tok::semi, diag::err_expected_after, DeclSpec::getSpecifierName(TagType, PPol)); // Push this token back into the preprocessor and change our current token // to ';' so that the rest of the code recovers as though there were an // ';' after the definition. PP.EnterToken(Tok); Tok.setKind(tok::semi); } } } /// ParseBaseClause - Parse the base-clause of a C++ class [C++ class.derived]. /// /// base-clause : [C++ class.derived] /// ':' base-specifier-list /// base-specifier-list: /// base-specifier '...'[opt] /// base-specifier-list ',' base-specifier '...'[opt] void Parser::ParseBaseClause(Decl *ClassDecl) { assert(Tok.is(tok::colon) && "Not a base clause"); ConsumeToken(); // Build up an array of parsed base specifiers. SmallVector<CXXBaseSpecifier *, 8> BaseInfo; while (true) { // Parse a base-specifier. BaseResult Result = ParseBaseSpecifier(ClassDecl); if (Result.isInvalid()) { // Skip the rest of this base specifier, up until the comma or // opening brace. SkipUntil(tok::comma, tok::l_brace, StopAtSemi | StopBeforeMatch); } else { // Add this to our array of base specifiers. BaseInfo.push_back(Result.get()); } // If the next token is a comma, consume it and keep reading // base-specifiers. if (!TryConsumeToken(tok::comma)) break; } // Attach the base specifiers Actions.ActOnBaseSpecifiers(ClassDecl, BaseInfo.data(), BaseInfo.size()); } /// ParseBaseSpecifier - Parse a C++ base-specifier. A base-specifier is /// one entry in the base class list of a class specifier, for example: /// class foo : public bar, virtual private baz { /// 'public bar' and 'virtual private baz' are each base-specifiers. /// /// base-specifier: [C++ class.derived] /// attribute-specifier-seq[opt] base-type-specifier /// attribute-specifier-seq[opt] 'virtual' access-specifier[opt] /// base-type-specifier /// attribute-specifier-seq[opt] access-specifier 'virtual'[opt] /// base-type-specifier BaseResult Parser::ParseBaseSpecifier(Decl *ClassDecl) { bool IsVirtual = false; SourceLocation StartLoc = Tok.getLocation(); ParsedAttributesWithRange Attributes(AttrFactory); MaybeParseCXX11Attributes(Attributes); // Parse the 'virtual' keyword. if (TryConsumeToken(tok::kw_virtual)) { if (getLangOpts().HLSL) Diag(Tok, diag::err_hlsl_unsupported_construct) << "virtual base type"; // HLSL Change IsVirtual = true; } CheckMisplacedCXX11Attribute(Attributes, StartLoc); // Parse an (optional) access specifier. AccessSpecifier Access = getAccessSpecifierIfPresent(); if (Access != AS_none) Diag(Tok, diag::err_hlsl_unsupported_construct) << "base type access specifier"; // HLSL Change if (Access != AS_none) ConsumeToken(); if (getLangOpts().HLSL) Access = AS_public; // HLSL Change - always use public for hlsl. CheckMisplacedCXX11Attribute(Attributes, StartLoc); // Parse the 'virtual' keyword (again!), in case it came after the // access specifier. if (Tok.is(tok::kw_virtual)) { if (getLangOpts().HLSL) Diag(Tok, diag::err_hlsl_unsupported_construct) << "virtual base type"; // HLSL Change SourceLocation VirtualLoc = ConsumeToken(); if (IsVirtual) { // Complain about duplicate 'virtual' Diag(VirtualLoc, diag::err_dup_virtual) << FixItHint::CreateRemoval(VirtualLoc); } IsVirtual = true; } CheckMisplacedCXX11Attribute(Attributes, StartLoc); // Parse the class-name. SourceLocation EndLocation; SourceLocation BaseLoc; TypeResult BaseType = ParseBaseTypeSpecifier(BaseLoc, EndLocation); if (BaseType.isInvalid()) return true; // Parse the optional ellipsis (for a pack expansion). The ellipsis is // actually part of the base-specifier-list grammar productions, but we // parse it here for convenience. SourceLocation EllipsisLoc; TryConsumeToken(tok::ellipsis, EllipsisLoc); if (getLangOpts().HLSL && EllipsisLoc != SourceLocation()) Diag(Tok, diag::err_hlsl_unsupported_construct) << "base type ellipsis"; // HLSL Change // Find the complete source range for the base-specifier. SourceRange Range(StartLoc, EndLocation); // Notify semantic analysis that we have parsed a complete // base-specifier. return Actions.ActOnBaseSpecifier(ClassDecl, Range, Attributes, IsVirtual, Access, BaseType.get(), BaseLoc, EllipsisLoc); } /// getAccessSpecifierIfPresent - Determine whether the next token is /// a C++ access-specifier. /// /// access-specifier: [C++ class.derived] /// 'private' /// 'protected' /// 'public' AccessSpecifier Parser::getAccessSpecifierIfPresent() const { switch (Tok.getKind()) { default: return AS_none; case tok::kw_private: return AS_private; case tok::kw_protected: return AS_protected; case tok::kw_public: return AS_public; } } /// \brief If the given declarator has any parts for which parsing has to be /// delayed, e.g., default arguments or an exception-specification, create a /// late-parsed method declaration record to handle the parsing at the end of /// the class definition. void Parser::HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl) { DeclaratorChunk::FunctionTypeInfo &FTI = DeclaratorInfo.getFunctionTypeInfo(); // If there was a late-parsed exception-specification, we'll need a // late parse bool NeedLateParse = FTI.getExceptionSpecType() == EST_Unparsed; if (!NeedLateParse) { // Look ahead to see if there are any default args for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) { auto Param = cast<ParmVarDecl>(FTI.Params[ParamIdx].Param); if (Param->hasUnparsedDefaultArg()) { NeedLateParse = true; break; } } } if (NeedLateParse) { // Push this method onto the stack of late-parsed method // declarations. auto LateMethod = new LateParsedMethodDeclaration(this, ThisDecl); getCurrentClass().LateParsedDeclarations.push_back(LateMethod); LateMethod->TemplateScope = getCurScope()->isTemplateParamScope(); // Stash the exception-specification tokens in the late-pased method. LateMethod->ExceptionSpecTokens = FTI.ExceptionSpecTokens; FTI.ExceptionSpecTokens = 0; // Push tokens for each parameter. Those that do not have // defaults will be NULL. LateMethod->DefaultArgs.reserve(FTI.NumParams); for (unsigned ParamIdx = 0; ParamIdx < FTI.NumParams; ++ParamIdx) LateMethod->DefaultArgs.push_back(LateParsedDefaultArgument( FTI.Params[ParamIdx].Param, FTI.Params[ParamIdx].DefaultArgTokens)); } } /// isCXX11VirtSpecifier - Determine whether the given token is a C++11 /// virt-specifier. /// /// virt-specifier: /// override /// final VirtSpecifiers::Specifier Parser::isCXX11VirtSpecifier(const Token &Tok) const { if (!getLangOpts().CPlusPlus || Tok.isNot(tok::identifier) || getLangOpts().HLSL) // HLSL Change: remove support for override and final return VirtSpecifiers::VS_None; IdentifierInfo *II = Tok.getIdentifierInfo(); // Initialize the contextual keywords. if (!Ident_final) { Ident_final = &PP.getIdentifierTable().get("final"); if (getLangOpts().MicrosoftExt) Ident_sealed = &PP.getIdentifierTable().get("sealed"); Ident_override = &PP.getIdentifierTable().get("override"); } if (II == Ident_override) return VirtSpecifiers::VS_Override; if (II == Ident_sealed) return VirtSpecifiers::VS_Sealed; if (II == Ident_final) return VirtSpecifiers::VS_Final; return VirtSpecifiers::VS_None; } /// ParseOptionalCXX11VirtSpecifierSeq - Parse a virt-specifier-seq. /// /// virt-specifier-seq: /// virt-specifier /// virt-specifier-seq virt-specifier void Parser::ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc) { while (true) { VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(); if (Specifier == VirtSpecifiers::VS_None) return; if (FriendLoc.isValid()) { Diag(Tok.getLocation(), diag::err_friend_decl_spec) << VirtSpecifiers::getSpecifierName(Specifier) << FixItHint::CreateRemoval(Tok.getLocation()) << SourceRange(FriendLoc, FriendLoc); ConsumeToken(); continue; } // C++ [class.mem]p8: // A virt-specifier-seq shall contain at most one of each virt-specifier. const char *PrevSpec = nullptr; if (VS.SetSpecifier(Specifier, Tok.getLocation(), PrevSpec)) Diag(Tok.getLocation(), diag::err_duplicate_virt_specifier) << PrevSpec << FixItHint::CreateRemoval(Tok.getLocation()); if (IsInterface && (Specifier == VirtSpecifiers::VS_Final || Specifier == VirtSpecifiers::VS_Sealed)) { Diag(Tok.getLocation(), diag::err_override_control_interface) << VirtSpecifiers::getSpecifierName(Specifier); } else if (Specifier == VirtSpecifiers::VS_Sealed) { Diag(Tok.getLocation(), diag::ext_ms_sealed_keyword); } else { Diag(Tok.getLocation(), getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_override_control_keyword : diag::ext_override_control_keyword) << VirtSpecifiers::getSpecifierName(Specifier); } ConsumeToken(); } } /// isCXX11FinalKeyword - Determine whether the next token is a C++11 /// 'final' or Microsoft 'sealed' contextual keyword. bool Parser::isCXX11FinalKeyword() const { if (getLangOpts().HLSL) return false; // HLSL Change - HLSL does not support final/sealed/override. VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(); return Specifier == VirtSpecifiers::VS_Final || Specifier == VirtSpecifiers::VS_Sealed; } /// \brief Parse a C++ member-declarator up to, but not including, the optional /// brace-or-equal-initializer or pure-specifier. bool Parser::ParseCXXMemberDeclaratorBeforeInitializer( Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateParsedAttrs) { // member-declarator: // declarator pure-specifier[opt] // declarator brace-or-equal-initializer[opt] // identifier[opt] ':' constant-expression if (Tok.isNot(tok::colon)) ParseDeclarator(DeclaratorInfo); else DeclaratorInfo.SetIdentifier(nullptr, Tok.getLocation()); if (!DeclaratorInfo.isFunctionDeclarator() && TryConsumeToken(tok::colon)) { assert(DeclaratorInfo.isPastIdentifier() && "don't know where identifier would go yet?"); BitfieldSize = ParseConstantExpression(); if (BitfieldSize.isInvalid()) SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch); } else { ParseOptionalCXX11VirtSpecifierSeq( VS, getCurrentClass().IsInterface, DeclaratorInfo.getDeclSpec().getFriendSpecLoc()); if (!VS.isUnset()) MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS); } // If a simple-asm-expr is present, parse it. if (Tok.is(tok::kw_asm)) { // HLSL Change Starts - disallow asm if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch); return true; } // HLSL Change Ends SourceLocation Loc; ExprResult AsmLabel(ParseSimpleAsm(&Loc)); if (AsmLabel.isInvalid()) SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch); DeclaratorInfo.setAsmLabel(AsmLabel.get()); DeclaratorInfo.SetRangeEnd(Loc); } // If attributes exist after the declarator, but before an '{', parse them. MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); MaybeParseHLSLAttributes(DeclaratorInfo); // HLSL Change: Parse semantic on struct members // For compatibility with code written to older Clang, also accept a // virt-specifier *after* the GNU attributes. if (!getLangOpts().HLSL && BitfieldSize.isUnset() && VS.isUnset()) { // HLSL Change - disallowed ParseOptionalCXX11VirtSpecifierSeq( VS, getCurrentClass().IsInterface, DeclaratorInfo.getDeclSpec().getFriendSpecLoc()); if (!VS.isUnset()) { // If we saw any GNU-style attributes that are known to GCC followed by a // virt-specifier, issue a GCC-compat warning. const AttributeList *Attr = DeclaratorInfo.getAttributes(); while (Attr) { if (Attr->isKnownToGCC() && !Attr->isCXX11Attribute()) Diag(Attr->getLoc(), diag::warn_gcc_attribute_location); Attr = Attr->getNext(); } MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(DeclaratorInfo, VS); } } // If this has neither a name nor a bit width, something has gone seriously // wrong. Skip until the semi-colon or }. if (!DeclaratorInfo.hasName() && BitfieldSize.isUnset()) { // If so, skip until the semi-colon or a }. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); return true; } return false; } /// \brief Look for declaration specifiers possibly occurring after C++11 /// virt-specifier-seq and diagnose them. void Parser::MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq( Declarator &D, VirtSpecifiers &VS) { DeclSpec DS(AttrFactory); // GNU-style and C++11 attributes are not allowed here, but they will be // handled by the caller. Diagnose everything else. ParseTypeQualifierListOpt(DS, AR_NoAttributesParsed, false); D.ExtendWithDeclSpec(DS); if (D.isFunctionDeclarator()) { auto &Function = D.getFunctionTypeInfo(); if (DS.getTypeQualifiers() != DeclSpec::TQ_unspecified) { auto DeclSpecCheck = [&] (DeclSpec::TQ TypeQual, const char *FixItName, SourceLocation SpecLoc, unsigned* QualifierLoc) { FixItHint Insertion; if (DS.getTypeQualifiers() & TypeQual) { if (!(Function.TypeQuals & TypeQual)) { std::string Name(FixItName); Name += " "; Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name.c_str()); Function.TypeQuals |= TypeQual; *QualifierLoc = SpecLoc.getRawEncoding(); } Diag(SpecLoc, diag::err_declspec_after_virtspec) << FixItName << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier()) << FixItHint::CreateRemoval(SpecLoc) << Insertion; } }; DeclSpecCheck(DeclSpec::TQ_const, "const", DS.getConstSpecLoc(), &Function.ConstQualifierLoc); DeclSpecCheck(DeclSpec::TQ_volatile, "volatile", DS.getVolatileSpecLoc(), &Function.VolatileQualifierLoc); DeclSpecCheck(DeclSpec::TQ_restrict, "restrict", DS.getRestrictSpecLoc(), &Function.RestrictQualifierLoc); } // Parse ref-qualifiers. bool RefQualifierIsLValueRef = true; SourceLocation RefQualifierLoc; if (ParseRefQualifier(RefQualifierIsLValueRef, RefQualifierLoc)) { const char *Name = (RefQualifierIsLValueRef ? "& " : "&& "); FixItHint Insertion = FixItHint::CreateInsertion(VS.getFirstLocation(), Name); Function.RefQualifierIsLValueRef = RefQualifierIsLValueRef; Function.RefQualifierLoc = RefQualifierLoc.getRawEncoding(); Diag(RefQualifierLoc, diag::err_declspec_after_virtspec) << (RefQualifierIsLValueRef ? "&" : "&&") << VirtSpecifiers::getSpecifierName(VS.getLastSpecifier()) << FixItHint::CreateRemoval(RefQualifierLoc) << Insertion; D.SetRangeEnd(RefQualifierLoc); } } } /// ParseCXXClassMemberDeclaration - Parse a C++ class member declaration. /// /// member-declaration: /// decl-specifier-seq[opt] member-declarator-list[opt] ';' /// function-definition ';'[opt] /// ::[opt] nested-name-specifier template[opt] unqualified-id ';'[TODO] /// using-declaration [TODO] /// [C++0x] static_assert-declaration /// template-declaration /// [GNU] '__extension__' member-declaration /// /// member-declarator-list: /// member-declarator /// member-declarator-list ',' member-declarator /// /// member-declarator: /// declarator virt-specifier-seq[opt] pure-specifier[opt] /// declarator constant-initializer[opt] /// [C++11] declarator brace-or-equal-initializer[opt] /// identifier[opt] ':' constant-expression /// /// virt-specifier-seq: /// virt-specifier /// virt-specifier-seq virt-specifier /// /// virt-specifier: /// override /// final /// [MS] sealed /// /// pure-specifier: /// '= 0' /// /// constant-initializer: /// '=' constant-expression /// void Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS, AttributeList *AccessAttrs, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject *TemplateDiags) { if (Tok.is(tok::at)) { if (getLangOpts().ObjC1 && NextToken().isObjCAtKeyword(tok::objc_defs)) Diag(Tok, diag::err_at_defs_cxx); else Diag(Tok, diag::err_at_in_class); ConsumeToken(); SkipUntil(tok::r_brace, StopAtSemi); return; } // Turn on colon protection early, while parsing declspec, although there is // nothing to protect there. It prevents from false errors if error recovery // incorrectly determines where the declspec ends, as in the example: // struct A { enum class B { C }; }; // const int C = 4; // struct D { A::B : C; }; ColonProtectionRAIIObject X(*this); // Access declarations. bool MalformedTypeSpec = false; if (!TemplateInfo.Kind && Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw___super)) { if (TryAnnotateCXXScopeToken()) MalformedTypeSpec = true; bool isAccessDecl; if (Tok.isNot(tok::annot_cxxscope)) isAccessDecl = false; else if (NextToken().is(tok::identifier)) isAccessDecl = GetLookAheadToken(2).is(tok::semi); else isAccessDecl = NextToken().is(tok::kw_operator); if (isAccessDecl) { // Collect the scope specifier token we annotated earlier. CXXScopeSpec SS; ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); if (SS.isInvalid()) { SkipUntil(tok::semi); return; } // Try to parse an unqualified-id. SourceLocation TemplateKWLoc; UnqualifiedId Name; if (ParseUnqualifiedId(SS, false, true, true, ParsedType(), TemplateKWLoc, Name)) { SkipUntil(tok::semi); return; } // TODO: recover from mistakenly-qualified operator declarations. if (ExpectAndConsume(tok::semi, diag::err_expected_after, "access declaration")) { SkipUntil(tok::semi); return; } Actions.ActOnUsingDeclaration(getCurScope(), AS, /* HasUsingKeyword */ false, SourceLocation(), SS, Name, /* AttrList */ nullptr, /* HasTypenameKeyword */ false, SourceLocation()); return; } } // static_assert-declaration. A templated static_assert declaration is // diagnosed in Parser::ParseSingleDeclarationAfterTemplate. if (!TemplateInfo.Kind && Tok.isOneOf(tok::kw_static_assert, tok::kw__Static_assert)) { SourceLocation DeclEnd; ParseStaticAssertDeclaration(DeclEnd); return; } if (Tok.is(tok::kw_template)) { assert(!TemplateInfo.TemplateParams && "Nested template improperly parsed?"); // HLSL Change Starts if (getLangOpts().HLSL && getLangOpts().HLSLVersion < hlsl::LangStd::v2021) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); SkipUntil(tok::r_brace, StopAtSemi); return; } // HLSL Change Ends SourceLocation DeclEnd; ParseDeclarationStartingWithTemplate(Declarator::MemberContext, DeclEnd, AS, AccessAttrs); return; } // Handle: member-declaration ::= '__extension__' member-declaration if (Tok.is(tok::kw___extension__)) { // __extension__ silences extension warnings in the subexpression. ExtensionRAIIObject O(Diags); // Use RAII to do this. ConsumeToken(); return ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo, TemplateDiags); } ParsedAttributesWithRange attrs(AttrFactory); ParsedAttributesWithRange FnAttrs(AttrFactory); // Optional C++11 attribute-specifier MaybeParseCXX11Attributes(attrs); MaybeParseHLSLAttributes(attrs); // HLSL Change // We need to keep these attributes for future diagnostic // before they are taken over by declaration specifier. FnAttrs.addAll(attrs.getList()); FnAttrs.Range = attrs.Range; MaybeParseMicrosoftAttributes(attrs); if (Tok.is(tok::kw_using)) { ProhibitAttributes(attrs); // Eat 'using'. SourceLocation UsingLoc = ConsumeToken(); if (Tok.is(tok::kw_namespace)) { Diag(UsingLoc, diag::err_using_namespace_in_class); SkipUntil(tok::semi, StopBeforeMatch); } else { SourceLocation DeclEnd; // Otherwise, it must be a using-declaration or an alias-declaration. ParseUsingDeclaration(Declarator::MemberContext, TemplateInfo, UsingLoc, DeclEnd, AS); } return; } // Hold late-parsed attributes so we can attach a Decl to them later. LateParsedAttrList CommonLateParsedAttrs; // decl-specifier-seq: // Parse the common declaration-specifiers piece. ParsingDeclSpec DS(*this, TemplateDiags); DS.takeAttributesFrom(attrs); if (MalformedTypeSpec) DS.SetTypeSpecError(); ParseDeclarationSpecifiers(DS, TemplateInfo, AS, DSC_class, &CommonLateParsedAttrs); // Turn off colon protection that was set for declspec. X.restore(); // If we had a free-standing type definition with a missing semicolon, we // may get this far before the problem becomes obvious. if (DS.hasTagDefinition() && TemplateInfo.Kind == ParsedTemplateInfo::NonTemplate && DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_class, &CommonLateParsedAttrs)) return; MultiTemplateParamsArg TemplateParams( TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->data() : nullptr, TemplateInfo.TemplateParams? TemplateInfo.TemplateParams->size() : 0); if (TryConsumeToken(tok::semi)) { if (DS.isFriendSpecified()) ProhibitAttributes(FnAttrs); Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS, TemplateParams); DS.complete(TheDecl); return; } ParsingDeclarator DeclaratorInfo(*this, DS, Declarator::MemberContext); VirtSpecifiers VS; // Hold late-parsed attributes so we can attach a Decl to them later. LateParsedAttrList LateParsedAttrs; SourceLocation EqualLoc; SourceLocation PureSpecLoc; auto TryConsumePureSpecifier = [&] (bool AllowDefinition) { if (Tok.isNot(tok::equal)) return false; auto &Zero = NextToken(); SmallString<8> Buffer; if (Zero.isNot(tok::numeric_constant) || Zero.getLength() != 1 || PP.getSpelling(Zero, Buffer) != "0") return false; auto &After = GetLookAheadToken(2); if (!After.isOneOf(tok::semi, tok::comma) && !(AllowDefinition && After.isOneOf(tok::l_brace, tok::colon, tok::kw_try))) return false; EqualLoc = ConsumeToken(); PureSpecLoc = ConsumeToken(); return true; }; SmallVector<Decl *, 8> DeclsInGroup; ExprResult BitfieldSize; bool ExpectSemi = true; // Parse the first declarator. if (ParseCXXMemberDeclaratorBeforeInitializer( DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) { TryConsumeToken(tok::semi); return; } // Check for a member function definition. if (BitfieldSize.isUnset()) { // MSVC permits pure specifier on inline functions defined at class scope. // Hence check for =0 before checking for function definition. if (getLangOpts().MicrosoftExt && DeclaratorInfo.isDeclarationOfFunction()) TryConsumePureSpecifier(/*AllowDefinition*/ true); FunctionDefinitionKind DefinitionKind = FDK_Declaration; // function-definition: // // In C++11, a non-function declarator followed by an open brace is a // braced-init-list for an in-class member initialization, not an // erroneous function definition. if (Tok.is(tok::l_brace) && !getLangOpts().CPlusPlus11) { DefinitionKind = FDK_Definition; } else if (DeclaratorInfo.isFunctionDeclarator()) { if (Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try)) { DefinitionKind = FDK_Definition; } else if (Tok.is(tok::equal)) { const Token &KW = NextToken(); if (KW.is(tok::kw_default)) DefinitionKind = FDK_Defaulted; else if (KW.is(tok::kw_delete)) DefinitionKind = FDK_Deleted; } } DeclaratorInfo.setFunctionDefinitionKind(DefinitionKind); // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains // to a friend declaration, that declaration shall be a definition. if (DeclaratorInfo.isFunctionDeclarator() && DefinitionKind != FDK_Definition && DS.isFriendSpecified()) { // Diagnose attributes that appear before decl specifier: // [[]] friend int foo(); ProhibitAttributes(FnAttrs); } if (DefinitionKind != FDK_Declaration) { if (!DeclaratorInfo.isFunctionDeclarator()) { Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_func_def_no_params); ConsumeBrace(); SkipUntil(tok::r_brace); // Consume the optional ';' TryConsumeToken(tok::semi); return; } if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_function_declared_typedef); // Recover by treating the 'typedef' as spurious. DS.ClearStorageClassSpecs(); } Decl *FunDecl = ParseCXXInlineMethodDef(AS, AccessAttrs, DeclaratorInfo, TemplateInfo, VS, PureSpecLoc); if (FunDecl) { for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) { CommonLateParsedAttrs[i]->addDecl(FunDecl); } for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) { LateParsedAttrs[i]->addDecl(FunDecl); } } LateParsedAttrs.clear(); // Consume the ';' - it's optional unless we have a delete or default if (Tok.is(tok::semi)) ConsumeExtraSemi(AfterMemberFunctionDefinition); return; } } // member-declarator-list: // member-declarator // member-declarator-list ',' member-declarator while (1) { InClassInitStyle HasInClassInit = ICIS_NoInit; bool HasStaticInitializer = false; if (Tok.isOneOf(tok::equal, tok::l_brace) && PureSpecLoc.isInvalid()) { // HLSL Change Begin - only allow member default for static const. if (DS.getStorageClassSpec() != DeclSpec::SCS_static || !(DS.getTypeQualifiers() & Qualifiers::Const)) Diag(Tok, diag::err_hlsl_unsupported_member_default); // HLSL Change End if (BitfieldSize.get()) { Diag(Tok, diag::err_bitfield_member_init); SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch); } else if (DeclaratorInfo.isDeclarationOfFunction()) { // It's a pure-specifier. if (!TryConsumePureSpecifier(/*AllowFunctionDefinition*/ false)) // Parse it as an expression so that Sema can diagnose it. HasStaticInitializer = true; } else if (DeclaratorInfo.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static && DeclaratorInfo.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && !DS.isFriendSpecified()) { // It's a default member initializer. HasInClassInit = Tok.is(tok::equal) ? ICIS_CopyInit : ICIS_ListInit; } else { HasStaticInitializer = true; } } // NOTE: If Sema is the Action module and declarator is an instance field, // this call will *not* return the created decl; It will return null. // See Sema::ActOnCXXMemberDeclarator for details. NamedDecl *ThisDecl = nullptr; if (DS.isFriendSpecified()) { assert(!getLangOpts().HLSL && "unreachable in HLSL"); // HLSL Change // C++11 [dcl.attr.grammar] p4: If an attribute-specifier-seq appertains // to a friend declaration, that declaration shall be a definition. // // Diagnose attributes that appear in a friend member function declarator: // friend int foo [[]] (); SmallVector<SourceRange, 4> Ranges; DeclaratorInfo.getCXX11AttributeRanges(Ranges); for (SmallVectorImpl<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end(); I != E; ++I) Diag((*I).getBegin(), diag::err_attributes_not_allowed) << *I; ThisDecl = Actions.ActOnFriendFunctionDecl(getCurScope(), DeclaratorInfo, TemplateParams); } else { ThisDecl = Actions.ActOnCXXMemberDeclarator(getCurScope(), AS, DeclaratorInfo, TemplateParams, BitfieldSize.get(), VS, HasInClassInit); if (VarTemplateDecl *VT = ThisDecl ? dyn_cast<VarTemplateDecl>(ThisDecl) : nullptr) // Re-direct this decl to refer to the templated decl so that we can // initialize it. ThisDecl = VT->getTemplatedDecl(); if (ThisDecl && AccessAttrs) Actions.ProcessDeclAttributeList(getCurScope(), ThisDecl, AccessAttrs); } // Error recovery might have converted a non-static member into a static // member. if (HasInClassInit != ICIS_NoInit && DeclaratorInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) { HasInClassInit = ICIS_NoInit; HasStaticInitializer = true; } if (ThisDecl && PureSpecLoc.isValid()) Actions.ActOnPureSpecifier(ThisDecl, PureSpecLoc); // Handle the initializer. if (HasInClassInit != ICIS_NoInit) { // The initializer was deferred; parse it and cache the tokens. Diag(Tok, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_nonstatic_member_init : diag::ext_nonstatic_member_init); if (DeclaratorInfo.isArrayOfUnknownBound()) { // C++11 [dcl.array]p3: An array bound may also be omitted when the // declarator is followed by an initializer. // // A brace-or-equal-initializer for a member-declarator is not an // initializer in the grammar, so this is ill-formed. Diag(Tok, diag::err_incomplete_array_member_init); SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch); // Avoid later warnings about a class member of incomplete type. if (ThisDecl) ThisDecl->setInvalidDecl(); } else ParseCXXNonStaticMemberInitializer(ThisDecl); } else if (HasStaticInitializer) { // Normal initializer. ExprResult Init = ParseCXXMemberInitializer( ThisDecl, DeclaratorInfo.isDeclarationOfFunction(), EqualLoc); if (Init.isInvalid()) SkipUntil(tok::comma, StopAtSemi | StopBeforeMatch); else if (ThisDecl) Actions.AddInitializerToDecl(ThisDecl, Init.get(), EqualLoc.isInvalid(), DS.containsPlaceholderType()); } else if (ThisDecl && DS.getStorageClassSpec() == DeclSpec::SCS_static) // No initializer. Actions.ActOnUninitializedDecl(ThisDecl, DS.containsPlaceholderType()); if (ThisDecl) { if (!ThisDecl->isInvalidDecl()) { // Set the Decl for any late parsed attributes for (unsigned i = 0, ni = CommonLateParsedAttrs.size(); i < ni; ++i) CommonLateParsedAttrs[i]->addDecl(ThisDecl); for (unsigned i = 0, ni = LateParsedAttrs.size(); i < ni; ++i) LateParsedAttrs[i]->addDecl(ThisDecl); } Actions.FinalizeDeclaration(ThisDecl); DeclsInGroup.push_back(ThisDecl); if (DeclaratorInfo.isFunctionDeclarator() && DeclaratorInfo.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) HandleMemberFunctionDeclDelays(DeclaratorInfo, ThisDecl); } LateParsedAttrs.clear(); DeclaratorInfo.complete(ThisDecl); // If we don't have a comma, it is either the end of the list (a ';') // or an error, bail out. SourceLocation CommaLoc; if (!TryConsumeToken(tok::comma, CommaLoc)) break; if (Tok.isAtStartOfLine() && !MightBeDeclarator(Declarator::MemberContext)) { // This comma was followed by a line-break and something which can't be // the start of a declarator. The comma was probably a typo for a // semicolon. Diag(CommaLoc, diag::err_expected_semi_declaration) << FixItHint::CreateReplacement(CommaLoc, ";"); ExpectSemi = false; break; } // Parse the next declarator. DeclaratorInfo.clear(); VS.clear(); BitfieldSize = ExprResult(/*Invalid=*/false); EqualLoc = PureSpecLoc = SourceLocation(); DeclaratorInfo.setCommaLoc(CommaLoc); // GNU attributes are allowed before the second and subsequent declarator. MaybeParseGNUAttributes(DeclaratorInfo); MaybeParseHLSLAttributes(DeclaratorInfo); // HLSL Change if (ParseCXXMemberDeclaratorBeforeInitializer( DeclaratorInfo, VS, BitfieldSize, LateParsedAttrs)) break; } if (ExpectSemi && ExpectAndConsume(tok::semi, diag::err_expected_semi_decl_list)) { // Skip to end of block or statement. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); // If we stopped at a ';', eat it. TryConsumeToken(tok::semi); return; } Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup); } /// ParseCXXMemberInitializer - Parse the brace-or-equal-initializer. /// Also detect and reject any attempted defaulted/deleted function definition. /// The location of the '=', if any, will be placed in EqualLoc. /// /// This does not check for a pure-specifier; that's handled elsewhere. /// /// brace-or-equal-initializer: /// '=' initializer-expression /// braced-init-list /// /// initializer-clause: /// assignment-expression /// braced-init-list /// /// defaulted/deleted function-definition: /// '=' 'default' /// '=' 'delete' /// /// Prior to C++0x, the assignment-expression in an initializer-clause must /// be a constant-expression. ExprResult Parser::ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc) { assert(Tok.isOneOf(tok::equal, tok::l_brace) && "Data member initializer not starting with '=' or '{'"); EnterExpressionEvaluationContext Context(Actions, Sema::PotentiallyEvaluated, D); if (TryConsumeToken(tok::equal, EqualLoc)) { if (Tok.is(tok::kw_delete)) { // In principle, an initializer of '= delete p;' is legal, but it will // never type-check. It's better to diagnose it as an ill-formed expression // than as an ill-formed deleted non-function member. // An initializer of '= delete p, foo' will never be parsed, because // a top-level comma always ends the initializer expression. const Token &Next = NextToken(); if (IsFunction || Next.isOneOf(tok::semi, tok::comma, tok::eof)) { if (IsFunction) Diag(ConsumeToken(), diag::err_default_delete_in_multiple_declaration) << 1 /* delete */; else Diag(ConsumeToken(), diag::err_deleted_non_function); return ExprError(); } } else if (Tok.is(tok::kw_default)) { if (IsFunction) Diag(Tok, diag::err_default_delete_in_multiple_declaration) << 0 /* default */; else Diag(ConsumeToken(), diag::err_default_special_members); return ExprError(); } } if (const auto *PD = dyn_cast_or_null<MSPropertyDecl>(D)) { Diag(Tok, diag::err_ms_property_initializer) << PD; return ExprError(); } return ParseInitializer(); } void Parser::SkipCXXMemberSpecification(SourceLocation RecordLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl) { // Skip the optional 'final' keyword. if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) { assert(isCXX11FinalKeyword() && "not a class definition"); ConsumeToken(); // Diagnose any C++11 attributes after 'final' keyword. // We deliberately discard these attributes. ParsedAttributesWithRange Attrs(AttrFactory); CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc); // This can only happen if we had malformed misplaced attributes; // we only get called if there is a colon or left-brace after the // attributes. if (Tok.isNot(tok::colon) && Tok.isNot(tok::l_brace)) return; } // Skip the base clauses. This requires actually parsing them, because // otherwise we can't be sure where they end (a left brace may appear // within a template argument). if (Tok.is(tok::colon)) { // Enter the scope of the class so that we can correctly parse its bases. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); ParsingClassDefinition ParsingDef(*this, TagDecl, /*NonNestedClass*/ true, TagType == DeclSpec::TST_interface); auto OldContext = Actions.ActOnTagStartSkippedDefinition(getCurScope(), TagDecl); // Parse the bases but don't attach them to the class. ParseBaseClause(nullptr); Actions.ActOnTagFinishSkippedDefinition(OldContext); if (!Tok.is(tok::l_brace)) { Diag(PP.getLocForEndOfToken(PrevTokLocation), diag::err_expected_lbrace_after_base_specifiers); return; } } // Skip the body. assert(Tok.is(tok::l_brace)); BalancedDelimiterTracker T(*this, tok::l_brace); T.consumeOpen(); T.skipToEnd(); // Parse and discard any trailing attributes. ParsedAttributes Attrs(AttrFactory); if (Tok.is(tok::kw___attribute)) MaybeParseGNUAttributes(Attrs); } /// ParseCXXMemberSpecification - Parse the class definition. /// /// member-specification: /// member-declaration member-specification[opt] /// access-specifier ':' member-specification[opt] /// void Parser::ParseCXXMemberSpecification(SourceLocation RecordLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl) { assert((TagType == DeclSpec::TST_struct || TagType == DeclSpec::TST_interface || TagType == DeclSpec::TST_union || TagType == DeclSpec::TST_class) && "Invalid TagType!"); // HLSL Change Begin - Support hierarchial time tracing. llvm::TimeTraceScope TimeScope("ParseClass", [&]() { if (auto *TD = dyn_cast_or_null<NamedDecl>(TagDecl)) return TD->getQualifiedNameAsString(); return std::string("<anonymous>"); }); // HLSL Change End - Support hierarchial time tracing. PrettyDeclStackTraceEntry CrashInfo(Actions, TagDecl, RecordLoc, "parsing struct/union/class body"); // Determine whether this is a non-nested class. Note that local // classes are *not* considered to be nested classes. bool NonNestedClass = true; if (!ClassStack.empty()) { for (const Scope *S = getCurScope(); S; S = S->getParent()) { if (S->isClassScope()) { // We're inside a class scope, so this is a nested class. NonNestedClass = false; // HLSL Change Starts if (getLangOpts().HLSL && getLangOpts().HLSLVersion < hlsl::LangStd::v2016 && cast<NamedDecl>(TagDecl)->getDeclName()) { Diag(RecordLoc, diag::err_hlsl_unsupported_nested_struct); break; } else { // HLSL Change Ends - succeeding block is now conditional // The Microsoft extension __interface does not permit nested classes. if (getCurrentClass().IsInterface) { Diag(RecordLoc, diag::err_invalid_member_in_interface) << /*ErrorType=*/6 << (isa<NamedDecl>(TagDecl) ? cast<NamedDecl>(TagDecl)->getQualifiedNameAsString() : "(anonymous)"); } } // HLSL Change - close conditional break; } if ((S->getFlags() & Scope::FnScope)) // If we're in a function or function template then this is a local // class rather than a nested class. break; } } // Enter a scope for the class. ParseScope ClassScope(this, Scope::ClassScope|Scope::DeclScope); // Note that we are parsing a new (potentially-nested) class definition. ParsingClassDefinition ParsingDef(*this, TagDecl, NonNestedClass, TagType == DeclSpec::TST_interface); if (TagDecl) Actions.ActOnTagStartDefinition(getCurScope(), TagDecl); SourceLocation FinalLoc; bool IsFinalSpelledSealed = false; // Parse the optional 'final' keyword. if (getLangOpts().CPlusPlus && Tok.is(tok::identifier)) { VirtSpecifiers::Specifier Specifier = isCXX11VirtSpecifier(Tok); assert((Specifier == VirtSpecifiers::VS_Final || Specifier == VirtSpecifiers::VS_Sealed) && "not a class definition"); FinalLoc = ConsumeToken(); IsFinalSpelledSealed = Specifier == VirtSpecifiers::VS_Sealed; if (TagType == DeclSpec::TST_interface) Diag(FinalLoc, diag::err_override_control_interface) << VirtSpecifiers::getSpecifierName(Specifier); else if (Specifier == VirtSpecifiers::VS_Final) Diag(FinalLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_override_control_keyword : diag::ext_override_control_keyword) << VirtSpecifiers::getSpecifierName(Specifier); else if (Specifier == VirtSpecifiers::VS_Sealed) Diag(FinalLoc, diag::ext_ms_sealed_keyword); // Parse any C++11 attributes after 'final' keyword. // These attributes are not allowed to appear here, // and the only possible place for them to appertain // to the class would be between class-key and class-name. CheckMisplacedCXX11Attribute(Attrs, AttrFixitLoc); // ParseClassSpecifier() does only a superficial check for attributes before // deciding to call this method. For example, for // `class C final alignas ([l) {` it will decide that this looks like a // misplaced attribute since it sees `alignas '(' ')'`. But the actual // attribute parsing code will try to parse the '[' as a constexpr lambda // and consume enough tokens that the alignas parsing code will eat the // opening '{'. So bail out if the next token isn't one we expect. if (!Tok.is(tok::colon) && !Tok.is(tok::l_brace)) { if (TagDecl) Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); return; } } if (Tok.is(tok::colon)) { ParseBaseClause(TagDecl); if (!Tok.is(tok::l_brace)) { bool SuggestFixIt = false; SourceLocation BraceLoc = PP.getLocForEndOfToken(PrevTokLocation); if (Tok.isAtStartOfLine()) { switch (Tok.getKind()) { case tok::kw_private: case tok::kw_protected: case tok::kw_public: SuggestFixIt = NextToken().getKind() == tok::colon; break; case tok::kw_static_assert: case tok::r_brace: case tok::kw_using: // base-clause can have simple-template-id; 'template' can't be there case tok::kw_template: SuggestFixIt = true; break; case tok::identifier: SuggestFixIt = isConstructorDeclarator(true); break; default: SuggestFixIt = isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false); break; } } DiagnosticBuilder LBraceDiag = Diag(BraceLoc, diag::err_expected_lbrace_after_base_specifiers); if (SuggestFixIt) { LBraceDiag << FixItHint::CreateInsertion(BraceLoc, " {"); // Try recovering from missing { after base-clause. PP.EnterToken(Tok); Tok.setKind(tok::l_brace); } else { if (TagDecl) Actions.ActOnTagDefinitionError(getCurScope(), TagDecl); return; } } } assert(Tok.is(tok::l_brace)); BalancedDelimiterTracker T(*this, tok::l_brace); T.consumeOpen(); if (TagDecl) Actions.ActOnStartCXXMemberDeclarations(getCurScope(), TagDecl, FinalLoc, IsFinalSpelledSealed, T.getOpenLocation()); // C++ 11p3: Members of a class defined with the keyword class are private // by default. Members of a class defined with the keywords struct or union // are public by default. AccessSpecifier CurAS; if (TagType == DeclSpec::TST_class) CurAS = AS_private; else CurAS = AS_public; // HLSL Change Starts if (getLangOpts().HLSL) CurAS = AS_public; // HLSL only has public // HLSL Change Ends ParsedAttributes AccessAttrs(AttrFactory); if (TagDecl) { // While we still have something to read, read the member-declarations. while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { // Each iteration of this loop reads one member-declaration. if (!getLangOpts().HLSL && getLangOpts().MicrosoftExt && Tok.isOneOf(tok::kw___if_exists, // HLSL Change - remove support tok::kw___if_not_exists)) { ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS); continue; } // Check for extraneous top-level semicolon. if (Tok.is(tok::semi)) { ConsumeExtraSemi(InsideStruct, TagType); continue; } if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_vis)) { // HLSL Change - remove support HandlePragmaVisibility(); continue; } if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_pack)) { // HLSL Change - remove support HandlePragmaPack(); continue; } if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_align)) { // HLSL Change - remove support HandlePragmaAlign(); continue; } if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_openmp)) { // HLSL Change - remove support ParseOpenMPDeclarativeDirective(); continue; } if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_ms_pointers_to_members)) { // HLSL Change - remove support HandlePragmaMSPointersToMembers(); continue; } if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_ms_pragma)) { // HLSL Change - remove support HandlePragmaMSPragma(); continue; } // If we see a namespace here, a close brace was missing somewhere. if (Tok.is(tok::kw_namespace)) { DiagnoseUnexpectedNamespace(cast<NamedDecl>(TagDecl)); break; } AccessSpecifier AS = getAccessSpecifierIfPresent(); if (AS != AS_none) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); ConsumeToken(); if (Tok.is(tok::colon)) ConsumeToken(); continue; } // HLSL Change Ends // Current token is a C++ access specifier. CurAS = AS; SourceLocation ASLoc = Tok.getLocation(); unsigned TokLength = Tok.getLength(); ConsumeToken(); AccessAttrs.clear(); MaybeParseGNUAttributes(AccessAttrs); SourceLocation EndLoc; if (TryConsumeToken(tok::colon, EndLoc)) { } else if (TryConsumeToken(tok::semi, EndLoc)) { Diag(EndLoc, diag::err_expected) << tok::colon << FixItHint::CreateReplacement(EndLoc, ":"); } else { EndLoc = ASLoc.getLocWithOffset(TokLength); Diag(EndLoc, diag::err_expected) << tok::colon << FixItHint::CreateInsertion(EndLoc, ":"); } // The Microsoft extension __interface does not permit non-public // access specifiers. if (TagType == DeclSpec::TST_interface && CurAS != AS_public) { Diag(ASLoc, diag::err_access_specifier_interface) << (CurAS == AS_protected); } if (Actions.ActOnAccessSpecifier(AS, ASLoc, EndLoc, AccessAttrs.getList())) { // found another attribute than only annotations AccessAttrs.clear(); } continue; } // Parse all the comma separated declarators. ParseCXXClassMemberDeclaration(CurAS, AccessAttrs.getList()); } T.consumeClose(); } else { SkipUntil(tok::r_brace); } // If attributes exist after class contents, parse them. ParsedAttributes attrs(AttrFactory); MaybeParseGNUAttributes(attrs); if (TagDecl) Actions.ActOnFinishCXXMemberSpecification(getCurScope(), RecordLoc, TagDecl, T.getOpenLocation(), T.getCloseLocation(), attrs.getList()); // C++11 [class.mem]p2: // Within the class member-specification, the class is regarded as complete // within function bodies, default arguments, exception-specifications, and // brace-or-equal-initializers for non-static data members (including such // things in nested classes). if (TagDecl && NonNestedClass) { // We are not inside a nested class. This class and its nested classes // are complete and we can parse the delayed portions of method // declarations and the lexed inline method definitions, along with any // delayed attributes. SourceLocation SavedPrevTokLocation = PrevTokLocation; ParseLexedAttributes(getCurrentClass()); ParseLexedMethodDeclarations(getCurrentClass()); // We've finished with all pending member declarations. Actions.ActOnFinishCXXMemberDecls(); ParseLexedMemberInitializers(getCurrentClass()); ParseLexedMethodDefs(getCurrentClass()); PrevTokLocation = SavedPrevTokLocation; // We've finished parsing everything, including default argument // initializers. Actions.ActOnFinishCXXMemberDefaultArgs(TagDecl); } if (TagDecl) Actions.ActOnTagFinishDefinition(getCurScope(), TagDecl, T.getCloseLocation()); // Leave the class scope. ParsingDef.Pop(); ClassScope.Exit(); } void Parser::DiagnoseUnexpectedNamespace(NamedDecl *D) { assert(Tok.is(tok::kw_namespace)); // FIXME: Suggest where the close brace should have gone by looking // at indentation changes within the definition body. Diag(D->getLocation(), diag::err_missing_end_of_definition) << D; Diag(Tok.getLocation(), diag::note_missing_end_of_definition_before) << D; // Push '};' onto the token stream to recover. PP.EnterToken(Tok); Tok.startToken(); Tok.setLocation(PP.getLocForEndOfToken(PrevTokLocation)); Tok.setKind(tok::semi); PP.EnterToken(Tok); Tok.setKind(tok::r_brace); } /// ParseConstructorInitializer - Parse a C++ constructor initializer, /// which explicitly initializes the members or base classes of a /// class (C++ [class.base.init]). For example, the three initializers /// after the ':' in the Derived constructor below: /// /// @code /// class Base { }; /// class Derived : Base { /// int x; /// float f; /// public: /// Derived(float f) : Base(), x(17), f(f) { } /// }; /// @endcode /// /// [C++] ctor-initializer: /// ':' mem-initializer-list /// /// [C++] mem-initializer-list: /// mem-initializer ...[opt] /// mem-initializer ...[opt] , mem-initializer-list void Parser::ParseConstructorInitializer(Decl *ConstructorDecl) { assert(Tok.is(tok::colon) && "Constructor initializer always starts with ':'"); // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "constructor initializer"; return; } // HLSL Change Ends // Poison the SEH identifiers so they are flagged as illegal in constructor // initializers. PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); SourceLocation ColonLoc = ConsumeToken(); SmallVector<CXXCtorInitializer*, 4> MemInitializers; bool AnyErrors = false; do { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteConstructorInitializer(ConstructorDecl, MemInitializers); return cutOffParsing(); } else { MemInitResult MemInit = ParseMemInitializer(ConstructorDecl); if (!MemInit.isInvalid()) MemInitializers.push_back(MemInit.get()); else AnyErrors = true; } if (Tok.is(tok::comma)) ConsumeToken(); else if (Tok.is(tok::l_brace)) break; // If the next token looks like a base or member initializer, assume that // we're just missing a comma. else if (Tok.isOneOf(tok::identifier, tok::coloncolon)) { SourceLocation Loc = PP.getLocForEndOfToken(PrevTokLocation); Diag(Loc, diag::err_ctor_init_missing_comma) << FixItHint::CreateInsertion(Loc, ", "); } else { // Skip over garbage, until we get to '{'. Don't eat the '{'. Diag(Tok.getLocation(), diag::err_expected_either) << tok::l_brace << tok::comma; SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); break; } } while (true); Actions.ActOnMemInitializers(ConstructorDecl, ColonLoc, MemInitializers, AnyErrors); } /// ParseMemInitializer - Parse a C++ member initializer, which is /// part of a constructor initializer that explicitly initializes one /// member or base class (C++ [class.base.init]). See /// ParseConstructorInitializer for an example. /// /// [C++] mem-initializer: /// mem-initializer-id '(' expression-list[opt] ')' /// [C++0x] mem-initializer-id braced-init-list /// /// [C++] mem-initializer-id: /// '::'[opt] nested-name-specifier[opt] class-name /// identifier MemInitResult Parser::ParseMemInitializer(Decl *ConstructorDecl) { assert(!getLangOpts().HLSL && "unreachable from HLSL - without constructors, no mem initializers"); // HLSL Change // parse '::'[opt] nested-name-specifier[opt] CXXScopeSpec SS; ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); ParsedType TemplateTypeTy; if (Tok.is(tok::annot_template_id)) { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); if (TemplateId->Kind == TNK_Type_template || TemplateId->Kind == TNK_Dependent_template_name) { AnnotateTemplateIdTokenAsType(); assert(Tok.is(tok::annot_typename) && "template-id -> type failed"); TemplateTypeTy = getTypeAnnotation(Tok); } } // Uses of decltype will already have been converted to annot_decltype by // ParseOptionalCXXScopeSpecifier at this point. if (!TemplateTypeTy && Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_decltype)) { Diag(Tok, diag::err_expected_member_or_base_name); return true; } IdentifierInfo *II = nullptr; DeclSpec DS(AttrFactory); SourceLocation IdLoc = Tok.getLocation(); if (Tok.is(tok::annot_decltype)) { // Get the decltype expression, if there is one. ParseDecltypeSpecifier(DS); } else { if (Tok.is(tok::identifier)) // Get the identifier. This may be a member name or a class name, // but we'll let the semantic analysis determine which it is. II = Tok.getIdentifierInfo(); ConsumeToken(); } // Parse the '('. if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists); ExprResult InitList = ParseBraceInitializer(); if (InitList.isInvalid()) return true; SourceLocation EllipsisLoc; TryConsumeToken(tok::ellipsis, EllipsisLoc); return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, TemplateTypeTy, DS, IdLoc, InitList.get(), EllipsisLoc); } else if(Tok.is(tok::l_paren)) { BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); // Parse the optional expression-list. ExprVector ArgExprs; CommaLocsTy CommaLocs; if (Tok.isNot(tok::r_paren) && ParseExpressionList(ArgExprs, CommaLocs)) { SkipUntil(tok::r_paren, StopAtSemi); return true; } T.consumeClose(); SourceLocation EllipsisLoc; TryConsumeToken(tok::ellipsis, EllipsisLoc); return Actions.ActOnMemInitializer(ConstructorDecl, getCurScope(), SS, II, TemplateTypeTy, DS, IdLoc, T.getOpenLocation(), ArgExprs, T.getCloseLocation(), EllipsisLoc); } if (getLangOpts().CPlusPlus11) return Diag(Tok, diag::err_expected_either) << tok::l_paren << tok::l_brace; else return Diag(Tok, diag::err_expected) << tok::l_paren; } /// \brief Parse a C++ exception-specification if present (C++0x [except.spec]). /// /// exception-specification: /// dynamic-exception-specification /// noexcept-specification /// /// noexcept-specification: /// 'noexcept' /// 'noexcept' '(' constant-expression ')' ExceptionSpecificationType Parser::tryParseExceptionSpecification(bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens) { ExceptionSpecificationType Result = EST_None; ExceptionSpecTokens = 0; // Handle delayed parsing of exception-specifications. if (Delayed) { if (Tok.isNot(tok::kw_throw) && Tok.isNot(tok::kw_noexcept)) return EST_None; // HLSL Change Starts if (getLangOpts().HLSL) { assert(Tok.isNot(tok::kw_noexcept)); // not a keyword in the language. Diag(SpecificationRange.getBegin(), diag::err_hlsl_unsupported_construct) << "exception specification"; return Result; } // HLSL Change Ends // Consume and cache the starting token. bool IsNoexcept = Tok.is(tok::kw_noexcept); Token StartTok = Tok; SpecificationRange = SourceRange(ConsumeToken()); // Check for a '('. if (!Tok.is(tok::l_paren)) { // If this is a bare 'noexcept', we're done. if (IsNoexcept) { Diag(Tok, diag::warn_cxx98_compat_noexcept_decl); NoexceptExpr = 0; return EST_BasicNoexcept; } Diag(Tok, diag::err_expected_lparen_after) << "throw"; return EST_DynamicNone; } // Cache the tokens for the exception-specification. ExceptionSpecTokens = new CachedTokens; ExceptionSpecTokens->push_back(StartTok); // 'throw' or 'noexcept' ExceptionSpecTokens->push_back(Tok); // '(' SpecificationRange.setEnd(ConsumeParen()); // '(' ConsumeAndStoreUntil(tok::r_paren, *ExceptionSpecTokens, /*StopAtSemi=*/true, /*ConsumeFinalToken=*/true); SpecificationRange.setEnd(Tok.getLocation()); return EST_Unparsed; } // See if there's a dynamic specification. if (Tok.is(tok::kw_throw)) { Result = ParseDynamicExceptionSpecification(SpecificationRange, DynamicExceptions, DynamicExceptionRanges); assert(DynamicExceptions.size() == DynamicExceptionRanges.size() && "Produced different number of exception types and ranges."); // HLSL Change Starts if (getLangOpts().HLSL) { assert(Tok.isNot(tok::kw_noexcept)); // not a keyword in the language. Diag(SpecificationRange.getBegin(), diag::err_hlsl_unsupported_construct) << "exception specification"; return Result; } // HLSL Change Ends } // HLSL Change Starts if (getLangOpts().HLSL) { assert(Tok.isNot(tok::kw_noexcept)); // not a keyword in the language. return Result; } // HLSL Change Ends // If there's no noexcept specification, we're done. if (Tok.isNot(tok::kw_noexcept)) return Result; Diag(Tok, diag::warn_cxx98_compat_noexcept_decl); // If we already had a dynamic specification, parse the noexcept for, // recovery, but emit a diagnostic and don't store the results. SourceRange NoexceptRange; ExceptionSpecificationType NoexceptType = EST_None; SourceLocation KeywordLoc = ConsumeToken(); if (Tok.is(tok::l_paren)) { // There is an argument. BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); NoexceptType = EST_ComputedNoexcept; NoexceptExpr = ParseConstantExpression(); T.consumeClose(); // The argument must be contextually convertible to bool. We use // ActOnBooleanCondition for this purpose. if (!NoexceptExpr.isInvalid()) { NoexceptExpr = Actions.ActOnBooleanCondition(getCurScope(), KeywordLoc, NoexceptExpr.get()); NoexceptRange = SourceRange(KeywordLoc, T.getCloseLocation()); } else { NoexceptType = EST_None; } } else { // There is no argument. NoexceptType = EST_BasicNoexcept; NoexceptRange = SourceRange(KeywordLoc, KeywordLoc); } if (Result == EST_None) { SpecificationRange = NoexceptRange; Result = NoexceptType; // If there's a dynamic specification after a noexcept specification, // parse that and ignore the results. if (Tok.is(tok::kw_throw)) { Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); ParseDynamicExceptionSpecification(NoexceptRange, DynamicExceptions, DynamicExceptionRanges); } } else { Diag(Tok.getLocation(), diag::err_dynamic_and_noexcept_specification); } return Result; } static void diagnoseDynamicExceptionSpecification( Parser &P, const SourceRange &Range, bool IsNoexcept) { if (P.getLangOpts().CPlusPlus11 && !P.getLangOpts().HLSL) { // HLSL Change - don't try to fix this for HLSL const char *Replacement = IsNoexcept ? "noexcept" : "noexcept(false)"; P.Diag(Range.getBegin(), diag::warn_exception_spec_deprecated) << Range; P.Diag(Range.getBegin(), diag::note_exception_spec_deprecated) << Replacement << FixItHint::CreateReplacement(Range, Replacement); } } /// ParseDynamicExceptionSpecification - Parse a C++ /// dynamic-exception-specification (C++ [except.spec]). /// /// dynamic-exception-specification: /// 'throw' '(' type-id-list [opt] ')' /// [MS] 'throw' '(' '...' ')' /// /// type-id-list: /// type-id ... [opt] /// type-id-list ',' type-id ... [opt] /// ExceptionSpecificationType Parser::ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges) { assert(Tok.is(tok::kw_throw) && "expected throw"); SpecificationRange.setBegin(ConsumeToken()); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.consumeOpen()) { Diag(Tok, diag::err_expected_lparen_after) << "throw"; SpecificationRange.setEnd(SpecificationRange.getBegin()); return EST_DynamicNone; } // Parse throw(...), a Microsoft extension that means "this function // can throw anything". if (Tok.is(tok::ellipsis)) { SourceLocation EllipsisLoc = ConsumeToken(); if (!getLangOpts().MicrosoftExt) Diag(EllipsisLoc, diag::ext_ellipsis_exception_spec); T.consumeClose(); SpecificationRange.setEnd(T.getCloseLocation()); diagnoseDynamicExceptionSpecification(*this, SpecificationRange, false); return EST_MSAny; } // Parse the sequence of type-ids. SourceRange Range; while (Tok.isNot(tok::r_paren)) { TypeResult Res(ParseTypeName(&Range)); if (Tok.is(tok::ellipsis)) { // C++0x [temp.variadic]p5: // - In a dynamic-exception-specification (15.4); the pattern is a // type-id. SourceLocation Ellipsis = ConsumeToken(); Range.setEnd(Ellipsis); if (!Res.isInvalid()) Res = Actions.ActOnPackExpansion(Res.get(), Ellipsis); } if (!Res.isInvalid()) { Exceptions.push_back(Res.get()); Ranges.push_back(Range); } if (!TryConsumeToken(tok::comma)) break; } T.consumeClose(); SpecificationRange.setEnd(T.getCloseLocation()); diagnoseDynamicExceptionSpecification(*this, SpecificationRange, Exceptions.empty()); return Exceptions.empty() ? EST_DynamicNone : EST_Dynamic; } /// ParseTrailingReturnType - Parse a trailing return type on a new-style /// function declaration. TypeResult Parser::ParseTrailingReturnType(SourceRange &Range) { assert(!getLangOpts().HLSL && "unreachable from HLSL, no lambda or new-style function declaration support"); // HLSL Change assert(Tok.is(tok::arrow) && "expected arrow"); ConsumeToken(); return ParseTypeName(&Range, Declarator::TrailingReturnContext); } /// \brief We have just started parsing the definition of a new class, /// so push that class onto our stack of classes that is currently /// being parsed. Sema::ParsingClassState Parser::PushParsingClass(Decl *ClassDecl, bool NonNestedClass, bool IsInterface) { assert((NonNestedClass || !ClassStack.empty()) && "Nested class without outer class"); ClassStack.push(new ParsingClass(ClassDecl, NonNestedClass, IsInterface)); return Actions.PushParsingClass(); } /// \brief Deallocate the given parsed class and all of its nested /// classes. void Parser::DeallocateParsedClasses(Parser::ParsingClass *Class) { for (unsigned I = 0, N = Class->LateParsedDeclarations.size(); I != N; ++I) delete Class->LateParsedDeclarations[I]; delete Class; } /// \brief Pop the top class of the stack of classes that are /// currently being parsed. /// /// This routine should be called when we have finished parsing the /// definition of a class, but have not yet popped the Scope /// associated with the class's definition. void Parser::PopParsingClass(Sema::ParsingClassState state) { assert(!ClassStack.empty() && "Mismatched push/pop for class parsing"); Actions.PopParsingClass(state); ParsingClass *Victim = ClassStack.top(); ClassStack.pop(); if (Victim->TopLevelClass) { // Deallocate all of the nested classes of this class, // recursively: we don't need to keep any of this information. DeallocateParsedClasses(Victim); return; } assert(!ClassStack.empty() && "Missing top-level class?"); if (Victim->LateParsedDeclarations.empty()) { // The victim is a nested class, but we will not need to perform // any processing after the definition of this class since it has // no members whose handling was delayed. Therefore, we can just // remove this nested class. DeallocateParsedClasses(Victim); return; } // This nested class has some members that will need to be processed // after the top-level class is completely defined. Therefore, add // it to the list of nested classes within its parent. assert(getCurScope()->isClassScope() && "Nested class outside of class scope?"); ClassStack.top()->LateParsedDeclarations.push_back(new LateParsedClass(this, Victim)); Victim->TemplateScope = getCurScope()->getParent()->isTemplateParamScope(); } /// \brief Try to parse an 'identifier' which appears within an attribute-token. /// /// \return the parsed identifier on success, and 0 if the next token is not an /// attribute-token. /// /// C++11 [dcl.attr.grammar]p3: /// If a keyword or an alternative token that satisfies the syntactic /// requirements of an identifier is contained in an attribute-token, /// it is considered an identifier. IdentifierInfo *Parser::TryParseCXX11AttributeIdentifier(SourceLocation &Loc) { switch (Tok.getKind()) { default: // Identifiers and keywords have identifier info attached. if (!Tok.isAnnotation()) { if (IdentifierInfo *II = Tok.getIdentifierInfo()) { Loc = ConsumeToken(); return II; } } return nullptr; case tok::ampamp: // 'and' case tok::pipe: // 'bitor' case tok::pipepipe: // 'or' case tok::caret: // 'xor' case tok::tilde: // 'compl' case tok::amp: // 'bitand' case tok::ampequal: // 'and_eq' case tok::pipeequal: // 'or_eq' case tok::caretequal: // 'xor_eq' case tok::exclaim: // 'not' case tok::exclaimequal: // 'not_eq' // Alternative tokens do not have identifier info, but their spelling // starts with an alphabetical character. SmallString<8> SpellingBuf; SourceLocation SpellingLoc = PP.getSourceManager().getSpellingLoc(Tok.getLocation()); StringRef Spelling = PP.getSpelling(SpellingLoc, SpellingBuf); if (isLetter(Spelling[0])) { Loc = ConsumeToken(); return &PP.getIdentifierTable().get(Spelling); } return nullptr; } } static bool IsBuiltInOrStandardCXX11Attribute(IdentifierInfo *AttrName, IdentifierInfo *ScopeName) { switch (AttributeList::getKind(AttrName, ScopeName, AttributeList::AS_CXX11)) { case AttributeList::AT_CarriesDependency: case AttributeList::AT_Deprecated: case AttributeList::AT_FallThrough: case AttributeList::AT_CXX11NoReturn: { return true; } default: return false; } } /// ParseCXX11AttributeArgs -- Parse a C++11 attribute-argument-clause. /// /// [C++11] attribute-argument-clause: /// '(' balanced-token-seq ')' /// /// [C++11] balanced-token-seq: /// balanced-token /// balanced-token-seq balanced-token /// /// [C++11] balanced-token: /// '(' balanced-token-seq ')' /// '[' balanced-token-seq ']' /// '{' balanced-token-seq '}' /// any token but '(', ')', '[', ']', '{', or '}' bool Parser::ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc) { assert(Tok.is(tok::l_paren) && "Not a C++11 attribute argument list"); SourceLocation LParenLoc = Tok.getLocation(); // If the attribute isn't known, we will not attempt to parse any // arguments. if (!hasAttribute(AttrSyntax::CXX, ScopeName, AttrName, getTargetInfo().getTriple(), getLangOpts())) { // Eat the left paren, then skip to the ending right paren. ConsumeParen(); SkipUntil(tok::r_paren); return false; } if (ScopeName && ScopeName->getName() == "gnu") // GNU-scoped attributes have some special cases to handle GNU-specific // behaviors. ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, ScopeLoc, AttributeList::AS_CXX11, nullptr); else { unsigned NumArgs = ParseAttributeArgsCommon(AttrName, AttrNameLoc, Attrs, EndLoc, ScopeName, ScopeLoc, AttributeList::AS_CXX11); const AttributeList *Attr = Attrs.getList(); if (Attr && IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName)) { // If the attribute is a standard or built-in attribute and we are // parsing an argument list, we need to determine whether this attribute // was allowed to have an argument list (such as [[deprecated]]), and how // many arguments were parsed (so we can diagnose on [[deprecated()]]). if (Attr->getMaxArgs() && !NumArgs) { // The attribute was allowed to have arguments, but none were provided // even though the attribute parsed successfully. This is an error. Diag(LParenLoc, diag::err_attribute_requires_arguments) << AttrName; } else if (!Attr->getMaxArgs()) { // The attribute parsed successfully, but was not allowed to have any // arguments. It doesn't matter whether any were provided -- the // presence of the argument list (even if empty) is diagnosed. Diag(LParenLoc, diag::err_cxx11_attribute_forbids_arguments) << AttrName << FixItHint::CreateRemoval(SourceRange(LParenLoc, *EndLoc)); } } } return true; } /// ParseCXX11AttributeSpecifier - Parse a C++11 attribute-specifier. /// /// [C++11] attribute-specifier: /// '[' '[' attribute-list ']' ']' /// alignment-specifier /// /// [C++11] attribute-list: /// attribute[opt] /// attribute-list ',' attribute[opt] /// attribute '...' /// attribute-list ',' attribute '...' /// /// [C++11] attribute: /// attribute-token attribute-argument-clause[opt] /// /// [C++11] attribute-token: /// identifier /// attribute-scoped-token /// /// [C++11] attribute-scoped-token: /// attribute-namespace '::' identifier /// /// [C++11] attribute-namespace: /// identifier void Parser::ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *endLoc) { if (Tok.is(tok::kw_alignas)) { Diag(Tok.getLocation(), diag::warn_cxx98_compat_alignas); ParseAlignmentSpecifier(attrs, endLoc); return; } assert(Tok.is(tok::l_square) && NextToken().is(tok::l_square) && "Not a C++11 attribute list"); Diag(Tok.getLocation(), diag::warn_cxx98_compat_attribute); ConsumeBracket(); ConsumeBracket(); llvm::SmallDenseMap<IdentifierInfo*, SourceLocation, 4> SeenAttrs; while (Tok.isNot(tok::r_square)) { // attribute not present if (TryConsumeToken(tok::comma)) continue; SourceLocation ScopeLoc, AttrLoc; IdentifierInfo *ScopeName = nullptr, *AttrName = nullptr; AttrName = TryParseCXX11AttributeIdentifier(AttrLoc); if (!AttrName) // Break out to the "expected ']'" diagnostic. break; // scoped attribute if (TryConsumeToken(tok::coloncolon)) { ScopeName = AttrName; ScopeLoc = AttrLoc; AttrName = TryParseCXX11AttributeIdentifier(AttrLoc); if (!AttrName) { Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; SkipUntil(tok::r_square, tok::comma, StopAtSemi | StopBeforeMatch); continue; } } bool StandardAttr = IsBuiltInOrStandardCXX11Attribute(AttrName, ScopeName); bool AttrParsed = false; if (StandardAttr && !SeenAttrs.insert(std::make_pair(AttrName, AttrLoc)).second) Diag(AttrLoc, diag::err_cxx11_attribute_repeated) << AttrName << SourceRange(SeenAttrs[AttrName]); // Parse attribute arguments if (Tok.is(tok::l_paren)) AttrParsed = ParseCXX11AttributeArgs(AttrName, AttrLoc, attrs, endLoc, ScopeName, ScopeLoc); if (!AttrParsed) attrs.addNew(AttrName, SourceRange(ScopeLoc.isValid() ? ScopeLoc : AttrLoc, AttrLoc), ScopeName, ScopeLoc, nullptr, 0, AttributeList::AS_CXX11); if (TryConsumeToken(tok::ellipsis)) Diag(Tok, diag::err_cxx11_attribute_forbids_ellipsis) << AttrName->getName(); } if (ExpectAndConsume(tok::r_square)) SkipUntil(tok::r_square); if (endLoc) *endLoc = Tok.getLocation(); if (ExpectAndConsume(tok::r_square)) SkipUntil(tok::r_square); } /// ParseCXX11Attributes - Parse a C++11 attribute-specifier-seq. /// /// attribute-specifier-seq: /// attribute-specifier-seq[opt] attribute-specifier void Parser::ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc) { assert(getLangOpts().CPlusPlus11 || getLangOpts().HLSL); // HLSL Change SourceLocation StartLoc = Tok.getLocation(), Loc; if (!endLoc) endLoc = &Loc; do { ParseCXX11AttributeSpecifier(attrs, endLoc); } while (isCXX11AttributeSpecifier()); attrs.Range = SourceRange(StartLoc, *endLoc); } void Parser::DiagnoseAndSkipCXX11Attributes() { // Start and end location of an attribute or an attribute list. SourceLocation StartLoc = Tok.getLocation(); SourceLocation EndLoc = SkipCXX11Attributes(); if (EndLoc.isValid()) { SourceRange Range(StartLoc, EndLoc); Diag(StartLoc, diag::err_attributes_not_allowed) << Range; } } SourceLocation Parser::SkipCXX11Attributes() { SourceLocation EndLoc; if (!isCXX11AttributeSpecifier()) return EndLoc; do { if (Tok.is(tok::l_square)) { BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); T.skipToEnd(); EndLoc = T.getCloseLocation(); } else { assert(Tok.is(tok::kw_alignas) && "not an attribute specifier"); ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (!T.consumeOpen()) T.skipToEnd(); EndLoc = T.getCloseLocation(); } } while (isCXX11AttributeSpecifier()); return EndLoc; } /// ParseMicrosoftAttributes - Parse Microsoft attributes [Attr] /// /// [MS] ms-attribute: /// '[' token-seq ']' /// /// [MS] ms-attribute-seq: /// ms-attribute[opt] /// ms-attribute ms-attribute-seq void Parser::ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc) { assert(!getLangOpts().HLSL && "unreachable code for HLSL - Microsoft extension parsing is disabled"); // HLSL Change assert(Tok.is(tok::l_square) && "Not a Microsoft attribute list"); do { // FIXME: If this is actually a C++11 attribute, parse it as one. BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); SkipUntil(tok::r_square, StopAtSemi | StopBeforeMatch); T.consumeClose(); if (endLoc) *endLoc = T.getCloseLocation(); } while (Tok.is(tok::l_square)); } void Parser::ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, AccessSpecifier& CurAS) { assert(!getLangOpts().HLSL && "unreachable code for HLSL - if-exists extension parsing skipped"); // HLSL Change IfExistsCondition Result; if (ParseMicrosoftIfExistsCondition(Result)) return; BalancedDelimiterTracker Braces(*this, tok::l_brace); if (Braces.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; return; } switch (Result.Behavior) { case IEB_Parse: // Parse the declarations below. break; case IEB_Dependent: Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) << Result.IsIfExists; // Fall through to skip. LLVM_FALLTHROUGH; // HLSL Change case IEB_Skip: Braces.skipToEnd(); return; } while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { // __if_exists, __if_not_exists can nest. if (Tok.isOneOf(tok::kw___if_exists, tok::kw___if_not_exists)) { ParseMicrosoftIfExistsClassDeclaration((DeclSpec::TST)TagType, CurAS); continue; } // Check for extraneous top-level semicolon. if (Tok.is(tok::semi)) { ConsumeExtraSemi(InsideStruct, TagType); continue; } AccessSpecifier AS = getAccessSpecifierIfPresent(); if (AS != AS_none) { // Current token is a C++ access specifier. CurAS = AS; SourceLocation ASLoc = Tok.getLocation(); ConsumeToken(); if (Tok.is(tok::colon)) Actions.ActOnAccessSpecifier(AS, ASLoc, Tok.getLocation()); else Diag(Tok, diag::err_expected) << tok::colon; ConsumeToken(); continue; } // Parse all the comma separated declarators. ParseCXXClassMemberDeclaration(CurAS, nullptr); } Braces.consumeClose(); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseInit.cpp
//===--- ParseInit.cpp - Initializer Parsing ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements initializer parsing as specified by C99 6.7.8. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "RAIIObjectsForParser.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Sema/Designator.h" #include "clang/Sema/Scope.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/raw_ostream.h" using namespace clang; /// MayBeDesignationStart - Return true if the current token might be the start /// of a designator. If we can tell it is impossible that it is a designator, /// return false. bool Parser::MayBeDesignationStart() { switch (Tok.getKind()) { default: return false; case tok::period: // designator: '.' identifier return true; case tok::l_square: { // designator: array-designator if (!PP.getLangOpts().CPlusPlus11) return true; // C++11 lambda expressions and C99 designators can be ambiguous all the // way through the closing ']' and to the next character. Handle the easy // cases here, and fall back to tentative parsing if those fail. switch (PP.LookAhead(0).getKind()) { case tok::equal: case tok::r_square: // Definitely starts a lambda expression. return false; case tok::amp: case tok::kw_this: case tok::identifier: // We have to do additional analysis, because these could be the // start of a constant expression or a lambda capture list. break; default: // Anything not mentioned above cannot occur following a '[' in a // lambda expression. return true; } // Handle the complicated case below. break; } case tok::identifier: // designation: identifier ':' return PP.LookAhead(0).is(tok::colon); } // Parse up to (at most) the token after the closing ']' to determine // whether this is a C99 designator or a lambda. TentativeParsingAction Tentative(*this); LambdaIntroducer Intro; bool SkippedInits = false; Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits)); if (DiagID) { // If this can't be a lambda capture list, it's a designator. Tentative.Revert(); return true; } // Once we hit the closing square bracket, we look at the next // token. If it's an '=', this is a designator. Otherwise, it's a // lambda expression. This decision favors lambdas over the older // GNU designator syntax, which allows one to omit the '=', but is // consistent with GCC. tok::TokenKind Kind = Tok.getKind(); // FIXME: If we didn't skip any inits, parse the lambda from here // rather than throwing away then reparsing the LambdaIntroducer. Tentative.Revert(); return Kind == tok::equal; } static void CheckArrayDesignatorSyntax(Parser &P, SourceLocation Loc, Designation &Desig) { // If we have exactly one array designator, this used the GNU // 'designation: array-designator' extension, otherwise there should be no // designators at all! if (Desig.getNumDesignators() == 1 && (Desig.getDesignator(0).isArrayDesignator() || Desig.getDesignator(0).isArrayRangeDesignator())) P.Diag(Loc, diag::ext_gnu_missing_equal_designator); else if (Desig.getNumDesignators() > 0) P.Diag(Loc, diag::err_expected_equal_designator); } /// ParseInitializerWithPotentialDesignator - Parse the 'initializer' production /// checking to see if the token stream starts with a designator. /// /// designation: /// designator-list '=' /// [GNU] array-designator /// [GNU] identifier ':' /// /// designator-list: /// designator /// designator-list designator /// /// designator: /// array-designator /// '.' identifier /// /// array-designator: /// '[' constant-expression ']' /// [GNU] '[' constant-expression '...' constant-expression ']' /// /// NOTE: [OBC] allows '[ objc-receiver objc-message-args ]' as an /// initializer (because it is an expression). We need to consider this case /// when parsing array designators. /// ExprResult Parser::ParseInitializerWithPotentialDesignator() { // If this is the old-style GNU extension: // designation ::= identifier ':' // Handle it as a field designator. Otherwise, this must be the start of a // normal expression. if (Tok.is(tok::identifier)) { const IdentifierInfo *FieldName = Tok.getIdentifierInfo(); SmallString<256> NewSyntax; llvm::raw_svector_ostream(NewSyntax) << '.' << FieldName->getName() << " = "; SourceLocation NameLoc = ConsumeToken(); // Eat the identifier. assert(Tok.is(tok::colon) && "MayBeDesignationStart not working properly!"); SourceLocation ColonLoc = ConsumeToken(); Diag(NameLoc, diag::ext_gnu_old_style_field_designator) << FixItHint::CreateReplacement(SourceRange(NameLoc, ColonLoc), NewSyntax); Designation D; D.AddDesignator(Designator::getField(FieldName, SourceLocation(), NameLoc)); return Actions.ActOnDesignatedInitializer(D, ColonLoc, true, ParseInitializer()); } // Desig - This is initialized when we see our first designator. We may have // an objc message send with no designator, so we don't want to create this // eagerly. Designation Desig; // Parse each designator in the designator list until we find an initializer. while (Tok.is(tok::period) || Tok.is(tok::l_square)) { if (Tok.is(tok::period)) { // designator: '.' identifier SourceLocation DotLoc = ConsumeToken(); if (Tok.isNot(tok::identifier)) { Diag(Tok.getLocation(), diag::err_expected_field_designator); return ExprError(); } Desig.AddDesignator(Designator::getField(Tok.getIdentifierInfo(), DotLoc, Tok.getLocation())); ConsumeToken(); // Eat the identifier. continue; } // We must have either an array designator now or an objc message send. assert(Tok.is(tok::l_square) && "Unexpected token!"); // Handle the two forms of array designator: // array-designator: '[' constant-expression ']' // array-designator: '[' constant-expression '...' constant-expression ']' // // Also, we have to handle the case where the expression after the // designator an an objc message send: '[' objc-message-expr ']'. // Interesting cases are: // [foo bar] -> objc message send // [foo] -> array designator // [foo ... bar] -> array designator // [4][foo bar] -> obsolete GNU designation with objc message send. // // We do not need to check for an expression starting with [[ here. If it // contains an Objective-C message send, then it is not an ill-formed // attribute. If it is a lambda-expression within an array-designator, then // it will be rejected because a constant-expression cannot begin with a // lambda-expression. InMessageExpressionRAIIObject InMessage(*this, true); BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); SourceLocation StartLoc = T.getOpenLocation(); ExprResult Idx; // If Objective-C is enabled and this is a typename (class message // send) or send to 'super', parse this as a message send // expression. We handle C++ and C separately, since C++ requires // much more complicated parsing. if (getLangOpts().ObjC1 && getLangOpts().CPlusPlus) { // Send to 'super'. if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == Ident_super && NextToken().isNot(tok::period) && getCurScope()->isInObjcMethodScope()) { CheckArrayDesignatorSyntax(*this, StartLoc, Desig); return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, ConsumeToken(), ParsedType(), nullptr); } // Parse the receiver, which is either a type or an expression. bool IsExpr; void *TypeOrExpr; if (ParseObjCXXMessageReceiver(IsExpr, TypeOrExpr)) { SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } // If the receiver was a type, we have a class message; parse // the rest of it. if (!IsExpr) { CheckArrayDesignatorSyntax(*this, StartLoc, Desig); return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, SourceLocation(), ParsedType::getFromOpaquePtr(TypeOrExpr), nullptr); } // If the receiver was an expression, we still don't know // whether we have a message send or an array designator; just // adopt the expression for further analysis below. // FIXME: potentially-potentially evaluated expression above? Idx = ExprResult(static_cast<Expr*>(TypeOrExpr)); } else if (getLangOpts().ObjC1 && Tok.is(tok::identifier)) { IdentifierInfo *II = Tok.getIdentifierInfo(); SourceLocation IILoc = Tok.getLocation(); ParsedType ReceiverType; // Three cases. This is a message send to a type: [type foo] // This is a message send to super: [super foo] // This is a message sent to an expr: [super.bar foo] switch (Actions.getObjCMessageKind( getCurScope(), II, IILoc, II == Ident_super, NextToken().is(tok::period), ReceiverType)) { case Sema::ObjCSuperMessage: CheckArrayDesignatorSyntax(*this, StartLoc, Desig); return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, ConsumeToken(), ParsedType(), nullptr); case Sema::ObjCClassMessage: CheckArrayDesignatorSyntax(*this, StartLoc, Desig); ConsumeToken(); // the identifier if (!ReceiverType) { SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } // Parse type arguments and protocol qualifiers. if (Tok.is(tok::less)) { SourceLocation NewEndLoc; TypeResult NewReceiverType = parseObjCTypeArgsAndProtocolQualifiers(IILoc, ReceiverType, /*consumeLastToken=*/true, NewEndLoc); if (!NewReceiverType.isUsable()) { SkipUntil(tok::r_square, StopAtSemi); return ExprError(); } ReceiverType = NewReceiverType.get(); } return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, SourceLocation(), ReceiverType, nullptr); case Sema::ObjCInstanceMessage: // Fall through; we'll just parse the expression and // (possibly) treat this like an Objective-C message send // later. break; } } // Parse the index expression, if we haven't already gotten one // above (which can only happen in Objective-C++). // Note that we parse this as an assignment expression, not a constant // expression (allowing *=, =, etc) to handle the objc case. Sema needs // to validate that the expression is a constant. // FIXME: We also need to tell Sema that we're in a // potentially-potentially evaluated context. if (!Idx.get()) { Idx = ParseAssignmentExpression(); if (Idx.isInvalid()) { SkipUntil(tok::r_square, StopAtSemi); return Idx; } } // Given an expression, we could either have a designator (if the next // tokens are '...' or ']' or an objc message send. If this is an objc // message send, handle it now. An objc-message send is the start of // an assignment-expression production. if (getLangOpts().ObjC1 && Tok.isNot(tok::ellipsis) && Tok.isNot(tok::r_square)) { CheckArrayDesignatorSyntax(*this, Tok.getLocation(), Desig); return ParseAssignmentExprWithObjCMessageExprStart(StartLoc, SourceLocation(), ParsedType(), Idx.get()); } // If this is a normal array designator, remember it. if (Tok.isNot(tok::ellipsis)) { Desig.AddDesignator(Designator::getArray(Idx.get(), StartLoc)); } else { // Handle the gnu array range extension. Diag(Tok, diag::ext_gnu_array_range); SourceLocation EllipsisLoc = ConsumeToken(); ExprResult RHS(ParseConstantExpression()); if (RHS.isInvalid()) { SkipUntil(tok::r_square, StopAtSemi); return RHS; } Desig.AddDesignator(Designator::getArrayRange(Idx.get(), RHS.get(), StartLoc, EllipsisLoc)); } T.consumeClose(); Desig.getDesignator(Desig.getNumDesignators() - 1).setRBracketLoc( T.getCloseLocation()); } // Okay, we're done with the designator sequence. We know that there must be // at least one designator, because the only case we can get into this method // without a designator is when we have an objc message send. That case is // handled and returned from above. assert(!Desig.empty() && "Designator is empty?"); // Handle a normal designator sequence end, which is an equal. if (Tok.is(tok::equal)) { SourceLocation EqualLoc = ConsumeToken(); return Actions.ActOnDesignatedInitializer(Desig, EqualLoc, false, ParseInitializer()); } // We read some number of designators and found something that isn't an = or // an initializer. If we have exactly one array designator, this // is the GNU 'designation: array-designator' extension. Otherwise, it is a // parse error. if (Desig.getNumDesignators() == 1 && (Desig.getDesignator(0).isArrayDesignator() || Desig.getDesignator(0).isArrayRangeDesignator())) { Diag(Tok, diag::ext_gnu_missing_equal_designator) << FixItHint::CreateInsertion(Tok.getLocation(), "= "); return Actions.ActOnDesignatedInitializer(Desig, Tok.getLocation(), true, ParseInitializer()); } Diag(Tok, diag::err_expected_equal_designator); return ExprError(); } /// ParseBraceInitializer - Called when parsing an initializer that has a /// leading open brace. /// /// initializer: [C99 6.7.8] /// '{' initializer-list '}' /// '{' initializer-list ',' '}' /// [GNU] '{' '}' /// /// initializer-list: /// designation[opt] initializer ...[opt] /// initializer-list ',' designation[opt] initializer ...[opt] /// ExprResult Parser::ParseBraceInitializer() { // HLSL Note - this is used for float f[] = { 1, 2, 3 }; InMessageExpressionRAIIObject InMessage(*this, false); BalancedDelimiterTracker T(*this, tok::l_brace); T.consumeOpen(); SourceLocation LBraceLoc = T.getOpenLocation(); /// InitExprs - This is the actual list of expressions contained in the /// initializer. ExprVector InitExprs; if (Tok.is(tok::r_brace)) { // Empty initializers are a C++ feature and a GNU extension to C. if (!getLangOpts().CPlusPlus) Diag(LBraceLoc, diag::ext_gnu_empty_initializer); // Match the '}'. return Actions.ActOnInitList(LBraceLoc, None, ConsumeBrace()); } bool InitExprsOk = true; while (1) { // Handle Microsoft __if_exists/if_not_exists if necessary. if (getLangOpts().MicrosoftExt && (Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists))) { if (ParseMicrosoftIfExistsBraceInitializer(InitExprs, InitExprsOk)) { if (Tok.isNot(tok::comma)) break; ConsumeToken(); } if (Tok.is(tok::r_brace)) break; continue; } // Parse: designation[opt] initializer // If we know that this cannot be a designation, just parse the nested // initializer directly. ExprResult SubElt; if (MayBeDesignationStart()) SubElt = ParseInitializerWithPotentialDesignator(); else SubElt = ParseInitializer(); if (Tok.is(tok::ellipsis)) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "expansion"; InitExprsOk = false; SkipUntil(tok::r_brace, StopBeforeMatch); break; } // HLSL Change Ends SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken()); } SubElt = Actions.CorrectDelayedTyposInExpr(SubElt.get()); // If we couldn't parse the subelement, bail out. if (SubElt.isUsable()) { InitExprs.push_back(SubElt.get()); } else { InitExprsOk = false; // We have two ways to try to recover from this error: if the code looks // grammatically ok (i.e. we have a comma coming up) try to continue // parsing the rest of the initializer. This allows us to emit // diagnostics for later elements that we find. If we don't see a comma, // assume there is a parse error, and just skip to recover. // FIXME: This comment doesn't sound right. If there is a r_brace // immediately, it can't be an error, since there is no other way of // leaving this loop except through this if. if (Tok.isNot(tok::comma)) { SkipUntil(tok::r_brace, StopBeforeMatch); break; } } // If we don't have a comma continued list, we're done. if (Tok.isNot(tok::comma)) break; // TODO: save comma locations if some client cares. ConsumeToken(); // Handle trailing comma. if (Tok.is(tok::r_brace)) break; } bool closed = !T.consumeClose(); if (InitExprsOk && closed) return Actions.ActOnInitList(LBraceLoc, InitExprs, T.getCloseLocation()); return ExprError(); // an error occurred. } // Return true if a comma (or closing brace) is necessary after the // __if_exists/if_not_exists statement. bool Parser::ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change bool trailingComma = false; IfExistsCondition Result; if (ParseMicrosoftIfExistsCondition(Result)) return false; BalancedDelimiterTracker Braces(*this, tok::l_brace); if (Braces.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; return false; } switch (Result.Behavior) { case IEB_Parse: // Parse the declarations below. break; case IEB_Dependent: Diag(Result.KeywordLoc, diag::warn_microsoft_dependent_exists) << Result.IsIfExists; // Fall through to skip. LLVM_FALLTHROUGH; // HLSL Change case IEB_Skip: Braces.skipToEnd(); return false; } while (!isEofOrEom()) { trailingComma = false; // If we know that this cannot be a designation, just parse the nested // initializer directly. ExprResult SubElt; if (MayBeDesignationStart()) SubElt = ParseInitializerWithPotentialDesignator(); else SubElt = ParseInitializer(); if (Tok.is(tok::ellipsis)) SubElt = Actions.ActOnPackExpansion(SubElt.get(), ConsumeToken()); // If we couldn't parse the subelement, bail out. if (!SubElt.isInvalid()) InitExprs.push_back(SubElt.get()); else InitExprsOk = false; if (Tok.is(tok::comma)) { ConsumeToken(); trailingComma = true; } if (Tok.is(tok::r_brace)) break; } Braces.consumeClose(); return !trailingComma; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseTemplate.cpp
//===--- ParseTemplate.cpp - Template Parsing -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements parsing of C++ templates. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "RAIIObjectsForParser.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclTemplate.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/Scope.h" #include "llvm/Support/TimeProfiler.h" // HLSL Change using namespace clang; /// \brief Parse a template declaration, explicit instantiation, or /// explicit specialization. Decl * Parser::ParseDeclarationStartingWithTemplate(unsigned Context, SourceLocation &DeclEnd, AccessSpecifier AS, AttributeList *AccessAttrs) { ObjCDeclContextSwitch ObjCDC(*this); if (Tok.is(tok::kw_template) && NextToken().isNot(tok::less)) { return ParseExplicitInstantiation(Context, SourceLocation(), ConsumeToken(), DeclEnd, AS); } return ParseTemplateDeclarationOrSpecialization(Context, DeclEnd, AS, AccessAttrs); } /// \brief Parse a template declaration or an explicit specialization. /// /// Template declarations include one or more template parameter lists /// and either the function or class template declaration. Explicit /// specializations contain one or more 'template < >' prefixes /// followed by a (possibly templated) declaration. Since the /// syntactic form of both features is nearly identical, we parse all /// of the template headers together and let semantic analysis sort /// the declarations from the explicit specializations. /// /// template-declaration: [C++ temp] /// 'export'[opt] 'template' '<' template-parameter-list '>' declaration /// /// explicit-specialization: [ C++ temp.expl.spec] /// 'template' '<' '>' declaration Decl * Parser::ParseTemplateDeclarationOrSpecialization(unsigned Context, SourceLocation &DeclEnd, AccessSpecifier AS, AttributeList *AccessAttrs) { assert(Tok.isOneOf(tok::kw_export, tok::kw_template) && "Token does not start a template declaration."); // Enter template-parameter scope. ParseScope TemplateParmScope(this, Scope::TemplateParamScope); // Tell the action that names should be checked in the context of // the declaration to come. ParsingDeclRAIIObject ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent); // Parse multiple levels of template headers within this template // parameter scope, e.g., // // template<typename T> // template<typename U> // class A<T>::B { ... }; // // We parse multiple levels non-recursively so that we can build a // single data structure containing all of the template parameter // lists to easily differentiate between the case above and: // // template<typename T> // class A { // template<typename U> class B; // }; // // In the first case, the action for declaring A<T>::B receives // both template parameter lists. In the second case, the action for // defining A<T>::B receives just the inner template parameter list // (and retrieves the outer template parameter list from its // context). bool isSpecialization = true; bool LastParamListWasEmpty = false; TemplateParameterLists ParamLists; TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); do { // Consume the 'export', if any. SourceLocation ExportLoc; TryConsumeToken(tok::kw_export, ExportLoc); // Consume the 'template', which should be here. SourceLocation TemplateLoc; if (!TryConsumeToken(tok::kw_template, TemplateLoc)) { Diag(Tok.getLocation(), diag::err_expected_template); return nullptr; } // Parse the '<' template-parameter-list '>' SourceLocation LAngleLoc, RAngleLoc; SmallVector<Decl*, 4> TemplateParams; if (ParseTemplateParameters(CurTemplateDepthTracker.getDepth(), TemplateParams, LAngleLoc, RAngleLoc)) { // Skip until the semi-colon or a '}'. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); TryConsumeToken(tok::semi); return nullptr; } ParamLists.push_back( Actions.ActOnTemplateParameterList(CurTemplateDepthTracker.getDepth(), ExportLoc, TemplateLoc, LAngleLoc, TemplateParams.data(), TemplateParams.size(), RAngleLoc)); if (!TemplateParams.empty()) { isSpecialization = false; ++CurTemplateDepthTracker; if (TryConsumeToken(tok::kw_requires)) { ExprResult ER = Actions.CorrectDelayedTyposInExpr(ParseConstraintExpression()); if (!ER.isUsable()) { // Skip until the semi-colon or a '}'. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); TryConsumeToken(tok::semi); return nullptr; } } } else { LastParamListWasEmpty = true; } } while (Tok.isOneOf(tok::kw_export, tok::kw_template)); // Parse the actual template declaration. return ParseSingleDeclarationAfterTemplate(Context, ParsedTemplateInfo(&ParamLists, isSpecialization, LastParamListWasEmpty), ParsingTemplateParams, DeclEnd, AS, AccessAttrs); } /// \brief Parse a single declaration that declares a template, /// template specialization, or explicit instantiation of a template. /// /// \param DeclEnd will receive the source location of the last token /// within this declaration. /// /// \param AS the access specifier associated with this /// declaration. Will be AS_none for namespace-scope declarations. /// /// \returns the new declaration. Decl * Parser::ParseSingleDeclarationAfterTemplate( unsigned Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromTParams, SourceLocation &DeclEnd, AccessSpecifier AS, AttributeList *AccessAttrs) { assert(TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate && "Template information required"); if (Tok.is(tok::kw_static_assert)) { // A static_assert declaration may not be templated. Diag(Tok.getLocation(), diag::err_templated_invalid_declaration) << TemplateInfo.getSourceRange(); // Parse the static_assert declaration to improve error recovery. return ParseStaticAssertDeclaration(DeclEnd); } if (Context == Declarator::MemberContext) { // We are parsing a member template. ParseCXXClassMemberDeclaration(AS, AccessAttrs, TemplateInfo, &DiagsFromTParams); return nullptr; } ParsedAttributesWithRange prefixAttrs(AttrFactory); MaybeParseCXX11Attributes(prefixAttrs); // HLSL Change: comment only - MaybeParseHLSLAttributes would go here if allowed at this point if (Tok.is(tok::kw_using)) return ParseUsingDirectiveOrDeclaration(Context, TemplateInfo, DeclEnd, prefixAttrs); // Parse the declaration specifiers, stealing any diagnostics from // the template parameters. ParsingDeclSpec DS(*this, &DiagsFromTParams); ParseDeclarationSpecifiers(DS, TemplateInfo, AS, getDeclSpecContextFromDeclaratorContext(Context)); if (Tok.is(tok::semi)) { ProhibitAttributes(prefixAttrs); DeclEnd = ConsumeToken(); Decl *Decl = Actions.ParsedFreeStandingDeclSpec( getCurScope(), AS, DS, TemplateInfo.TemplateParams ? *TemplateInfo.TemplateParams : MultiTemplateParamsArg(), TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation); DS.complete(Decl); return Decl; } // Move the attributes from the prefix into the DS. if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) ProhibitAttributes(prefixAttrs); else DS.takeAttributesFrom(prefixAttrs); // Parse the declarator. ParsingDeclarator DeclaratorInfo(*this, DS, (Declarator::TheContext)Context); ParseDeclarator(DeclaratorInfo); // Error parsing the declarator? if (!DeclaratorInfo.hasName()) { // If so, skip until the semi-colon or a }. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); if (Tok.is(tok::semi)) ConsumeToken(); return nullptr; } // HLSL Change Begin - Support hierarchial time tracing. llvm::TimeTraceScope TimeScope("ParseTemplate", [&]() { return DeclaratorInfo.getIdentifier() != nullptr ? DeclaratorInfo.getIdentifier()->getName() : "<unknown>"; }); // HLSL Change End - Support hierarchial time tracing. LateParsedAttrList LateParsedAttrs(true); if (DeclaratorInfo.isFunctionDeclarator()) MaybeParseGNUAttributes(DeclaratorInfo, &LateParsedAttrs); if (DeclaratorInfo.isFunctionDeclarator() && isStartOfFunctionDefinition(DeclaratorInfo)) { // Function definitions are only allowed at file scope and in C++ classes. // The C++ inline method definition case is handled elsewhere, so we only // need to handle the file scope definition case. if (Context != Declarator::FileContext) { Diag(Tok, diag::err_function_definition_not_allowed); SkipMalformedDecl(); return nullptr; } if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) { // Recover by ignoring the 'typedef'. This was probably supposed to be // the 'typename' keyword, which we should have already suggested adding // if it's appropriate. Diag(DS.getStorageClassSpecLoc(), diag::err_function_declared_typedef) << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); DS.ClearStorageClassSpecs(); } if (TemplateInfo.Kind == ParsedTemplateInfo::ExplicitInstantiation) { if (DeclaratorInfo.getName().getKind() != UnqualifiedId::IK_TemplateId) { // If the declarator-id is not a template-id, issue a diagnostic and // recover by ignoring the 'template' keyword. Diag(Tok, diag::err_template_defn_explicit_instantiation) << 0; return ParseFunctionDefinition(DeclaratorInfo, ParsedTemplateInfo(), &LateParsedAttrs); } else { SourceLocation LAngleLoc = PP.getLocForEndOfToken(TemplateInfo.TemplateLoc); Diag(DeclaratorInfo.getIdentifierLoc(), diag::err_explicit_instantiation_with_definition) << SourceRange(TemplateInfo.TemplateLoc) << FixItHint::CreateInsertion(LAngleLoc, "<>"); // Recover as if it were an explicit specialization. TemplateParameterLists FakedParamLists; FakedParamLists.push_back(Actions.ActOnTemplateParameterList( 0, SourceLocation(), TemplateInfo.TemplateLoc, LAngleLoc, nullptr, 0, LAngleLoc)); return ParseFunctionDefinition( DeclaratorInfo, ParsedTemplateInfo(&FakedParamLists, /*isSpecialization=*/true, /*LastParamListWasEmpty=*/true), &LateParsedAttrs); } } return ParseFunctionDefinition(DeclaratorInfo, TemplateInfo, &LateParsedAttrs); } // Parse this declaration. Decl *ThisDecl = ParseDeclarationAfterDeclarator(DeclaratorInfo, TemplateInfo); if (Tok.is(tok::comma)) { Diag(Tok, diag::err_multiple_template_declarators) << (int)TemplateInfo.Kind; SkipUntil(tok::semi); return ThisDecl; } // Eat the semi colon after the declaration. ExpectAndConsumeSemi(diag::err_expected_semi_declaration); if (LateParsedAttrs.size() > 0) ParseLexedAttributeList(LateParsedAttrs, ThisDecl, true, false); DeclaratorInfo.complete(ThisDecl); return ThisDecl; } /// ParseTemplateParameters - Parses a template-parameter-list enclosed in /// angle brackets. Depth is the depth of this template-parameter-list, which /// is the number of template headers directly enclosing this template header. /// TemplateParams is the current list of template parameters we're building. /// The template parameter we parse will be added to this list. LAngleLoc and /// RAngleLoc will receive the positions of the '<' and '>', respectively, /// that enclose this template parameter list. /// /// \returns true if an error occurred, false otherwise. bool Parser::ParseTemplateParameters(unsigned Depth, SmallVectorImpl<Decl*> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc) { // Get the template parameter list. if (!TryConsumeToken(tok::less, LAngleLoc)) { Diag(Tok.getLocation(), diag::err_expected_less_after) << "template"; return true; } // Try to parse the template parameter list. bool Failed = false; if (!Tok.is(tok::greater) && !Tok.is(tok::greatergreater)) Failed = ParseTemplateParameterList(Depth, TemplateParams); if (Tok.is(tok::greatergreater)) { // No diagnostic required here: a template-parameter-list can only be // followed by a declaration or, for a template template parameter, the // 'class' keyword. Therefore, the second '>' will be diagnosed later. // This matters for elegant diagnosis of: // template<template<typename>> struct S; Tok.setKind(tok::greater); RAngleLoc = Tok.getLocation(); Tok.setLocation(Tok.getLocation().getLocWithOffset(1)); } else if (!TryConsumeToken(tok::greater, RAngleLoc) && Failed) { Diag(Tok.getLocation(), diag::err_expected) << tok::greater; return true; } return false; } /// ParseTemplateParameterList - Parse a template parameter list. If /// the parsing fails badly (i.e., closing bracket was left out), this /// will try to put the token stream in a reasonable position (closing /// a statement, etc.) and return false. /// /// template-parameter-list: [C++ temp] /// template-parameter /// template-parameter-list ',' template-parameter bool Parser::ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<Decl*> &TemplateParams) { while (1) { if (Decl *TmpParam = ParseTemplateParameter(Depth, TemplateParams.size())) { TemplateParams.push_back(TmpParam); } else { // If we failed to parse a template parameter, skip until we find // a comma or closing brace. SkipUntil(tok::comma, tok::greater, tok::greatergreater, StopAtSemi | StopBeforeMatch); } // Did we find a comma or the end of the template parameter list? if (Tok.is(tok::comma)) { ConsumeToken(); } else if (Tok.isOneOf(tok::greater, tok::greatergreater)) { // Don't consume this... that's done by template parser. break; } else { // Somebody probably forgot to close the template. Skip ahead and // try to get out of the expression. This error is currently // subsumed by whatever goes on in ParseTemplateParameter. Diag(Tok.getLocation(), diag::err_expected_comma_greater); SkipUntil(tok::comma, tok::greater, tok::greatergreater, StopAtSemi | StopBeforeMatch); return false; } } return true; } /// \brief Determine whether the parser is at the start of a template /// type parameter. bool Parser::isStartOfTemplateTypeParameter() { if (Tok.is(tok::kw_class)) { // "class" may be the start of an elaborated-type-specifier or a // type-parameter. Per C++ [temp.param]p3, we prefer the type-parameter. switch (NextToken().getKind()) { case tok::equal: case tok::comma: case tok::greater: case tok::greatergreater: case tok::ellipsis: return true; case tok::identifier: // This may be either a type-parameter or an elaborated-type-specifier. // We have to look further. break; default: return false; } switch (GetLookAheadToken(2).getKind()) { case tok::equal: case tok::comma: case tok::greater: case tok::greatergreater: return true; default: return false; } } if (Tok.isNot(tok::kw_typename)) return false; // C++ [temp.param]p2: // There is no semantic difference between class and typename in a // template-parameter. typename followed by an unqualified-id // names a template type parameter. typename followed by a // qualified-id denotes the type in a non-type // parameter-declaration. Token Next = NextToken(); // If we have an identifier, skip over it. if (Next.getKind() == tok::identifier) Next = GetLookAheadToken(2); switch (Next.getKind()) { case tok::equal: case tok::comma: case tok::greater: case tok::greatergreater: case tok::ellipsis: return true; default: return false; } } /// ParseTemplateParameter - Parse a template-parameter (C++ [temp.param]). /// /// template-parameter: [C++ temp.param] /// type-parameter /// parameter-declaration /// /// type-parameter: (see below) /// 'class' ...[opt] identifier[opt] /// 'class' identifier[opt] '=' type-id /// 'typename' ...[opt] identifier[opt] /// 'typename' identifier[opt] '=' type-id /// 'template' '<' template-parameter-list '>' /// 'class' ...[opt] identifier[opt] /// 'template' '<' template-parameter-list '>' 'class' identifier[opt] /// = id-expression Decl *Parser::ParseTemplateParameter(unsigned Depth, unsigned Position) { if (isStartOfTemplateTypeParameter()) return ParseTypeParameter(Depth, Position); if (Tok.is(tok::kw_template)) return ParseTemplateTemplateParameter(Depth, Position); // If it's none of the above, then it must be a parameter declaration. // NOTE: This will pick up errors in the closure of the template parameter // list (e.g., template < ; Check here to implement >> style closures. return ParseNonTypeTemplateParameter(Depth, Position); } /// ParseTypeParameter - Parse a template type parameter (C++ [temp.param]). /// Other kinds of template parameters are parsed in /// ParseTemplateTemplateParameter and ParseNonTypeTemplateParameter. /// /// type-parameter: [C++ temp.param] /// 'class' ...[opt][C++0x] identifier[opt] /// 'class' identifier[opt] '=' type-id /// 'typename' ...[opt][C++0x] identifier[opt] /// 'typename' identifier[opt] '=' type-id Decl *Parser::ParseTypeParameter(unsigned Depth, unsigned Position) { assert(Tok.isOneOf(tok::kw_class, tok::kw_typename) && "A type-parameter starts with 'class' or 'typename'"); // Consume the 'class' or 'typename' keyword. bool TypenameKeyword = Tok.is(tok::kw_typename); SourceLocation KeyLoc = ConsumeToken(); // Grab the ellipsis (if given). SourceLocation EllipsisLoc; if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(EllipsisLoc, diag::err_hlsl_variadic_templates); return nullptr; } // HLSL Change Ends Diag(EllipsisLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_variadic_templates : diag::ext_variadic_templates); } // Grab the template parameter name (if given) SourceLocation NameLoc; IdentifierInfo *ParamName = nullptr; if (Tok.is(tok::identifier)) { ParamName = Tok.getIdentifierInfo(); NameLoc = ConsumeToken(); } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater, tok::greatergreater)) { // Unnamed template parameter. Don't have to do anything here, just // don't consume this token. } else { Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; return nullptr; } // Recover from misplaced ellipsis. bool AlreadyHasEllipsis = EllipsisLoc.isValid(); if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true); // Grab a default argument (if available). // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before // we introduce the type parameter into the local scope. SourceLocation EqualLoc; ParsedType DefaultArg; if (TryConsumeToken(tok::equal, EqualLoc)) DefaultArg = ParseTypeName(/*Range=*/nullptr, Declarator::TemplateTypeArgContext).get(); return Actions.ActOnTypeParameter(getCurScope(), TypenameKeyword, EllipsisLoc, KeyLoc, ParamName, NameLoc, Depth, Position, EqualLoc, DefaultArg); } /// ParseTemplateTemplateParameter - Handle the parsing of template /// template parameters. /// /// type-parameter: [C++ temp.param] /// 'template' '<' template-parameter-list '>' type-parameter-key /// ...[opt] identifier[opt] /// 'template' '<' template-parameter-list '>' type-parameter-key /// identifier[opt] = id-expression /// type-parameter-key: /// 'class' /// 'typename' [C++1z] Decl * Parser::ParseTemplateTemplateParameter(unsigned Depth, unsigned Position) { assert(Tok.is(tok::kw_template) && "Expected 'template' keyword"); // Handle the template <...> part. SourceLocation TemplateLoc = ConsumeToken(); SmallVector<Decl*,8> TemplateParams; SourceLocation LAngleLoc, RAngleLoc; { ParseScope TemplateParmScope(this, Scope::TemplateParamScope); if (ParseTemplateParameters(Depth + 1, TemplateParams, LAngleLoc, RAngleLoc)) { return nullptr; } } // Provide an ExtWarn if the C++1z feature of using 'typename' here is used. // Generate a meaningful error if the user forgot to put class before the // identifier, comma, or greater. Provide a fixit if the identifier, comma, // or greater appear immediately or after 'struct'. In the latter case, // replace the keyword with 'class'. if (!TryConsumeToken(tok::kw_class)) { bool Replace = Tok.isOneOf(tok::kw_typename, tok::kw_struct); const Token &Next = Tok.is(tok::kw_struct) ? NextToken() : Tok; if (Tok.is(tok::kw_typename)) { Diag(Tok.getLocation(), getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_template_template_param_typename : diag::ext_template_template_param_typename) << (!getLangOpts().CPlusPlus1z ? FixItHint::CreateReplacement(Tok.getLocation(), "class") : FixItHint()); } else if (Next.isOneOf(tok::identifier, tok::comma, tok::greater, tok::greatergreater, tok::ellipsis)) { Diag(Tok.getLocation(), diag::err_class_on_template_template_param) << (Replace ? FixItHint::CreateReplacement(Tok.getLocation(), "class") : FixItHint::CreateInsertion(Tok.getLocation(), "class ")); } else Diag(Tok.getLocation(), diag::err_class_on_template_template_param); if (Replace) ConsumeToken(); } // Parse the ellipsis, if given. SourceLocation EllipsisLoc; if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) { // HLSL Change Starts if (getLangOpts().HLSL) Diag(EllipsisLoc, diag::err_hlsl_variadic_templates); else // HLSL Change Ends Diag(EllipsisLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_variadic_templates : diag::ext_variadic_templates); } // Get the identifier, if given. SourceLocation NameLoc; IdentifierInfo *ParamName = nullptr; if (Tok.is(tok::identifier)) { ParamName = Tok.getIdentifierInfo(); NameLoc = ConsumeToken(); } else if (Tok.isOneOf(tok::equal, tok::comma, tok::greater, tok::greatergreater)) { // Unnamed template parameter. Don't have to do anything here, just // don't consume this token. } else { Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; return nullptr; } // Recover from misplaced ellipsis. bool AlreadyHasEllipsis = EllipsisLoc.isValid(); if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) DiagnoseMisplacedEllipsis(EllipsisLoc, NameLoc, AlreadyHasEllipsis, true); TemplateParameterList *ParamList = Actions.ActOnTemplateParameterList(Depth, SourceLocation(), TemplateLoc, LAngleLoc, TemplateParams.data(), TemplateParams.size(), RAngleLoc); // Grab a default argument (if available). // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before // we introduce the template parameter into the local scope. SourceLocation EqualLoc; ParsedTemplateArgument DefaultArg; if (TryConsumeToken(tok::equal, EqualLoc)) { DefaultArg = ParseTemplateTemplateArgument(); if (DefaultArg.isInvalid()) { Diag(Tok.getLocation(), diag::err_default_template_template_parameter_not_template); SkipUntil(tok::comma, tok::greater, tok::greatergreater, StopAtSemi | StopBeforeMatch); } } return Actions.ActOnTemplateTemplateParameter(getCurScope(), TemplateLoc, ParamList, EllipsisLoc, ParamName, NameLoc, Depth, Position, EqualLoc, DefaultArg); } /// ParseNonTypeTemplateParameter - Handle the parsing of non-type /// template parameters (e.g., in "template<int Size> class array;"). /// /// template-parameter: /// ... /// parameter-declaration Decl * Parser::ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position) { // Parse the declaration-specifiers (i.e., the type). // FIXME: The type should probably be restricted in some way... Not all // declarators (parts of declarators?) are accepted for parameters. DeclSpec DS(AttrFactory); ParseDeclarationSpecifiers(DS); // Parse this as a typename. Declarator ParamDecl(DS, Declarator::TemplateParamContext); ParseDeclarator(ParamDecl); if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { Diag(Tok.getLocation(), diag::err_expected_template_parameter); return nullptr; } // Recover from misplaced ellipsis. SourceLocation EllipsisLoc; if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) DiagnoseMisplacedEllipsisInDeclarator(EllipsisLoc, ParamDecl); // If there is a default value, parse it. // Per C++0x [basic.scope.pdecl]p9, we parse the default argument before // we introduce the template parameter into the local scope. SourceLocation EqualLoc; ExprResult DefaultArg; if (TryConsumeToken(tok::equal, EqualLoc)) { // C++ [temp.param]p15: // When parsing a default template-argument for a non-type // template-parameter, the first non-nested > is taken as the // end of the template-parameter-list rather than a greater-than // operator. GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); DefaultArg = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); if (DefaultArg.isInvalid()) SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch); } // Create the parameter. return Actions.ActOnNonTypeTemplateParameter(getCurScope(), ParamDecl, Depth, Position, EqualLoc, DefaultArg.get()); } void Parser::DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName) { FixItHint Insertion; if (!AlreadyHasEllipsis) Insertion = FixItHint::CreateInsertion(CorrectLoc, "..."); Diag(EllipsisLoc, diag::err_misplaced_ellipsis_in_declaration) << FixItHint::CreateRemoval(EllipsisLoc) << Insertion << !IdentifierHasName; } void Parser::DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D) { assert(EllipsisLoc.isValid()); bool AlreadyHasEllipsis = D.getEllipsisLoc().isValid(); if (!AlreadyHasEllipsis) D.setEllipsisLoc(EllipsisLoc); DiagnoseMisplacedEllipsis(EllipsisLoc, D.getIdentifierLoc(), AlreadyHasEllipsis, D.hasName()); } /// \brief Parses a '>' at the end of a template list. /// /// If this function encounters '>>', '>>>', '>=', or '>>=', it tries /// to determine if these tokens were supposed to be a '>' followed by /// '>', '>>', '>=', or '>='. It emits an appropriate diagnostic if necessary. /// /// \param RAngleLoc the location of the consumed '>'. /// /// \param ConsumeLastToken if true, the '>' is consumed. /// /// \param ObjCGenericList if true, this is the '>' closing an Objective-C /// type parameter or type argument list, rather than a C++ template parameter /// or argument list. /// /// \returns true, if current token does not start with '>', false otherwise. bool Parser::ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList) { // What will be left once we've consumed the '>'. tok::TokenKind RemainingToken; const char *ReplacementStr = "> >"; switch (Tok.getKind()) { default: Diag(Tok.getLocation(), diag::err_expected) << tok::greater; return true; case tok::greater: // Determine the location of the '>' token. Only consume this token // if the caller asked us to. RAngleLoc = Tok.getLocation(); if (ConsumeLastToken) ConsumeToken(); return false; case tok::greatergreater: RemainingToken = tok::greater; break; case tok::greatergreatergreater: RemainingToken = tok::greatergreater; break; case tok::greaterequal: RemainingToken = tok::equal; ReplacementStr = "> ="; break; case tok::greatergreaterequal: RemainingToken = tok::greaterequal; break; } // This template-id is terminated by a token which starts with a '>'. Outside // C++11, this is now error recovery, and in C++11, this is error recovery if // the token isn't '>>' or '>>>'. // '>>>' is for CUDA, where this sequence of characters is parsed into // tok::greatergreatergreater, rather than two separate tokens. // // We always allow this for Objective-C type parameter and type argument // lists. RAngleLoc = Tok.getLocation(); Token Next = NextToken(); if (!ObjCGenericList) { // The source range of the '>>' or '>=' at the start of the token. CharSourceRange ReplacementRange = CharSourceRange::getCharRange(RAngleLoc, Lexer::AdvanceToTokenCharacter(RAngleLoc, 2, PP.getSourceManager(), getLangOpts())); // A hint to put a space between the '>>'s. In order to make the hint as // clear as possible, we include the characters either side of the space in // the replacement, rather than just inserting a space at SecondCharLoc. FixItHint Hint1 = FixItHint::CreateReplacement(ReplacementRange, ReplacementStr); // A hint to put another space after the token, if it would otherwise be // lexed differently. FixItHint Hint2; if ((RemainingToken == tok::greater || RemainingToken == tok::greatergreater) && (Next.isOneOf(tok::greater, tok::greatergreater, tok::greatergreatergreater, tok::equal, tok::greaterequal, tok::greatergreaterequal, tok::equalequal)) && areTokensAdjacent(Tok, Next)) Hint2 = FixItHint::CreateInsertion(Next.getLocation(), " "); unsigned DiagId = diag::err_two_right_angle_brackets_need_space; if (getLangOpts().CPlusPlus11 && (Tok.is(tok::greatergreater) || Tok.is(tok::greatergreatergreater))) DiagId = diag::warn_cxx98_compat_two_right_angle_brackets; else if (Tok.is(tok::greaterequal)) DiagId = diag::err_right_angle_bracket_equal_needs_space; Diag(Tok.getLocation(), DiagId) << Hint1 << Hint2; } // Strip the initial '>' from the token. if (RemainingToken == tok::equal && Next.is(tok::equal) && areTokensAdjacent(Tok, Next)) { // Join two adjacent '=' tokens into one, for cases like: // void (*p)() = f<int>; // return f<int>==p; ConsumeToken(); Tok.setKind(tok::equalequal); Tok.setLength(Tok.getLength() + 1); } else { Tok.setKind(RemainingToken); Tok.setLength(Tok.getLength() - 1); } Tok.setLocation(Lexer::AdvanceToTokenCharacter(RAngleLoc, 1, PP.getSourceManager(), getLangOpts())); if (!ConsumeLastToken) { // Since we're not supposed to consume the '>' token, we need to push // this token and revert the current token back to the '>'. PP.EnterToken(Tok); Tok.setKind(tok::greater); Tok.setLength(1); Tok.setLocation(RAngleLoc); } return false; } /// \brief Parses a template-id that after the template name has /// already been parsed. /// /// This routine takes care of parsing the enclosed template argument /// list ('<' template-parameter-list [opt] '>') and placing the /// results into a form that can be transferred to semantic analysis. /// /// \param Template the template declaration produced by isTemplateName /// /// \param TemplateNameLoc the source location of the template name /// /// \param SS if non-NULL, the nested-name-specifier preceding the /// template name. /// /// \param ConsumeLastToken if true, then we will consume the last /// token that forms the template-id. Otherwise, we will leave the /// last token in the stream (e.g., so that it can be replaced with an /// annotation token). bool Parser::ParseTemplateIdAfterTemplateName(TemplateTy Template, SourceLocation TemplateNameLoc, const CXXScopeSpec &SS, bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc) { assert(Tok.is(tok::less) && "Must have already parsed the template-name"); // Consume the '<'. LAngleLoc = ConsumeToken(); // Parse the optional template-argument-list. bool Invalid = false; { GreaterThanIsOperatorScope G(GreaterThanIsOperator, false); if (Tok.isNot(tok::greater) && Tok.isNot(tok::greatergreater)) Invalid = ParseTemplateArgumentList(TemplateArgs); if (Invalid) { // Try to find the closing '>'. if (ConsumeLastToken) SkipUntil(tok::greater, StopAtSemi); else SkipUntil(tok::greater, StopAtSemi | StopBeforeMatch); return true; } } return ParseGreaterThanInTemplateList(RAngleLoc, ConsumeLastToken, /*ObjCGenericList=*/false); } /// \brief Replace the tokens that form a simple-template-id with an /// annotation token containing the complete template-id. /// /// The first token in the stream must be the name of a template that /// is followed by a '<'. This routine will parse the complete /// simple-template-id and replace the tokens with a single annotation /// token with one of two different kinds: if the template-id names a /// type (and \p AllowTypeAnnotation is true), the annotation token is /// a type annotation that includes the optional nested-name-specifier /// (\p SS). Otherwise, the annotation token is a template-id /// annotation that does not include the optional /// nested-name-specifier. /// /// \param Template the declaration of the template named by the first /// token (an identifier), as returned from \c Action::isTemplateName(). /// /// \param TNK the kind of template that \p Template /// refers to, as returned from \c Action::isTemplateName(). /// /// \param SS if non-NULL, the nested-name-specifier that precedes /// this template name. /// /// \param TemplateKWLoc if valid, specifies that this template-id /// annotation was preceded by the 'template' keyword and gives the /// location of that keyword. If invalid (the default), then this /// template-id was not preceded by a 'template' keyword. /// /// \param AllowTypeAnnotation if true (the default), then a /// simple-template-id that refers to a class template, template /// template parameter, or other template that produces a type will be /// replaced with a type annotation token. Otherwise, the /// simple-template-id is always replaced with a template-id /// annotation token. /// /// If an unrecoverable parse error occurs and no annotation token can be /// formed, this function returns true. /// bool Parser::AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation) { assert(getLangOpts().CPlusPlus && "Can only annotate template-ids in C++"); assert(Template && (Tok.is(tok::less) || getLangOpts().HLSL) && // HLSL Change "Parser isn't at the beginning of a template-id"); // Consume the template-name. SourceLocation TemplateNameLoc = TemplateName.getSourceRange().getBegin(); // Parse the enclosed template argument list. SourceLocation LAngleLoc, RAngleLoc; TemplateArgList TemplateArgs; // HLSL Change Starts - allow template names without '<>' bool Invalid; bool ShouldParse = Tok.is(tok::less) || !getLangOpts().HLSL; if (ShouldParse) { // HLSL Change - make following conditional Invalid = ParseTemplateIdAfterTemplateName(Template, TemplateNameLoc, SS, false, LAngleLoc, TemplateArgs, RAngleLoc); } else { Invalid = false; RAngleLoc = LAngleLoc = Tok.getLocation(); } // HLSL Change Ends if (Invalid) { // If we failed to parse the template ID but skipped ahead to a >, we're not // going to be able to form a token annotation. Eat the '>' if present. TryConsumeToken(tok::greater); return true; } ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs); // Build the annotation token. if (TNK == TNK_Type_template && AllowTypeAnnotation) { TypeResult Type = Actions.ActOnTemplateIdType(SS, TemplateKWLoc, Template, TemplateNameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc); if (Type.isInvalid()) { // If we failed to parse the template ID but skipped ahead to a >, we're not // going to be able to form a token annotation. Eat the '>' if present. TryConsumeToken(tok::greater); return true; } Tok.setKind(tok::annot_typename); setTypeAnnotation(Tok, Type.get()); if (SS.isNotEmpty()) Tok.setLocation(SS.getBeginLoc()); else if (TemplateKWLoc.isValid()) Tok.setLocation(TemplateKWLoc); else Tok.setLocation(TemplateNameLoc); } else { // Build a template-id annotation token that can be processed // later. Tok.setKind(tok::annot_template_id); TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds); TemplateId->TemplateNameLoc = TemplateNameLoc; if (TemplateName.getKind() == UnqualifiedId::IK_Identifier) { TemplateId->Name = TemplateName.Identifier; TemplateId->Operator = OO_None; } else { TemplateId->Name = nullptr; TemplateId->Operator = TemplateName.OperatorFunctionId.Operator; } TemplateId->SS = SS; TemplateId->TemplateKWLoc = TemplateKWLoc; TemplateId->Template = Template; TemplateId->Kind = TNK; TemplateId->LAngleLoc = LAngleLoc; TemplateId->RAngleLoc = RAngleLoc; ParsedTemplateArgument *Args = TemplateId->getTemplateArgs(); for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) Args[Arg] = ParsedTemplateArgument(TemplateArgs[Arg]); Tok.setAnnotationValue(TemplateId); if (TemplateKWLoc.isValid()) Tok.setLocation(TemplateKWLoc); else Tok.setLocation(TemplateNameLoc); } // Common fields for the annotation token Tok.setAnnotationEndLoc(RAngleLoc); // In case the tokens were cached, have Preprocessor replace them with the // annotation token. PP.AnnotateCachedTokens(Tok); return false; } /// \brief Replaces a template-id annotation token with a type /// annotation token. /// /// If there was a failure when forming the type from the template-id, /// a type annotation token will still be created, but will have a /// NULL type pointer to signify an error. void Parser::AnnotateTemplateIdTokenAsType() { assert(Tok.is(tok::annot_template_id) && "Requires template-id tokens"); TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); assert((TemplateId->Kind == TNK_Type_template || TemplateId->Kind == TNK_Dependent_template_name) && "Only works for type and dependent templates"); ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), TemplateId->NumArgs); TypeResult Type = Actions.ActOnTemplateIdType(TemplateId->SS, TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc); // Create the new "type" annotation token. Tok.setKind(tok::annot_typename); setTypeAnnotation(Tok, Type.isInvalid() ? ParsedType() : Type.get()); if (TemplateId->SS.isNotEmpty()) // it was a C++ qualified type name. Tok.setLocation(TemplateId->SS.getBeginLoc()); // End location stays the same // Replace the template-id annotation token, and possible the scope-specifier // that precedes it, with the typename annotation token. PP.AnnotateCachedTokens(Tok); } /// \brief Determine whether the given token can end a template argument. static bool isEndOfTemplateArgument(Token Tok) { return Tok.isOneOf(tok::comma, tok::greater, tok::greatergreater); } /// \brief Parse a C++ template template argument. ParsedTemplateArgument Parser::ParseTemplateTemplateArgument() { if (!Tok.is(tok::identifier) && !Tok.is(tok::coloncolon) && !Tok.is(tok::annot_cxxscope)) return ParsedTemplateArgument(); // C++0x [temp.arg.template]p1: // A template-argument for a template template-parameter shall be the name // of a class template or an alias template, expressed as id-expression. // // We parse an id-expression that refers to a class template or alias // template. The grammar we parse is: // // nested-name-specifier[opt] template[opt] identifier ...[opt] // // followed by a token that terminates a template argument, such as ',', // '>', or (in some cases) '>>'. CXXScopeSpec SS; // nested-name-specifier, if present ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); ParsedTemplateArgument Result; SourceLocation EllipsisLoc; if (SS.isSet() && Tok.is(tok::kw_template)) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "template template argument"; return Result; } // HLSL Change Ends // Parse the optional 'template' keyword following the // nested-name-specifier. SourceLocation TemplateKWLoc = ConsumeToken(); if (Tok.is(tok::identifier)) { // We appear to have a dependent template name. UnqualifiedId Name; Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); ConsumeToken(); // the identifier TryConsumeToken(tok::ellipsis, EllipsisLoc); // If the next token signals the end of a template argument, // then we have a dependent template name that could be a template // template argument. TemplateTy Template; if (isEndOfTemplateArgument(Tok) && Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc, Name, /*ObjectType=*/ ParsedType(), /*EnteringContext=*/false, Template)) Result = ParsedTemplateArgument(SS, Template, Name.StartLocation); } } else if (Tok.is(tok::identifier)) { // We may have a (non-dependent) template name. TemplateTy Template; UnqualifiedId Name; Name.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); ConsumeToken(); // the identifier TryConsumeToken(tok::ellipsis, EllipsisLoc); if (isEndOfTemplateArgument(Tok)) { bool MemberOfUnknownSpecialization; TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false, Name, /*ObjectType=*/ ParsedType(), /*EnteringContext=*/false, Template, MemberOfUnknownSpecialization); if (TNK == TNK_Dependent_template_name || TNK == TNK_Type_template) { // We have an id-expression that refers to a class template or // (C++0x) alias template. Result = ParsedTemplateArgument(SS, Template, Name.StartLocation); } } } // If this is a pack expansion, build it as such. if (EllipsisLoc.isValid() && !Result.isInvalid()) Result = Actions.ActOnPackExpansion(Result, EllipsisLoc); return Result; } /// ParseTemplateArgument - Parse a C++ template argument (C++ [temp.names]). /// /// template-argument: [C++ 14.2] /// constant-expression /// type-id /// id-expression ParsedTemplateArgument Parser::ParseTemplateArgument() { // C++ [temp.arg]p2: // In a template-argument, an ambiguity between a type-id and an // expression is resolved to a type-id, regardless of the form of // the corresponding template-parameter. // // Therefore, we initially try to parse a type-id. if (isCXXTypeId(TypeIdAsTemplateArgument)) { SourceLocation Loc = Tok.getLocation(); TypeResult TypeArg = ParseTypeName(/*Range=*/nullptr, Declarator::TemplateTypeArgContext); if (TypeArg.isInvalid()) return ParsedTemplateArgument(); return ParsedTemplateArgument(ParsedTemplateArgument::Type, TypeArg.get().getAsOpaquePtr(), Loc); } // Try to parse a template template argument. { TentativeParsingAction TPA(*this); ParsedTemplateArgument TemplateTemplateArgument = ParseTemplateTemplateArgument(); if (!TemplateTemplateArgument.isInvalid()) { TPA.Commit(); return TemplateTemplateArgument; } // Revert this tentative parse to parse a non-type template argument. TPA.Revert(); } // Parse a non-type template argument. SourceLocation Loc = Tok.getLocation(); ExprResult ExprArg = ParseConstantExpression(MaybeTypeCast); if (ExprArg.isInvalid() || !ExprArg.get()) return ParsedTemplateArgument(); return ParsedTemplateArgument(ParsedTemplateArgument::NonType, ExprArg.get(), Loc); } /// \brief Determine whether the current tokens can only be parsed as a /// template argument list (starting with the '<') and never as a '<' /// expression. bool Parser::IsTemplateArgumentList(unsigned Skip) { struct AlwaysRevertAction : TentativeParsingAction { AlwaysRevertAction(Parser &P) : TentativeParsingAction(P) { } ~AlwaysRevertAction() { Revert(); } } Tentative(*this); while (Skip) { ConsumeToken(); --Skip; } // '<' if (!TryConsumeToken(tok::less)) return false; // An empty template argument list. if (Tok.is(tok::greater)) return true; // See whether we have declaration specifiers, which indicate a type. while (isCXXDeclarationSpecifier() == TPResult::True) ConsumeToken(); // If we have a '>' or a ',' then this is a template argument list. return Tok.isOneOf(tok::greater, tok::comma); } /// ParseTemplateArgumentList - Parse a C++ template-argument-list /// (C++ [temp.names]). Returns true if there was an error. /// /// template-argument-list: [C++ 14.2] /// template-argument /// template-argument-list ',' template-argument bool Parser::ParseTemplateArgumentList(TemplateArgList &TemplateArgs) { // Template argument lists are constant-evaluation contexts. EnterExpressionEvaluationContext EvalContext(Actions,Sema::ConstantEvaluated); ColonProtectionRAIIObject ColonProtection(*this, false); do { ParsedTemplateArgument Arg = ParseTemplateArgument(); SourceLocation EllipsisLoc; if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(EllipsisLoc, diag::err_hlsl_unsupported_construct) << "ellipsis"; SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch); return true; } // HLSL Change Ends Arg = Actions.ActOnPackExpansion(Arg, EllipsisLoc); } // HLSL Change - end conditional block if (Arg.isInvalid()) { SkipUntil(tok::comma, tok::greater, StopAtSemi | StopBeforeMatch); return true; } // Save this template argument. TemplateArgs.push_back(Arg); // If the next token is a comma, consume it and keep reading // arguments. } while (TryConsumeToken(tok::comma)); return false; } /// \brief Parse a C++ explicit template instantiation /// (C++ [temp.explicit]). /// /// explicit-instantiation: /// 'extern' [opt] 'template' declaration /// /// Note that the 'extern' is a GNU extension and C++11 feature. Decl *Parser::ParseExplicitInstantiation(unsigned Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, AccessSpecifier AS) { // This isn't really required here. ParsingDeclRAIIObject ParsingTemplateParams(*this, ParsingDeclRAIIObject::NoParent); return ParseSingleDeclarationAfterTemplate(Context, ParsedTemplateInfo(ExternLoc, TemplateLoc), ParsingTemplateParams, DeclEnd, AS); } SourceRange Parser::ParsedTemplateInfo::getSourceRange() const { if (TemplateParams) return getTemplateParamsRange(TemplateParams->data(), TemplateParams->size()); SourceRange R(TemplateLoc); if (ExternLoc.isValid()) R.setBegin(ExternLoc); return R; } void Parser::LateTemplateParserCallback(void *P, LateParsedTemplate &LPT) { ((Parser *)P)->ParseLateTemplatedFuncDef(LPT); } /// \brief Late parse a C++ function template in Microsoft mode. void Parser::ParseLateTemplatedFuncDef(LateParsedTemplate &LPT) { if (!LPT.D) return; // Get the FunctionDecl. FunctionDecl *FunD = LPT.D->getAsFunction(); // Track template parameter depth. TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); // To restore the context after late parsing. Sema::ContextRAII GlobalSavedContext( Actions, Actions.Context.getTranslationUnitDecl()); SmallVector<ParseScope*, 4> TemplateParamScopeStack; // Get the list of DeclContexts to reenter. SmallVector<DeclContext*, 4> DeclContextsToReenter; DeclContext *DD = FunD; while (DD && !DD->isTranslationUnit()) { DeclContextsToReenter.push_back(DD); DD = DD->getLexicalParent(); } // Reenter template scopes from outermost to innermost. SmallVectorImpl<DeclContext *>::reverse_iterator II = DeclContextsToReenter.rbegin(); for (; II != DeclContextsToReenter.rend(); ++II) { TemplateParamScopeStack.push_back(new ParseScope(this, Scope::TemplateParamScope)); unsigned NumParamLists = Actions.ActOnReenterTemplateScope(getCurScope(), cast<Decl>(*II)); CurTemplateDepthTracker.addDepth(NumParamLists); if (*II != FunD) { TemplateParamScopeStack.push_back(new ParseScope(this, Scope::DeclScope)); Actions.PushDeclContext(Actions.getCurScope(), *II); } } assert(!LPT.Toks.empty() && "Empty body!"); // Append the current token at the end of the new token stream so that it // doesn't get lost. LPT.Toks.push_back(Tok); PP.EnterTokenStream(LPT.Toks.data(), LPT.Toks.size(), true, false); // Consume the previously pushed token. ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true); assert(Tok.isOneOf(tok::l_brace, tok::colon, tok::kw_try) && "Inline method not starting with '{', ':' or 'try'"); // Parse the method body. Function body parsing code is similar enough // to be re-used for method bodies as well. ParseScope FnScope(this, Scope::FnScope|Scope::DeclScope); // Recreate the containing function DeclContext. Sema::ContextRAII FunctionSavedContext(Actions, Actions.getContainingDC(FunD)); Actions.ActOnStartOfFunctionDef(getCurScope(), FunD); if (Tok.is(tok::kw_try)) { ParseFunctionTryBlock(LPT.D, FnScope); } else { if (Tok.is(tok::colon)) ParseConstructorInitializer(LPT.D); else Actions.ActOnDefaultCtorInitializers(LPT.D); if (Tok.is(tok::l_brace)) { assert((!isa<FunctionTemplateDecl>(LPT.D) || cast<FunctionTemplateDecl>(LPT.D) ->getTemplateParameters() ->getDepth() == TemplateParameterDepth - 1) && "TemplateParameterDepth should be greater than the depth of " "current template being instantiated!"); ParseFunctionStatementBody(LPT.D, FnScope); Actions.UnmarkAsLateParsedTemplate(FunD); } else Actions.ActOnFinishFunctionBody(LPT.D, nullptr); } // Exit scopes. FnScope.Exit(); SmallVectorImpl<ParseScope *>::reverse_iterator I = TemplateParamScopeStack.rbegin(); for (; I != TemplateParamScopeStack.rend(); ++I) delete *I; } /// \brief Lex a delayed template function for late parsing. void Parser::LexTemplateFunctionForLateParsing(CachedTokens &Toks) { tok::TokenKind kind = Tok.getKind(); if (!ConsumeAndStoreFunctionPrologue(Toks)) { // Consume everything up to (and including) the matching right brace. ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); } // If we're in a function-try-block, we need to store all the catch blocks. if (kind == tok::kw_try) { while (Tok.is(tok::kw_catch)) { ConsumeAndStoreUntil(tok::l_brace, Toks, /*StopAtSemi=*/false); ConsumeAndStoreUntil(tok::r_brace, Toks, /*StopAtSemi=*/false); } } }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseOpenMP.cpp
//===--- ParseOpenMP.cpp - OpenMP directives parsing ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// \brief This file implements parsing of all OpenMP directives and clauses. /// //===----------------------------------------------------------------------===// #include "RAIIObjectsForParser.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/StmtOpenMP.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Sema/Scope.h" #include "llvm/ADT/PointerIntPair.h" using namespace clang; //===----------------------------------------------------------------------===// // OpenMP declarative directives. //===----------------------------------------------------------------------===// static OpenMPDirectiveKind ParseOpenMPDirectiveKind(Parser &P) { // Array of foldings: F[i][0] F[i][1] ===> F[i][2]. // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd // TODO: add other combined directives in topological order. const OpenMPDirectiveKind F[][3] = { {OMPD_unknown /*cancellation*/, OMPD_unknown /*point*/, OMPD_cancellation_point}, {OMPD_for, OMPD_simd, OMPD_for_simd}, {OMPD_parallel, OMPD_for, OMPD_parallel_for}, {OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd}, {OMPD_parallel, OMPD_sections, OMPD_parallel_sections}}; auto Tok = P.getCurToken(); auto DKind = Tok.isAnnotation() ? OMPD_unknown : getOpenMPDirectiveKind(P.getPreprocessor().getSpelling(Tok)); bool TokenMatched = false; for (unsigned i = 0; i < llvm::array_lengthof(F); ++i) { if (!Tok.isAnnotation() && DKind == OMPD_unknown) { TokenMatched = (i == 0) && !P.getPreprocessor().getSpelling(Tok).compare("cancellation"); } else { TokenMatched = DKind == F[i][0] && DKind != OMPD_unknown; } if (TokenMatched) { Tok = P.getPreprocessor().LookAhead(0); auto SDKind = Tok.isAnnotation() ? OMPD_unknown : getOpenMPDirectiveKind(P.getPreprocessor().getSpelling(Tok)); if (!Tok.isAnnotation() && DKind == OMPD_unknown) { TokenMatched = (i == 0) && !P.getPreprocessor().getSpelling(Tok).compare("point"); } else { TokenMatched = SDKind == F[i][1] && SDKind != OMPD_unknown; } if (TokenMatched) { P.ConsumeToken(); DKind = F[i][2]; } } } return DKind; } /// \brief Parsing of declarative OpenMP directives. /// /// threadprivate-directive: /// annot_pragma_openmp 'threadprivate' simple-variable-list /// Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirective() { assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!"); ParenBraceBracketBalancer BalancerRAIIObj(*this); SourceLocation Loc = ConsumeToken(); SmallVector<Expr *, 5> Identifiers; auto DKind = ParseOpenMPDirectiveKind(*this); switch (DKind) { case OMPD_threadprivate: ConsumeToken(); if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Identifiers, true)) { // The last seen token is annot_pragma_openmp_end - need to check for // extra tokens. if (Tok.isNot(tok::annot_pragma_openmp_end)) { Diag(Tok, diag::warn_omp_extra_tokens_at_eol) << getOpenMPDirectiveName(OMPD_threadprivate); SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); } // Skip the last annot_pragma_openmp_end. ConsumeToken(); return Actions.ActOnOpenMPThreadprivateDirective(Loc, Identifiers); } break; case OMPD_unknown: Diag(Tok, diag::err_omp_unknown_directive); break; case OMPD_parallel: case OMPD_simd: case OMPD_task: case OMPD_taskyield: case OMPD_barrier: case OMPD_taskwait: case OMPD_taskgroup: case OMPD_flush: case OMPD_for: case OMPD_for_simd: case OMPD_sections: case OMPD_section: case OMPD_single: case OMPD_master: case OMPD_ordered: case OMPD_critical: case OMPD_parallel_for: case OMPD_parallel_for_simd: case OMPD_parallel_sections: case OMPD_atomic: case OMPD_target: case OMPD_teams: case OMPD_cancellation_point: case OMPD_cancel: Diag(Tok, diag::err_omp_unexpected_directive) << getOpenMPDirectiveName(DKind); break; } SkipUntil(tok::annot_pragma_openmp_end); return DeclGroupPtrTy(); } /// \brief Parsing of declarative or executable OpenMP directives. /// /// threadprivate-directive: /// annot_pragma_openmp 'threadprivate' simple-variable-list /// annot_pragma_openmp_end /// /// executable-directive: /// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' | /// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] | /// 'parallel for' | 'parallel sections' | 'task' | 'taskyield' | /// 'barrier' | 'taskwait' | 'flush' | 'ordered' | 'atomic' | /// 'for simd' | 'parallel for simd' | 'target' | 'teams' | 'taskgroup' /// {clause} /// annot_pragma_openmp_end /// StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(bool StandAloneAllowed) { assert(Tok.is(tok::annot_pragma_openmp) && "Not an OpenMP directive!"); ParenBraceBracketBalancer BalancerRAIIObj(*this); SmallVector<Expr *, 5> Identifiers; SmallVector<OMPClause *, 5> Clauses; SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>, OMPC_unknown + 1> FirstClauses(OMPC_unknown + 1); unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope | Scope::OpenMPDirectiveScope; SourceLocation Loc = ConsumeToken(), EndLoc; auto DKind = ParseOpenMPDirectiveKind(*this); OpenMPDirectiveKind CancelRegion = OMPD_unknown; // Name of critical directive. DeclarationNameInfo DirName; StmtResult Directive = StmtError(); bool HasAssociatedStatement = true; bool FlushHasClause = false; switch (DKind) { case OMPD_threadprivate: ConsumeToken(); if (!ParseOpenMPSimpleVarList(OMPD_threadprivate, Identifiers, false)) { // The last seen token is annot_pragma_openmp_end - need to check for // extra tokens. if (Tok.isNot(tok::annot_pragma_openmp_end)) { Diag(Tok, diag::warn_omp_extra_tokens_at_eol) << getOpenMPDirectiveName(OMPD_threadprivate); SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); } DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(Loc, Identifiers); Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation()); } SkipUntil(tok::annot_pragma_openmp_end); break; case OMPD_flush: if (PP.LookAhead(0).is(tok::l_paren)) { FlushHasClause = true; // Push copy of the current token back to stream to properly parse // pseudo-clause OMPFlushClause. PP.EnterToken(Tok); } LLVM_FALLTHROUGH; // HLSL Change case OMPD_taskyield: case OMPD_barrier: case OMPD_taskwait: case OMPD_cancellation_point: case OMPD_cancel: if (!StandAloneAllowed) { Diag(Tok, diag::err_omp_immediate_directive) << getOpenMPDirectiveName(DKind); } HasAssociatedStatement = false; // Fall through for further analysis. LLVM_FALLTHROUGH; // HLSL Change case OMPD_parallel: case OMPD_simd: case OMPD_for: case OMPD_for_simd: case OMPD_sections: case OMPD_single: case OMPD_section: case OMPD_master: case OMPD_critical: case OMPD_parallel_for: case OMPD_parallel_for_simd: case OMPD_parallel_sections: case OMPD_task: case OMPD_ordered: case OMPD_atomic: case OMPD_target: case OMPD_teams: case OMPD_taskgroup: { ConsumeToken(); // Parse directive name of the 'critical' directive if any. if (DKind == OMPD_critical) { BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); if (!T.consumeOpen()) { if (Tok.isAnyIdentifier()) { DirName = DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation()); ConsumeAnyToken(); } else { Diag(Tok, diag::err_omp_expected_identifier_for_critical); } T.consumeClose(); } } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) { CancelRegion = ParseOpenMPDirectiveKind(*this); if (Tok.isNot(tok::annot_pragma_openmp_end)) ConsumeToken(); } if (isOpenMPLoopDirective(DKind)) ScopeFlags |= Scope::OpenMPLoopDirectiveScope; if (isOpenMPSimdDirective(DKind)) ScopeFlags |= Scope::OpenMPSimdDirectiveScope; ParseScope OMPDirectiveScope(this, ScopeFlags); Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc); while (Tok.isNot(tok::annot_pragma_openmp_end)) { OpenMPClauseKind CKind = Tok.isAnnotation() ? OMPC_unknown : FlushHasClause ? OMPC_flush : getOpenMPClauseKind(PP.getSpelling(Tok)); Actions.StartOpenMPClause(CKind); FlushHasClause = false; OMPClause *Clause = ParseOpenMPClause(DKind, CKind, !FirstClauses[CKind].getInt()); FirstClauses[CKind].setInt(true); if (Clause) { FirstClauses[CKind].setPointer(Clause); Clauses.push_back(Clause); } // Skip ',' if any. if (Tok.is(tok::comma)) ConsumeToken(); Actions.EndOpenMPClause(); } // End location of the directive. EndLoc = Tok.getLocation(); // Consume final annot_pragma_openmp_end. ConsumeToken(); StmtResult AssociatedStmt; bool CreateDirective = true; if (HasAssociatedStatement) { // The body is a block scope like in Lambdas and Blocks. Sema::CompoundScopeRAII CompoundScope(Actions); Actions.ActOnOpenMPRegionStart(DKind, getCurScope()); Actions.ActOnStartOfCompoundStmt(); // Parse statement AssociatedStmt = ParseStatement(); Actions.ActOnFinishOfCompoundStmt(); AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses); CreateDirective = AssociatedStmt.isUsable(); } if (CreateDirective) Directive = Actions.ActOnOpenMPExecutableDirective( DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc, EndLoc); // Exit scope. Actions.EndOpenMPDSABlock(Directive.get()); OMPDirectiveScope.Exit(); break; } case OMPD_unknown: Diag(Tok, diag::err_omp_unknown_directive); SkipUntil(tok::annot_pragma_openmp_end); break; } return Directive; } /// \brief Parses list of simple variables for '#pragma omp threadprivate' /// directive. /// /// simple-variable-list: /// '(' id-expression {, id-expression} ')' /// bool Parser::ParseOpenMPSimpleVarList(OpenMPDirectiveKind Kind, SmallVectorImpl<Expr *> &VarList, bool AllowScopeSpecifier) { VarList.clear(); // Parse '('. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); if (T.expectAndConsume(diag::err_expected_lparen_after, getOpenMPDirectiveName(Kind))) return true; bool IsCorrect = true; bool NoIdentIsFound = true; // Read tokens while ')' or annot_pragma_openmp_end is not found. while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) { CXXScopeSpec SS; SourceLocation TemplateKWLoc; UnqualifiedId Name; // Read var name. Token PrevTok = Tok; NoIdentIsFound = false; if (AllowScopeSpecifier && getLangOpts().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS, ParsedType(), false)) { IsCorrect = false; SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); } else if (ParseUnqualifiedId(SS, false, false, false, ParsedType(), TemplateKWLoc, Name)) { IsCorrect = false; SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) { IsCorrect = false; SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); Diag(PrevTok.getLocation(), diag::err_expected) << tok::identifier << SourceRange(PrevTok.getLocation(), PrevTokLocation); } else { DeclarationNameInfo NameInfo = Actions.GetNameFromUnqualifiedId(Name); ExprResult Res = Actions.ActOnOpenMPIdExpression(getCurScope(), SS, NameInfo); if (Res.isUsable()) VarList.push_back(Res.get()); } // Consume ','. if (Tok.is(tok::comma)) { ConsumeToken(); } } if (NoIdentIsFound) { Diag(Tok, diag::err_expected) << tok::identifier; IsCorrect = false; } // Parse ')'. IsCorrect = !T.consumeClose() && IsCorrect; return !IsCorrect && VarList.empty(); } /// \brief Parsing of OpenMP clauses. /// /// clause: /// if-clause | final-clause | num_threads-clause | safelen-clause | /// default-clause | private-clause | firstprivate-clause | shared-clause /// | linear-clause | aligned-clause | collapse-clause | /// lastprivate-clause | reduction-clause | proc_bind-clause | /// schedule-clause | copyin-clause | copyprivate-clause | untied-clause | /// mergeable-clause | flush-clause | read-clause | write-clause | /// update-clause | capture-clause | seq_cst-clause /// OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause) { OMPClause *Clause = nullptr; bool ErrorFound = false; // Check if clause is allowed for the given directive. if (CKind != OMPC_unknown && !isAllowedClauseForDirective(DKind, CKind)) { Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind); ErrorFound = true; } switch (CKind) { case OMPC_if: case OMPC_final: case OMPC_num_threads: case OMPC_safelen: case OMPC_collapse: // OpenMP [2.5, Restrictions] // At most one if clause can appear on the directive. // At most one num_threads clause can appear on the directive. // OpenMP [2.8.1, simd construct, Restrictions] // Only one safelen clause can appear on a simd directive. // Only one collapse clause can appear on a simd directive. // OpenMP [2.11.1, task Construct, Restrictions] // At most one if clause can appear on the directive. // At most one final clause can appear on the directive. if (!FirstClause) { Diag(Tok, diag::err_omp_more_one_clause) << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind); ErrorFound = true; } Clause = ParseOpenMPSingleExprClause(CKind); break; case OMPC_default: case OMPC_proc_bind: // OpenMP [2.14.3.1, Restrictions] // Only a single default clause may be specified on a parallel, task or // teams directive. // OpenMP [2.5, parallel Construct, Restrictions] // At most one proc_bind clause can appear on the directive. if (!FirstClause) { Diag(Tok, diag::err_omp_more_one_clause) << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind); ErrorFound = true; } Clause = ParseOpenMPSimpleClause(CKind); break; case OMPC_schedule: // OpenMP [2.7.1, Restrictions, p. 3] // Only one schedule clause can appear on a loop directive. if (!FirstClause) { Diag(Tok, diag::err_omp_more_one_clause) << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind); ErrorFound = true; } Clause = ParseOpenMPSingleExprWithArgClause(CKind); break; case OMPC_ordered: case OMPC_nowait: case OMPC_untied: case OMPC_mergeable: case OMPC_read: case OMPC_write: case OMPC_update: case OMPC_capture: case OMPC_seq_cst: // OpenMP [2.7.1, Restrictions, p. 9] // Only one ordered clause can appear on a loop directive. // OpenMP [2.7.1, Restrictions, C/C++, p. 4] // Only one nowait clause can appear on a for directive. if (!FirstClause) { Diag(Tok, diag::err_omp_more_one_clause) << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind); ErrorFound = true; } Clause = ParseOpenMPClause(CKind); break; case OMPC_private: case OMPC_firstprivate: case OMPC_lastprivate: case OMPC_shared: case OMPC_reduction: case OMPC_linear: case OMPC_aligned: case OMPC_copyin: case OMPC_copyprivate: case OMPC_flush: case OMPC_depend: Clause = ParseOpenMPVarListClause(CKind); break; case OMPC_unknown: Diag(Tok, diag::warn_omp_extra_tokens_at_eol) << getOpenMPDirectiveName(DKind); SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch); break; case OMPC_threadprivate: Diag(Tok, diag::err_omp_unexpected_clause) << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind); SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch); break; } return ErrorFound ? nullptr : Clause; } /// \brief Parsing of OpenMP clauses with single expressions like 'if', /// 'final', 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams' or /// 'thread_limit'. /// /// if-clause: /// 'if' '(' expression ')' /// /// final-clause: /// 'final' '(' expression ')' /// /// num_threads-clause: /// 'num_threads' '(' expression ')' /// /// safelen-clause: /// 'safelen' '(' expression ')' /// /// collapse-clause: /// 'collapse' '(' expression ')' /// OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind) { SourceLocation Loc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); if (T.expectAndConsume(diag::err_expected_lparen_after, getOpenMPClauseName(Kind))) return nullptr; ExprResult LHS(ParseCastExpression(false, false, NotTypeCast)); ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional)); // Parse ')'. T.consumeClose(); if (Val.isInvalid()) return nullptr; return Actions.ActOnOpenMPSingleExprClause( Kind, Val.get(), Loc, T.getOpenLocation(), T.getCloseLocation()); } /// \brief Parsing of simple OpenMP clauses like 'default' or 'proc_bind'. /// /// default-clause: /// 'default' '(' 'none' | 'shared' ') /// /// proc_bind-clause: /// 'proc_bind' '(' 'master' | 'close' | 'spread' ') /// OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind) { SourceLocation Loc = Tok.getLocation(); SourceLocation LOpen = ConsumeToken(); // Parse '('. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); if (T.expectAndConsume(diag::err_expected_lparen_after, getOpenMPClauseName(Kind))) return nullptr; unsigned Type = getOpenMPSimpleClauseType( Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)); SourceLocation TypeLoc = Tok.getLocation(); if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && Tok.isNot(tok::annot_pragma_openmp_end)) ConsumeAnyToken(); // Parse ')'. T.consumeClose(); return Actions.ActOnOpenMPSimpleClause(Kind, Type, TypeLoc, LOpen, Loc, Tok.getLocation()); } /// \brief Parsing of OpenMP clauses like 'ordered'. /// /// ordered-clause: /// 'ordered' /// /// nowait-clause: /// 'nowait' /// /// untied-clause: /// 'untied' /// /// mergeable-clause: /// 'mergeable' /// /// read-clause: /// 'read' /// OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind) { SourceLocation Loc = Tok.getLocation(); ConsumeAnyToken(); return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation()); } /// \brief Parsing of OpenMP clauses with single expressions and some additional /// argument like 'schedule' or 'dist_schedule'. /// /// schedule-clause: /// 'schedule' '(' kind [',' expression ] ')' /// OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind) { SourceLocation Loc = ConsumeToken(); SourceLocation CommaLoc; // Parse '('. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); if (T.expectAndConsume(diag::err_expected_lparen_after, getOpenMPClauseName(Kind))) return nullptr; ExprResult Val; unsigned Type = getOpenMPSimpleClauseType( Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok)); SourceLocation KLoc = Tok.getLocation(); if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) && Tok.isNot(tok::annot_pragma_openmp_end)) ConsumeAnyToken(); if (Kind == OMPC_schedule && (Type == OMPC_SCHEDULE_static || Type == OMPC_SCHEDULE_dynamic || Type == OMPC_SCHEDULE_guided) && Tok.is(tok::comma)) { CommaLoc = ConsumeAnyToken(); ExprResult LHS(ParseCastExpression(false, false, NotTypeCast)); Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional); if (Val.isInvalid()) return nullptr; } // Parse ')'. T.consumeClose(); return Actions.ActOnOpenMPSingleExprWithArgClause( Kind, Type, Val.get(), Loc, T.getOpenLocation(), KLoc, CommaLoc, T.getCloseLocation()); } static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec, UnqualifiedId &ReductionId) { SourceLocation TemplateKWLoc; if (ReductionIdScopeSpec.isEmpty()) { auto OOK = OO_None; switch (P.getCurToken().getKind()) { case tok::plus: OOK = OO_Plus; break; case tok::minus: OOK = OO_Minus; break; case tok::star: OOK = OO_Star; break; case tok::amp: OOK = OO_Amp; break; case tok::pipe: OOK = OO_Pipe; break; case tok::caret: OOK = OO_Caret; break; case tok::ampamp: OOK = OO_AmpAmp; break; case tok::pipepipe: OOK = OO_PipePipe; break; default: break; } if (OOK != OO_None) { SourceLocation OpLoc = P.ConsumeToken(); SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()}; ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations); return false; } } return P.ParseUnqualifiedId(ReductionIdScopeSpec, /*EnteringContext*/ false, /*AllowDestructorName*/ false, /*AllowConstructorName*/ false, ParsedType(), TemplateKWLoc, ReductionId); } /// \brief Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate', /// 'shared', 'copyin', 'copyprivate', 'flush' or 'reduction'. /// /// private-clause: /// 'private' '(' list ')' /// firstprivate-clause: /// 'firstprivate' '(' list ')' /// lastprivate-clause: /// 'lastprivate' '(' list ')' /// shared-clause: /// 'shared' '(' list ')' /// linear-clause: /// 'linear' '(' list [ ':' linear-step ] ')' /// aligned-clause: /// 'aligned' '(' list [ ':' alignment ] ')' /// reduction-clause: /// 'reduction' '(' reduction-identifier ':' list ')' /// copyprivate-clause: /// 'copyprivate' '(' list ')' /// flush-clause: /// 'flush' '(' list ')' /// depend-clause: /// 'depend' '(' in | out | inout : list ')' /// OMPClause *Parser::ParseOpenMPVarListClause(OpenMPClauseKind Kind) { SourceLocation Loc = Tok.getLocation(); SourceLocation LOpen = ConsumeToken(); SourceLocation ColonLoc = SourceLocation(); // Optional scope specifier and unqualified id for reduction identifier. CXXScopeSpec ReductionIdScopeSpec; UnqualifiedId ReductionId; bool InvalidReductionId = false; OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; SourceLocation DepLoc; // Parse '('. BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end); if (T.expectAndConsume(diag::err_expected_lparen_after, getOpenMPClauseName(Kind))) return nullptr; // Handle reduction-identifier for reduction clause. if (Kind == OMPC_reduction) { ColonProtectionRAIIObject ColonRAII(*this); if (getLangOpts().CPlusPlus) { ParseOptionalCXXScopeSpecifier(ReductionIdScopeSpec, ParsedType(), false); } InvalidReductionId = ParseReductionId(*this, ReductionIdScopeSpec, ReductionId); if (InvalidReductionId) { SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); } if (Tok.is(tok::colon)) { ColonLoc = ConsumeToken(); } else { Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier"; } } else if (Kind == OMPC_depend) { // Handle dependency type for depend clause. ColonProtectionRAIIObject ColonRAII(*this); DepKind = static_cast<OpenMPDependClauseKind>(getOpenMPSimpleClauseType( Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "")); DepLoc = Tok.getLocation(); if (DepKind == OMPC_DEPEND_unknown) { SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); } else { ConsumeToken(); } if (Tok.is(tok::colon)) { ColonLoc = ConsumeToken(); } else { Diag(Tok, diag::warn_pragma_expected_colon) << "dependency type"; } } SmallVector<Expr *, 5> Vars; bool IsComma = ((Kind != OMPC_reduction) && (Kind != OMPC_depend)) || ((Kind == OMPC_reduction) && !InvalidReductionId) || ((Kind == OMPC_depend) && DepKind != OMPC_DEPEND_unknown); const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned); while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) && Tok.isNot(tok::annot_pragma_openmp_end))) { ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail); // Parse variable ExprResult VarExpr = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); if (VarExpr.isUsable()) { Vars.push_back(VarExpr.get()); } else { SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); } // Skip ',' if any IsComma = Tok.is(tok::comma); if (IsComma) ConsumeToken(); else if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end) && (!MayHaveTail || Tok.isNot(tok::colon))) Diag(Tok, diag::err_omp_expected_punc) << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush) : getOpenMPClauseName(Kind)) << (Kind == OMPC_flush); } // Parse ':' linear-step (or ':' alignment). Expr *TailExpr = nullptr; const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon); if (MustHaveTail) { ColonLoc = Tok.getLocation(); ConsumeToken(); ExprResult Tail = Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression()); if (Tail.isUsable()) TailExpr = Tail.get(); else SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch); } // Parse ')'. T.consumeClose(); if ((Kind == OMPC_depend && DepKind != OMPC_DEPEND_unknown && Vars.empty()) || (Kind != OMPC_depend && Vars.empty()) || (MustHaveTail && !TailExpr) || InvalidReductionId) return nullptr; return Actions.ActOnOpenMPVarListClause( Kind, Vars, TailExpr, Loc, LOpen, ColonLoc, Tok.getLocation(), ReductionIdScopeSpec, ReductionId.isValid() ? Actions.GetNameFromUnqualifiedId(ReductionId) : DeclarationNameInfo(), DepKind, DepLoc); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseHLSL.cpp
//===--- ParseHLSL.cpp - HLSL Parsing -------------------------------------===// /////////////////////////////////////////////////////////////////////////////// // // // ParseHLSL.cpp // // Copyright (C) Microsoft Corporation. All rights reserved. // // This file is distributed under the University of Illinois Open Source // // License. See LICENSE.TXT for details. // // // // This file implements the HLSLportions of the Parser interfaces. // // // /////////////////////////////////////////////////////////////////////////////// #include "RAIIObjectsForParser.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclTemplate.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/OperatorKinds.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/PrettyDeclStackTrace.h" #include "clang/Sema/Scope.h" #include "clang/Sema/SemaDiagnostic.h" #include "llvm/ADT/SmallString.h" using namespace clang; Decl *Parser::ParseCTBuffer(unsigned Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &CTBAttrs, SourceLocation InlineLoc) { assert((Tok.is(tok::kw_cbuffer) || Tok.is(tok::kw_tbuffer)) && "Not a cbuffer or tbuffer!"); bool isCBuffer = Tok.is(tok::kw_cbuffer); SourceLocation BufferLoc = ConsumeToken(); // eat the 'cbuffer or tbuffer'. if (!Tok.is(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; return nullptr; } IdentifierInfo *identifier = Tok.getIdentifierInfo(); SourceLocation identifierLoc = ConsumeToken(); // consume identifier std::vector<hlsl::UnusualAnnotation *> hlslAttrs; MaybeParseHLSLAttributes(hlslAttrs); ParseScope BufferScope(this, Scope::DeclScope); BalancedDelimiterTracker T(*this, tok::l_brace); if (T.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; return nullptr; } Decl *decl = Actions.ActOnStartHLSLBuffer(getCurScope(), isCBuffer, BufferLoc, identifier, identifierLoc, hlslAttrs, T.getOpenLocation()); // Process potential C++11 attribute specifiers Actions.ProcessDeclAttributeList(getCurScope(), decl, CTBAttrs.getList()); while (Tok.isNot(tok::r_brace) && Tok.isNot(tok::eof)) { ParsedAttributesWithRange attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); MaybeParseHLSLAttributes(attrs); MaybeParseMicrosoftAttributes(attrs); ParseExternalDeclaration(attrs); } T.consumeClose(); DeclEnd = T.getCloseLocation(); BufferScope.Exit(); Actions.ActOnFinishHLSLBuffer(decl, DeclEnd); return decl; } /// ParseHLSLAttributeSpecifier - Parse an HLSL attribute-specifier. /// /// [HLSL] attribute-specifier: /// '[' attribute[opt] ']' /// /// [HLSL] attribute: /// attribute-token attribute-argument-clause[opt] /// /// [HLSL] attribute-token: /// identifier /// /// [HLSL] attribute-argument-clause: /// '(' attribute-params ')' /// /// [HLSL] attribute-params: /// constant-expr /// attribute-params ',' constant-expr /// void Parser::ParseHLSLAttributeSpecifier(ParsedAttributes &attrs, SourceLocation *endLoc) { assert(getLangOpts().HLSL); assert(Tok.is(tok::l_square) && "Not an HLSL attribute list"); ConsumeBracket(); llvm::SmallDenseMap<IdentifierInfo *, SourceLocation, 4> SeenAttrs; // '[]' is valid. if (Tok.is(tok::r_square)) { *endLoc = ConsumeBracket(); return; } if (!Tok.isAnyIdentifier()) { Diag(Tok, diag::err_expected) << tok::identifier; SkipUntil(tok::r_square); return; } SourceLocation AttrLoc; IdentifierInfo *AttrName = 0; AttrName = TryParseCXX11AttributeIdentifier(AttrLoc); assert(AttrName != nullptr && "already called isAnyIdenfier before"); // Parse attribute arguments if (Tok.is(tok::l_paren)) { ParseGNUAttributeArgs(AttrName, AttrLoc, attrs, endLoc, nullptr, SourceLocation(), AttributeList::AS_CXX11, nullptr); } else { attrs.addNew(AttrName, AttrLoc, nullptr, SourceLocation(), 0, 0, AttributeList::AS_CXX11); } if (endLoc) *endLoc = Tok.getLocation(); if (ExpectAndConsume(tok::r_square, diag::err_expected)) SkipUntil(tok::r_square); } /// ParseHLSLAttributes - Parse an HLSL attribute-specifier-seq. /// /// attribute-specifier-seq: /// attribute-specifier-seq[opt] attribute-specifier void Parser::ParseHLSLAttributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc) { assert(getLangOpts().HLSL); SourceLocation StartLoc = Tok.getLocation(), Loc; if (!endLoc) endLoc = &Loc; do { ParseHLSLAttributeSpecifier(attrs, endLoc); } while (Tok.is(tok::l_square)); attrs.Range = SourceRange(StartLoc, *endLoc); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseExprCXX.cpp
//===--- ParseExprCXX.cpp - C++ Expression Parsing ------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Expression parsing implementation for C++. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "RAIIObjectsForParser.h" #include "dxc/Support/HLSLVersion.h" #include "clang/AST/DeclTemplate.h" #include "clang/Basic/PrettyStackTrace.h" #include "clang/Lex/LiteralSupport.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Parse/Parser.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/Scope.h" #include "llvm/Support/ErrorHandling.h" // // /////////////////////////////////////////////////////////////////////////////// using namespace clang; static int SelectDigraphErrorMessage(tok::TokenKind Kind) { switch (Kind) { // template name case tok::unknown: return 0; // casts case tok::kw_const_cast: return 1; case tok::kw_dynamic_cast: return 2; case tok::kw_reinterpret_cast: return 3; case tok::kw_static_cast: return 4; default: llvm_unreachable("Unknown type for digraph error message."); } } // Are the two tokens adjacent in the same source file? bool Parser::areTokensAdjacent(const Token &First, const Token &Second) { SourceManager &SM = PP.getSourceManager(); SourceLocation FirstLoc = SM.getSpellingLoc(First.getLocation()); SourceLocation FirstEnd = FirstLoc.getLocWithOffset(First.getLength()); return FirstEnd == SM.getSpellingLoc(Second.getLocation()); } // Suggest fixit for "<::" after a cast. static void FixDigraph(Parser &P, Preprocessor &PP, Token &DigraphToken, Token &ColonToken, tok::TokenKind Kind, bool AtDigraph) { // Pull '<:' and ':' off token stream. if (!AtDigraph) PP.Lex(DigraphToken); PP.Lex(ColonToken); SourceRange Range; Range.setBegin(DigraphToken.getLocation()); Range.setEnd(ColonToken.getLocation()); P.Diag(DigraphToken.getLocation(), diag::err_missing_whitespace_digraph) << SelectDigraphErrorMessage(Kind) << FixItHint::CreateReplacement(Range, "< ::"); // Update token information to reflect their change in token type. ColonToken.setKind(tok::coloncolon); ColonToken.setLocation(ColonToken.getLocation().getLocWithOffset(-1)); ColonToken.setLength(2); DigraphToken.setKind(tok::less); DigraphToken.setLength(1); // Push new tokens back to token stream. PP.EnterToken(ColonToken); if (!AtDigraph) PP.EnterToken(DigraphToken); } // Check for '<::' which should be '< ::' instead of '[:' when following // a template name. void Parser::CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectType, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS) { if (!Next.is(tok::l_square) || Next.getLength() != 2) return; Token SecondToken = GetLookAheadToken(2); if (!SecondToken.is(tok::colon) || !areTokensAdjacent(Next, SecondToken)) return; TemplateTy Template; UnqualifiedId TemplateName; TemplateName.setIdentifier(&II, Tok.getLocation()); bool MemberOfUnknownSpecialization; if (!Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false, TemplateName, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization)) return; FixDigraph(*this, PP, Next, SecondToken, tok::unknown, /*AtDigraph*/false); } /// \brief Emits an error for a left parentheses after a double colon. /// /// When a '(' is found after a '::', emit an error. Attempt to fix the token /// stream by removing the '(', and the matching ')' if found. void Parser::CheckForLParenAfterColonColon() { if (!Tok.is(tok::l_paren)) return; Token LParen = Tok; Token NextTok = GetLookAheadToken(1); Token StarTok = NextTok; // Check for (identifier or (*identifier Token IdentifierTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : StarTok; if (IdentifierTok.isNot(tok::identifier)) return; // Eat the '('. ConsumeParen(); Token RParen; RParen.setLocation(SourceLocation()); // Do we have a ')' ? NextTok = StarTok.is(tok::star) ? GetLookAheadToken(2) : GetLookAheadToken(1); if (NextTok.is(tok::r_paren)) { RParen = NextTok; // Eat the '*' if it is present. if (StarTok.is(tok::star)) ConsumeToken(); // Eat the identifier. ConsumeToken(); // Add the identifier token back. PP.EnterToken(IdentifierTok); // Add the '*' back if it was present. if (StarTok.is(tok::star)) PP.EnterToken(StarTok); // Eat the ')'. ConsumeParen(); } Diag(LParen.getLocation(), diag::err_paren_after_colon_colon) << FixItHint::CreateRemoval(LParen.getLocation()) << FixItHint::CreateRemoval(RParen.getLocation()); } /// \brief Parse global scope or nested-name-specifier if present. /// /// Parses a C++ global scope specifier ('::') or nested-name-specifier (which /// may be preceded by '::'). Note that this routine will not parse ::new or /// ::delete; it will just leave them in the token stream. /// /// '::'[opt] nested-name-specifier /// '::' /// /// nested-name-specifier: /// type-name '::' /// namespace-name '::' /// nested-name-specifier identifier '::' /// nested-name-specifier 'template'[opt] simple-template-id '::' /// /// /// \param SS the scope specifier that will be set to the parsed /// nested-name-specifier (or empty) /// /// \param ObjectType if this nested-name-specifier is being parsed following /// the "." or "->" of a member access expression, this parameter provides the /// type of the object whose members are being accessed. /// /// \param EnteringContext whether we will be entering into the context of /// the nested-name-specifier after parsing it. /// /// \param MayBePseudoDestructor When non-NULL, points to a flag that /// indicates whether this nested-name-specifier may be part of a /// pseudo-destructor name. In this case, the flag will be set false /// if we don't actually end up parsing a destructor name. Moreorover, /// if we do end up determining that we are parsing a destructor name, /// the last component of the nested-name-specifier is not parsed as /// part of the scope specifier. /// /// \param IsTypename If \c true, this nested-name-specifier is known to be /// part of a type name. This is used to improve error recovery. /// /// \param LastII When non-NULL, points to an IdentifierInfo* that will be /// filled in with the leading identifier in the last component of the /// nested-name-specifier, if any. /// /// \returns true if there was an error parsing a scope specifier bool Parser::ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext, bool *MayBePseudoDestructor, bool IsTypename, IdentifierInfo **LastII) { assert(getLangOpts().CPlusPlus && "Call sites of this function should be guarded by checking for C++"); if (Tok.is(tok::annot_cxxscope)) { assert(!LastII && "want last identifier but have already annotated scope"); assert(!MayBePseudoDestructor && "unexpected annot_cxxscope"); Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS); ConsumeToken(); return false; } if (Tok.is(tok::annot_template_id)) { // If the current token is an annotated template id, it may already have // a scope specifier. Restore it. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); SS = TemplateId->SS; } // Has to happen before any "return false"s in this function. bool CheckForDestructor = false; if (MayBePseudoDestructor && *MayBePseudoDestructor) { CheckForDestructor = true; *MayBePseudoDestructor = false; } if (LastII) *LastII = nullptr; bool HasScopeSpecifier = false; if (Tok.is(tok::coloncolon)) { // ::new and ::delete aren't nested-name-specifiers. tok::TokenKind NextKind = NextToken().getKind(); if (NextKind == tok::kw_new || NextKind == tok::kw_delete) return false; if (NextKind == tok::l_brace) { // It is invalid to have :: {, consume the scope qualifier and pretend // like we never saw it. Diag(ConsumeToken(), diag::err_expected) << tok::identifier; } else { // '::' - Global scope qualifier. if (Actions.ActOnCXXGlobalScopeSpecifier(ConsumeToken(), SS)) return true; CheckForLParenAfterColonColon(); HasScopeSpecifier = true; } } if (Tok.is(tok::kw___super)) { SourceLocation SuperLoc = ConsumeToken(); if (!Tok.is(tok::coloncolon)) { Diag(Tok.getLocation(), diag::err_expected_coloncolon_after_super); return true; } return Actions.ActOnSuperScopeSpecifier(SuperLoc, ConsumeToken(), SS); } if (!HasScopeSpecifier && Tok.isOneOf(tok::kw_decltype, tok::annot_decltype)) { DeclSpec DS(AttrFactory); SourceLocation DeclLoc = Tok.getLocation(); SourceLocation EndLoc = ParseDecltypeSpecifier(DS); SourceLocation CCLoc; if (!TryConsumeToken(tok::coloncolon, CCLoc)) { AnnotateExistingDecltypeSpecifier(DS, DeclLoc, EndLoc); return false; } if (Actions.ActOnCXXNestedNameSpecifierDecltype(SS, DS, CCLoc)) SS.SetInvalid(SourceRange(DeclLoc, CCLoc)); HasScopeSpecifier = true; } while (true) { if (HasScopeSpecifier) { // C++ [basic.lookup.classref]p5: // If the qualified-id has the form // // ::class-name-or-namespace-name::... // // the class-name-or-namespace-name is looked up in global scope as a // class-name or namespace-name. // // To implement this, we clear out the object type as soon as we've // seen a leading '::' or part of a nested-name-specifier. ObjectType = ParsedType(); if (Tok.is(tok::code_completion)) { // Code completion for a nested-name-specifier, where the code // code completion token follows the '::'. Actions.CodeCompleteQualifiedId(getCurScope(), SS, EnteringContext); // Include code completion token into the range of the scope otherwise // when we try to annotate the scope tokens the dangling code completion // token will cause assertion in // Preprocessor::AnnotatePreviousCachedTokens. SS.setEndLoc(Tok.getLocation()); cutOffParsing(); return true; } } // nested-name-specifier: // nested-name-specifier 'template'[opt] simple-template-id '::' // Parse the optional 'template' keyword, then make sure we have // 'identifier <' after it. if (Tok.is(tok::kw_template)) { // HLSL Change Starts - template is reserved if (getLangOpts().HLSL && getLangOpts().HLSLVersion < hlsl::LangStd::v2021) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); ConsumeToken(); return true; } // HLSL Change Ends // If we don't have a scope specifier or an object type, this isn't a // nested-name-specifier, since they aren't allowed to start with // 'template'. if (!HasScopeSpecifier && !ObjectType) break; TentativeParsingAction TPA(*this); SourceLocation TemplateKWLoc = ConsumeToken(); UnqualifiedId TemplateName; if (Tok.is(tok::identifier)) { // Consume the identifier. TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); ConsumeToken(); } else if (Tok.is(tok::kw_operator)) { // HLSL Change Starts if (getLangOpts().HLSL && getLangOpts().HLSLVersion < hlsl::LangStd::v2021) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); TPA.Commit(); return true; } // HLSL Change Ends // We don't need to actually parse the unqualified-id in this case, // because a simple-template-id cannot start with 'operator', but // go ahead and parse it anyway for consistency with the case where // we already annotated the template-id. if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, TemplateName)) { TPA.Commit(); break; } if (TemplateName.getKind() != UnqualifiedId::IK_OperatorFunctionId && TemplateName.getKind() != UnqualifiedId::IK_LiteralOperatorId) { Diag(TemplateName.getSourceRange().getBegin(), diag::err_id_after_template_in_nested_name_spec) << TemplateName.getSourceRange(); TPA.Commit(); break; } } else { TPA.Revert(); break; } // If the next token is not '<', we have a qualified-id that refers // to a template name, such as T::template apply, but is not a // template-id. if (Tok.isNot(tok::less)) { TPA.Revert(); break; } // Commit to parsing the template-id. TPA.Commit(); TemplateTy Template; if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType, EnteringContext, Template)) { if (AnnotateTemplateIdToken(Template, TNK, SS, TemplateKWLoc, TemplateName, false)) return true; } else return true; continue; } if (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) { // We have // // template-id '::' // // So we need to check whether the template-id is a simple-template-id of // the right kind (it should name a type or be dependent), and then // convert it into a type within the nested-name-specifier. TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde)) { *MayBePseudoDestructor = true; return false; } if (LastII) *LastII = TemplateId->Name; // Consume the template-id token. ConsumeToken(); assert(Tok.is(tok::coloncolon) && "NextToken() not working properly!"); SourceLocation CCLoc = ConsumeToken(); HasScopeSpecifier = true; ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), TemplateId->NumArgs); if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), SS, TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc, CCLoc, EnteringContext)) { SourceLocation StartLoc = SS.getBeginLoc().isValid()? SS.getBeginLoc() : TemplateId->TemplateNameLoc; SS.SetInvalid(SourceRange(StartLoc, CCLoc)); } continue; } // The rest of the nested-name-specifier possibilities start with // tok::identifier. if (Tok.isNot(tok::identifier)) break; IdentifierInfo &II = *Tok.getIdentifierInfo(); // nested-name-specifier: // type-name '::' // namespace-name '::' // nested-name-specifier identifier '::' Token Next = NextToken(); // If we get foo:bar, this is almost certainly a typo for foo::bar. Recover // and emit a fixit hint for it. if (Next.is(tok::colon) && !ColonIsSacred && !getLangOpts().HLSL) { // HLSL Change - in HLSL ':' is used for binding, etc... // much more frequently than people use '::' for // nested-name-specifier. if (Actions.IsInvalidUnlessNestedName(getCurScope(), SS, II, Tok.getLocation(), Next.getLocation(), ObjectType, EnteringContext) && // If the token after the colon isn't an identifier, it's still an // error, but they probably meant something else strange so don't // recover like this. PP.LookAhead(1).is(tok::identifier)) { Diag(Next, diag::err_unexpected_colon_in_nested_name_spec) << FixItHint::CreateReplacement(Next.getLocation(), "::"); // Recover as if the user wrote '::'. Next.setKind(tok::coloncolon); } } if (Next.is(tok::coloncolon) && GetLookAheadToken(2).is(tok::l_brace)) { // It is invalid to have :: {, consume the scope qualifier and pretend // like we never saw it. Token Identifier = Tok; // Stash away the identifier. ConsumeToken(); // Eat the identifier, current token is now '::'. Diag(PP.getLocForEndOfToken(ConsumeToken()), diag::err_expected) << tok::identifier; UnconsumeToken(Identifier); // Stick the identifier back. Next = NextToken(); // Point Next at the '{' token. } if (Next.is(tok::coloncolon)) { if (CheckForDestructor && GetLookAheadToken(2).is(tok::tilde) && !Actions.isNonTypeNestedNameSpecifier( getCurScope(), SS, Tok.getLocation(), II, ObjectType)) { *MayBePseudoDestructor = true; return false; } if (ColonIsSacred) { const Token &Next2 = GetLookAheadToken(2); if (Next2.is(tok::kw_private) || Next2.is(tok::kw_protected) || Next2.is(tok::kw_public) || Next2.is(tok::kw_virtual)) { Diag(Next2, diag::err_unexpected_token_in_nested_name_spec) << Next2.getName() << FixItHint::CreateReplacement(Next.getLocation(), ":"); Token ColonColon; PP.Lex(ColonColon); ColonColon.setKind(tok::colon); PP.EnterToken(ColonColon); break; } } if (LastII) *LastII = &II; // We have an identifier followed by a '::'. Lookup this name // as the name in a nested-name-specifier. Token Identifier = Tok; SourceLocation IdLoc = ConsumeToken(); assert(Tok.isOneOf(tok::coloncolon, tok::colon) && "NextToken() not working properly!"); Token ColonColon = Tok; SourceLocation CCLoc = ConsumeToken(); CheckForLParenAfterColonColon(); bool IsCorrectedToColon = false; bool *CorrectionFlagPtr = ColonIsSacred ? &IsCorrectedToColon : nullptr; if (Actions.ActOnCXXNestedNameSpecifier(getCurScope(), II, IdLoc, CCLoc, ObjectType, EnteringContext, SS, false, CorrectionFlagPtr)) { // Identifier is not recognized as a nested name, but we can have // mistyped '::' instead of ':'. if (CorrectionFlagPtr && IsCorrectedToColon) { ColonColon.setKind(tok::colon); PP.EnterToken(Tok); PP.EnterToken(ColonColon); Tok = Identifier; break; } SS.SetInvalid(SourceRange(IdLoc, CCLoc)); } HasScopeSpecifier = true; continue; } if (!getLangOpts().HLSL) { // HLSL Change - ignore digraph/trigraph processing CheckForTemplateAndDigraph(Next, ObjectType, EnteringContext, II, SS); } // nested-name-specifier: // type-name '<' if (Next.is(tok::less)) { TemplateTy Template; UnqualifiedId TemplateName; TemplateName.setIdentifier(&II, Tok.getLocation()); bool MemberOfUnknownSpecialization; if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false, TemplateName, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization)) { // We have found a template name, so annotate this token // with a template-id annotation. We do not permit the // template-id to be translated into a type annotation, // because some clients (e.g., the parsing of class template // specializations) still want to see the original template-id // token. ConsumeToken(); if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), TemplateName, false)) return true; continue; } if (MemberOfUnknownSpecialization && (ObjectType || SS.isSet()) && (IsTypename || IsTemplateArgumentList(1))) { // We have something like t::getAs<T>, where getAs is a // member of an unknown specialization. However, this will only // parse correctly as a template, so suggest the keyword 'template' // before 'getAs' and treat this as a dependent template name. unsigned DiagID = diag::err_missing_dependent_template_keyword; if (getLangOpts().MicrosoftExt) DiagID = diag::warn_missing_dependent_template_keyword; Diag(Tok.getLocation(), DiagID) << II.getName() << FixItHint::CreateInsertion(Tok.getLocation(), "template "); if (TemplateNameKind TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, SourceLocation(), TemplateName, ObjectType, EnteringContext, Template)) { // Consume the identifier. ConsumeToken(); if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), TemplateName, false)) return true; } else return true; continue; } } // We don't have any tokens that form the beginning of a // nested-name-specifier, so we're done. break; } // Even if we didn't see any pieces of a nested-name-specifier, we // still check whether there is a tilde in this position, which // indicates a potential pseudo-destructor. if (CheckForDestructor && Tok.is(tok::tilde)) *MayBePseudoDestructor = true; return false; } ExprResult Parser::tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement) { SourceLocation TemplateKWLoc; UnqualifiedId Name; if (ParseUnqualifiedId(SS, /*EnteringContext=*/false, /*AllowDestructorName=*/false, /*AllowConstructorName=*/false, /*ObjectType=*/ParsedType(), TemplateKWLoc, Name)) return ExprError(); // This is only the direct operand of an & operator if it is not // followed by a postfix-expression suffix. if (isAddressOfOperand && isPostfixExpressionSuffixStart()) isAddressOfOperand = false; return Actions.ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Name, Tok.is(tok::l_paren), isAddressOfOperand, nullptr, /*IsInlineAsmIdentifier=*/false, &Replacement); } /// ParseCXXIdExpression - Handle id-expression. /// /// id-expression: /// unqualified-id /// qualified-id /// /// qualified-id: /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id /// '::' identifier /// '::' operator-function-id /// '::' template-id /// /// NOTE: The standard specifies that, for qualified-id, the parser does not /// expect: /// /// '::' conversion-function-id /// '::' '~' class-name /// /// This may cause a slight inconsistency on diagnostics: /// /// class C {}; /// namespace A {} /// void f() { /// :: A :: ~ C(); // Some Sema error about using destructor with a /// // namespace. /// :: ~ C(); // Some Parser error like 'unexpected ~'. /// } /// /// We simplify the parser a bit and make it work like: /// /// qualified-id: /// '::'[opt] nested-name-specifier 'template'[opt] unqualified-id /// '::' unqualified-id /// /// That way Sema can handle and report similar errors for namespaces and the /// global scope. /// /// The isAddressOfOperand parameter indicates that this id-expression is a /// direct operand of the address-of operator. This is, besides member contexts, /// the only place where a qualified-id naming a non-static class member may /// appear. /// ExprResult Parser::ParseCXXIdExpression(bool isAddressOfOperand) { // qualified-id: // '::'[opt] nested-name-specifier 'template'[opt] unqualified-id // '::' unqualified-id // CXXScopeSpec SS; ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false); Token Replacement; ExprResult Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement); if (Result.isUnset()) { // If the ExprResult is valid but null, then typo correction suggested a // keyword replacement that needs to be reparsed. UnconsumeToken(Replacement); Result = tryParseCXXIdExpression(SS, isAddressOfOperand, Replacement); } assert(!Result.isUnset() && "Typo correction suggested a keyword replacement " "for a previous keyword suggestion"); return Result; } /// ParseLambdaExpression - Parse a C++11 lambda expression. /// /// lambda-expression: /// lambda-introducer lambda-declarator[opt] compound-statement /// /// lambda-introducer: /// '[' lambda-capture[opt] ']' /// /// lambda-capture: /// capture-default /// capture-list /// capture-default ',' capture-list /// /// capture-default: /// '&' /// '=' /// /// capture-list: /// capture /// capture-list ',' capture /// /// capture: /// simple-capture /// init-capture [C++1y] /// /// simple-capture: /// identifier /// '&' identifier /// 'this' /// /// init-capture: [C++1y] /// identifier initializer /// '&' identifier initializer /// /// lambda-declarator: /// '(' parameter-declaration-clause ')' attribute-specifier[opt] /// 'mutable'[opt] exception-specification[opt] /// trailing-return-type[opt] /// ExprResult Parser::ParseLambdaExpression() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change // Parse lambda-introducer. LambdaIntroducer Intro; Optional<unsigned> DiagID = ParseLambdaIntroducer(Intro); if (DiagID) { Diag(Tok, DiagID.getValue()); SkipUntil(tok::r_square, StopAtSemi); SkipUntil(tok::l_brace, StopAtSemi); SkipUntil(tok::r_brace, StopAtSemi); return ExprError(); } return ParseLambdaExpressionAfterIntroducer(Intro); } /// TryParseLambdaExpression - Use lookahead and potentially tentative /// parsing to determine if we are looking at a C++0x lambda expression, and parse /// it if we are. /// /// If we are not looking at a lambda expression, returns ExprError(). ExprResult Parser::TryParseLambdaExpression() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(getLangOpts().CPlusPlus11 && Tok.is(tok::l_square) && "Not at the start of a possible lambda expression."); const Token Next = NextToken(), After = GetLookAheadToken(2); // If lookahead indicates this is a lambda... if (Next.is(tok::r_square) || // [] Next.is(tok::equal) || // [= (Next.is(tok::amp) && // [&] or [&, (After.is(tok::r_square) || After.is(tok::comma))) || (Next.is(tok::identifier) && // [identifier] After.is(tok::r_square))) { return ParseLambdaExpression(); } // If lookahead indicates an ObjC message send... // [identifier identifier if (Next.is(tok::identifier) && After.is(tok::identifier)) { return ExprEmpty(); } // Here, we're stuck: lambda introducers and Objective-C message sends are // unambiguous, but it requires arbitrary lookhead. [a,b,c,d,e,f,g] is a // lambda, and [a,b,c,d,e,f,g h] is a Objective-C message send. Instead of // writing two routines to parse a lambda introducer, just try to parse // a lambda introducer first, and fall back if that fails. // (TryParseLambdaIntroducer never produces any diagnostic output.) LambdaIntroducer Intro; if (TryParseLambdaIntroducer(Intro)) return ExprEmpty(); return ParseLambdaExpressionAfterIntroducer(Intro); } /// \brief Parse a lambda introducer. /// \param Intro A LambdaIntroducer filled in with information about the /// contents of the lambda-introducer. /// \param SkippedInits If non-null, we are disambiguating between an Obj-C /// message send and a lambda expression. In this mode, we will /// sometimes skip the initializers for init-captures and not fully /// populate \p Intro. This flag will be set to \c true if we do so. /// \return A DiagnosticID if it hit something unexpected. The location for /// for the diagnostic is that of the current token. Optional<unsigned> Parser::ParseLambdaIntroducer(LambdaIntroducer &Intro, bool *SkippedInits) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change typedef Optional<unsigned> DiagResult; assert(Tok.is(tok::l_square) && "Lambda expressions begin with '['."); BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); Intro.Range.setBegin(T.getOpenLocation()); bool first = true; // Parse capture-default. if (Tok.is(tok::amp) && (NextToken().is(tok::comma) || NextToken().is(tok::r_square))) { Intro.Default = LCD_ByRef; Intro.DefaultLoc = ConsumeToken(); first = false; } else if (Tok.is(tok::equal)) { Intro.Default = LCD_ByCopy; Intro.DefaultLoc = ConsumeToken(); first = false; } while (Tok.isNot(tok::r_square)) { if (!first) { if (Tok.isNot(tok::comma)) { // Provide a completion for a lambda introducer here. Except // in Objective-C, where this is Almost Surely meant to be a message // send. In that case, fail here and let the ObjC message // expression parser perform the completion. if (Tok.is(tok::code_completion) && !(getLangOpts().ObjC1 && Intro.Default == LCD_None && !Intro.Captures.empty())) { Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, /*AfterAmpersand=*/false); cutOffParsing(); break; } return DiagResult(diag::err_expected_comma_or_rsquare); } ConsumeToken(); } if (Tok.is(tok::code_completion)) { // If we're in Objective-C++ and we have a bare '[', then this is more // likely to be a message receiver. if (getLangOpts().ObjC1 && first) Actions.CodeCompleteObjCMessageReceiver(getCurScope()); else Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, /*AfterAmpersand=*/false); cutOffParsing(); break; } first = false; // Parse capture. LambdaCaptureKind Kind = LCK_ByCopy; SourceLocation Loc; IdentifierInfo *Id = nullptr; SourceLocation EllipsisLoc; ExprResult Init; if (Tok.is(tok::kw_this)) { Kind = LCK_This; Loc = ConsumeToken(); } else { if (Tok.is(tok::amp)) { Kind = LCK_ByRef; ConsumeToken(); if (Tok.is(tok::code_completion)) { Actions.CodeCompleteLambdaIntroducer(getCurScope(), Intro, /*AfterAmpersand=*/true); cutOffParsing(); break; } } if (Tok.is(tok::identifier)) { Id = Tok.getIdentifierInfo(); Loc = ConsumeToken(); } else if (Tok.is(tok::kw_this)) { // FIXME: If we want to suggest a fixit here, will need to return more // than just DiagnosticID. Perhaps full DiagnosticBuilder that can be // Clear()ed to prevent emission in case of tentative parsing? return DiagResult(diag::err_this_captured_by_reference); } else { return DiagResult(diag::err_expected_capture); } if (Tok.is(tok::l_paren)) { BalancedDelimiterTracker Parens(*this, tok::l_paren); Parens.consumeOpen(); ExprVector Exprs; CommaLocsTy Commas; if (SkippedInits) { Parens.skipToEnd(); *SkippedInits = true; } else if (ParseExpressionList(Exprs, Commas)) { Parens.skipToEnd(); Init = ExprError(); } else { Parens.consumeClose(); Init = Actions.ActOnParenListExpr(Parens.getOpenLocation(), Parens.getCloseLocation(), Exprs); } } else if (Tok.isOneOf(tok::l_brace, tok::equal)) { // Each lambda init-capture forms its own full expression, which clears // Actions.MaybeODRUseExprs. So create an expression evaluation context // to save the necessary state, and restore it later. EnterExpressionEvaluationContext EC(Actions, Sema::PotentiallyEvaluated); bool HadEquals = TryConsumeToken(tok::equal); if (!SkippedInits) { // Warn on constructs that will change meaning when we implement N3922 if (!HadEquals && Tok.is(tok::l_brace)) { Diag(Tok, diag::warn_init_capture_direct_list_init) << FixItHint::CreateInsertion(Tok.getLocation(), "="); } Init = ParseInitializer(); } else if (Tok.is(tok::l_brace)) { BalancedDelimiterTracker Braces(*this, tok::l_brace); Braces.consumeOpen(); Braces.skipToEnd(); *SkippedInits = true; } else { // We're disambiguating this: // // [..., x = expr // // We need to find the end of the following expression in order to // determine whether this is an Obj-C message send's receiver, a // C99 designator, or a lambda init-capture. // // Parse the expression to find where it ends, and annotate it back // onto the tokens. We would have parsed this expression the same way // in either case: both the RHS of an init-capture and the RHS of an // assignment expression are parsed as an initializer-clause, and in // neither case can anything be added to the scope between the '[' and // here. // // FIXME: This is horrible. Adding a mechanism to skip an expression // would be much cleaner. // FIXME: If there is a ',' before the next ']' or ':', we can skip to // that instead. (And if we see a ':' with no matching '?', we can // classify this as an Obj-C message send.) SourceLocation StartLoc = Tok.getLocation(); InMessageExpressionRAIIObject MaybeInMessageExpression(*this, true); Init = ParseInitializer(); if (Tok.getLocation() != StartLoc) { // Back out the lexing of the token after the initializer. PP.RevertCachedTokens(1); // Replace the consumed tokens with an appropriate annotation. Tok.setLocation(StartLoc); Tok.setKind(tok::annot_primary_expr); setExprAnnotation(Tok, Init); Tok.setAnnotationEndLoc(PP.getLastCachedTokenLocation()); PP.AnnotateCachedTokens(Tok); // Consume the annotated initializer. ConsumeToken(); } } } else TryConsumeToken(tok::ellipsis, EllipsisLoc); } // If this is an init capture, process the initialization expression // right away. For lambda init-captures such as the following: // const int x = 10; // auto L = [i = x+1](int a) { // return [j = x+2, // &k = x](char b) { }; // }; // keep in mind that each lambda init-capture has to have: // - its initialization expression executed in the context // of the enclosing/parent decl-context. // - but the variable itself has to be 'injected' into the // decl-context of its lambda's call-operator (which has // not yet been created). // Each init-expression is a full-expression that has to get // Sema-analyzed (for capturing etc.) before its lambda's // call-operator's decl-context, scope & scopeinfo are pushed on their // respective stacks. Thus if any variable is odr-used in the init-capture // it will correctly get captured in the enclosing lambda, if one exists. // The init-variables above are created later once the lambdascope and // call-operators decl-context is pushed onto its respective stack. // Since the lambda init-capture's initializer expression occurs in the // context of the enclosing function or lambda, therefore we can not wait // till a lambda scope has been pushed on before deciding whether the // variable needs to be captured. We also need to process all // lvalue-to-rvalue conversions and discarded-value conversions, // so that we can avoid capturing certain constant variables. // For e.g., // void test() { // const int x = 10; // auto L = [&z = x](char a) { <-- don't capture by the current lambda // return [y = x](int i) { <-- don't capture by enclosing lambda // return y; // } // }; // If x was not const, the second use would require 'L' to capture, and // that would be an error. ParsedType InitCaptureParsedType; if (Init.isUsable()) { // Get the pointer and store it in an lvalue, so we can use it as an // out argument. Expr *InitExpr = Init.get(); // This performs any lvalue-to-rvalue conversions if necessary, which // can affect what gets captured in the containing decl-context. QualType InitCaptureType = Actions.performLambdaInitCaptureInitialization( Loc, Kind == LCK_ByRef, Id, InitExpr); Init = InitExpr; InitCaptureParsedType.set(InitCaptureType); } Intro.addCapture(Kind, Loc, Id, EllipsisLoc, Init, InitCaptureParsedType); } T.consumeClose(); Intro.Range.setEnd(T.getCloseLocation()); return DiagResult(); } /// TryParseLambdaIntroducer - Tentatively parse a lambda introducer. /// /// Returns true if it hit something unexpected. bool Parser::TryParseLambdaIntroducer(LambdaIntroducer &Intro) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change TentativeParsingAction PA(*this); bool SkippedInits = false; Optional<unsigned> DiagID(ParseLambdaIntroducer(Intro, &SkippedInits)); if (DiagID) { PA.Revert(); return true; } if (SkippedInits) { // Parse it again, but this time parse the init-captures too. PA.Revert(); Intro = LambdaIntroducer(); DiagID = ParseLambdaIntroducer(Intro); assert(!DiagID && "parsing lambda-introducer failed on reparse"); return false; } PA.Commit(); return false; } /// ParseLambdaExpressionAfterIntroducer - Parse the rest of a lambda /// expression. ExprResult Parser::ParseLambdaExpressionAfterIntroducer( LambdaIntroducer &Intro) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change SourceLocation LambdaBeginLoc = Intro.Range.getBegin(); Diag(LambdaBeginLoc, diag::warn_cxx98_compat_lambda); PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), LambdaBeginLoc, "lambda expression parsing"); // FIXME: Call into Actions to add any init-capture declarations to the // scope while parsing the lambda-declarator and compound-statement. // Parse lambda-declarator[opt]. DeclSpec DS(AttrFactory); Declarator D(DS, Declarator::LambdaExprContext); TemplateParameterDepthRAII CurTemplateDepthTracker(TemplateParameterDepth); Actions.PushLambdaScope(); TypeResult TrailingReturnType; if (Tok.is(tok::l_paren)) { ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | Scope::FunctionDeclarationScope | Scope::DeclScope); SourceLocation DeclEndLoc; BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); SourceLocation LParenLoc = T.getOpenLocation(); // Parse parameter-declaration-clause. ParsedAttributes Attr(AttrFactory); SmallVector<DeclaratorChunk::ParamInfo, 16> ParamInfo; SourceLocation EllipsisLoc; if (Tok.isNot(tok::r_paren)) { Actions.RecordParsingTemplateParameterDepth(TemplateParameterDepth); ParseParameterDeclarationClause(D, Attr, ParamInfo, EllipsisLoc); // For a generic lambda, each 'auto' within the parameter declaration // clause creates a template type parameter, so increment the depth. if (Actions.getCurGenericLambda()) ++CurTemplateDepthTracker; } T.consumeClose(); SourceLocation RParenLoc = T.getCloseLocation(); DeclEndLoc = RParenLoc; // GNU-style attributes must be parsed before the mutable specifier to be // compatible with GCC. MaybeParseGNUAttributes(Attr, &DeclEndLoc); // MSVC-style attributes must be parsed before the mutable specifier to be // compatible with MSVC. MaybeParseMicrosoftDeclSpecs(Attr, &DeclEndLoc); // Parse 'mutable'[opt]. SourceLocation MutableLoc; if (TryConsumeToken(tok::kw_mutable, MutableLoc)) DeclEndLoc = MutableLoc; // Parse exception-specification[opt]. ExceptionSpecificationType ESpecType = EST_None; SourceRange ESpecRange; SmallVector<ParsedType, 2> DynamicExceptions; SmallVector<SourceRange, 2> DynamicExceptionRanges; ExprResult NoexceptExpr; CachedTokens *ExceptionSpecTokens; ESpecType = tryParseExceptionSpecification(/*Delayed=*/false, ESpecRange, DynamicExceptions, DynamicExceptionRanges, NoexceptExpr, ExceptionSpecTokens); if (ESpecType != EST_None) DeclEndLoc = ESpecRange.getEnd(); // Parse attribute-specifier[opt]. MaybeParseCXX11Attributes(Attr, &DeclEndLoc); assert(!getLangOpts().HLSL); // HLSL Change: in lieu of MaybeParseHLSLAttributes - lambdas not allowed SourceLocation FunLocalRangeEnd = DeclEndLoc; // Parse trailing-return-type[opt]. if (Tok.is(tok::arrow)) { FunLocalRangeEnd = Tok.getLocation(); SourceRange Range; TrailingReturnType = ParseTrailingReturnType(Range); if (Range.getEnd().isValid()) DeclEndLoc = Range.getEnd(); } PrototypeScope.Exit(); SourceLocation NoLoc; D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true, /*isAmbiguous=*/false, LParenLoc, ParamInfo.data(), ParamInfo.size(), EllipsisLoc, RParenLoc, DS.getTypeQualifiers(), /*RefQualifierIsLValueRef=*/true, /*RefQualifierLoc=*/NoLoc, /*ConstQualifierLoc=*/NoLoc, /*VolatileQualifierLoc=*/NoLoc, /*RestrictQualifierLoc=*/NoLoc, MutableLoc, ESpecType, ESpecRange.getBegin(), DynamicExceptions.data(), DynamicExceptionRanges.data(), DynamicExceptions.size(), NoexceptExpr.isUsable() ? NoexceptExpr.get() : nullptr, /*ExceptionSpecTokens*/nullptr, LParenLoc, FunLocalRangeEnd, D, TrailingReturnType), Attr, DeclEndLoc); } else if (Tok.isOneOf(tok::kw_mutable, tok::arrow, tok::kw___attribute) || (Tok.is(tok::l_square) && NextToken().is(tok::l_square))) { // It's common to forget that one needs '()' before 'mutable', an attribute // specifier, or the result type. Deal with this. unsigned TokKind = 0; switch (Tok.getKind()) { case tok::kw_mutable: TokKind = 0; break; case tok::arrow: TokKind = 1; break; case tok::kw___attribute: case tok::l_square: TokKind = 2; break; default: llvm_unreachable("Unknown token kind"); } Diag(Tok, diag::err_lambda_missing_parens) << TokKind << FixItHint::CreateInsertion(Tok.getLocation(), "() "); SourceLocation DeclLoc = Tok.getLocation(); SourceLocation DeclEndLoc = DeclLoc; // GNU-style attributes must be parsed before the mutable specifier to be // compatible with GCC. ParsedAttributes Attr(AttrFactory); MaybeParseGNUAttributes(Attr, &DeclEndLoc); // Parse 'mutable', if it's there. SourceLocation MutableLoc; if (Tok.is(tok::kw_mutable)) { MutableLoc = ConsumeToken(); DeclEndLoc = MutableLoc; } // Parse attribute-specifier[opt]. MaybeParseCXX11Attributes(Attr, &DeclEndLoc); // Parse the return type, if there is one. if (Tok.is(tok::arrow)) { SourceRange Range; TrailingReturnType = ParseTrailingReturnType(Range); if (Range.getEnd().isValid()) DeclEndLoc = Range.getEnd(); } SourceLocation NoLoc; D.AddTypeInfo(DeclaratorChunk::getFunction(/*hasProto=*/true, /*isAmbiguous=*/false, /*LParenLoc=*/NoLoc, /*Params=*/nullptr, /*NumParams=*/0, /*EllipsisLoc=*/NoLoc, /*RParenLoc=*/NoLoc, /*TypeQuals=*/0, /*RefQualifierIsLValueRef=*/true, /*RefQualifierLoc=*/NoLoc, /*ConstQualifierLoc=*/NoLoc, /*VolatileQualifierLoc=*/NoLoc, /*RestrictQualifierLoc=*/NoLoc, MutableLoc, EST_None, /*ESpecLoc=*/NoLoc, /*Exceptions=*/nullptr, /*ExceptionRanges=*/nullptr, /*NumExceptions=*/0, /*NoexceptExpr=*/nullptr, /*ExceptionSpecTokens=*/nullptr, DeclLoc, DeclEndLoc, D, TrailingReturnType), Attr, DeclEndLoc); } // FIXME: Rename BlockScope -> ClosureScope if we decide to continue using // it. unsigned ScopeFlags = Scope::BlockScope | Scope::FnScope | Scope::DeclScope; ParseScope BodyScope(this, ScopeFlags); Actions.ActOnStartOfLambdaDefinition(Intro, D, getCurScope()); // Parse compound-statement. if (!Tok.is(tok::l_brace)) { Diag(Tok, diag::err_expected_lambda_body); Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); return ExprError(); } StmtResult Stmt(ParseCompoundStatementBody()); BodyScope.Exit(); if (!Stmt.isInvalid() && !TrailingReturnType.isInvalid()) return Actions.ActOnLambdaExpr(LambdaBeginLoc, Stmt.get(), getCurScope()); Actions.ActOnLambdaError(LambdaBeginLoc, getCurScope()); return ExprError(); } /// ParseCXXCasts - This handles the various ways to cast expressions to another /// type. /// /// postfix-expression: [C++ 5.2p1] /// 'dynamic_cast' '<' type-name '>' '(' expression ')' /// 'static_cast' '<' type-name '>' '(' expression ')' /// 'reinterpret_cast' '<' type-name '>' '(' expression ')' /// 'const_cast' '<' type-name '>' '(' expression ')' /// ExprResult Parser::ParseCXXCasts() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change tok::TokenKind Kind = Tok.getKind(); const char *CastName = nullptr; // For error messages switch (Kind) { default: llvm_unreachable("Unknown C++ cast!"); case tok::kw_const_cast: CastName = "const_cast"; break; case tok::kw_dynamic_cast: CastName = "dynamic_cast"; break; case tok::kw_reinterpret_cast: CastName = "reinterpret_cast"; break; case tok::kw_static_cast: CastName = "static_cast"; break; } SourceLocation OpLoc = ConsumeToken(); SourceLocation LAngleBracketLoc = Tok.getLocation(); // Check for "<::" which is parsed as "[:". If found, fix token stream, // diagnose error, suggest fix, and recover parsing. if (Tok.is(tok::l_square) && Tok.getLength() == 2) { Token Next = NextToken(); if (Next.is(tok::colon) && areTokensAdjacent(Tok, Next)) FixDigraph(*this, PP, Tok, Next, Kind, /*AtDigraph*/true); } if (ExpectAndConsume(tok::less, diag::err_expected_less_after, CastName)) return ExprError(); // Parse the common declaration-specifiers piece. DeclSpec DS(AttrFactory); ParseSpecifierQualifierList(DS); // Parse the abstract-declarator, if present. Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); ParseDeclarator(DeclaratorInfo); SourceLocation RAngleBracketLoc = Tok.getLocation(); if (ExpectAndConsume(tok::greater)) return ExprError(Diag(LAngleBracketLoc, diag::note_matching) << tok::less); SourceLocation LParenLoc, RParenLoc; BalancedDelimiterTracker T(*this, tok::l_paren); if (T.expectAndConsume(diag::err_expected_lparen_after, CastName)) return ExprError(); ExprResult Result = ParseExpression(); // Match the ')'. T.consumeClose(); if (!Result.isInvalid() && !DeclaratorInfo.isInvalidType()) Result = Actions.ActOnCXXNamedCast(OpLoc, Kind, LAngleBracketLoc, DeclaratorInfo, RAngleBracketLoc, T.getOpenLocation(), Result.get(), T.getCloseLocation()); return Result; } /// ParseCXXTypeid - This handles the C++ typeid expression. /// /// postfix-expression: [C++ 5.2p1] /// 'typeid' '(' expression ')' /// 'typeid' '(' type-id ')' /// ExprResult Parser::ParseCXXTypeid() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::kw_typeid) && "Not 'typeid'!"); SourceLocation OpLoc = ConsumeToken(); SourceLocation LParenLoc, RParenLoc; BalancedDelimiterTracker T(*this, tok::l_paren); // typeid expressions are always parenthesized. if (T.expectAndConsume(diag::err_expected_lparen_after, "typeid")) return ExprError(); LParenLoc = T.getOpenLocation(); ExprResult Result; // C++0x [expr.typeid]p3: // When typeid is applied to an expression other than an lvalue of a // polymorphic class type [...] The expression is an unevaluated // operand (Clause 5). // // Note that we can't tell whether the expression is an lvalue of a // polymorphic class type until after we've parsed the expression; we // speculatively assume the subexpression is unevaluated, and fix it up // later. // // We enter the unevaluated context before trying to determine whether we // have a type-id, because the tentative parse logic will try to resolve // names, and must treat them as unevaluated. EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated, Sema::ReuseLambdaContextDecl); if (isTypeIdInParens()) { TypeResult Ty = ParseTypeName(); // Match the ')'. T.consumeClose(); RParenLoc = T.getCloseLocation(); if (Ty.isInvalid() || RParenLoc.isInvalid()) return ExprError(); Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/true, Ty.get().getAsOpaquePtr(), RParenLoc); } else { Result = ParseExpression(); // Match the ')'. if (Result.isInvalid()) SkipUntil(tok::r_paren, StopAtSemi); else { T.consumeClose(); RParenLoc = T.getCloseLocation(); if (RParenLoc.isInvalid()) return ExprError(); Result = Actions.ActOnCXXTypeid(OpLoc, LParenLoc, /*isType=*/false, Result.get(), RParenLoc); } } return Result; } /// ParseCXXUuidof - This handles the Microsoft C++ __uuidof expression. /// /// '__uuidof' '(' expression ')' /// '__uuidof' '(' type-id ')' /// ExprResult Parser::ParseCXXUuidof() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::kw___uuidof) && "Not '__uuidof'!"); SourceLocation OpLoc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); // __uuidof expressions are always parenthesized. if (T.expectAndConsume(diag::err_expected_lparen_after, "__uuidof")) return ExprError(); ExprResult Result; if (isTypeIdInParens()) { TypeResult Ty = ParseTypeName(); // Match the ')'. T.consumeClose(); if (Ty.isInvalid()) return ExprError(); Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/true, Ty.get().getAsOpaquePtr(), T.getCloseLocation()); } else { EnterExpressionEvaluationContext Unevaluated(Actions, Sema::Unevaluated); Result = ParseExpression(); // Match the ')'. if (Result.isInvalid()) SkipUntil(tok::r_paren, StopAtSemi); else { T.consumeClose(); Result = Actions.ActOnCXXUuidof(OpLoc, T.getOpenLocation(), /*isType=*/false, Result.get(), T.getCloseLocation()); } } return Result; } /// \brief Parse a C++ pseudo-destructor expression after the base, /// . or -> operator, and nested-name-specifier have already been /// parsed. /// /// postfix-expression: [C++ 5.2] /// postfix-expression . pseudo-destructor-name /// postfix-expression -> pseudo-destructor-name /// /// pseudo-destructor-name: /// ::[opt] nested-name-specifier[opt] type-name :: ~type-name /// ::[opt] nested-name-specifier template simple-template-id :: /// ~type-name /// ::[opt] nested-name-specifier[opt] ~type-name /// ExprResult Parser::ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType) { // We're parsing either a pseudo-destructor-name or a dependent // member access that has the same form as a // pseudo-destructor-name. We parse both in the same way and let // the action model sort them out. // // Note that the ::[opt] nested-name-specifier[opt] has already // been parsed, and if there was a simple-template-id, it has // been coalesced into a template-id annotation token. UnqualifiedId FirstTypeName; SourceLocation CCLoc; if (Tok.is(tok::identifier)) { FirstTypeName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); ConsumeToken(); assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); CCLoc = ConsumeToken(); } else if (Tok.is(tok::annot_template_id)) { // FIXME: retrieve TemplateKWLoc from template-id annotation and // store it in the pseudo-dtor node (to be used when instantiating it). FirstTypeName.setTemplateId( (TemplateIdAnnotation *)Tok.getAnnotationValue()); ConsumeToken(); assert(Tok.is(tok::coloncolon) &&"ParseOptionalCXXScopeSpecifier fail"); CCLoc = ConsumeToken(); } else { FirstTypeName.setIdentifier(nullptr, SourceLocation()); } // Parse the tilde. assert(Tok.is(tok::tilde) && "ParseOptionalCXXScopeSpecifier fail"); SourceLocation TildeLoc = ConsumeToken(); if (Tok.is(tok::kw_decltype) && !FirstTypeName.isValid() && SS.isEmpty()) { DeclSpec DS(AttrFactory); ParseDecltypeSpecifier(DS); if (DS.getTypeSpecType() == TST_error) return ExprError(); return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind, TildeLoc, DS); } if (!Tok.is(tok::identifier)) { Diag(Tok, diag::err_destructor_tilde_identifier); return ExprError(); } // Parse the second type. UnqualifiedId SecondTypeName; IdentifierInfo *Name = Tok.getIdentifierInfo(); SourceLocation NameLoc = ConsumeToken(); SecondTypeName.setIdentifier(Name, NameLoc); // If there is a '<', the second type name is a template-id. Parse // it as such. if (Tok.is(tok::less) && ParseUnqualifiedIdTemplateId(SS, SourceLocation(), Name, NameLoc, false, ObjectType, SecondTypeName, /*AssumeTemplateName=*/true)) return ExprError(); return Actions.ActOnPseudoDestructorExpr(getCurScope(), Base, OpLoc, OpKind, SS, FirstTypeName, CCLoc, TildeLoc, SecondTypeName); } /// ParseCXXBoolLiteral - This handles the C++ Boolean literals. /// /// boolean-literal: [C++ 2.13.5] /// 'true' /// 'false' ExprResult Parser::ParseCXXBoolLiteral() { tok::TokenKind Kind = Tok.getKind(); return Actions.ActOnCXXBoolLiteral(ConsumeToken(), Kind); } /// ParseThrowExpression - This handles the C++ throw expression. /// /// throw-expression: [C++ 15] /// 'throw' assignment-expression[opt] ExprResult Parser::ParseThrowExpression() { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::kw_throw) && "Not throw!"); SourceLocation ThrowLoc = ConsumeToken(); // Eat the throw token. // If the current token isn't the start of an assignment-expression, // then the expression is not present. This handles things like: // "C ? throw : (void)42", which is crazy but legal. switch (Tok.getKind()) { // FIXME: move this predicate somewhere common. case tok::semi: case tok::r_paren: case tok::r_square: case tok::r_brace: case tok::colon: case tok::comma: return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, nullptr); default: ExprResult Expr(ParseAssignmentExpression()); if (Expr.isInvalid()) return Expr; return Actions.ActOnCXXThrow(getCurScope(), ThrowLoc, Expr.get()); } } /// ParseCXXThis - This handles the C++ 'this' pointer. /// /// C++ 9.3.2: In the body of a non-static member function, the keyword this is /// a non-lvalue expression whose value is the address of the object for which /// the function is called. ExprResult Parser::ParseCXXThis() { assert(Tok.is(tok::kw_this) && "Not 'this'!"); SourceLocation ThisLoc = ConsumeToken(); return Actions.ActOnCXXThis(ThisLoc); } /// ParseCXXTypeConstructExpression - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). /// See [C++ 5.2.3]. /// /// postfix-expression: [C++ 5.2p1] /// simple-type-specifier '(' expression-list[opt] ')' /// [C++0x] simple-type-specifier braced-init-list /// typename-specifier '(' expression-list[opt] ')' /// [C++0x] typename-specifier braced-init-list /// ExprResult Parser::ParseCXXTypeConstructExpression(const DeclSpec &DS) { Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get(); assert((Tok.is(tok::l_paren) || (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace))) && "Expected '(' or '{'!"); if (Tok.is(tok::l_brace) && !getLangOpts().HLSL) { // HLSL Change - covered by assertion, but this helps compiler remove brace initialization code ExprResult Init = ParseBraceInitializer(); if (Init.isInvalid()) return Init; Expr *InitList = Init.get(); return Actions.ActOnCXXTypeConstructExpr(TypeRep, SourceLocation(), MultiExprArg(&InitList, 1), SourceLocation()); } else { BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); ExprVector Exprs; CommaLocsTy CommaLocs; if (Tok.isNot(tok::r_paren)) { if (ParseExpressionList(Exprs, CommaLocs, [&] { Actions.CodeCompleteConstructor(getCurScope(), TypeRep.get()->getCanonicalTypeInternal(), DS.getLocEnd(), Exprs); })) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } } // Match the ')'. T.consumeClose(); // TypeRep could be null, if it references an invalid typedef. if (!TypeRep) return ExprError(); assert((Exprs.size() == 0 || Exprs.size()-1 == CommaLocs.size())&& "Unexpected number of commas!"); return Actions.ActOnCXXTypeConstructExpr(TypeRep, T.getOpenLocation(), Exprs, T.getCloseLocation()); } } /// ParseCXXCondition - if/switch/while condition expression. /// /// condition: /// expression /// type-specifier-seq declarator '=' assignment-expression /// [C++11] type-specifier-seq declarator '=' initializer-clause /// [C++11] type-specifier-seq declarator braced-init-list /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] /// '=' assignment-expression /// /// \param ExprOut if the condition was parsed as an expression, the parsed /// expression. /// /// \param DeclOut if the condition was parsed as a declaration, the parsed /// declaration. /// /// \param Loc The location of the start of the statement that requires this /// condition, e.g., the "for" in a for loop. /// /// \param ConvertToBoolean Whether the condition expression should be /// converted to a boolean value. /// /// \returns true if there was a parsing, false otherwise. bool Parser::ParseCXXCondition(ExprResult &ExprOut, Decl *&DeclOut, SourceLocation Loc, bool ConvertToBoolean) { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Condition); cutOffParsing(); return true; } ParsedAttributesWithRange attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); MaybeParseHLSLAttributes(attrs); // HLSL Change if (!isCXXConditionDeclaration()) { ProhibitAttributes(attrs); // Parse the expression. ExprOut = ParseExpression(); // expression DeclOut = nullptr; if (ExprOut.isInvalid()) return true; // If required, convert to a boolean value. if (ConvertToBoolean) ExprOut = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprOut.get()); return ExprOut.isInvalid(); } // type-specifier-seq DeclSpec DS(AttrFactory); DS.takeAttributesFrom(attrs); ParseSpecifierQualifierList(DS, AS_none, DSC_condition); // declarator Declarator DeclaratorInfo(DS, Declarator::ConditionContext); ParseDeclarator(DeclaratorInfo); // simple-asm-expr[opt] if (Tok.is(tok::kw_asm)) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); return true; } // HLSL Change Ends SourceLocation Loc; ExprResult AsmLabel(ParseSimpleAsm(&Loc)); if (AsmLabel.isInvalid()) { SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); return true; } DeclaratorInfo.setAsmLabel(AsmLabel.get()); DeclaratorInfo.SetRangeEnd(Loc); } // If attributes are present, parse them. MaybeParseGNUAttributes(DeclaratorInfo); // Type-check the declaration itself. DeclResult Dcl = Actions.ActOnCXXConditionDeclaration(getCurScope(), DeclaratorInfo); DeclOut = Dcl.get(); ExprOut = ExprError(); // '=' assignment-expression // If a '==' or '+=' is found, suggest a fixit to '='. bool CopyInitialization = isTokenEqualOrEqualTypo(); if (CopyInitialization) ConsumeToken(); ExprResult InitExpr = ExprError(); if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) { Diag(Tok.getLocation(), diag::warn_cxx98_compat_generalized_initializer_lists); InitExpr = ParseBraceInitializer(); } else if (CopyInitialization) { InitExpr = ParseAssignmentExpression(); } else if (Tok.is(tok::l_paren)) { // This was probably an attempt to initialize the variable. SourceLocation LParen = ConsumeParen(), RParen = LParen; if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) RParen = ConsumeParen(); Diag(DeclOut ? DeclOut->getLocation() : LParen, diag::err_expected_init_in_condition_lparen) << SourceRange(LParen, RParen); } else { Diag(DeclOut ? DeclOut->getLocation() : Tok.getLocation(), diag::err_expected_init_in_condition); } if (!InitExpr.isInvalid()) Actions.AddInitializerToDecl(DeclOut, InitExpr.get(), !CopyInitialization, DS.containsPlaceholderType()); else Actions.ActOnInitializerError(DeclOut); // FIXME: Build a reference to this declaration? Convert it to bool? // (This is currently handled by Sema). Actions.FinalizeDeclaration(DeclOut); return false; } /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. /// /// simple-type-specifier: /// '::'[opt] nested-name-specifier[opt] type-name /// '::'[opt] nested-name-specifier 'template' simple-template-id [TODO] /// char /// wchar_t /// bool /// short /// int /// long /// signed /// unsigned /// float /// double /// void /// [GNU] typeof-specifier /// [C++0x] auto [TODO] /// /// type-name: /// class-name /// enum-name /// typedef-name /// void Parser::ParseCXXSimpleTypeSpecifier(DeclSpec &DS) { DS.SetRangeStart(Tok.getLocation()); const char *PrevSpec; unsigned DiagID; SourceLocation Loc = Tok.getLocation(); const clang::PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); switch (Tok.getKind()) { case tok::identifier: // foo::bar case tok::coloncolon: // ::foo::bar llvm_unreachable("Annotation token should already be formed!"); default: llvm_unreachable("Not a simple-type-specifier token!"); // type-name case tok::annot_typename: { if (getTypeAnnotation(Tok)) DS.SetTypeSpecType(DeclSpec::TST_typename, Loc, PrevSpec, DiagID, getTypeAnnotation(Tok), Policy); else DS.SetTypeSpecError(); DS.SetRangeEnd(Tok.getAnnotationEndLoc()); ConsumeToken(); DS.Finish(Diags, PP, Policy); return; } // builtin types case tok::kw_short: // HLSL Change Starts - handle certain types as reserved keywords HLSLReservedKeyword: if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); ConsumeToken(); DS.SetTypeSpecError(); DS.Finish(Diags, PP, Policy); return; } // HLSL Change Ends DS.SetTypeSpecWidth(DeclSpec::TSW_short, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_long: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL DS.SetTypeSpecWidth(DeclSpec::TSW_long, Loc, PrevSpec, DiagID, Policy); break; case tok::kw___int64: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL DS.SetTypeSpecWidth(DeclSpec::TSW_longlong, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_signed: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL DS.SetTypeSpecSign(DeclSpec::TSS_signed, Loc, PrevSpec, DiagID); break; case tok::kw_unsigned: DS.SetTypeSpecSign(DeclSpec::TSS_unsigned, Loc, PrevSpec, DiagID); break; case tok::kw_void: DS.SetTypeSpecType(DeclSpec::TST_void, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_char: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL DS.SetTypeSpecType(DeclSpec::TST_char, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_int: DS.SetTypeSpecType(DeclSpec::TST_int, Loc, PrevSpec, DiagID, Policy); break; case tok::kw___int128: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL DS.SetTypeSpecType(DeclSpec::TST_int128, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_half: DS.SetTypeSpecType(DeclSpec::TST_half, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_float: DS.SetTypeSpecType(DeclSpec::TST_float, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_double: DS.SetTypeSpecType(DeclSpec::TST_double, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_wchar_t: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL DS.SetTypeSpecType(DeclSpec::TST_wchar, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_char16_t: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL DS.SetTypeSpecType(DeclSpec::TST_char16, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_char32_t: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL DS.SetTypeSpecType(DeclSpec::TST_char32, Loc, PrevSpec, DiagID, Policy); break; case tok::kw_bool: DS.SetTypeSpecType(DeclSpec::TST_bool, Loc, PrevSpec, DiagID, Policy); break; case tok::annot_decltype: case tok::kw_decltype: DS.SetRangeEnd(ParseDecltypeSpecifier(DS)); return DS.Finish(Diags, PP, Policy); // GNU typeof support. case tok::kw_typeof: if (getLangOpts().HLSL) { goto HLSLReservedKeyword; } // HLSL Change - reserved for HLSL ParseTypeofSpecifier(DS); DS.Finish(Diags, PP, Policy); return; } if (Tok.is(tok::annot_typename)) DS.SetRangeEnd(Tok.getAnnotationEndLoc()); else DS.SetRangeEnd(Tok.getLocation()); ConsumeToken(); DS.Finish(Diags, PP, Policy); } /// ParseCXXTypeSpecifierSeq - Parse a C++ type-specifier-seq (C++ /// [dcl.name]), which is a non-empty sequence of type-specifiers, /// e.g., "const short int". Note that the DeclSpec is *not* finished /// by parsing the type-specifier-seq, because these sequences are /// typically followed by some form of declarator. Returns true and /// emits diagnostics if this is not a type-specifier-seq, false /// otherwise. /// /// type-specifier-seq: [C++ 8.1] /// type-specifier type-specifier-seq[opt] /// bool Parser::ParseCXXTypeSpecifierSeq(DeclSpec &DS) { ParseSpecifierQualifierList(DS, AS_none, DSC_type_specifier); DS.Finish(Diags, PP, Actions.getASTContext().getPrintingPolicy()); return false; } /// \brief Finish parsing a C++ unqualified-id that is a template-id of /// some form. /// /// This routine is invoked when a '<' is encountered after an identifier or /// operator-function-id is parsed by \c ParseUnqualifiedId() to determine /// whether the unqualified-id is actually a template-id. This routine will /// then parse the template arguments and form the appropriate template-id to /// return to the caller. /// /// \param SS the nested-name-specifier that precedes this template-id, if /// we're actually parsing a qualified-id. /// /// \param Name for constructor and destructor names, this is the actual /// identifier that may be a template-name. /// /// \param NameLoc the location of the class-name in a constructor or /// destructor. /// /// \param EnteringContext whether we're entering the scope of the /// nested-name-specifier. /// /// \param ObjectType if this unqualified-id occurs within a member access /// expression, the type of the base object whose member is being accessed. /// /// \param Id as input, describes the template-name or operator-function-id /// that precedes the '<'. If template arguments were parsed successfully, /// will be updated with the template-id. /// /// \param AssumeTemplateId When true, this routine will assume that the name /// refers to a template without performing name lookup to verify. /// /// \returns true if a parse error occurred, false otherwise. bool Parser::ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Id, bool AssumeTemplateId) { assert((AssumeTemplateId || Tok.is(tok::less)) && "Expected '<' to finish parsing a template-id"); TemplateTy Template; TemplateNameKind TNK = TNK_Non_template; switch (Id.getKind()) { case UnqualifiedId::IK_Identifier: case UnqualifiedId::IK_OperatorFunctionId: case UnqualifiedId::IK_LiteralOperatorId: if (AssumeTemplateId) { TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext, Template); if (TNK == TNK_Non_template) return true; } else { bool MemberOfUnknownSpecialization; TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), Id, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization); if (TNK == TNK_Non_template && MemberOfUnknownSpecialization && ObjectType && IsTemplateArgumentList()) { // We have something like t->getAs<T>(), where getAs is a // member of an unknown specialization. However, this will only // parse correctly as a template, so suggest the keyword 'template' // before 'getAs' and treat this as a dependent template name. std::string Name; if (Id.getKind() == UnqualifiedId::IK_Identifier) Name = Id.Identifier->getName(); else { Name = "operator "; if (Id.getKind() == UnqualifiedId::IK_OperatorFunctionId) Name += getOperatorSpelling(Id.OperatorFunctionId.Operator); else Name += Id.Identifier->getName(); } Diag(Id.StartLocation, diag::err_missing_dependent_template_keyword) << Name << FixItHint::CreateInsertion(Id.StartLocation, "template "); TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc, Id, ObjectType, EnteringContext, Template); if (TNK == TNK_Non_template) return true; } } break; case UnqualifiedId::IK_ConstructorName: { UnqualifiedId TemplateName; bool MemberOfUnknownSpecialization; TemplateName.setIdentifier(Name, NameLoc); TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), TemplateName, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization); break; } case UnqualifiedId::IK_DestructorName: { UnqualifiedId TemplateName; bool MemberOfUnknownSpecialization; TemplateName.setIdentifier(Name, NameLoc); if (ObjectType) { TNK = Actions.ActOnDependentTemplateName(getCurScope(), SS, TemplateKWLoc, TemplateName, ObjectType, EnteringContext, Template); if (TNK == TNK_Non_template) return true; } else { TNK = Actions.isTemplateName(getCurScope(), SS, TemplateKWLoc.isValid(), TemplateName, ObjectType, EnteringContext, Template, MemberOfUnknownSpecialization); if (TNK == TNK_Non_template && !Id.DestructorName.get()) { Diag(NameLoc, diag::err_destructor_template_id) << Name << SS.getRange(); return true; } } break; } default: return false; } if (TNK == TNK_Non_template) return false; // Parse the enclosed template argument list. SourceLocation LAngleLoc, RAngleLoc; TemplateArgList TemplateArgs; if (Tok.is(tok::less) && ParseTemplateIdAfterTemplateName(Template, Id.StartLocation, SS, true, LAngleLoc, TemplateArgs, RAngleLoc)) return true; if (Id.getKind() == UnqualifiedId::IK_Identifier || Id.getKind() == UnqualifiedId::IK_OperatorFunctionId || Id.getKind() == UnqualifiedId::IK_LiteralOperatorId) { // Form a parsed representation of the template-id to be stored in the // UnqualifiedId. TemplateIdAnnotation *TemplateId = TemplateIdAnnotation::Allocate(TemplateArgs.size(), TemplateIds); // FIXME: Store name for literal operator too. if (Id.getKind() == UnqualifiedId::IK_Identifier) { TemplateId->Name = Id.Identifier; TemplateId->Operator = OO_None; TemplateId->TemplateNameLoc = Id.StartLocation; } else { TemplateId->Name = nullptr; TemplateId->Operator = Id.OperatorFunctionId.Operator; TemplateId->TemplateNameLoc = Id.StartLocation; } TemplateId->SS = SS; TemplateId->TemplateKWLoc = TemplateKWLoc; TemplateId->Template = Template; TemplateId->Kind = TNK; TemplateId->LAngleLoc = LAngleLoc; TemplateId->RAngleLoc = RAngleLoc; ParsedTemplateArgument *Args = TemplateId->getTemplateArgs(); for (unsigned Arg = 0, ArgEnd = TemplateArgs.size(); Arg != ArgEnd; ++Arg) Args[Arg] = TemplateArgs[Arg]; Id.setTemplateId(TemplateId); return false; } // Bundle the template arguments together. ASTTemplateArgsPtr TemplateArgsPtr(TemplateArgs); // Constructor and destructor names. TypeResult Type = Actions.ActOnTemplateIdType(SS, TemplateKWLoc, Template, NameLoc, LAngleLoc, TemplateArgsPtr, RAngleLoc, /*IsCtorOrDtorName=*/true); if (Type.isInvalid()) return true; if (Id.getKind() == UnqualifiedId::IK_ConstructorName) Id.setConstructorName(Type.get(), NameLoc, RAngleLoc); else Id.setDestructorName(Id.StartLocation, Type.get(), RAngleLoc); return false; } /// \brief Parse an operator-function-id or conversion-function-id as part /// of a C++ unqualified-id. /// /// This routine is responsible only for parsing the operator-function-id or /// conversion-function-id; it does not handle template arguments in any way. /// /// \code /// operator-function-id: [C++ 13.5] /// 'operator' operator /// /// operator: one of /// new delete new[] delete[] /// + - * / % ^ & | ~ /// ! = < > += -= *= /= %= /// ^= &= |= << >> >>= <<= == != /// <= >= && || ++ -- , ->* -> /// () [] /// /// conversion-function-id: [C++ 12.3.2] /// operator conversion-type-id /// /// conversion-type-id: /// type-specifier-seq conversion-declarator[opt] /// /// conversion-declarator: /// ptr-operator conversion-declarator[opt] /// \endcode /// /// \param SS The nested-name-specifier that preceded this unqualified-id. If /// non-empty, then we are parsing the unqualified-id of a qualified-id. /// /// \param EnteringContext whether we are entering the scope of the /// nested-name-specifier. /// /// \param ObjectType if this unqualified-id occurs within a member access /// expression, the type of the base object whose member is being accessed. /// /// \param Result on a successful parse, contains the parsed unqualified-id. /// /// \returns true if parsing fails, false otherwise. bool Parser::ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result) { assert((!getLangOpts().HLSL || getLangOpts().HLSLVersion >= hlsl::LangStd::v2021) && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::kw_operator) && "Expected 'operator' keyword"); // Consume the 'operator' keyword. SourceLocation KeywordLoc = ConsumeToken(); // Determine what kind of operator name we have. unsigned SymbolIdx = 0; SourceLocation SymbolLocations[3]; OverloadedOperatorKind Op = OO_None; switch (Tok.getKind()) { case tok::kw_new: case tok::kw_delete: { bool isNew = Tok.getKind() == tok::kw_new; // Consume the 'new' or 'delete'. SymbolLocations[SymbolIdx++] = ConsumeToken(); // Check for array new/delete. if (Tok.is(tok::l_square) && (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square))) { // Consume the '[' and ']'. BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); T.consumeClose(); if (T.getCloseLocation().isInvalid()) return true; SymbolLocations[SymbolIdx++] = T.getOpenLocation(); SymbolLocations[SymbolIdx++] = T.getCloseLocation(); Op = isNew? OO_Array_New : OO_Array_Delete; } else { Op = isNew? OO_New : OO_Delete; } break; } #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \ case tok::Token: \ SymbolLocations[SymbolIdx++] = ConsumeToken(); \ Op = OO_##Name; \ break; #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly) #include "clang/Basic/OperatorKinds.def" case tok::l_paren: { // Consume the '(' and ')'. BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); T.consumeClose(); if (T.getCloseLocation().isInvalid()) return true; SymbolLocations[SymbolIdx++] = T.getOpenLocation(); SymbolLocations[SymbolIdx++] = T.getCloseLocation(); Op = OO_Call; break; } case tok::l_square: { // Consume the '[' and ']'. BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); T.consumeClose(); if (T.getCloseLocation().isInvalid()) return true; SymbolLocations[SymbolIdx++] = T.getOpenLocation(); SymbolLocations[SymbolIdx++] = T.getCloseLocation(); Op = OO_Subscript; break; } case tok::code_completion: { // Code completion for the operator name. Actions.CodeCompleteOperatorName(getCurScope()); cutOffParsing(); // Don't try to parse any further. return true; } default: break; } if (Op != OO_None) { // We have parsed an operator-function-id. Result.setOperatorFunctionId(KeywordLoc, Op, SymbolLocations); return false; } // Parse a literal-operator-id. // // literal-operator-id: C++11 [over.literal] // operator string-literal identifier // operator user-defined-string-literal if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) { Diag(Tok.getLocation(), diag::warn_cxx98_compat_literal_operator); SourceLocation DiagLoc; unsigned DiagId = 0; // We're past translation phase 6, so perform string literal concatenation // before checking for "". SmallVector<Token, 4> Toks; SmallVector<SourceLocation, 4> TokLocs; while (isTokenStringLiteral()) { if (!Tok.is(tok::string_literal) && !DiagId) { // C++11 [over.literal]p1: // The string-literal or user-defined-string-literal in a // literal-operator-id shall have no encoding-prefix [...]. DiagLoc = Tok.getLocation(); DiagId = diag::err_literal_operator_string_prefix; } Toks.push_back(Tok); TokLocs.push_back(ConsumeStringToken()); } StringLiteralParser Literal(Toks, PP); if (Literal.hadError) return true; // Grab the literal operator's suffix, which will be either the next token // or a ud-suffix from the string literal. IdentifierInfo *II = nullptr; SourceLocation SuffixLoc; if (!Literal.getUDSuffix().empty()) { II = &PP.getIdentifierTable().get(Literal.getUDSuffix()); SuffixLoc = Lexer::AdvanceToTokenCharacter(TokLocs[Literal.getUDSuffixToken()], Literal.getUDSuffixOffset(), PP.getSourceManager(), getLangOpts()); } else if (Tok.is(tok::identifier)) { II = Tok.getIdentifierInfo(); SuffixLoc = ConsumeToken(); TokLocs.push_back(SuffixLoc); } else { Diag(Tok.getLocation(), diag::err_expected) << tok::identifier; return true; } // The string literal must be empty. if (!Literal.GetString().empty() || Literal.Pascal) { // C++11 [over.literal]p1: // The string-literal or user-defined-string-literal in a // literal-operator-id shall [...] contain no characters // other than the implicit terminating '\0'. DiagLoc = TokLocs.front(); DiagId = diag::err_literal_operator_string_not_empty; } if (DiagId) { // This isn't a valid literal-operator-id, but we think we know // what the user meant. Tell them what they should have written. SmallString<32> Str; Str += "\"\" "; Str += II->getName(); Diag(DiagLoc, DiagId) << FixItHint::CreateReplacement( SourceRange(TokLocs.front(), TokLocs.back()), Str); } Result.setLiteralOperatorId(II, KeywordLoc, SuffixLoc); return Actions.checkLiteralOperatorId(SS, Result); } // Parse a conversion-function-id. // // conversion-function-id: [C++ 12.3.2] // operator conversion-type-id // // conversion-type-id: // type-specifier-seq conversion-declarator[opt] // // conversion-declarator: // ptr-operator conversion-declarator[opt] // Parse the type-specifier-seq. DeclSpec DS(AttrFactory); if (ParseCXXTypeSpecifierSeq(DS)) // FIXME: ObjectType? return true; // Parse the conversion-declarator, which is merely a sequence of // ptr-operators. Declarator D(DS, Declarator::ConversionIdContext); ParseDeclaratorInternal(D, /*DirectDeclParser=*/nullptr); // Finish up the type. TypeResult Ty = Actions.ActOnTypeName(getCurScope(), D); if (Ty.isInvalid()) return true; // Note that this is a conversion-function-id. Result.setConversionFunctionId(KeywordLoc, Ty.get(), D.getSourceRange().getEnd()); return false; } /// \brief Parse a C++ unqualified-id (or a C identifier), which describes the /// name of an entity. /// /// \code /// unqualified-id: [C++ expr.prim.general] /// identifier /// operator-function-id /// conversion-function-id /// [C++0x] literal-operator-id [TODO] /// ~ class-name /// template-id /// /// \endcode /// /// \param SS The nested-name-specifier that preceded this unqualified-id. If /// non-empty, then we are parsing the unqualified-id of a qualified-id. /// /// \param EnteringContext whether we are entering the scope of the /// nested-name-specifier. /// /// \param AllowDestructorName whether we allow parsing of a destructor name. /// /// \param AllowConstructorName whether we allow parsing a constructor name. /// /// \param ObjectType if this unqualified-id occurs within a member access /// expression, the type of the base object whose member is being accessed. /// /// \param Result on a successful parse, contains the parsed unqualified-id. /// /// \returns true if parsing fails, false otherwise. bool Parser::ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, ParsedType ObjectType, SourceLocation& TemplateKWLoc, UnqualifiedId &Result) { // Handle 'A::template B'. This is for template-ids which have not // already been annotated by ParseOptionalCXXScopeSpecifier(). bool TemplateSpecified = false; if (getLangOpts().CPlusPlus && Tok.is(tok::kw_template) && (ObjectType || SS.isSet())) { TemplateSpecified = true; TemplateKWLoc = ConsumeToken(); } // unqualified-id: // identifier // template-id (when it hasn't already been annotated) if (Tok.is(tok::identifier)) { // Consume the identifier. IdentifierInfo *Id = Tok.getIdentifierInfo(); SourceLocation IdLoc = ConsumeToken(); if (!getLangOpts().CPlusPlus) { // If we're not in C++, only identifiers matter. Record the // identifier and return. Result.setIdentifier(Id, IdLoc); return false; } if (AllowConstructorName && Actions.isCurrentClassName(*Id, getCurScope(), &SS)) { // We have parsed a constructor name. ParsedType Ty = Actions.getTypeName(*Id, IdLoc, getCurScope(), &SS, false, false, ParsedType(), /*IsCtorOrDtorName=*/true, /*NonTrivialTypeSourceInfo=*/true); Result.setConstructorName(Ty, IdLoc, IdLoc); } else { // We have parsed an identifier. Result.setIdentifier(Id, IdLoc); } // If the next token is a '<', we may have a template. if (TemplateSpecified || Tok.is(tok::less)) return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, Id, IdLoc, EnteringContext, ObjectType, Result, TemplateSpecified); return false; } // unqualified-id: // template-id (already parsed and annotated) if (Tok.is(tok::annot_template_id)) { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); // If the template-name names the current class, then this is a constructor if (AllowConstructorName && TemplateId->Name && Actions.isCurrentClassName(*TemplateId->Name, getCurScope(), &SS)) { if (SS.isSet()) { // C++ [class.qual]p2 specifies that a qualified template-name // is taken as the constructor name where a constructor can be // declared. Thus, the template arguments are extraneous, so // complain about them and remove them entirely. Diag(TemplateId->TemplateNameLoc, diag::err_out_of_line_constructor_template_id) << TemplateId->Name << FixItHint::CreateRemoval( SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc)); ParsedType Ty = Actions.getTypeName(*TemplateId->Name, TemplateId->TemplateNameLoc, getCurScope(), &SS, false, false, ParsedType(), /*IsCtorOrDtorName=*/true, /*NontrivialTypeSourceInfo=*/true); Result.setConstructorName(Ty, TemplateId->TemplateNameLoc, TemplateId->RAngleLoc); ConsumeToken(); return false; } Result.setConstructorTemplateId(TemplateId); ConsumeToken(); return false; } // We have already parsed a template-id; consume the annotation token as // our unqualified-id. Result.setTemplateId(TemplateId); TemplateKWLoc = TemplateId->TemplateKWLoc; ConsumeToken(); return false; } // unqualified-id: // operator-function-id // conversion-function-id if (Tok.is(tok::kw_operator)) { // HLSL Change Starts if (getLangOpts().HLSL && getLangOpts().HLSLVersion < hlsl::LangStd::v2021) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); ConsumeToken(); return true; } // HLSL Change Ends if (ParseUnqualifiedIdOperator(SS, EnteringContext, ObjectType, Result)) return true; // If we have an operator-function-id or a literal-operator-id and the next // token is a '<', we may have a // // template-id: // operator-function-id < template-argument-list[opt] > if ((Result.getKind() == UnqualifiedId::IK_OperatorFunctionId || Result.getKind() == UnqualifiedId::IK_LiteralOperatorId) && (TemplateSpecified || Tok.is(tok::less))) return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, nullptr, SourceLocation(), EnteringContext, ObjectType, Result, TemplateSpecified); return false; } if (getLangOpts().CPlusPlus && (AllowDestructorName || SS.isSet()) && Tok.is(tok::tilde)) { // C++ [expr.unary.op]p10: // There is an ambiguity in the unary-expression ~X(), where X is a // class-name. The ambiguity is resolved in favor of treating ~ as a // unary complement rather than treating ~X as referring to a destructor. // Parse the '~'. SourceLocation TildeLoc = ConsumeToken(); if (SS.isEmpty() && Tok.is(tok::kw_decltype)) { DeclSpec DS(AttrFactory); SourceLocation EndLoc = ParseDecltypeSpecifier(DS); if (ParsedType Type = Actions.getDestructorType(DS, ObjectType)) { Result.setDestructorName(TildeLoc, Type, EndLoc); return false; } return true; } // Parse the class-name. if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_destructor_tilde_identifier); return true; } // If the user wrote ~T::T, correct it to T::~T. DeclaratorScopeObj DeclScopeObj(*this, SS); if (!TemplateSpecified && NextToken().is(tok::coloncolon)) { // Don't let ParseOptionalCXXScopeSpecifier() "correct" // `int A; struct { ~A::A(); };` to `int A; struct { ~A:A(); };`, // it will confuse this recovery logic. ColonProtectionRAIIObject ColonRAII(*this, false); if (SS.isSet()) { AnnotateScopeToken(SS, /*NewAnnotation*/true); SS.clear(); } if (ParseOptionalCXXScopeSpecifier(SS, ObjectType, EnteringContext)) return true; if (SS.isNotEmpty()) ObjectType = ParsedType(); if (Tok.isNot(tok::identifier) || NextToken().is(tok::coloncolon) || !SS.isSet()) { Diag(TildeLoc, diag::err_destructor_tilde_scope); return true; } // Recover as if the tilde had been written before the identifier. Diag(TildeLoc, diag::err_destructor_tilde_scope) << FixItHint::CreateRemoval(TildeLoc) << FixItHint::CreateInsertion(Tok.getLocation(), "~"); // Temporarily enter the scope for the rest of this function. if (Actions.ShouldEnterDeclaratorScope(getCurScope(), SS)) DeclScopeObj.EnterDeclaratorScope(); } // Parse the class-name (or template-name in a simple-template-id). IdentifierInfo *ClassName = Tok.getIdentifierInfo(); SourceLocation ClassNameLoc = ConsumeToken(); if (TemplateSpecified || Tok.is(tok::less)) { Result.setDestructorName(TildeLoc, ParsedType(), ClassNameLoc); return ParseUnqualifiedIdTemplateId(SS, TemplateKWLoc, ClassName, ClassNameLoc, EnteringContext, ObjectType, Result, TemplateSpecified); } // Note that this is a destructor name. ParsedType Ty = Actions.getDestructorName(TildeLoc, *ClassName, ClassNameLoc, getCurScope(), SS, ObjectType, EnteringContext); if (!Ty) return true; Result.setDestructorName(TildeLoc, Ty, ClassNameLoc); return false; } Diag(Tok, diag::err_expected_unqualified_id) << getLangOpts().CPlusPlus; return true; } /// ParseCXXNewExpression - Parse a C++ new-expression. New is used to allocate /// memory in a typesafe manner and call constructors. /// /// This method is called to parse the new expression after the optional :: has /// been already parsed. If the :: was present, "UseGlobal" is true and "Start" /// is its location. Otherwise, "Start" is the location of the 'new' token. /// /// new-expression: /// '::'[opt] 'new' new-placement[opt] new-type-id /// new-initializer[opt] /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' /// new-initializer[opt] /// /// new-placement: /// '(' expression-list ')' /// /// new-type-id: /// type-specifier-seq new-declarator[opt] /// [GNU] attributes type-specifier-seq new-declarator[opt] /// /// new-declarator: /// ptr-operator new-declarator[opt] /// direct-new-declarator /// /// new-initializer: /// '(' expression-list[opt] ')' /// [C++0x] braced-init-list /// ExprResult Parser::ParseCXXNewExpression(bool UseGlobal, SourceLocation Start) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::kw_new) && "expected 'new' token"); ConsumeToken(); // Consume 'new' // A '(' now can be a new-placement or the '(' wrapping the type-id in the // second form of new-expression. It can't be a new-type-id. ExprVector PlacementArgs; SourceLocation PlacementLParen, PlacementRParen; SourceRange TypeIdParens; DeclSpec DS(AttrFactory); Declarator DeclaratorInfo(DS, Declarator::CXXNewContext); if (Tok.is(tok::l_paren)) { // If it turns out to be a placement, we change the type location. BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); PlacementLParen = T.getOpenLocation(); if (ParseExpressionListOrTypeId(PlacementArgs, DeclaratorInfo)) { SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); return ExprError(); } T.consumeClose(); PlacementRParen = T.getCloseLocation(); if (PlacementRParen.isInvalid()) { SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); return ExprError(); } if (PlacementArgs.empty()) { // Reset the placement locations. There was no placement. TypeIdParens = T.getRange(); PlacementLParen = PlacementRParen = SourceLocation(); } else { // We still need the type. if (Tok.is(tok::l_paren)) { BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); MaybeParseGNUAttributes(DeclaratorInfo); ParseSpecifierQualifierList(DS); DeclaratorInfo.SetSourceRange(DS.getSourceRange()); ParseDeclarator(DeclaratorInfo); T.consumeClose(); TypeIdParens = T.getRange(); } else { MaybeParseGNUAttributes(DeclaratorInfo); if (ParseCXXTypeSpecifierSeq(DS)) DeclaratorInfo.setInvalidType(true); else { DeclaratorInfo.SetSourceRange(DS.getSourceRange()); ParseDeclaratorInternal(DeclaratorInfo, &Parser::ParseDirectNewDeclarator); } } } } else { // A new-type-id is a simplified type-id, where essentially the // direct-declarator is replaced by a direct-new-declarator. MaybeParseGNUAttributes(DeclaratorInfo); if (ParseCXXTypeSpecifierSeq(DS)) DeclaratorInfo.setInvalidType(true); else { DeclaratorInfo.SetSourceRange(DS.getSourceRange()); ParseDeclaratorInternal(DeclaratorInfo, &Parser::ParseDirectNewDeclarator); } } if (DeclaratorInfo.isInvalidType()) { SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); return ExprError(); } ExprResult Initializer; if (Tok.is(tok::l_paren)) { SourceLocation ConstructorLParen, ConstructorRParen; ExprVector ConstructorArgs; BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); ConstructorLParen = T.getOpenLocation(); if (Tok.isNot(tok::r_paren)) { CommaLocsTy CommaLocs; if (ParseExpressionList(ConstructorArgs, CommaLocs, [&] { ParsedType TypeRep = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo).get(); Actions.CodeCompleteConstructor(getCurScope(), TypeRep.get()->getCanonicalTypeInternal(), DeclaratorInfo.getLocEnd(), ConstructorArgs); })) { SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); return ExprError(); } } T.consumeClose(); ConstructorRParen = T.getCloseLocation(); if (ConstructorRParen.isInvalid()) { SkipUntil(tok::semi, StopAtSemi | StopBeforeMatch); return ExprError(); } Initializer = Actions.ActOnParenListExpr(ConstructorLParen, ConstructorRParen, ConstructorArgs); } else if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus11) { Diag(Tok.getLocation(), diag::warn_cxx98_compat_generalized_initializer_lists); Initializer = ParseBraceInitializer(); } if (Initializer.isInvalid()) return Initializer; return Actions.ActOnCXXNew(Start, UseGlobal, PlacementLParen, PlacementArgs, PlacementRParen, TypeIdParens, DeclaratorInfo, Initializer.get()); } /// ParseDirectNewDeclarator - Parses a direct-new-declarator. Intended to be /// passed to ParseDeclaratorInternal. /// /// direct-new-declarator: /// '[' expression ']' /// direct-new-declarator '[' constant-expression ']' /// void Parser::ParseDirectNewDeclarator(Declarator &D) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change // Parse the array dimensions. bool first = true; while (Tok.is(tok::l_square)) { // An array-size expression can't start with a lambda. if (CheckProhibitedCXX11Attribute()) continue; BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); ExprResult Size(first ? ParseExpression() : ParseConstantExpression()); if (Size.isInvalid()) { // Recover SkipUntil(tok::r_square, StopAtSemi); return; } first = false; T.consumeClose(); // Attributes here appertain to the array type. C++11 [expr.new]p5. ParsedAttributes Attrs(AttrFactory); MaybeParseCXX11Attributes(Attrs); // HLSL Change: comment only - MaybeParseHLSLAttributes would go here if allowed at this point D.AddTypeInfo(DeclaratorChunk::getArray(0, /*static=*/false, /*star=*/false, Size.get(), T.getOpenLocation(), T.getCloseLocation()), Attrs, T.getCloseLocation()); if (T.getCloseLocation().isInvalid()) return; } } /// ParseExpressionListOrTypeId - Parse either an expression-list or a type-id. /// This ambiguity appears in the syntax of the C++ new operator. /// /// new-expression: /// '::'[opt] 'new' new-placement[opt] '(' type-id ')' /// new-initializer[opt] /// /// new-placement: /// '(' expression-list ')' /// bool Parser::ParseExpressionListOrTypeId( SmallVectorImpl<Expr*> &PlacementArgs, Declarator &D) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change // The '(' was already consumed. if (isTypeIdInParens()) { ParseSpecifierQualifierList(D.getMutableDeclSpec()); D.SetSourceRange(D.getDeclSpec().getSourceRange()); ParseDeclarator(D); return D.isInvalidType(); } // It's not a type, it has to be an expression list. // Discard the comma locations - ActOnCXXNew has enough parameters. CommaLocsTy CommaLocs; return ParseExpressionList(PlacementArgs, CommaLocs); } /// ParseCXXDeleteExpression - Parse a C++ delete-expression. Delete is used /// to free memory allocated by new. /// /// This method is called to parse the 'delete' expression after the optional /// '::' has been already parsed. If the '::' was present, "UseGlobal" is true /// and "Start" is its location. Otherwise, "Start" is the location of the /// 'delete' token. /// /// delete-expression: /// '::'[opt] 'delete' cast-expression /// '::'[opt] 'delete' '[' ']' cast-expression ExprResult Parser::ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start) { assert(!getLangOpts().HLSL && "not supported in HLSL - unreachable"); // HLSL Change assert(Tok.is(tok::kw_delete) && "Expected 'delete' keyword"); ConsumeToken(); // Consume 'delete' // Array delete? bool ArrayDelete = false; if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) { // C++11 [expr.delete]p1: // Whenever the delete keyword is followed by empty square brackets, it // shall be interpreted as [array delete]. // [Footnote: A lambda expression with a lambda-introducer that consists // of empty square brackets can follow the delete keyword if // the lambda expression is enclosed in parentheses.] // FIXME: Produce a better diagnostic if the '[]' is unambiguously a // lambda-introducer. ArrayDelete = true; BalancedDelimiterTracker T(*this, tok::l_square); T.consumeOpen(); T.consumeClose(); if (T.getCloseLocation().isInvalid()) return ExprError(); } ExprResult Operand(ParseCastExpression(false)); if (Operand.isInvalid()) return Operand; return Actions.ActOnCXXDelete(Start, UseGlobal, ArrayDelete, Operand.get()); } static TypeTrait TypeTraitFromTokKind(tok::TokenKind kind) { switch (kind) { default: llvm_unreachable("Not a known type trait"); #define TYPE_TRAIT_1(Spelling, Name, Key) \ case tok::kw_ ## Spelling: return UTT_ ## Name; #define TYPE_TRAIT_2(Spelling, Name, Key) \ case tok::kw_ ## Spelling: return BTT_ ## Name; #include "clang/Basic/TokenKinds.def" #define TYPE_TRAIT_N(Spelling, Name, Key) \ case tok::kw_ ## Spelling: return TT_ ## Name; #include "clang/Basic/TokenKinds.def" } } static ArrayTypeTrait ArrayTypeTraitFromTokKind(tok::TokenKind kind) { switch(kind) { default: llvm_unreachable("Not a known binary type trait"); case tok::kw___array_rank: return ATT_ArrayRank; case tok::kw___array_extent: return ATT_ArrayExtent; } } static ExpressionTrait ExpressionTraitFromTokKind(tok::TokenKind kind) { switch(kind) { default: llvm_unreachable("Not a known unary expression trait."); case tok::kw___is_lvalue_expr: return ET_IsLValueExpr; case tok::kw___is_rvalue_expr: return ET_IsRValueExpr; } } static unsigned TypeTraitArity(tok::TokenKind kind) { switch (kind) { default: llvm_unreachable("Not a known type trait"); #define TYPE_TRAIT(N,Spelling,K) case tok::kw_##Spelling: return N; #include "clang/Basic/TokenKinds.def" } } /// \brief Parse the built-in type-trait pseudo-functions that allow /// implementation of the TR1/C++11 type traits templates. /// /// primary-expression: /// unary-type-trait '(' type-id ')' /// binary-type-trait '(' type-id ',' type-id ')' /// type-trait '(' type-id-seq ')' /// /// type-id-seq: /// type-id ...[opt] type-id-seq[opt] /// ExprResult Parser::ParseTypeTrait() { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << Tok.getName(); ConsumeToken(); BalancedDelimiterTracker p(*this, tok::l_paren); if (!p.expectAndConsume()) p.skipToEnd(); return ExprError(); } // HLSL Change Ends tok::TokenKind Kind = Tok.getKind(); unsigned Arity = TypeTraitArity(Kind); SourceLocation Loc = ConsumeToken(); BalancedDelimiterTracker Parens(*this, tok::l_paren); if (Parens.expectAndConsume()) return ExprError(); SmallVector<ParsedType, 2> Args; do { // Parse the next type. TypeResult Ty = ParseTypeName(); if (Ty.isInvalid()) { Parens.skipToEnd(); return ExprError(); } // Parse the ellipsis, if present. if (Tok.is(tok::ellipsis)) { Ty = Actions.ActOnPackExpansion(Ty.get(), ConsumeToken()); if (Ty.isInvalid()) { Parens.skipToEnd(); return ExprError(); } } // Add this type to the list of arguments. Args.push_back(Ty.get()); } while (TryConsumeToken(tok::comma)); if (Parens.consumeClose()) return ExprError(); SourceLocation EndLoc = Parens.getCloseLocation(); if (Arity && Args.size() != Arity) { Diag(EndLoc, diag::err_type_trait_arity) << Arity << 0 << (Arity > 1) << (int)Args.size() << SourceRange(Loc); return ExprError(); } if (!Arity && Args.empty()) { Diag(EndLoc, diag::err_type_trait_arity) << 1 << 1 << 1 << (int)Args.size() << SourceRange(Loc); return ExprError(); } return Actions.ActOnTypeTrait(TypeTraitFromTokKind(Kind), Loc, Args, EndLoc); } /// ParseArrayTypeTrait - Parse the built-in array type-trait /// pseudo-functions. /// /// primary-expression: /// [Embarcadero] '__array_rank' '(' type-id ')' /// [Embarcadero] '__array_extent' '(' type-id ',' expression ')' /// ExprResult Parser::ParseArrayTypeTrait() { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << Tok.getName(); ConsumeToken(); BalancedDelimiterTracker p(*this, tok::l_paren); if (!p.expectAndConsume()) p.skipToEnd(); return ExprError(); } // HLSL Change Ends ArrayTypeTrait ATT = ArrayTypeTraitFromTokKind(Tok.getKind()); SourceLocation Loc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.expectAndConsume()) return ExprError(); TypeResult Ty = ParseTypeName(); if (Ty.isInvalid()) { SkipUntil(tok::comma, StopAtSemi); SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } switch (ATT) { case ATT_ArrayRank: { T.consumeClose(); return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), nullptr, T.getCloseLocation()); } case ATT_ArrayExtent: { if (ExpectAndConsume(tok::comma)) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } ExprResult DimExpr = ParseExpression(); T.consumeClose(); return Actions.ActOnArrayTypeTrait(ATT, Loc, Ty.get(), DimExpr.get(), T.getCloseLocation()); } } llvm_unreachable("Invalid ArrayTypeTrait!"); } /// ParseExpressionTrait - Parse built-in expression-trait /// pseudo-functions like __is_lvalue_expr( xxx ). /// /// primary-expression: /// [Embarcadero] expression-trait '(' expression ')' /// ExprResult Parser::ParseExpressionTrait() { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << Tok.getName(); ConsumeToken(); BalancedDelimiterTracker p(*this, tok::l_paren); if (!p.expectAndConsume()) p.skipToEnd(); return ExprError(); } // HLSL Change Ends ExpressionTrait ET = ExpressionTraitFromTokKind(Tok.getKind()); SourceLocation Loc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.expectAndConsume()) return ExprError(); ExprResult Expr = ParseExpression(); T.consumeClose(); return Actions.ActOnExpressionTrait(ET, Loc, Expr.get(), T.getCloseLocation()); } /// ParseCXXAmbiguousParenExpression - We have parsed the left paren of a /// parenthesized ambiguous type-id. This uses tentative parsing to disambiguate /// based on the context past the parens. ExprResult Parser::ParseCXXAmbiguousParenExpression(ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt) { assert(getLangOpts().CPlusPlus && "Should only be called for C++!"); assert(ExprType == CastExpr && "Compound literals are not ambiguous!"); assert(isTypeIdInParens() && "Not a type-id!"); ExprResult Result(true); CastTy = ParsedType(); // We need to disambiguate a very ugly part of the C++ syntax: // // (T())x; - type-id // (T())*x; - type-id // (T())/x; - expression // (T()); - expression // // The bad news is that we cannot use the specialized tentative parser, since // it can only verify that the thing inside the parens can be parsed as // type-id, it is not useful for determining the context past the parens. // // The good news is that the parser can disambiguate this part without // making any unnecessary Action calls. // // It uses a scheme similar to parsing inline methods. The parenthesized // tokens are cached, the context that follows is determined (possibly by // parsing a cast-expression), and then we re-introduce the cached tokens // into the token stream and parse them appropriately. ParenParseOption ParseAs; CachedTokens Toks; // Store the tokens of the parentheses. We will parse them after we determine // the context that follows them. if (!ConsumeAndStoreUntil(tok::r_paren, Toks)) { // We didn't find the ')' we expected. Tracker.consumeClose(); return ExprError(); } if (Tok.is(tok::l_brace)) { ParseAs = CompoundLiteral; } else { bool NotCastExpr; if (Tok.is(tok::l_paren) && NextToken().is(tok::r_paren)) { NotCastExpr = true; } else { // Try parsing the cast-expression that may follow. // If it is not a cast-expression, NotCastExpr will be true and no token // will be consumed. ColonProt.restore(); Result = ParseCastExpression(false/*isUnaryExpression*/, false/*isAddressofOperand*/, NotCastExpr, // type-id has priority. IsTypeCast); } // If we parsed a cast-expression, it's really a type-id, otherwise it's // an expression. ParseAs = NotCastExpr ? SimpleExpr : CastExpr; } // The current token should go after the cached tokens. Toks.push_back(Tok); // Re-enter the stored parenthesized tokens into the token stream, so we may // parse them now. PP.EnterTokenStream(Toks.data(), Toks.size(), true/*DisableMacroExpansion*/, false/*OwnsTokens*/); // Drop the current token and bring the first cached one. It's the same token // as when we entered this function. ConsumeAnyToken(); if (ParseAs >= CompoundLiteral) { // Parse the type declarator. DeclSpec DS(AttrFactory); Declarator DeclaratorInfo(DS, Declarator::TypeNameContext); { ColonProtectionRAIIObject InnerColonProtection(*this); ParseSpecifierQualifierList(DS); ParseDeclarator(DeclaratorInfo); } // Match the ')'. Tracker.consumeClose(); ColonProt.restore(); if (ParseAs == CompoundLiteral) { // HLSL Change Starts if (getLangOpts().HLSL) { // (type-name) { initializer-list } Diag(Tok, diag::err_hlsl_unsupported_construct) << "compound literal"; return ExprError(); } // HLSL Change Ends ExprType = CompoundLiteral; if (DeclaratorInfo.isInvalidType()) return ExprError(); TypeResult Ty = Actions.ActOnTypeName(getCurScope(), DeclaratorInfo); return ParseCompoundLiteralExpression(Ty.get(), Tracker.getOpenLocation(), Tracker.getCloseLocation()); } // We parsed '(' type-id ')' and the thing after it wasn't a '{'. assert(ParseAs == CastExpr); if (DeclaratorInfo.isInvalidType()) return ExprError(); // Result is what ParseCastExpression returned earlier. if (!Result.isInvalid()) Result = Actions.ActOnCastExpr(getCurScope(), Tracker.getOpenLocation(), DeclaratorInfo, CastTy, Tracker.getCloseLocation(), Result.get()); return Result; } // Not a compound literal, and not followed by a cast-expression. assert(ParseAs == SimpleExpr); ExprType = SimpleExpr; Result = ParseExpression(); if (!Result.isInvalid() && Tok.is(tok::r_paren)) Result = Actions.ActOnParenExpr(Tracker.getOpenLocation(), Tok.getLocation(), Result.get()); // Match the ')'. if (Result.isInvalid()) { SkipUntil(tok::r_paren, StopAtSemi); return ExprError(); } Tracker.consumeClose(); return Result; }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseStmt.cpp
//===--- ParseStmt.cpp - Statement and Block Parser -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Statement and Block portions of the Parser // interface. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "RAIIObjectsForParser.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/Attributes.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/PrettyStackTrace.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/LoopHint.h" #include "clang/Sema/PrettyDeclStackTrace.h" #include "clang/Sema/Scope.h" #include "clang/Sema/TypoCorrection.h" #include "llvm/ADT/SmallString.h" using namespace clang; //===----------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. //===----------------------------------------------------------------------===// /// \brief Parse a standalone statement (for instance, as the body of an 'if', /// 'while', or 'for'). StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc) { StmtResult Res; // We may get back a null statement if we found a #pragma. Keep going until // we get an actual statement. do { StmtVector Stmts; Res = ParseStatementOrDeclaration(Stmts, true, TrailingElseLoc); } while (!Res.isInvalid() && !Res.get()); return Res; } /// ParseStatementOrDeclaration - Read 'statement' or 'declaration'. /// StatementOrDeclaration: /// statement /// declaration /// /// statement: /// labeled-statement /// compound-statement /// expression-statement /// selection-statement /// iteration-statement /// jump-statement /// [C++] declaration-statement /// [C++] try-block /// [MS] seh-try-block /// [OBC] objc-throw-statement /// [OBC] objc-try-catch-statement /// [OBC] objc-synchronized-statement /// [GNU] asm-statement /// [OMP] openmp-construct [TODO] /// /// labeled-statement: /// identifier ':' statement /// 'case' constant-expression ':' statement /// 'default' ':' statement /// /// selection-statement: /// if-statement /// switch-statement /// /// iteration-statement: /// while-statement /// do-statement /// for-statement /// /// expression-statement: /// expression[opt] ';' /// /// jump-statement: /// 'goto' identifier ';' /// 'continue' ';' /// 'break' ';' /// 'return' expression[opt] ';' /// [GNU] 'goto' '*' expression ';' /// /// [OBC] objc-throw-statement: /// [OBC] '@' 'throw' expression ';' /// [OBC] '@' 'throw' ';' /// StmtResult Parser::ParseStatementOrDeclaration(StmtVector &Stmts, bool OnlyStatement, SourceLocation *TrailingElseLoc) { ParenBraceBracketBalancer BalancerRAIIObj(*this); ParsedAttributesWithRange Attrs(AttrFactory); MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true); MaybeParseHLSLAttributes(Attrs); // HLSL Change StmtResult Res = ParseStatementOrDeclarationAfterAttributes(Stmts, OnlyStatement, TrailingElseLoc, Attrs); assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) && "attributes on empty statement"); if (Attrs.empty() || Res.isInvalid()) return Res; return Actions.ProcessStmtAttributes(Res.get(), Attrs.getList(), Attrs.Range); } namespace { class StatementFilterCCC : public CorrectionCandidateCallback { public: StatementFilterCCC(Token nextTok) : NextToken(nextTok) { WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square, tok::identifier, tok::star, tok::amp); WantExpressionKeywords = nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period); WantRemainingKeywords = nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace); WantCXXNamedCasts = false; } bool ValidateCandidate(const TypoCorrection &candidate) override { if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>()) return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD); if (NextToken.is(tok::equal)) return candidate.getCorrectionDeclAs<VarDecl>(); if (NextToken.is(tok::period) && candidate.getCorrectionDeclAs<NamespaceDecl>()) return false; return CorrectionCandidateCallback::ValidateCandidate(candidate); } private: Token NextToken; }; } StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(StmtVector &Stmts, bool OnlyStatement, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs) { const char *SemiError = nullptr; StmtResult Res; // Cases in this switch statement should fall through if the parser expects // the token to end in a semicolon (in which case SemiError should be set), // or they directly 'return;' if not. Retry: tok::TokenKind Kind = Tok.getKind(); SourceLocation AtLoc; switch (Kind) { case tok::at: // May be a @try or @throw statement { // HLSL Change Starts assert(!getLangOpts().HLSL && "HLSL does not recognize '@' as a token"); if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change Ends ProhibitAttributes(Attrs); // TODO: is it correct? AtLoc = ConsumeToken(); // consume @ return ParseObjCAtStatement(AtLoc); } case tok::code_completion: Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement); cutOffParsing(); return StmtError(); // HLSL Change Starts case tok::kw_precise: case tok::kw_sample: case tok::kw_globallycoherent: case tok::kw_center: case tok::kw_indices: case tok::kw_vertices: case tok::kw_primitives: case tok::kw_payload: { // FXC compatiblity: these are keywords when used as modifiers, but in // FXC they can also be used an identifiers. If the next token is a // punctuator, then we are using them as identifers. Need to change // the token type to tok::identifier and fall through to the next case. // E.g., center = <RHS>. if (!tok::isPunctuator(NextToken().getKind())) { goto tok_default_case; } else { Tok.setKind(tok::identifier); LLVM_FALLTHROUGH; } } // HLSL Change Ends case tok::identifier: { Token Next = NextToken(); if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "label"; SkipUntil(tok::semi); return StmtError(); } // HLSL Change Ends // identifier ':' statement return ParseLabeledStatement(Attrs); } // Look up the identifier, and typo-correct it to a keyword if it's not // found. if (Next.isNot(tok::coloncolon)) { // Try to limit which sets of keywords should be included in typo // correction based on what the next token is. if (TryAnnotateName(/*IsAddressOfOperand*/ false, llvm::make_unique<StatementFilterCCC>(Next)) == ANK_Error) { // Handle errors here by skipping up to the next semicolon or '}', and // eat the semicolon if that's what stopped us. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); if (Tok.is(tok::semi)) ConsumeToken(); return StmtError(); } // If the identifier was typo-corrected, try again. if (Tok.isNot(tok::identifier)) goto Retry; } // Fall through } LLVM_FALLTHROUGH; // HLSL Change default: { tok_default_case: // HLSL Change - add to target cases dead-code'd by HLSL if ((getLangOpts().CPlusPlus || !OnlyStatement) && isDeclarationStatement()) { SourceLocation DeclStart = Tok.getLocation(), DeclEnd; DeclGroupPtrTy Decl = ParseDeclaration(Declarator::BlockContext, DeclEnd, Attrs); return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd); } if (Tok.is(tok::r_brace)) { Diag(Tok, diag::err_expected_statement); return StmtError(); } return ParseExprStatement(); } case tok::kw_case: // C99 6.8.1: labeled-statement return ParseCaseStatement(); case tok::kw_default: // C99 6.8.1: labeled-statement return ParseDefaultStatement(); case tok::l_brace: // C99 6.8.2: compound-statement return ParseCompoundStatement(); case tok::semi: { // C99 6.8.3p3: expression[opt] ';' bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro(); return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro); } case tok::kw_if: // C99 6.8.4.1: if-statement return ParseIfStatement(TrailingElseLoc); case tok::kw_switch: // C99 6.8.4.2: switch-statement return ParseSwitchStatement(TrailingElseLoc); case tok::kw_while: // C99 6.8.5.1: while-statement return ParseWhileStatement(TrailingElseLoc); case tok::kw_do: // C99 6.8.5.2: do-statement Res = ParseDoStatement(); SemiError = "do/while"; break; case tok::kw_for: // C99 6.8.5.3: for-statement return ParseForStatement(TrailingElseLoc); case tok::kw_goto: // C99 6.8.6.1: goto-statement // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "goto"; SkipUntil(tok::semi); return StmtError(); } // HLSL Change Ends Res = ParseGotoStatement(); SemiError = "goto"; break; case tok::kw_continue: // C99 6.8.6.2: continue-statement Res = ParseContinueStatement(); SemiError = "continue"; break; case tok::kw_break: // C99 6.8.6.3: break-statement Res = ParseBreakStatement(); SemiError = "break"; break; case tok::kw_return: // C99 6.8.6.4: return-statement Res = ParseReturnStatement(); SemiError = "return"; break; case tok::kw_asm: { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); SkipUntil(tok::semi); return StmtError(); } // HLSL Change Ends ProhibitAttributes(Attrs); bool msAsm = false; Res = ParseAsmStatement(msAsm); Res = Actions.ActOnFinishFullStmt(Res.get()); if (msAsm) return Res; SemiError = "asm"; break; } case tok::kw___if_exists: case tok::kw___if_not_exists: ProhibitAttributes(Attrs); ParseMicrosoftIfExistsStatement(Stmts); // An __if_exists block is like a compound statement, but it doesn't create // a new scope. return StmtEmpty(); case tok::kw_try: // C++ 15: try-block // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_reserved_keyword) << Tok.getName(); SkipUntil(tok::semi); return StmtError(); } // HLSL Change Ends return ParseCXXTryBlock(); case tok::kw___try: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); // TODO: is it correct? return ParseSEHTryBlock(); case tok::kw___leave: Res = ParseSEHLeaveStatement(); SemiError = "__leave"; break; case tok::annot_pragma_vis: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); HandlePragmaVisibility(); return StmtEmpty(); case tok::annot_pragma_pack: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); HandlePragmaPack(); return StmtEmpty(); case tok::annot_pragma_msstruct: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); HandlePragmaMSStruct(); return StmtEmpty(); case tok::annot_pragma_align: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); HandlePragmaAlign(); return StmtEmpty(); case tok::annot_pragma_weak: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); HandlePragmaWeak(); return StmtEmpty(); case tok::annot_pragma_weakalias: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); HandlePragmaWeakAlias(); return StmtEmpty(); case tok::annot_pragma_redefine_extname: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); HandlePragmaRedefineExtname(); return StmtEmpty(); case tok::annot_pragma_fp_contract: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); Diag(Tok, diag::err_pragma_fp_contract_scope); ConsumeToken(); return StmtError(); case tok::annot_pragma_opencl_extension: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); HandlePragmaOpenCLExtension(); return StmtEmpty(); case tok::annot_pragma_captured: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); return HandlePragmaCaptured(); case tok::annot_pragma_openmp: if (getLangOpts().HLSL) goto tok_default_case; // HLSL Change - remove unsupported case ProhibitAttributes(Attrs); return ParseOpenMPDeclarativeOrExecutableDirective(!OnlyStatement); // HLSL Change Starts case tok::kw_discard: return HandleHLSLDiscardStmt(ExprResult(false).get()); // HLSL Change Ends case tok::annot_pragma_ms_pointers_to_members: ProhibitAttributes(Attrs); HandlePragmaMSPointersToMembers(); return StmtEmpty(); case tok::annot_pragma_ms_pragma: ProhibitAttributes(Attrs); HandlePragmaMSPragma(); return StmtEmpty(); case tok::annot_pragma_loop_hint: ProhibitAttributes(Attrs); return ParsePragmaLoopHint(Stmts, OnlyStatement, TrailingElseLoc, Attrs); } // If we reached this code, the statement must end in a semicolon. if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) { // If the result was valid, then we do want to diagnose this. Use // ExpectAndConsume to emit the diagnostic, even though we know it won't // succeed. ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError); // Skip until we see a } or ;, but don't eat it. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); } return Res; } /// \brief Parse an expression statement. StmtResult Parser::ParseExprStatement() { // If a case keyword is missing, this is where it should be inserted. Token OldToken = Tok; // expression[opt] ';' ExprResult Expr(ParseExpression()); if (Expr.isInvalid()) { // If the expression is invalid, skip ahead to the next semicolon or '}'. // Not doing this opens us up to the possibility of infinite loops if // ParseExpression does not consume any tokens. SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); if (Tok.is(tok::semi)) ConsumeToken(); return Actions.ActOnExprStmtError(); } if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() && Actions.CheckCaseExpression(Expr.get())) { // If a constant expression is followed by a colon inside a switch block, // suggest a missing case keyword. Diag(OldToken, diag::err_expected_case_before_expression) << FixItHint::CreateInsertion(OldToken.getLocation(), "case "); // Recover parsing as a case statement. return ParseCaseStatement(/*MissingCase=*/true, Expr); } // Otherwise, eat the semicolon. ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); return Actions.ActOnExprStmt(Expr); } /// ParseSEHTryBlockCommon /// /// seh-try-block: /// '__try' compound-statement seh-handler /// /// seh-handler: /// seh-except-block /// seh-finally-block /// StmtResult Parser::ParseSEHTryBlock() { assert(!getLangOpts().HLSL && "no exception parsing support in HLSL"); // HLSL Change assert(Tok.is(tok::kw___try) && "Expected '__try'"); SourceLocation TryLoc = ConsumeToken(); if (Tok.isNot(tok::l_brace)) return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace); StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false, Scope::DeclScope | Scope::SEHTryScope)); if(TryBlock.isInvalid()) return TryBlock; StmtResult Handler; if (Tok.is(tok::identifier) && Tok.getIdentifierInfo() == getSEHExceptKeyword()) { SourceLocation Loc = ConsumeToken(); Handler = ParseSEHExceptBlock(Loc); } else if (Tok.is(tok::kw___finally)) { SourceLocation Loc = ConsumeToken(); Handler = ParseSEHFinallyBlock(Loc); } else { return StmtError(Diag(Tok, diag::err_seh_expected_handler)); } if(Handler.isInvalid()) return Handler; return Actions.ActOnSEHTryBlock(false /* IsCXXTry */, TryLoc, TryBlock.get(), Handler.get()); } /// ParseSEHExceptBlock - Handle __except /// /// seh-except-block: /// '__except' '(' seh-filter-expression ')' compound-statement /// StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) { assert(!getLangOpts().HLSL && "no exception parsing support in HLSL"); // HLSL Change PoisonIdentifierRAIIObject raii(Ident__exception_code, false), raii2(Ident___exception_code, false), raii3(Ident_GetExceptionCode, false); if (ExpectAndConsume(tok::l_paren)) return StmtError(); ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope | Scope::SEHExceptScope); if (getLangOpts().Borland) { Ident__exception_info->setIsPoisoned(false); Ident___exception_info->setIsPoisoned(false); Ident_GetExceptionInfo->setIsPoisoned(false); } ExprResult FilterExpr; { ParseScopeFlags FilterScope(this, getCurScope()->getFlags() | Scope::SEHFilterScope); FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression()); } if (getLangOpts().Borland) { Ident__exception_info->setIsPoisoned(true); Ident___exception_info->setIsPoisoned(true); Ident_GetExceptionInfo->setIsPoisoned(true); } if(FilterExpr.isInvalid()) return StmtError(); if (ExpectAndConsume(tok::r_paren)) return StmtError(); if (Tok.isNot(tok::l_brace)) return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace); StmtResult Block(ParseCompoundStatement()); if(Block.isInvalid()) return Block; return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get()); } /// ParseSEHFinallyBlock - Handle __finally /// /// seh-finally-block: /// '__finally' compound-statement /// StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) { assert(!getLangOpts().HLSL && "no exception parsing support in HLSL"); // HLSL Change PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false), raii2(Ident___abnormal_termination, false), raii3(Ident_AbnormalTermination, false); if (Tok.isNot(tok::l_brace)) return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace); ParseScope FinallyScope(this, 0); Actions.ActOnStartSEHFinallyBlock(); StmtResult Block(ParseCompoundStatement()); if(Block.isInvalid()) { Actions.ActOnAbortSEHFinallyBlock(); return Block; } return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get()); } /// Handle __leave /// /// seh-leave-statement: /// '__leave' ';' /// StmtResult Parser::ParseSEHLeaveStatement() { assert(!getLangOpts().HLSL && "no exception parsing support in HLSL"); // HLSL Change SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'. return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope()); } /// ParseLabeledStatement - We have an identifier and a ':' after it. /// /// labeled-statement: /// identifier ':' statement /// [GNU] identifier ':' attributes[opt] statement /// StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs) { assert(!getLangOpts().HLSL && "no label parsing support in HLSL (case and default handled elsewhere)"); // HLSL Change assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() && "Not an identifier!"); Token IdentTok = Tok; // Save the whole token. ConsumeToken(); // eat the identifier. assert(Tok.is(tok::colon) && "Not a label!"); // identifier ':' statement SourceLocation ColonLoc = ConsumeToken(); // Read label attributes, if present. StmtResult SubStmt; if (Tok.is(tok::kw___attribute)) { ParsedAttributesWithRange TempAttrs(AttrFactory); ParseGNUAttributes(TempAttrs); // In C++, GNU attributes only apply to the label if they are followed by a // semicolon, to disambiguate label attributes from attributes on a labeled // declaration. // // This doesn't quite match what GCC does; if the attribute list is empty // and followed by a semicolon, GCC will reject (it appears to parse the // attributes as part of a statement in that case). That looks like a bug. if (!getLangOpts().CPlusPlus || Tok.is(tok::semi)) attrs.takeAllFrom(TempAttrs); else if (isDeclarationStatement()) { StmtVector Stmts; // FIXME: We should do this whether or not we have a declaration // statement, but that doesn't work correctly (because ProhibitAttributes // can't handle GNU attributes), so only call it in the one case where // GNU attributes are allowed. SubStmt = ParseStatementOrDeclarationAfterAttributes( Stmts, /*OnlyStmts*/ true, nullptr, TempAttrs); if (!TempAttrs.empty() && !SubStmt.isInvalid()) SubStmt = Actions.ProcessStmtAttributes( SubStmt.get(), TempAttrs.getList(), TempAttrs.Range); } else { Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi; } } // If we've not parsed a statement yet, parse one now. if (!SubStmt.isInvalid() && !SubStmt.isUsable()) SubStmt = ParseStatement(); // Broken substmt shouldn't prevent the label from being added to the AST. if (SubStmt.isInvalid()) SubStmt = Actions.ActOnNullStmt(ColonLoc); LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(), IdentTok.getLocation()); if (AttributeList *Attrs = attrs.getList()) { Actions.ProcessDeclAttributeList(Actions.CurScope, LD, Attrs); attrs.clear(); } return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc, SubStmt.get()); } /// ParseCaseStatement /// labeled-statement: /// 'case' constant-expression ':' statement /// [GNU] 'case' constant-expression '...' constant-expression ':' statement /// StmtResult Parser::ParseCaseStatement(bool MissingCase, ExprResult Expr) { assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!"); // It is very very common for code to contain many case statements recursively // nested, as in (but usually without indentation): // case 1: // case 2: // case 3: // case 4: // case 5: etc. // // Parsing this naively works, but is both inefficient and can cause us to run // out of stack space in our recursive descent parser. As a special case, // flatten this recursion into an iterative loop. This is complex and gross, // but all the grossness is constrained to ParseCaseStatement (and some // weirdness in the actions), so this is just local grossness :). // TopLevelCase - This is the highest level we have parsed. 'case 1' in the // example above. StmtResult TopLevelCase(true); // DeepestParsedCaseStmt - This is the deepest statement we have parsed, which // gets updated each time a new case is parsed, and whose body is unset so // far. When parsing 'case 4', this is the 'case 3' node. Stmt *DeepestParsedCaseStmt = nullptr; // While we have case statements, eat and stack them. SourceLocation ColonLoc; do { SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() : ConsumeToken(); // eat the 'case'. ColonLoc = SourceLocation(); if (Tok.is(tok::code_completion)) { Actions.CodeCompleteCase(getCurScope()); cutOffParsing(); return StmtError(); } /// We don't want to treat 'case x : y' as a potential typo for 'case x::y'. /// Disable this form of error recovery while we're parsing the case /// expression. ColonProtectionRAIIObject ColonProtection(*this); ExprResult LHS; if (!MissingCase) { LHS = ParseConstantExpression(); if (!getLangOpts().CPlusPlus11) { LHS = Actions.CorrectDelayedTyposInExpr(LHS, [this](class Expr *E) { return Actions.VerifyIntegerConstantExpression(E); }); } if (LHS.isInvalid()) { // If constant-expression is parsed unsuccessfully, recover by skipping // current case statement (moving to the colon that ends it). if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) { TryConsumeToken(tok::colon, ColonLoc); continue; } return StmtError(); } } else { LHS = Expr; MissingCase = false; } // GNU case range extension. SourceLocation DotDotDotLoc; ExprResult RHS; if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) { // HLSL Change Starts - disallow range extension if (getLangOpts().HLSL) { Diag(DotDotDotLoc, diag::err_hlsl_unsupported_construct) << "case range"; } else { // HLSL Change Ends - next line is now conditional Diag(DotDotDotLoc, diag::ext_gnu_case_range); } // HLSL Change - close conditional RHS = ParseConstantExpression(); if (RHS.isInvalid()) { if (SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch)) { TryConsumeToken(tok::colon, ColonLoc); continue; } return StmtError(); } } ColonProtection.restore(); if (TryConsumeToken(tok::colon, ColonLoc)) { } else if (TryConsumeToken(tok::semi, ColonLoc) || TryConsumeToken(tok::coloncolon, ColonLoc)) { // Treat "case blah;" or "case blah::" as a typo for "case blah:". Diag(ColonLoc, diag::err_expected_after) << "'case'" << tok::colon << FixItHint::CreateReplacement(ColonLoc, ":"); } else { SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation); Diag(ExpectedLoc, diag::err_expected_after) << "'case'" << tok::colon << FixItHint::CreateInsertion(ExpectedLoc, ":"); ColonLoc = ExpectedLoc; } StmtResult Case = Actions.ActOnCaseStmt(CaseLoc, LHS.get(), DotDotDotLoc, RHS.get(), ColonLoc); // If we had a sema error parsing this case, then just ignore it and // continue parsing the sub-stmt. if (Case.isInvalid()) { if (TopLevelCase.isInvalid()) // No parsed case stmts. return ParseStatement(); // Otherwise, just don't add it as a nested case. } else { // If this is the first case statement we parsed, it becomes TopLevelCase. // Otherwise we link it into the current chain. Stmt *NextDeepest = Case.get(); if (TopLevelCase.isInvalid()) TopLevelCase = Case; else Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get()); DeepestParsedCaseStmt = NextDeepest; } // Handle all case statements. } while (Tok.is(tok::kw_case)); // If we found a non-case statement, start by parsing it. StmtResult SubStmt; if (Tok.isNot(tok::r_brace)) { SubStmt = ParseStatement(); } else { // Nicely diagnose the common error "switch (X) { case 4: }", which is // not valid. If ColonLoc doesn't point to a valid text location, there was // another parsing error, so avoid producing extra diagnostics. if (ColonLoc.isValid()) { SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc); Diag(AfterColonLoc, diag::err_label_end_of_compound_statement) << FixItHint::CreateInsertion(AfterColonLoc, " ;"); } SubStmt = StmtError(); } // Install the body into the most deeply-nested case. if (DeepestParsedCaseStmt) { // Broken sub-stmt shouldn't prevent forming the case statement properly. if (SubStmt.isInvalid()) SubStmt = Actions.ActOnNullStmt(SourceLocation()); Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get()); } // Return the top level parsed statement tree. return TopLevelCase; } /// ParseDefaultStatement /// labeled-statement: /// 'default' ':' statement /// Note that this does not parse the 'statement' at the end. /// StmtResult Parser::ParseDefaultStatement() { assert(Tok.is(tok::kw_default) && "Not a default stmt!"); SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'. SourceLocation ColonLoc; if (TryConsumeToken(tok::colon, ColonLoc)) { } else if (TryConsumeToken(tok::semi, ColonLoc)) { // Treat "default;" as a typo for "default:". Diag(ColonLoc, diag::err_expected_after) << "'default'" << tok::colon << FixItHint::CreateReplacement(ColonLoc, ":"); } else { SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation); Diag(ExpectedLoc, diag::err_expected_after) << "'default'" << tok::colon << FixItHint::CreateInsertion(ExpectedLoc, ":"); ColonLoc = ExpectedLoc; } StmtResult SubStmt; if (Tok.isNot(tok::r_brace)) { SubStmt = ParseStatement(); } else { // Diagnose the common error "switch (X) {... default: }", which is // not valid. SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc); Diag(AfterColonLoc, diag::err_label_end_of_compound_statement) << FixItHint::CreateInsertion(AfterColonLoc, " ;"); SubStmt = true; } // Broken sub-stmt shouldn't prevent forming the case statement properly. if (SubStmt.isInvalid()) SubStmt = Actions.ActOnNullStmt(ColonLoc); return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt.get(), getCurScope()); } StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) { return ParseCompoundStatement(isStmtExpr, Scope::DeclScope); } /// ParseCompoundStatement - Parse a "{}" block. /// /// compound-statement: [C99 6.8.2] /// { block-item-list[opt] } /// [GNU] { label-declarations block-item-list } [TODO] /// /// block-item-list: /// block-item /// block-item-list block-item /// /// block-item: /// declaration /// [GNU] '__extension__' declaration /// statement /// /// [GNU] label-declarations: /// [GNU] label-declaration /// [GNU] label-declarations label-declaration /// /// [GNU] label-declaration: /// [GNU] '__label__' identifier-list ';' /// StmtResult Parser::ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags) { assert(Tok.is(tok::l_brace) && "Not a compount stmt!"); // Enter a scope to hold everything within the compound stmt. Compound // statements can always hold declarations. ParseScope CompoundScope(this, ScopeFlags); // Parse the statements in the body. return ParseCompoundStatementBody(isStmtExpr); } /// Parse any pragmas at the start of the compound expression. We handle these /// separately since some pragmas (FP_CONTRACT) must appear before any C /// statement in the compound, but may be intermingled with other pragmas. void Parser::ParseCompoundStatementLeadingPragmas() { if (getLangOpts().HLSL) return; // HLSL Change - none of these pragmas are supported bool checkForPragmas = true; while (checkForPragmas) { switch (Tok.getKind()) { case tok::annot_pragma_vis: HandlePragmaVisibility(); break; case tok::annot_pragma_pack: HandlePragmaPack(); break; case tok::annot_pragma_msstruct: HandlePragmaMSStruct(); break; case tok::annot_pragma_align: HandlePragmaAlign(); break; case tok::annot_pragma_weak: HandlePragmaWeak(); break; case tok::annot_pragma_weakalias: HandlePragmaWeakAlias(); break; case tok::annot_pragma_redefine_extname: HandlePragmaRedefineExtname(); break; case tok::annot_pragma_opencl_extension: HandlePragmaOpenCLExtension(); break; case tok::annot_pragma_fp_contract: HandlePragmaFPContract(); break; case tok::annot_pragma_ms_pointers_to_members: HandlePragmaMSPointersToMembers(); break; case tok::annot_pragma_ms_pragma: HandlePragmaMSPragma(); break; default: checkForPragmas = false; break; } } } /// ParseCompoundStatementBody - Parse a sequence of statements and invoke the /// ActOnCompoundStmt action. This expects the '{' to be the current token, and /// consume the '}' at the end of the block. It does not manipulate the scope /// stack. StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) { PrettyStackTraceLoc CrashInfo(PP.getSourceManager(), Tok.getLocation(), "in compound statement ('{}')"); // Record the state of the FP_CONTRACT pragma, restore on leaving the // compound statement. Sema::FPContractStateRAII SaveFPContractState(Actions); InMessageExpressionRAIIObject InMessage(*this, false); BalancedDelimiterTracker T(*this, tok::l_brace); if (T.consumeOpen()) return StmtError(); Sema::CompoundScopeRAII CompoundScope(Actions); // Parse any pragmas at the beginning of the compound statement. ParseCompoundStatementLeadingPragmas(); StmtVector Stmts; // "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are // only allowed at the start of a compound stmt regardless of the language. while (Tok.is(tok::kw___label__)) { // HLSL Change Starts if (getLangOpts().HLSL) { Diag(Tok, diag::err_hlsl_unsupported_construct) << "local label"; SkipUntil(tok::semi); break; } // HLSL Change Ends SourceLocation LabelLoc = ConsumeToken(); SmallVector<Decl *, 8> DeclsInGroup; while (1) { if (Tok.isNot(tok::identifier)) { Diag(Tok, diag::err_expected) << tok::identifier; break; } IdentifierInfo *II = Tok.getIdentifierInfo(); SourceLocation IdLoc = ConsumeToken(); DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc)); if (!TryConsumeToken(tok::comma)) break; } DeclSpec DS(AttrFactory); DeclGroupPtrTy Res = Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup); StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation()); ExpectAndConsumeSemi(diag::err_expected_semi_declaration); if (R.isUsable()) Stmts.push_back(R.get()); } while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { if (!getLangOpts().HLSL && Tok.is(tok::annot_pragma_unused)) { // HLSL Change - annot_pragma_unused is not produced in HLSL HandlePragmaUnused(); continue; } StmtResult R; if (Tok.isNot(tok::kw___extension__)) { R = ParseStatementOrDeclaration(Stmts, false); } else { // __extension__ can start declarations and it can also be a unary // operator for expressions. Consume multiple __extension__ markers here // until we can determine which is which. // FIXME: This loses extension expressions in the AST! SourceLocation ExtLoc = ConsumeToken(); while (Tok.is(tok::kw___extension__)) ConsumeToken(); ParsedAttributesWithRange attrs(AttrFactory); MaybeParseCXX11Attributes(attrs, nullptr, /*MightBeObjCMessageSend*/ true); MaybeParseHLSLAttributes(attrs); // HLSL Change // If this is the start of a declaration, parse it as such. if (isDeclarationStatement()) { // __extension__ silences extension warnings in the subdeclaration. // FIXME: Save the __extension__ on the decl as a node somehow? ExtensionRAIIObject O(Diags); SourceLocation DeclStart = Tok.getLocation(), DeclEnd; DeclGroupPtrTy Res = ParseDeclaration(Declarator::BlockContext, DeclEnd, attrs); R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd); } else { // Otherwise this was a unary __extension__ marker. ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc)); if (Res.isInvalid()) { SkipUntil(tok::semi); continue; } // FIXME: Use attributes? // Eat the semicolon at the end of stmt and convert the expr into a // statement. ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); R = Actions.ActOnExprStmt(Res); } } if (R.isUsable()) Stmts.push_back(R.get()); } SourceLocation CloseLoc = Tok.getLocation(); // We broke out of the while loop because we found a '}' or EOF. if (!T.consumeClose()) // Recover by creating a compound statement with what we parsed so far, // instead of dropping everything and returning StmtError(); CloseLoc = T.getCloseLocation(); return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc, Stmts, isStmtExpr); } /// ParseParenExprOrCondition: /// [C ] '(' expression ')' /// [C++] '(' condition ')' [not allowed if OnlyAllowCondition=true] /// /// This function parses and performs error recovery on the specified condition /// or expression (depending on whether we're in C++ or C mode). This function /// goes out of its way to recover well. It returns true if there was a parser /// error (the right paren couldn't be found), which indicates that the caller /// should try to recover harder. It returns false if the condition is /// successfully parsed. Note that a successful parse can still have semantic /// errors in the condition. bool Parser::ParseParenExprOrCondition(ExprResult &ExprResult, Decl *&DeclResult, SourceLocation Loc, bool ConvertToBoolean) { BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); if (getLangOpts().CPlusPlus) ParseCXXCondition(ExprResult, DeclResult, Loc, ConvertToBoolean); else { ExprResult = ParseExpression(); DeclResult = nullptr; // If required, convert to a boolean value. if (!ExprResult.isInvalid() && ConvertToBoolean) ExprResult = Actions.ActOnBooleanCondition(getCurScope(), Loc, ExprResult.get()); } // If the parser was confused by the condition and we don't have a ')', try to // recover by skipping ahead to a semi and bailing out. If condexp is // semantically invalid but we have well formed code, keep going. if (ExprResult.isInvalid() && !DeclResult && Tok.isNot(tok::r_paren)) { SkipUntil(tok::semi); // Skipping may have stopped if it found the containing ')'. If so, we can // continue parsing the if statement. if (Tok.isNot(tok::r_paren)) return true; } // Otherwise the condition is valid or the rparen is present. T.consumeClose(); // Check for extraneous ')'s to catch things like "if (foo())) {". We know // that all callers are looking for a statement after the condition, so ")" // isn't valid. while (Tok.is(tok::r_paren)) { Diag(Tok, diag::err_extraneous_rparen_in_condition) << FixItHint::CreateRemoval(Tok.getLocation()); ConsumeParen(); } return false; } /// ParseIfStatement /// if-statement: [C99 6.8.4.1] /// 'if' '(' expression ')' statement /// 'if' '(' expression ')' statement 'else' statement /// [C++] 'if' '(' condition ')' statement /// [C++] 'if' '(' condition ')' statement 'else' statement /// StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) { assert(Tok.is(tok::kw_if) && "Not an if stmt!"); SourceLocation IfLoc = ConsumeToken(); // eat the 'if'. if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen_after) << "if"; SkipUntil(tok::semi); return StmtError(); } bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; // C99 6.8.4p3 - In C99, the if statement is a block. This is not // the case for C90. // // C++ 6.4p3: // A name introduced by a declaration in a condition is in scope from its // point of declaration until the end of the substatements controlled by the // condition. // C++ 3.3.2p4: // Names declared in the for-init-statement, and in the condition of if, // while, for, and switch statements are local to the if, while, for, or // switch statement (including the controlled statement). // ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX); // Parse the condition. ExprResult CondExp; Decl *CondVar = nullptr; if (ParseParenExprOrCondition(CondExp, CondVar, IfLoc, true)) return StmtError(); FullExprArg FullCondExp(Actions.MakeFullExpr(CondExp.get(), IfLoc)); // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if // there is no compound stmt. C90 does not have this clause. We only do this // if the body isn't a compound statement to avoid push/pop in common cases. // // C++ 6.4p1: // The substatement in a selection-statement (each substatement, in the else // form of the if statement) implicitly defines a local scope. // // For C++ we create a scope for the condition and a new scope for // substatements because: // -When the 'then' scope exits, we want the condition declaration to still be // active for the 'else' scope too. // -Sema will detect name clashes by considering declarations of a // 'ControlScope' as part of its direct subscope. // -If we wanted the condition and substatement to be in the same scope, we // would have to notify ParseStatement not to create a new scope. It's // simpler to let it create a new scope. // ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); // Read the 'then' stmt. SourceLocation ThenStmtLoc = Tok.getLocation(); SourceLocation InnerStatementTrailingElseLoc; StmtResult ThenStmt(ParseStatement(&InnerStatementTrailingElseLoc)); // Pop the 'if' scope if needed. InnerScope.Exit(); // If it has an else, parse it. SourceLocation ElseLoc; SourceLocation ElseStmtLoc; StmtResult ElseStmt; if (Tok.is(tok::kw_else)) { if (TrailingElseLoc) *TrailingElseLoc = Tok.getLocation(); ElseLoc = ConsumeToken(); ElseStmtLoc = Tok.getLocation(); // C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if // there is no compound stmt. C90 does not have this clause. We only do // this if the body isn't a compound statement to avoid push/pop in common // cases. // // C++ 6.4p1: // The substatement in a selection-statement (each substatement, in the else // form of the if statement) implicitly defines a local scope. // ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); ElseStmt = ParseStatement(); // Pop the 'else' scope if needed. InnerScope.Exit(); } else if (Tok.is(tok::code_completion)) { Actions.CodeCompleteAfterIf(getCurScope()); cutOffParsing(); return StmtError(); } else if (InnerStatementTrailingElseLoc.isValid()) { Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else); } IfScope.Exit(); // If the then or else stmt is invalid and the other is valid (and present), // make turn the invalid one into a null stmt to avoid dropping the other // part. If both are invalid, return error. if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) || (ThenStmt.isInvalid() && ElseStmt.get() == nullptr) || (ThenStmt.get() == nullptr && ElseStmt.isInvalid())) { // Both invalid, or one is invalid and other is non-present: return error. return StmtError(); } // Now if either are invalid, replace with a ';'. if (ThenStmt.isInvalid()) ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc); if (ElseStmt.isInvalid()) ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc); return Actions.ActOnIfStmt(IfLoc, FullCondExp, CondVar, ThenStmt.get(), ElseLoc, ElseStmt.get()); } /// ParseSwitchStatement /// switch-statement: /// 'switch' '(' expression ')' statement /// [C++] 'switch' '(' condition ')' statement StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) { assert(Tok.is(tok::kw_switch) && "Not a switch stmt!"); SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'. if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen_after) << "switch"; SkipUntil(tok::semi); return StmtError(); } bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; // C99 6.8.4p3 - In C99, the switch statement is a block. This is // not the case for C90. Start the switch scope. // // C++ 6.4p3: // A name introduced by a declaration in a condition is in scope from its // point of declaration until the end of the substatements controlled by the // condition. // C++ 3.3.2p4: // Names declared in the for-init-statement, and in the condition of if, // while, for, and switch statements are local to the if, while, for, or // switch statement (including the controlled statement). // unsigned ScopeFlags = Scope::SwitchScope; if (C99orCXX) ScopeFlags |= Scope::DeclScope | Scope::ControlScope; ParseScope SwitchScope(this, ScopeFlags); // Parse the condition. ExprResult Cond; Decl *CondVar = nullptr; if (ParseParenExprOrCondition(Cond, CondVar, SwitchLoc, false)) return StmtError(); StmtResult Switch = Actions.ActOnStartOfSwitchStmt(SwitchLoc, Cond.get(), CondVar); if (Switch.isInvalid()) { // Skip the switch body. // FIXME: This is not optimal recovery, but parsing the body is more // dangerous due to the presence of case and default statements, which // will have no place to connect back with the switch. if (Tok.is(tok::l_brace)) { ConsumeBrace(); SkipUntil(tok::r_brace); } else SkipUntil(tok::semi); return Switch; } // C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if // there is no compound stmt. C90 does not have this clause. We only do this // if the body isn't a compound statement to avoid push/pop in common cases. // // C++ 6.4p1: // The substatement in a selection-statement (each substatement, in the else // form of the if statement) implicitly defines a local scope. // // See comments in ParseIfStatement for why we create a scope for the // condition and a new scope for substatement in C++. // getCurScope()->AddFlags(Scope::BreakScope); ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); // We have incremented the mangling number for the SwitchScope and the // InnerScope, which is one too many. if (C99orCXX) getCurScope()->decrementMSManglingNumber(); // Read the body statement. StmtResult Body(ParseStatement(TrailingElseLoc)); // Pop the scopes. InnerScope.Exit(); SwitchScope.Exit(); return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get()); } /// ParseWhileStatement /// while-statement: [C99 6.8.5.1] /// 'while' '(' expression ')' statement /// [C++] 'while' '(' condition ')' statement StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) { assert(Tok.is(tok::kw_while) && "Not a while stmt!"); SourceLocation WhileLoc = Tok.getLocation(); ConsumeToken(); // eat the 'while'. if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen_after) << "while"; SkipUntil(tok::semi); return StmtError(); } bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; // C99 6.8.5p5 - In C99, the while statement is a block. This is not // the case for C90. Start the loop scope. // // C++ 6.4p3: // A name introduced by a declaration in a condition is in scope from its // point of declaration until the end of the substatements controlled by the // condition. // C++ 3.3.2p4: // Names declared in the for-init-statement, and in the condition of if, // while, for, and switch statements are local to the if, while, for, or // switch statement (including the controlled statement). // unsigned ScopeFlags; if (C99orCXX) ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope | Scope::ControlScope; else ScopeFlags = Scope::BreakScope | Scope::ContinueScope; ParseScope WhileScope(this, ScopeFlags); // Parse the condition. ExprResult Cond; Decl *CondVar = nullptr; if (ParseParenExprOrCondition(Cond, CondVar, WhileLoc, true)) return StmtError(); FullExprArg FullCond(Actions.MakeFullExpr(Cond.get(), WhileLoc)); // C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if // there is no compound stmt. C90 does not have this clause. We only do this // if the body isn't a compound statement to avoid push/pop in common cases. // // C++ 6.5p2: // The substatement in an iteration-statement implicitly defines a local scope // which is entered and exited each time through the loop. // // See comments in ParseIfStatement for why we create a scope for the // condition and a new scope for substatement in C++. // ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); // Read the body statement. StmtResult Body(ParseStatement(TrailingElseLoc)); // Pop the body scope if needed. InnerScope.Exit(); WhileScope.Exit(); if ((Cond.isInvalid() && !CondVar) || Body.isInvalid()) return StmtError(); return Actions.ActOnWhileStmt(WhileLoc, FullCond, CondVar, Body.get()); } /// ParseDoStatement /// do-statement: [C99 6.8.5.2] /// 'do' statement 'while' '(' expression ')' ';' /// Note: this lets the caller parse the end ';'. StmtResult Parser::ParseDoStatement() { assert(Tok.is(tok::kw_do) && "Not a do stmt!"); SourceLocation DoLoc = ConsumeToken(); // eat the 'do'. // C99 6.8.5p5 - In C99, the do statement is a block. This is not // the case for C90. Start the loop scope. unsigned ScopeFlags; if (getLangOpts().C99) ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope; else ScopeFlags = Scope::BreakScope | Scope::ContinueScope; ParseScope DoScope(this, ScopeFlags); // C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if // there is no compound stmt. C90 does not have this clause. We only do this // if the body isn't a compound statement to avoid push/pop in common cases. // // C++ 6.5p2: // The substatement in an iteration-statement implicitly defines a local scope // which is entered and exited each time through the loop. // bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus; ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace)); // Read the body statement. StmtResult Body(ParseStatement()); // Pop the body scope if needed. InnerScope.Exit(); if (Tok.isNot(tok::kw_while)) { if (!Body.isInvalid()) { Diag(Tok, diag::err_expected_while); Diag(DoLoc, diag::note_matching) << "'do'"; SkipUntil(tok::semi, StopBeforeMatch); } return StmtError(); } SourceLocation WhileLoc = ConsumeToken(); if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen_after) << "do/while"; SkipUntil(tok::semi, StopBeforeMatch); return StmtError(); } // Parse the parenthesized expression. BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); // A do-while expression is not a condition, so can't have attributes. DiagnoseAndSkipCXX11Attributes(); ExprResult Cond = ParseExpression(); T.consumeClose(); DoScope.Exit(); if (Cond.isInvalid() || Body.isInvalid()) return StmtError(); return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(), Cond.get(), T.getCloseLocation()); } bool Parser::isForRangeIdentifier() { assert(Tok.is(tok::identifier)); const Token &Next = NextToken(); if (Next.is(tok::colon)) return true; if (Next.isOneOf(tok::l_square, tok::kw_alignas)) { TentativeParsingAction PA(*this); ConsumeToken(); SkipCXX11Attributes(); bool Result = Tok.is(tok::colon); PA.Revert(); return Result; } return false; } /// ParseForStatement /// for-statement: [C99 6.8.5.3] /// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement /// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement /// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')' /// [C++] statement /// [C++0x] 'for' '(' for-range-declaration : for-range-initializer ) statement /// [OBJC2] 'for' '(' declaration 'in' expr ')' statement /// [OBJC2] 'for' '(' expr 'in' expr ')' statement /// /// [C++] for-init-statement: /// [C++] expression-statement /// [C++] simple-declaration /// /// [C++0x] for-range-declaration: /// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator /// [C++0x] for-range-initializer: /// [C++0x] expression /// [C++0x] braced-init-list [TODO] StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) { assert(Tok.is(tok::kw_for) && "Not a for stmt!"); SourceLocation ForLoc = ConsumeToken(); // eat the 'for'. if (Tok.isNot(tok::l_paren)) { Diag(Tok, diag::err_expected_lparen_after) << "for"; SkipUntil(tok::semi); return StmtError(); } bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus || getLangOpts().ObjC1; // C99 6.8.5p5 - In C99, the for statement is a block. This is not // the case for C90. Start the loop scope. // // C++ 6.4p3: // A name introduced by a declaration in a condition is in scope from its // point of declaration until the end of the substatements controlled by the // condition. // C++ 3.3.2p4: // Names declared in the for-init-statement, and in the condition of if, // while, for, and switch statements are local to the if, while, for, or // switch statement (including the controlled statement). // C++ 6.5.3p1: // Names declared in the for-init-statement are in the same declarative-region // as those declared in the condition. // unsigned ScopeFlags = 0; if (C99orCXXorObjC) ScopeFlags = Scope::DeclScope | Scope::ControlScope; // HLSL Change Starts - leak declarations in for control parts into outer scope if (getLangOpts().HLSLVersion < hlsl::LangStd::v2021) { ScopeFlags = Scope::ForDeclScope; } // HLSL Change Ends ParseScope ForScope(this, ScopeFlags); BalancedDelimiterTracker T(*this, tok::l_paren); T.consumeOpen(); ExprResult Value; bool ForEach = false, ForRange = false; StmtResult FirstPart; bool SecondPartIsInvalid = false; FullExprArg SecondPart(Actions); ExprResult Collection; ForRangeInit ForRangeInit; FullExprArg ThirdPart(Actions); Decl *SecondVar = nullptr; if (Tok.is(tok::code_completion)) { Actions.CodeCompleteOrdinaryName(getCurScope(), C99orCXXorObjC? Sema::PCC_ForInit : Sema::PCC_Expression); cutOffParsing(); return StmtError(); } ParsedAttributesWithRange attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); // HLSL Change: comment only - MaybeParseHLSLAttributes would go here if allowed at this point // Parse the first part of the for specifier. if (Tok.is(tok::semi)) { // for (; ProhibitAttributes(attrs); // no first part, eat the ';'. ConsumeToken(); } else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) && isForRangeIdentifier() && !getLangOpts().HLSL) { // HLSL Change - disallow for-range ProhibitAttributes(attrs); IdentifierInfo *Name = Tok.getIdentifierInfo(); SourceLocation Loc = ConsumeToken(); MaybeParseCXX11Attributes(attrs); ForRangeInit.ColonLoc = ConsumeToken(); if (Tok.is(tok::l_brace)) ForRangeInit.RangeExpr = ParseBraceInitializer(); else ForRangeInit.RangeExpr = ParseExpression(); Diag(Loc, diag::err_for_range_identifier) << ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus1z) ? FixItHint::CreateInsertion(Loc, "auto &&") : FixItHint()); FirstPart = Actions.ActOnCXXForRangeIdentifier(getCurScope(), Loc, Name, attrs, attrs.Range.getEnd()); ForRange = true; } else if (isForInitDeclaration()) { // for (int X = 4; // Parse declaration, which eats the ';'. if (!C99orCXXorObjC) // Use of C99-style for loops in C90 mode? Diag(Tok, diag::ext_c99_variable_decl_in_for_loop); // In C++0x, "for (T NS:a" might not be a typo for :: bool MightBeForRangeStmt = getLangOpts().CPlusPlus && !getLangOpts().HLSL; // HLSL Change - disallow for-range ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt); SourceLocation DeclStart = Tok.getLocation(), DeclEnd; DeclGroupPtrTy DG = ParseSimpleDeclaration( Declarator::ForContext, DeclEnd, attrs, false, MightBeForRangeStmt ? &ForRangeInit : nullptr); FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation()); if (ForRangeInit.ParsedForRangeDecl()) { Diag(ForRangeInit.ColonLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_for_range : diag::ext_for_range); ForRange = true; } else if (Tok.is(tok::semi)) { // for (int x = 4; ConsumeToken(); } else if ((ForEach = isTokIdentifier_in())) { Actions.ActOnForEachDeclStmt(DG); // ObjC: for (id x in expr) ConsumeToken(); // consume 'in' if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCForCollection(getCurScope(), DG); cutOffParsing(); return StmtError(); } Collection = ParseExpression(); } else { Diag(Tok, diag::err_expected_semi_for); } } else { ProhibitAttributes(attrs); Value = Actions.CorrectDelayedTyposInExpr(ParseExpression()); ForEach = isTokIdentifier_in(); // Turn the expression into a stmt. if (!Value.isInvalid()) { if (ForEach) FirstPart = Actions.ActOnForEachLValueExpr(Value.get()); else FirstPart = Actions.ActOnExprStmt(Value); } if (Tok.is(tok::semi)) { ConsumeToken(); } else if (ForEach) { ConsumeToken(); // consume 'in' if (Tok.is(tok::code_completion)) { Actions.CodeCompleteObjCForCollection(getCurScope(), DeclGroupPtrTy()); cutOffParsing(); return StmtError(); } Collection = ParseExpression(); } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) { // User tried to write the reasonable, but ill-formed, for-range-statement // for (expr : expr) { ... } Diag(Tok, diag::err_for_range_expected_decl) << FirstPart.get()->getSourceRange(); SkipUntil(tok::r_paren, StopBeforeMatch); SecondPartIsInvalid = true; } else { if (!Value.isInvalid()) { Diag(Tok, diag::err_expected_semi_for); } else { // Skip until semicolon or rparen, don't consume it. SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); if (Tok.is(tok::semi)) ConsumeToken(); } } } // Parse the second part of the for specifier. getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope); if (!ForEach && !ForRange) { assert(!SecondPart.get() && "Shouldn't have a second expression yet."); // Parse the second part of the for specifier. if (Tok.is(tok::semi)) { // for (...;; // no second part. } else if (Tok.is(tok::r_paren)) { // missing both semicolons. } else { ExprResult Second; if (getLangOpts().CPlusPlus) ParseCXXCondition(Second, SecondVar, ForLoc, true); else { Second = ParseExpression(); if (!Second.isInvalid()) Second = Actions.ActOnBooleanCondition(getCurScope(), ForLoc, Second.get()); } SecondPartIsInvalid = Second.isInvalid(); SecondPart = Actions.MakeFullExpr(Second.get(), ForLoc); } if (Tok.isNot(tok::semi)) { if (!SecondPartIsInvalid || SecondVar) Diag(Tok, diag::err_expected_semi_for); else // Skip until semicolon or rparen, don't consume it. SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch); } if (Tok.is(tok::semi)) { ConsumeToken(); } // Parse the third part of the for specifier. if (Tok.isNot(tok::r_paren)) { // for (...;...;) ExprResult Third = ParseExpression(); // FIXME: The C++11 standard doesn't actually say that this is a // discarded-value expression, but it clearly should be. ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get()); } } // Match the ')'. T.consumeClose(); // We need to perform most of the semantic analysis for a C++0x for-range // statememt before parsing the body, in order to be able to deduce the type // of an auto-typed loop variable. StmtResult ForRangeStmt; StmtResult ForEachStmt; if (ForRange) { ForRangeStmt = Actions.ActOnCXXForRangeStmt(ForLoc, FirstPart.get(), ForRangeInit.ColonLoc, ForRangeInit.RangeExpr.get(), T.getCloseLocation(), Sema::BFRK_Build); // Similarly, we need to do the semantic analysis for a for-range // statement immediately in order to close over temporaries correctly. } else if (ForEach) { ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc, FirstPart.get(), Collection.get(), T.getCloseLocation()); } else { // In OpenMP loop region loop control variable must be captured and be // private. Perform analysis of first part (if any). if (getLangOpts().OpenMP && FirstPart.isUsable()) { Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get()); } } // C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if // there is no compound stmt. C90 does not have this clause. We only do this // if the body isn't a compound statement to avoid push/pop in common cases. // // C++ 6.5p2: // The substatement in an iteration-statement implicitly defines a local scope // which is entered and exited each time through the loop. // // See comments in ParseIfStatement for why we create a scope for // for-init-statement/condition and a new scope for substatement in C++. // ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC, Tok.is(tok::l_brace)); // The body of the for loop has the same local mangling number as the // for-init-statement. // It will only be incremented if the body contains other things that would // normally increment the mangling number (like a compound statement). if (C99orCXXorObjC) getCurScope()->decrementMSManglingNumber(); // Read the body statement. StmtResult Body(ParseStatement(TrailingElseLoc)); // Pop the body scope if needed. InnerScope.Exit(); // Leave the for-scope. ForScope.Exit(); if (Body.isInvalid()) return StmtError(); if (ForEach) return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(), Body.get()); if (ForRange) return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get()); return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(), SecondPart, SecondVar, ThirdPart, T.getCloseLocation(), Body.get()); } /// ParseGotoStatement /// jump-statement: /// 'goto' identifier ';' /// [GNU] 'goto' '*' expression ';' /// /// Note: this lets the caller parse the end ';'. /// StmtResult Parser::ParseGotoStatement() { assert(!getLangOpts().HLSL && "no goto parsing support in HLSL"); // HLSL Change assert(Tok.is(tok::kw_goto) && "Not a goto stmt!"); SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'. StmtResult Res; if (Tok.is(tok::identifier)) { LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(), Tok.getLocation()); Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD); ConsumeToken(); } else if (Tok.is(tok::star)) { // GNU indirect goto extension. Diag(Tok, diag::ext_gnu_indirect_goto); SourceLocation StarLoc = ConsumeToken(); ExprResult R(ParseExpression()); if (R.isInvalid()) { // Skip to the semicolon, but don't consume it. SkipUntil(tok::semi, StopBeforeMatch); return StmtError(); } Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get()); } else { Diag(Tok, diag::err_expected) << tok::identifier; return StmtError(); } return Res; } /// ParseContinueStatement /// jump-statement: /// 'continue' ';' /// /// Note: this lets the caller parse the end ';'. /// StmtResult Parser::ParseContinueStatement() { SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'. return Actions.ActOnContinueStmt(ContinueLoc, getCurScope()); } /// ParseBreakStatement /// jump-statement: /// 'break' ';' /// /// Note: this lets the caller parse the end ';'. /// StmtResult Parser::ParseBreakStatement() { SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'. return Actions.ActOnBreakStmt(BreakLoc, getCurScope()); } /// ParseReturnStatement /// jump-statement: /// 'return' expression[opt] ';' StmtResult Parser::ParseReturnStatement() { assert(Tok.is(tok::kw_return) && "Not a return stmt!"); SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'. ExprResult R; if (Tok.isNot(tok::semi)) { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteReturn(getCurScope()); cutOffParsing(); return StmtError(); } if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) { R = ParseInitializer(); if (R.isUsable()) // HLSL Change - take HLSL into account for error message Diag(R.get()->getLocStart(), getLangOpts().HLSL ? diag::err_hlsl_compat_generalized_initializer_lists : getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_generalized_initializer_lists : diag::ext_generalized_initializer_lists) << R.get()->getSourceRange(); } else R = ParseExpression(); if (R.isInvalid()) { SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch); return StmtError(); } } return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope()); } StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts, bool OnlyStatement, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs) { // Create temporary attribute list. ParsedAttributesWithRange TempAttrs(AttrFactory); // Get loop hints and consume annotated token. while (Tok.is(tok::annot_pragma_loop_hint)) { LoopHint Hint; if (!HandlePragmaLoopHint(Hint)) continue; ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc, ArgsUnion(Hint.ValueExpr)}; TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr, Hint.PragmaNameLoc->Loc, ArgHints, 4, AttributeList::AS_Pragma); } // Get the next statement. MaybeParseCXX11Attributes(Attrs); StmtResult S = ParseStatementOrDeclarationAfterAttributes( Stmts, OnlyStatement, TrailingElseLoc, Attrs); Attrs.takeAllFrom(TempAttrs); return S; } Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) { assert(Tok.is(tok::l_brace)); SourceLocation LBraceLoc = Tok.getLocation(); if (SkipFunctionBodies && (!Decl || Actions.canSkipFunctionBody(Decl)) && trySkippingFunctionBody()) { BodyScope.Exit(); return Actions.ActOnSkippedFunctionBody(Decl); } PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, LBraceLoc, "parsing function body"); // Do not enter a scope for the brace, as the arguments are in the same scope // (the function body) as the body itself. Instead, just read the statement // list and put it into a CompoundStmt for safe keeping. StmtResult FnBody(ParseCompoundStatementBody()); // If the function body could not be parsed, make a bogus compoundstmt. if (FnBody.isInvalid()) { Sema::CompoundScopeRAII CompoundScope(Actions); FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false); } BodyScope.Exit(); return Actions.ActOnFinishFunctionBody(Decl, FnBody.get()); } /// ParseFunctionTryBlock - Parse a C++ function-try-block. /// /// function-try-block: /// 'try' ctor-initializer[opt] compound-statement handler-seq /// Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) { assert(!getLangOpts().HLSL && "no exception parsing support in HLSL"); // HLSL Change assert(Tok.is(tok::kw_try) && "Expected 'try'"); SourceLocation TryLoc = ConsumeToken(); PrettyDeclStackTraceEntry CrashInfo(Actions, Decl, TryLoc, "parsing function try block"); // Constructor initializer list? if (Tok.is(tok::colon)) ParseConstructorInitializer(Decl); else Actions.ActOnDefaultCtorInitializers(Decl); if (SkipFunctionBodies && Actions.canSkipFunctionBody(Decl) && trySkippingFunctionBody()) { BodyScope.Exit(); return Actions.ActOnSkippedFunctionBody(Decl); } SourceLocation LBraceLoc = Tok.getLocation(); StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true)); // If we failed to parse the try-catch, we just give the function an empty // compound statement as the body. if (FnBody.isInvalid()) { Sema::CompoundScopeRAII CompoundScope(Actions); FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false); } BodyScope.Exit(); return Actions.ActOnFinishFunctionBody(Decl, FnBody.get()); } bool Parser::trySkippingFunctionBody() { assert(Tok.is(tok::l_brace)); assert(SkipFunctionBodies && "Should only be called when SkipFunctionBodies is enabled"); if (!PP.isCodeCompletionEnabled()) { ConsumeBrace(); SkipUntil(tok::r_brace); return true; } // We're in code-completion mode. Skip parsing for all function bodies unless // the body contains the code-completion point. TentativeParsingAction PA(*this); ConsumeBrace(); if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) { PA.Commit(); return true; } PA.Revert(); return false; } /// ParseCXXTryBlock - Parse a C++ try-block. /// /// try-block: /// 'try' compound-statement handler-seq /// StmtResult Parser::ParseCXXTryBlock() { assert(!getLangOpts().HLSL && "no exception parsing support in HLSL"); // HLSL Change assert(Tok.is(tok::kw_try) && "Expected 'try'"); SourceLocation TryLoc = ConsumeToken(); return ParseCXXTryBlockCommon(TryLoc); } /// ParseCXXTryBlockCommon - Parse the common part of try-block and /// function-try-block. /// /// try-block: /// 'try' compound-statement handler-seq /// /// function-try-block: /// 'try' ctor-initializer[opt] compound-statement handler-seq /// /// handler-seq: /// handler handler-seq[opt] /// /// [Borland] try-block: /// 'try' compound-statement seh-except-block /// 'try' compound-statement seh-finally-block /// StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) { assert(!getLangOpts().HLSL && "no exception parsing support in HLSL"); // HLSL Change if (Tok.isNot(tok::l_brace)) return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace); StmtResult TryBlock(ParseCompoundStatement(/*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope | (FnTry ? Scope::FnTryCatchScope : 0))); if (TryBlock.isInvalid()) return TryBlock; // Borland allows SEH-handlers with 'try' if ((Tok.is(tok::identifier) && Tok.getIdentifierInfo() == getSEHExceptKeyword()) || Tok.is(tok::kw___finally)) { // TODO: Factor into common return ParseSEHHandlerCommon(...) StmtResult Handler; if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) { SourceLocation Loc = ConsumeToken(); Handler = ParseSEHExceptBlock(Loc); } else { SourceLocation Loc = ConsumeToken(); Handler = ParseSEHFinallyBlock(Loc); } if(Handler.isInvalid()) return Handler; return Actions.ActOnSEHTryBlock(true /* IsCXXTry */, TryLoc, TryBlock.get(), Handler.get()); } else { StmtVector Handlers; // C++11 attributes can't appear here, despite this context seeming // statement-like. DiagnoseAndSkipCXX11Attributes(); if (Tok.isNot(tok::kw_catch)) return StmtError(Diag(Tok, diag::err_expected_catch)); while (Tok.is(tok::kw_catch)) { StmtResult Handler(ParseCXXCatchBlock(FnTry)); if (!Handler.isInvalid()) Handlers.push_back(Handler.get()); } // Don't bother creating the full statement if we don't have any usable // handlers. if (Handlers.empty()) return StmtError(); return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers); } } /// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard /// /// handler: /// 'catch' '(' exception-declaration ')' compound-statement /// /// exception-declaration: /// attribute-specifier-seq[opt] type-specifier-seq declarator /// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt] /// '...' /// StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) { assert(!getLangOpts().HLSL && "no exception parsing support in HLSL"); // HLSL Change assert(Tok.is(tok::kw_catch) && "Expected 'catch'"); SourceLocation CatchLoc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.expectAndConsume()) return StmtError(); // C++ 3.3.2p3: // The name in a catch exception-declaration is local to the handler and // shall not be redeclared in the outermost block of the handler. ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope | (FnCatch ? Scope::FnTryCatchScope : 0)); // exception-declaration is equivalent to '...' or a parameter-declaration // without default arguments. Decl *ExceptionDecl = nullptr; if (Tok.isNot(tok::ellipsis)) { ParsedAttributesWithRange Attributes(AttrFactory); MaybeParseCXX11Attributes(Attributes); assert(!getLangOpts().HLSL); // HLSL Change: in lieu of MaybeParseHLSLAttributes - catch blocks not allowed DeclSpec DS(AttrFactory); DS.takeAttributesFrom(Attributes); if (ParseCXXTypeSpecifierSeq(DS)) return StmtError(); Declarator ExDecl(DS, Declarator::CXXCatchContext); ParseDeclarator(ExDecl); ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl); } else ConsumeToken(); T.consumeClose(); if (T.getCloseLocation().isInvalid()) return StmtError(); if (Tok.isNot(tok::l_brace)) return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace); // FIXME: Possible draft standard bug: attribute-specifier should be allowed? StmtResult Block(ParseCompoundStatement()); if (Block.isInvalid()) return Block; return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get()); } void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) { assert(!getLangOpts().HLSL && "no __if_exists support in HLSL"); // HLSL Change IfExistsCondition Result; if (ParseMicrosoftIfExistsCondition(Result)) return; // Handle dependent statements by parsing the braces as a compound statement. // This is not the same behavior as Visual C++, which don't treat this as a // compound statement, but for Clang's type checking we can't have anything // inside these braces escaping to the surrounding code. if (Result.Behavior == IEB_Dependent) { if (!Tok.is(tok::l_brace)) { Diag(Tok, diag::err_expected) << tok::l_brace; return; } StmtResult Compound = ParseCompoundStatement(); if (Compound.isInvalid()) return; StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc, Result.IsIfExists, Result.SS, Result.Name, Compound.get()); if (DepResult.isUsable()) Stmts.push_back(DepResult.get()); return; } BalancedDelimiterTracker Braces(*this, tok::l_brace); if (Braces.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; return; } switch (Result.Behavior) { case IEB_Parse: // Parse the statements below. break; case IEB_Dependent: llvm_unreachable("Dependent case handled above"); case IEB_Skip: Braces.skipToEnd(); return; } // Condition is true, parse the statements. while (Tok.isNot(tok::r_brace)) { StmtResult R = ParseStatementOrDeclaration(Stmts, false); if (R.isUsable()) Stmts.push_back(R.get()); } Braces.consumeClose(); } // HLSL Change Starts StmtResult Parser::HandleHLSLDiscardStmt(Expr *Fn) { assert(Tok.is(tok::kw_discard)); SourceLocation Loc = ConsumeToken(); ExpectAndConsumeSemi(diag::err_expected_semi_after_expr); return Actions.ActOnHlslDiscardStmt(Loc); } // HLSL Change Ends
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/Parser.cpp
//===--- Parser.cpp - C Language Family Parser ----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Parser interfaces. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "RAIIObjectsForParser.h" #include "clang/AST/ASTConsumer.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclTemplate.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ParsedTemplate.h" #include "clang/Sema/Scope.h" #include "llvm/Support/raw_ostream.h" using namespace clang; namespace { /// \brief A comment handler that passes comments found by the preprocessor /// to the parser action. class ActionCommentHandler : public CommentHandler { Sema &S; public: explicit ActionCommentHandler(Sema &S) : S(S) { } bool HandleComment(Preprocessor &PP, SourceRange Comment) override { S.ActOnComment(Comment); return false; } }; /// \brief RAIIObject to destroy the contents of a SmallVector of /// TemplateIdAnnotation pointers and clear the vector. class DestroyTemplateIdAnnotationsRAIIObj { SmallVectorImpl<TemplateIdAnnotation *> &Container; public: DestroyTemplateIdAnnotationsRAIIObj( SmallVectorImpl<TemplateIdAnnotation *> &Container) : Container(Container) {} ~DestroyTemplateIdAnnotationsRAIIObj() { for (SmallVectorImpl<TemplateIdAnnotation *>::iterator I = Container.begin(), E = Container.end(); I != E; ++I) (*I)->Destroy(); Container.clear(); } }; } // end anonymous namespace IdentifierInfo *Parser::getSEHExceptKeyword() { // __except is accepted as a (contextual) keyword if (!Ident__except && (getLangOpts().MicrosoftExt || getLangOpts().Borland)) Ident__except = PP.getIdentifierInfo("__except"); return Ident__except; } Parser::Parser(Preprocessor &pp, Sema &actions, bool skipFunctionBodies) : PP(pp), Actions(actions), Diags(PP.getDiagnostics()), GreaterThanIsOperator(true), ColonIsSacred(false), InMessageExpression(false), TemplateParameterDepth(0), ParsingInObjCContainer(false) { SkipFunctionBodies = pp.isCodeCompletionEnabled() || skipFunctionBodies; Tok.startToken(); Tok.setKind(tok::eof); Actions.CurScope = nullptr; NumCachedScopes = 0; ParenCount = BracketCount = BraceCount = 0; CurParsedObjCImpl = nullptr; // Add #pragma handlers. These are removed and destroyed in the // destructor. initializePragmaHandlers(); CommentSemaHandler.reset(new ActionCommentHandler(actions)); PP.addCommentHandler(CommentSemaHandler.get()); PP.setCodeCompletionHandler(*this); } DiagnosticBuilder Parser::Diag(SourceLocation Loc, unsigned DiagID) { return Diags.Report(Loc, DiagID); } DiagnosticBuilder Parser::Diag(const Token &Tok, unsigned DiagID) { return Diag(Tok.getLocation(), DiagID); } /// \brief Emits a diagnostic suggesting parentheses surrounding a /// given range. /// /// \param Loc The location where we'll emit the diagnostic. /// \param DK The kind of diagnostic to emit. /// \param ParenRange Source range enclosing code that should be parenthesized. void Parser::SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange) { SourceLocation EndLoc = PP.getLocForEndOfToken(ParenRange.getEnd()); if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) { // We can't display the parentheses, so just dig the // warning/error and return. Diag(Loc, DK); return; } Diag(Loc, DK) << FixItHint::CreateInsertion(ParenRange.getBegin(), "(") << FixItHint::CreateInsertion(EndLoc, ")"); } static bool IsCommonTypo(tok::TokenKind ExpectedTok, const Token &Tok) { switch (ExpectedTok) { case tok::semi: return Tok.is(tok::colon) || Tok.is(tok::comma); // : or , for ; default: return false; } } bool Parser::ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned DiagID, StringRef Msg) { if (Tok.is(ExpectedTok) || Tok.is(tok::code_completion)) { ConsumeAnyToken(); return false; } // Detect common single-character typos and resume. if (IsCommonTypo(ExpectedTok, Tok)) { SourceLocation Loc = Tok.getLocation(); { DiagnosticBuilder DB = Diag(Loc, DiagID); DB << FixItHint::CreateReplacement( SourceRange(Loc), tok::getPunctuatorSpelling(ExpectedTok)); if (DiagID == diag::err_expected) DB << ExpectedTok; else if (DiagID == diag::err_expected_after) DB << Msg << ExpectedTok; else DB << Msg; } // Pretend there wasn't a problem. ConsumeAnyToken(); return false; } SourceLocation EndLoc = PP.getLocForEndOfToken(PrevTokLocation); const char *Spelling = nullptr; if (EndLoc.isValid()) Spelling = tok::getPunctuatorSpelling(ExpectedTok); DiagnosticBuilder DB = Spelling ? Diag(EndLoc, DiagID) << FixItHint::CreateInsertion(EndLoc, Spelling) : Diag(Tok, DiagID); if (DiagID == diag::err_expected) DB << ExpectedTok; else if (DiagID == diag::err_expected_after) DB << Msg << ExpectedTok; else DB << Msg; return true; } bool Parser::ExpectAndConsumeSemi(unsigned DiagID) { if (TryConsumeToken(tok::semi)) return false; if (Tok.is(tok::code_completion)) { handleUnexpectedCodeCompletionToken(); return false; } if ((Tok.is(tok::r_paren) || Tok.is(tok::r_square)) && NextToken().is(tok::semi)) { Diag(Tok, diag::err_extraneous_token_before_semi) << PP.getSpelling(Tok) << FixItHint::CreateRemoval(Tok.getLocation()); ConsumeAnyToken(); // The ')' or ']'. ConsumeToken(); // The ';'. return false; } return ExpectAndConsume(tok::semi, DiagID); } void Parser::ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST) { if (!Tok.is(tok::semi)) return; bool HadMultipleSemis = false; SourceLocation StartLoc = Tok.getLocation(); SourceLocation EndLoc = Tok.getLocation(); ConsumeToken(); while ((Tok.is(tok::semi) && !Tok.isAtStartOfLine())) { HadMultipleSemis = true; EndLoc = Tok.getLocation(); ConsumeToken(); } // C++11 allows extra semicolons at namespace scope, but not in any of the // other contexts. if (!getLangOpts().HLSL && (Kind == OutsideFunction && getLangOpts().CPlusPlus)) { // HLSL Change if (getLangOpts().CPlusPlus11) Diag(StartLoc, diag::warn_cxx98_compat_top_level_semi) << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); else Diag(StartLoc, diag::ext_extra_semi_cxx11) << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); return; } if (Kind != AfterMemberFunctionDefinition || HadMultipleSemis) Diag(StartLoc, diag::ext_extra_semi) << Kind << DeclSpec::getSpecifierName((DeclSpec::TST)TST, Actions.getASTContext().getPrintingPolicy()) << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); else // A single semicolon is valid after a member function definition. Diag(StartLoc, diag::warn_extra_semi_after_mem_fn_def) << FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc)); } //===----------------------------------------------------------------------===// // Error recovery. //===----------------------------------------------------------------------===// static bool HasFlagsSet(Parser::SkipUntilFlags L, Parser::SkipUntilFlags R) { return (static_cast<unsigned>(L) & static_cast<unsigned>(R)) != 0; } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless no flag StopBeforeMatch). Because we cannot guarantee that the /// token will ever occur, this skips to the next token, or to some likely /// good stopping point. If StopAtSemi is true, skipping will stop at a ';' /// character. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool Parser::SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags) { // We always want this function to skip at least one token if the first token // isn't T and if not at EOF. bool isFirstTokenSkipped = true; while (1) { // If we found one of the tokens, stop and return true. for (unsigned i = 0, NumToks = Toks.size(); i != NumToks; ++i) { if (Tok.is(Toks[i])) { if (HasFlagsSet(Flags, StopBeforeMatch)) { // Noop, don't consume the token. } else { ConsumeAnyToken(); } return true; } } // Important special case: The caller has given up and just wants us to // skip the rest of the file. Do this without recursing, since we can // get here precisely because the caller detected too much recursion. if (Toks.size() == 1 && Toks[0] == tok::eof && !HasFlagsSet(Flags, StopAtSemi) && !HasFlagsSet(Flags, StopAtCodeCompletion)) { while (Tok.isNot(tok::eof)) ConsumeAnyToken(); return true; } switch (Tok.getKind()) { case tok::eof: // Ran out of tokens. return false; case tok::annot_pragma_openmp_end: // Stop before an OpenMP pragma boundary. case tok::annot_module_begin: case tok::annot_module_end: case tok::annot_module_include: // Stop before we change submodules. They generally indicate a "good" // place to pick up parsing again (except in the special case where // we're trying to skip to EOF). return false; case tok::code_completion: if (!HasFlagsSet(Flags, StopAtCodeCompletion)) handleUnexpectedCodeCompletionToken(); return false; case tok::l_paren: // Recursively skip properly-nested parens. ConsumeParen(); if (HasFlagsSet(Flags, StopAtCodeCompletion)) SkipUntil(tok::r_paren, StopAtCodeCompletion); else SkipUntil(tok::r_paren); break; case tok::l_square: // Recursively skip properly-nested square brackets. ConsumeBracket(); if (HasFlagsSet(Flags, StopAtCodeCompletion)) SkipUntil(tok::r_square, StopAtCodeCompletion); else SkipUntil(tok::r_square); break; case tok::l_brace: // Recursively skip properly-nested braces. ConsumeBrace(); if (HasFlagsSet(Flags, StopAtCodeCompletion)) SkipUntil(tok::r_brace, StopAtCodeCompletion); else SkipUntil(tok::r_brace); break; // Okay, we found a ']' or '}' or ')', which we think should be balanced. // Since the user wasn't looking for this token (if they were, it would // already be handled), this isn't balanced. If there is a LHS token at a // higher level, we will assume that this matches the unbalanced token // and return it. Otherwise, this is a spurious RHS token, which we skip. case tok::r_paren: if (ParenCount && !isFirstTokenSkipped) return false; // Matches something. ConsumeParen(); break; case tok::r_square: if (BracketCount && !isFirstTokenSkipped) return false; // Matches something. ConsumeBracket(); break; case tok::r_brace: if (BraceCount && !isFirstTokenSkipped) return false; // Matches something. ConsumeBrace(); break; case tok::string_literal: case tok::wide_string_literal: case tok::utf8_string_literal: case tok::utf16_string_literal: case tok::utf32_string_literal: ConsumeStringToken(); break; case tok::semi: if (HasFlagsSet(Flags, StopAtSemi)) return false; LLVM_FALLTHROUGH; // HLSL Change default: // Skip this token. ConsumeToken(); break; } isFirstTokenSkipped = false; } } //===----------------------------------------------------------------------===// // Scope manipulation //===----------------------------------------------------------------------===// /// EnterScope - Start a new scope. void Parser::EnterScope(unsigned ScopeFlags) { if (NumCachedScopes) { Scope *N = ScopeCache[--NumCachedScopes]; N->Init(getCurScope(), ScopeFlags); Actions.CurScope = N; } else { Actions.CurScope = new Scope(getCurScope(), ScopeFlags, Diags); } } /// ExitScope - Pop a scope off the scope stack. void Parser::ExitScope() { assert(getCurScope() && "Scope imbalance!"); // Inform the actions module that this scope is going away if there are any // decls in it. Actions.ActOnPopScope(Tok.getLocation(), getCurScope()); Scope *OldScope = getCurScope(); Actions.CurScope = OldScope->getParent(); if (NumCachedScopes == ScopeCacheSize) delete OldScope; else ScopeCache[NumCachedScopes++] = OldScope; } /// Set the flags for the current scope to ScopeFlags. If ManageFlags is false, /// this object does nothing. Parser::ParseScopeFlags::ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags) : CurScope(ManageFlags ? Self->getCurScope() : nullptr) { if (CurScope) { OldFlags = CurScope->getFlags(); CurScope->setFlags(ScopeFlags); } } /// Restore the flags for the current scope to what they were before this /// object overrode them. Parser::ParseScopeFlags::~ParseScopeFlags() { if (CurScope) CurScope->setFlags(OldFlags); } //===----------------------------------------------------------------------===// // C99 6.9: External Definitions. //===----------------------------------------------------------------------===// Parser::~Parser() { // If we still have scopes active, delete the scope tree. delete getCurScope(); Actions.CurScope = nullptr; // Free the scope cache. for (unsigned i = 0, e = NumCachedScopes; i != e; ++i) delete ScopeCache[i]; resetPragmaHandlers(); PP.removeCommentHandler(CommentSemaHandler.get()); PP.clearCodeCompletionHandler(); if (getLangOpts().DelayedTemplateParsing && !PP.isIncrementalProcessingEnabled() && !TemplateIds.empty()) { // If an ASTConsumer parsed delay-parsed templates in their // HandleTranslationUnit() method, TemplateIds created there were not // guarded by a DestroyTemplateIdAnnotationsRAIIObj object in // ParseTopLevelDecl(). Destroy them here. DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds); } assert(TemplateIds.empty() && "Still alive TemplateIdAnnotations around?"); } /// Initialize - Warm up the parser. /// void Parser::Initialize() { // Create the translation unit scope. Install it as the current scope. assert(getCurScope() == nullptr && "A scope is already active?"); EnterScope(Scope::DeclScope); Actions.ActOnTranslationUnitScope(getCurScope()); // Initialization for Objective-C context sensitive keywords recognition. // Referenced in Parser::ParseObjCTypeQualifierList. if (getLangOpts().ObjC1) { ObjCTypeQuals[objc_in] = &PP.getIdentifierTable().get("in"); ObjCTypeQuals[objc_out] = &PP.getIdentifierTable().get("out"); ObjCTypeQuals[objc_inout] = &PP.getIdentifierTable().get("inout"); ObjCTypeQuals[objc_oneway] = &PP.getIdentifierTable().get("oneway"); ObjCTypeQuals[objc_bycopy] = &PP.getIdentifierTable().get("bycopy"); ObjCTypeQuals[objc_byref] = &PP.getIdentifierTable().get("byref"); ObjCTypeQuals[objc_nonnull] = &PP.getIdentifierTable().get("nonnull"); ObjCTypeQuals[objc_nullable] = &PP.getIdentifierTable().get("nullable"); ObjCTypeQuals[objc_null_unspecified] = &PP.getIdentifierTable().get("null_unspecified"); } Ident_instancetype = nullptr; Ident_final = nullptr; Ident_sealed = nullptr; Ident_override = nullptr; Ident_super = &PP.getIdentifierTable().get("super"); Ident_vector = nullptr; Ident_bool = nullptr; Ident_pixel = nullptr; if (getLangOpts().AltiVec || getLangOpts().ZVector) { Ident_vector = &PP.getIdentifierTable().get("vector"); Ident_bool = &PP.getIdentifierTable().get("bool"); } if (getLangOpts().AltiVec) Ident_pixel = &PP.getIdentifierTable().get("pixel"); Ident_introduced = nullptr; Ident_deprecated = nullptr; Ident_obsoleted = nullptr; Ident_unavailable = nullptr; Ident__except = nullptr; Ident__exception_code = Ident__exception_info = nullptr; Ident__abnormal_termination = Ident___exception_code = nullptr; Ident___exception_info = Ident___abnormal_termination = nullptr; Ident_GetExceptionCode = Ident_GetExceptionInfo = nullptr; Ident_AbnormalTermination = nullptr; if(getLangOpts().Borland) { Ident__exception_info = PP.getIdentifierInfo("_exception_info"); Ident___exception_info = PP.getIdentifierInfo("__exception_info"); Ident_GetExceptionInfo = PP.getIdentifierInfo("GetExceptionInformation"); Ident__exception_code = PP.getIdentifierInfo("_exception_code"); Ident___exception_code = PP.getIdentifierInfo("__exception_code"); Ident_GetExceptionCode = PP.getIdentifierInfo("GetExceptionCode"); Ident__abnormal_termination = PP.getIdentifierInfo("_abnormal_termination"); Ident___abnormal_termination = PP.getIdentifierInfo("__abnormal_termination"); Ident_AbnormalTermination = PP.getIdentifierInfo("AbnormalTermination"); PP.SetPoisonReason(Ident__exception_code,diag::err_seh___except_block); PP.SetPoisonReason(Ident___exception_code,diag::err_seh___except_block); PP.SetPoisonReason(Ident_GetExceptionCode,diag::err_seh___except_block); PP.SetPoisonReason(Ident__exception_info,diag::err_seh___except_filter); PP.SetPoisonReason(Ident___exception_info,diag::err_seh___except_filter); PP.SetPoisonReason(Ident_GetExceptionInfo,diag::err_seh___except_filter); PP.SetPoisonReason(Ident__abnormal_termination,diag::err_seh___finally_block); PP.SetPoisonReason(Ident___abnormal_termination,diag::err_seh___finally_block); PP.SetPoisonReason(Ident_AbnormalTermination,diag::err_seh___finally_block); } Actions.Initialize(); // Prime the lexer look-ahead. ConsumeToken(); } void Parser::LateTemplateParserCleanupCallback(void *P) { // While this RAII helper doesn't bracket any actual work, the destructor will // clean up annotations that were created during ActOnEndOfTranslationUnit // when incremental processing is enabled. DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(((Parser *)P)->TemplateIds); } /// ParseTopLevelDecl - Parse one top-level declaration, return whatever the /// action tells us to. This returns true if the EOF was encountered. bool Parser::ParseTopLevelDecl(DeclGroupPtrTy &Result) { DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds); // Skip over the EOF token, flagging end of previous input for incremental // processing if (PP.isIncrementalProcessingEnabled() && Tok.is(tok::eof)) ConsumeToken(); Result = DeclGroupPtrTy(); switch (Tok.getKind()) { case tok::annot_pragma_unused: if (getLangOpts().HLSL) break; // HLSL Change - this should merge with 'default' and avoid unused pragma handling HandlePragmaUnused(); return false; case tok::annot_module_include: if (getLangOpts().HLSL) break; // HLSL Change - HLSL does not support modules and cannot get to this codepath Actions.ActOnModuleInclude(Tok.getLocation(), reinterpret_cast<Module *>( Tok.getAnnotationValue())); ConsumeToken(); return false; case tok::annot_module_begin: if (getLangOpts().HLSL) break; // HLSL Change - HLSL does not support modules and cannot get to this codepath Actions.ActOnModuleBegin(Tok.getLocation(), reinterpret_cast<Module *>( Tok.getAnnotationValue())); ConsumeToken(); return false; case tok::annot_module_end: if (getLangOpts().HLSL) break; // HLSL Change - HLSL does not support modules and cannot get to this codepath Actions.ActOnModuleEnd(Tok.getLocation(), reinterpret_cast<Module *>( Tok.getAnnotationValue())); ConsumeToken(); return false; case tok::eof: // Late template parsing can begin. if (getLangOpts().DelayedTemplateParsing) Actions.SetLateTemplateParser(LateTemplateParserCallback, PP.isIncrementalProcessingEnabled() ? LateTemplateParserCleanupCallback : nullptr, this); if (!PP.isIncrementalProcessingEnabled()) Actions.ActOnEndOfTranslationUnit(); //else don't tell Sema that we ended parsing: more input might come. return true; // HLSL Change Starts - skip legacy effects technique syntax case tok::kw_technique: Diag(Tok.getLocation(), diag::warn_hlsl_effect_technique); SkipUntil(tok::l_brace); // skip through { SkipUntil(tok::r_brace); // skip through matching } Result = DeclGroupPtrTy(); return false; // HLSL Change Ends default: break; } ParsedAttributesWithRange attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); MaybeParseHLSLAttributes(attrs); // HLSL Change MaybeParseMicrosoftAttributes(attrs); Result = ParseExternalDeclaration(attrs); return false; } /// ParseExternalDeclaration: /// /// external-declaration: [C99 6.9], declaration: [C++ dcl.dcl] /// function-definition /// declaration /// [GNU] asm-definition /// [GNU] __extension__ external-declaration /// [OBJC] objc-class-definition /// [OBJC] objc-class-declaration /// [OBJC] objc-alias-declaration /// [OBJC] objc-protocol-definition /// [OBJC] objc-method-definition /// [OBJC] @end /// [C++] linkage-specification /// [GNU] asm-definition: /// simple-asm-expr ';' /// [C++11] empty-declaration /// [C++11] attribute-declaration /// /// [C++11] empty-declaration: /// ';' /// /// [C++0x/GNU] 'extern' 'template' declaration Parser::DeclGroupPtrTy Parser::ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS) { DestroyTemplateIdAnnotationsRAIIObj CleanupRAII(TemplateIds); ParenBraceBracketBalancer BalancerRAIIObj(*this); if (PP.isCodeCompletionReached()) { cutOffParsing(); return DeclGroupPtrTy(); } Decl *SingleDecl = nullptr; switch (Tok.getKind()) { case tok::annot_pragma_vis: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaVisibility(); return DeclGroupPtrTy(); case tok::annot_pragma_pack: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaPack(); return DeclGroupPtrTy(); case tok::annot_pragma_msstruct: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaMSStruct(); return DeclGroupPtrTy(); case tok::annot_pragma_align: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaAlign(); return DeclGroupPtrTy(); case tok::annot_pragma_weak: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaWeak(); return DeclGroupPtrTy(); case tok::annot_pragma_weakalias: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaWeakAlias(); return DeclGroupPtrTy(); case tok::annot_pragma_redefine_extname: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaRedefineExtname(); return DeclGroupPtrTy(); case tok::annot_pragma_fp_contract: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaFPContract(); return DeclGroupPtrTy(); case tok::annot_pragma_opencl_extension: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaOpenCLExtension(); return DeclGroupPtrTy(); case tok::annot_pragma_openmp: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing return ParseOpenMPDeclarativeDirective(); case tok::annot_pragma_ms_pointers_to_members: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaMSPointersToMembers(); return DeclGroupPtrTy(); case tok::annot_pragma_ms_vtordisp: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaMSVtorDisp(); return DeclGroupPtrTy(); case tok::annot_pragma_ms_pragma: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing HandlePragmaMSPragma(); return DeclGroupPtrTy(); case tok::semi: // Either a C++11 empty-declaration or attribute-declaration. SingleDecl = Actions.ActOnEmptyDeclaration(getCurScope(), attrs.getList(), Tok.getLocation()); ConsumeExtraSemi(OutsideFunction); break; case tok::r_brace: Diag(Tok, diag::err_extraneous_closing_brace); ConsumeBrace(); return DeclGroupPtrTy(); case tok::eof: Diag(Tok, diag::err_expected_external_declaration); return DeclGroupPtrTy(); case tok::kw___extension__: { // __extension__ silences extension warnings in the subexpression. ExtensionRAIIObject O(Diags); // Use RAII to do this. ConsumeToken(); return ParseExternalDeclaration(attrs); } case tok::kw_asm: { if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing ProhibitAttributes(attrs); SourceLocation StartLoc = Tok.getLocation(); SourceLocation EndLoc; ExprResult Result(ParseSimpleAsm(&EndLoc)); // Check if GNU-style InlineAsm is disabled. // Empty asm string is allowed because it will not introduce // any assembly code. if (!(getLangOpts().GNUAsm || Result.isInvalid())) { const auto *SL = cast<StringLiteral>(Result.get()); if (!SL->getString().trim().empty()) Diag(StartLoc, diag::err_gnu_inline_asm_disabled); } ExpectAndConsume(tok::semi, diag::err_expected_after, "top-level asm block"); if (Result.isInvalid()) return DeclGroupPtrTy(); SingleDecl = Actions.ActOnFileScopeAsmDecl(Result.get(), StartLoc, EndLoc); break; } case tok::at: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing return ParseObjCAtDirectives(); case tok::minus: case tok::plus: if (!getLangOpts().ObjC1) { Diag(Tok, diag::err_expected_external_declaration); ConsumeToken(); return DeclGroupPtrTy(); } SingleDecl = ParseObjCMethodDefinition(); break; case tok::code_completion: Actions.CodeCompleteOrdinaryName(getCurScope(), CurParsedObjCImpl? Sema::PCC_ObjCImplementation : Sema::PCC_Namespace); cutOffParsing(); return DeclGroupPtrTy(); // HLSL Change Starts: Ignore shared keyword for now case tok::kw_shared: ConsumeToken(); return ParseExternalDeclaration(attrs); // HLSL Change Ends // HLSL Change Starts: Start parsing declaration of cbuffer and tbuffers case tok::kw_cbuffer: case tok::kw_tbuffer: // HLSL Change Ends case tok::kw_using: case tok::kw_namespace: case tok::kw_typedef: case tok::kw_template: case tok::kw_export: // As in 'export template' case tok::kw_static_assert: case tok::kw__Static_assert: // A function definition cannot start with any of these keywords. { SourceLocation DeclEnd; return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs); } case tok::kw_static: // Parse (then ignore) 'static' prior to a template instantiation. This is // a GCC extension that we intentionally do not support. if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template)) { Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) << 0; SourceLocation DeclEnd; return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs); } goto dont_know; case tok::kw_inline: if (getLangOpts().CPlusPlus) { tok::TokenKind NextKind = NextToken().getKind(); // Inline namespaces. Allowed as an extension even in C++03. if (NextKind == tok::kw_namespace) { SourceLocation DeclEnd; return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs); } // Parse (then ignore) 'inline' prior to a template instantiation. This is // a GCC extension that we intentionally do not support. if (NextKind == tok::kw_template) { Diag(ConsumeToken(), diag::warn_static_inline_explicit_inst_ignored) << 1; SourceLocation DeclEnd; return ParseDeclaration(Declarator::FileContext, DeclEnd, attrs); } } goto dont_know; case tok::kw_extern: if (getLangOpts().CPlusPlus && NextToken().is(tok::kw_template) && !getLangOpts().HLSL) { // HLSL Change // Extern templates SourceLocation ExternLoc = ConsumeToken(); SourceLocation TemplateLoc = ConsumeToken(); Diag(ExternLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_extern_template : diag::ext_extern_template) << SourceRange(ExternLoc, TemplateLoc); SourceLocation DeclEnd; return Actions.ConvertDeclToDeclGroup( ParseExplicitInstantiation(Declarator::FileContext, ExternLoc, TemplateLoc, DeclEnd)); } goto dont_know; case tok::kw___if_exists: case tok::kw___if_not_exists: if (getLangOpts().HLSL) goto dont_know; // HLSL Change - skip unsupported processing ParseMicrosoftIfExistsExternalDeclaration(); return DeclGroupPtrTy(); default: dont_know: // We can't tell whether this is a function-definition or declaration yet. return ParseDeclarationOrFunctionDefinition(attrs, DS); } // This routine returns a DeclGroup, if the thing we parsed only contains a // single decl, convert it now. return Actions.ConvertDeclToDeclGroup(SingleDecl); } /// \brief Determine whether the current token, if it occurs after a /// declarator, continues a declaration or declaration list. bool Parser::isDeclarationAfterDeclarator() { // Check for '= delete' or '= default' if (!getLangOpts().HLSL && (getLangOpts().CPlusPlus && Tok.is(tok::equal))) { // HLSL Change - remove support const Token &KW = NextToken(); if (KW.is(tok::kw_default) || KW.is(tok::kw_delete)) return false; } return Tok.is(tok::equal) || // int X()= -> not a function def Tok.is(tok::comma) || // int X(), -> not a function def Tok.is(tok::semi) || // int X(); -> not a function def Tok.is(tok::kw_asm) || // int X() __asm__ -> not a function def Tok.is(tok::kw___attribute) || // int X() __attr__ -> not a function def (getLangOpts().CPlusPlus && Tok.is(tok::l_paren)); // int X(0) -> not a function def [C++] } /// \brief Determine whether the current token, if it occurs after a /// declarator, indicates the start of a function definition. bool Parser::isStartOfFunctionDefinition(const ParsingDeclarator &Declarator) { assert(Declarator.isFunctionDeclarator() && "Isn't a function declarator"); if (Tok.is(tok::l_brace)) // int X() {} return true; // Handle K&R C argument lists: int X(f) int f; {} if (!getLangOpts().CPlusPlus && Declarator.getFunctionTypeInfo().isKNRPrototype()) return isDeclarationSpecifier(); if (!getLangOpts().HLSL && getLangOpts().CPlusPlus && Tok.is(tok::equal)) { // HLSL Change - remove support const Token &KW = NextToken(); return KW.is(tok::kw_default) || KW.is(tok::kw_delete); } return Tok.is(tok::colon) || // X() : Base() {} (used for ctors) Tok.is(tok::kw_try); // X() try { ... } } /// ParseDeclarationOrFunctionDefinition - Parse either a function-definition or /// a declaration. We can't tell which we have until we read up to the /// compound-statement in function-definition. TemplateParams, if /// non-NULL, provides the template parameters when we're parsing a /// C++ template-declaration. /// /// function-definition: [C99 6.9.1] /// decl-specs declarator declaration-list[opt] compound-statement /// [C90] function-definition: [C99 6.7.1] - implicit int result /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement /// /// declaration: [C99 6.7] /// declaration-specifiers init-declarator-list[opt] ';' /// [!C99] init-declarator-list ';' [TODO: warn in c99 mode] /// [OMP] threadprivate-directive [TODO] /// Parser::DeclGroupPtrTy Parser::ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS) { // Parse the common declaration-specifiers piece. ParseDeclarationSpecifiers(DS, ParsedTemplateInfo(), AS, DSC_top_level); // If we had a free-standing type definition with a missing semicolon, we // may get this far before the problem becomes obvious. if (DS.hasTagDefinition() && DiagnoseMissingSemiAfterTagDefinition(DS, AS, DSC_top_level)) return DeclGroupPtrTy(); // C99 6.7.2.3p6: Handle "struct-or-union identifier;", "enum { X };" // declaration-specifiers init-declarator-list[opt] ';' if (Tok.is(tok::semi)) { ProhibitAttributes(attrs); ConsumeToken(); Decl *TheDecl = Actions.ParsedFreeStandingDeclSpec(getCurScope(), AS, DS); DS.complete(TheDecl); return Actions.ConvertDeclToDeclGroup(TheDecl); } DS.takeAttributesFrom(attrs); // ObjC2 allows prefix attributes on class interfaces and protocols. // FIXME: This still needs better diagnostics. We should only accept // attributes here, no types, etc. if (getLangOpts().ObjC2 && Tok.is(tok::at)) { SourceLocation AtLoc = ConsumeToken(); // the "@" if (!Tok.isObjCAtKeyword(tok::objc_interface) && !Tok.isObjCAtKeyword(tok::objc_protocol)) { Diag(Tok, diag::err_objc_unexpected_attr); SkipUntil(tok::semi); // FIXME: better skip? return DeclGroupPtrTy(); } DS.abort(); const char *PrevSpec = nullptr; unsigned DiagID; if (DS.SetTypeSpecType(DeclSpec::TST_unspecified, AtLoc, PrevSpec, DiagID, Actions.getASTContext().getPrintingPolicy())) Diag(AtLoc, DiagID) << PrevSpec; if (Tok.isObjCAtKeyword(tok::objc_protocol)) return ParseObjCAtProtocolDeclaration(AtLoc, DS.getAttributes()); return Actions.ConvertDeclToDeclGroup( ParseObjCAtInterfaceDeclaration(AtLoc, DS.getAttributes())); } // If the declspec consisted only of 'extern' and we have a string // literal following it, this must be a C++ linkage specifier like // 'extern "C"'. if (!getLangOpts().HLSL && getLangOpts().CPlusPlus && isTokenStringLiteral() && // HLSL Change - disallow extern "C" DS.getStorageClassSpec() == DeclSpec::SCS_extern && DS.getParsedSpecifiers() == DeclSpec::PQ_StorageClassSpecifier) { Decl *TheDecl = ParseLinkage(DS, Declarator::FileContext); return Actions.ConvertDeclToDeclGroup(TheDecl); } return ParseDeclGroup(DS, Declarator::FileContext); } Parser::DeclGroupPtrTy Parser::ParseDeclarationOrFunctionDefinition(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS, AccessSpecifier AS) { if (DS) { return ParseDeclOrFunctionDefInternal(attrs, *DS, AS); } else { ParsingDeclSpec PDS(*this); // Must temporarily exit the objective-c container scope for // parsing c constructs and re-enter objc container scope // afterwards. ObjCDeclContextSwitch ObjCDC(*this); return ParseDeclOrFunctionDefInternal(attrs, PDS, AS); } } /// ParseFunctionDefinition - We parsed and verified that the specified /// Declarator is well formed. If this is a K&R-style function, read the /// parameters declaration-list, then start the compound-statement. /// /// function-definition: [C99 6.9.1] /// decl-specs declarator declaration-list[opt] compound-statement /// [C90] function-definition: [C99 6.7.1] - implicit int result /// [C90] decl-specs[opt] declarator declaration-list[opt] compound-statement /// [C++] function-definition: [C++ 8.4] /// decl-specifier-seq[opt] declarator ctor-initializer[opt] /// function-body /// [C++] function-definition: [C++ 8.4] /// decl-specifier-seq[opt] declarator function-try-block /// Decl *Parser::ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, LateParsedAttrList *LateParsedAttrs) { // Poison SEH identifiers so they are flagged as illegal in function bodies. PoisonSEHIdentifiersRAIIObject PoisonSEHIdentifiers(*this, true); const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); // If this is C90 and the declspecs were completely missing, fudge in an // implicit int. We do this here because this is the only place where // declaration-specifiers are completely optional in the grammar. if (getLangOpts().ImplicitInt && D.getDeclSpec().isEmpty()) { const char *PrevSpec; unsigned DiagID; const PrintingPolicy &Policy = Actions.getASTContext().getPrintingPolicy(); D.getMutableDeclSpec().SetTypeSpecType(DeclSpec::TST_int, D.getIdentifierLoc(), PrevSpec, DiagID, Policy); D.SetRangeBegin(D.getDeclSpec().getSourceRange().getBegin()); } // If this declaration was formed with a K&R-style identifier list for the // arguments, parse declarations for all of the args next. // int foo(a,b) int a; float b; {} if (!getLangOpts().HLSL && FTI.isKNRPrototype()) // HLSL Change - there is no support for K&R-style functions ParseKNRParamDeclarations(D); // We should have either an opening brace or, in a C++ constructor, // we may have a colon. if (Tok.isNot(tok::l_brace) && ((getLangOpts().HLSL && Tok.isNot(tok::colon)) || // HLSL Change - for HLSL, only allow ':', not try or = (!getLangOpts().CPlusPlus || (Tok.isNot(tok::colon) && Tok.isNot(tok::kw_try) && Tok.isNot(tok::equal))))) { Diag(Tok, diag::err_expected_fn_body); // Skip over garbage, until we get to '{'. Don't eat the '{'. SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch); // If we didn't find the '{', bail out. if (Tok.isNot(tok::l_brace)) return nullptr; } // Check to make sure that any normal attributes are allowed to be on // a definition. Late parsed attributes are checked at the end. if (Tok.isNot(tok::equal)) { AttributeList *DtorAttrs = D.getAttributes(); while (DtorAttrs) { if (DtorAttrs->isKnownToGCC() && !DtorAttrs->isCXX11Attribute()) { Diag(DtorAttrs->getLoc(), diag::warn_attribute_on_function_definition) << DtorAttrs->getName(); } DtorAttrs = DtorAttrs->getNext(); } } // In delayed template parsing mode, for function template we consume the // tokens and store them for late parsing at the end of the translation unit. if (getLangOpts().DelayedTemplateParsing && Tok.isNot(tok::equal) && TemplateInfo.Kind == ParsedTemplateInfo::Template && Actions.canDelayFunctionBody(D)) { MultiTemplateParamsArg TemplateParameterLists(*TemplateInfo.TemplateParams); ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); Scope *ParentScope = getCurScope()->getParent(); D.setFunctionDefinitionKind(FDK_Definition); Decl *DP = Actions.HandleDeclarator(ParentScope, D, TemplateParameterLists); D.complete(DP); D.getMutableDeclSpec().abort(); CachedTokens Toks; LexTemplateFunctionForLateParsing(Toks); if (DP) { FunctionDecl *FnD = DP->getAsFunction(); Actions.CheckForFunctionRedefinition(FnD); Actions.MarkAsLateParsedTemplate(FnD, DP, Toks); } return DP; } else if (CurParsedObjCImpl && !getLangOpts().HLSL && // HLSL Change - remove support for Obj-C parsing !TemplateInfo.TemplateParams && (Tok.is(tok::l_brace) || Tok.is(tok::kw_try) || Tok.is(tok::colon)) && Actions.CurContext->isTranslationUnit()) { ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); Scope *ParentScope = getCurScope()->getParent(); D.setFunctionDefinitionKind(FDK_Definition); Decl *FuncDecl = Actions.HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); D.complete(FuncDecl); D.getMutableDeclSpec().abort(); if (FuncDecl) { // Consume the tokens and store them for later parsing. StashAwayMethodOrFunctionBodyTokens(FuncDecl); CurParsedObjCImpl->HasCFunction = true; return FuncDecl; } // FIXME: Should we really fall through here? } // Enter a scope for the function body. ParseScope BodyScope(this, Scope::FnScope|Scope::DeclScope); // Tell the actions module that we have entered a function definition with the // specified Declarator for the function. Decl *Res = TemplateInfo.TemplateParams? Actions.ActOnStartOfFunctionTemplateDef(getCurScope(), *TemplateInfo.TemplateParams, D) : Actions.ActOnStartOfFunctionDef(getCurScope(), D); // Break out of the ParsingDeclarator context before we parse the body. D.complete(Res); // Break out of the ParsingDeclSpec context, too. This const_cast is // safe because we're always the sole owner. D.getMutableDeclSpec().abort(); if (!getLangOpts().HLSL && TryConsumeToken(tok::equal)) { // HLSL Change: this has already been rejected in this function assert(getLangOpts().CPlusPlus && "Only C++ function definitions have '='"); bool Delete = false; SourceLocation KWLoc; if (TryConsumeToken(tok::kw_delete, KWLoc)) { Diag(KWLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_deleted_function : diag::ext_deleted_function); Actions.SetDeclDeleted(Res, KWLoc); Delete = true; } else if (TryConsumeToken(tok::kw_default, KWLoc)) { Diag(KWLoc, getLangOpts().CPlusPlus11 ? diag::warn_cxx98_compat_defaulted_function : diag::ext_defaulted_function); Actions.SetDeclDefaulted(Res, KWLoc); } else { llvm_unreachable("function definition after = not 'delete' or 'default'"); } if (Tok.is(tok::comma)) { Diag(KWLoc, diag::err_default_delete_in_multiple_declaration) << Delete; SkipUntil(tok::semi); } else if (ExpectAndConsume(tok::semi, diag::err_expected_after, Delete ? "delete" : "default")) { SkipUntil(tok::semi); } Stmt *GeneratedBody = Res ? Res->getBody() : nullptr; Actions.ActOnFinishFunctionBody(Res, GeneratedBody, false); return Res; } if (Tok.is(tok::kw_try) && !getLangOpts().HLSL) // HLSL Change: this has already been rejected in this function return ParseFunctionTryBlock(Res, BodyScope); // If we have a colon, then we're probably parsing a C++ // ctor-initializer. if (Tok.is(tok::colon)) { ParseConstructorInitializer(Res); // Recover from error. if (!Tok.is(tok::l_brace)) { BodyScope.Exit(); Actions.ActOnFinishFunctionBody(Res, nullptr); return Res; } } else Actions.ActOnDefaultCtorInitializers(Res); // Late attributes are parsed in the same scope as the function body. if (LateParsedAttrs) ParseLexedAttributeList(*LateParsedAttrs, Res, false, true); return ParseFunctionStatementBody(Res, BodyScope); } /// ParseKNRParamDeclarations - Parse 'declaration-list[opt]' which provides /// types for a function with a K&R-style identifier list for arguments. void Parser::ParseKNRParamDeclarations(Declarator &D) { // We know that the top-level of this declarator is a function. DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); // Enter function-declaration scope, limiting any declarators to the // function prototype scope, including parameter declarators. ParseScope PrototypeScope(this, Scope::FunctionPrototypeScope | Scope::FunctionDeclarationScope | Scope::DeclScope); // Read all the argument declarations. while (isDeclarationSpecifier()) { SourceLocation DSStart = Tok.getLocation(); // Parse the common declaration-specifiers piece. DeclSpec DS(AttrFactory); ParseDeclarationSpecifiers(DS); // C99 6.9.1p6: 'each declaration in the declaration list shall have at // least one declarator'. // NOTE: GCC just makes this an ext-warn. It's not clear what it does with // the declarations though. It's trivial to ignore them, really hard to do // anything else with them. if (TryConsumeToken(tok::semi)) { Diag(DSStart, diag::err_declaration_does_not_declare_param); continue; } // C99 6.9.1p6: Declarations shall contain no storage-class specifiers other // than register. if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && DS.getStorageClassSpec() != DeclSpec::SCS_register) { Diag(DS.getStorageClassSpecLoc(), diag::err_invalid_storage_class_in_func_decl); DS.ClearStorageClassSpecs(); } if (DS.getThreadStorageClassSpec() != DeclSpec::TSCS_unspecified) { Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_storage_class_in_func_decl); DS.ClearStorageClassSpecs(); } // Parse the first declarator attached to this declspec. Declarator ParmDeclarator(DS, Declarator::KNRTypeListContext); ParseDeclarator(ParmDeclarator); // Handle the full declarator list. while (1) { // If attributes are present, parse them. MaybeParseGNUAttributes(ParmDeclarator); // Ask the actions module to compute the type for this declarator. Decl *Param = Actions.ActOnParamDeclarator(getCurScope(), ParmDeclarator); if (Param && // A missing identifier has already been diagnosed. ParmDeclarator.getIdentifier()) { // Scan the argument list looking for the correct param to apply this // type. for (unsigned i = 0; ; ++i) { // C99 6.9.1p6: those declarators shall declare only identifiers from // the identifier list. if (i == FTI.NumParams) { Diag(ParmDeclarator.getIdentifierLoc(), diag::err_no_matching_param) << ParmDeclarator.getIdentifier(); break; } if (FTI.Params[i].Ident == ParmDeclarator.getIdentifier()) { // Reject redefinitions of parameters. if (FTI.Params[i].Param) { Diag(ParmDeclarator.getIdentifierLoc(), diag::err_param_redefinition) << ParmDeclarator.getIdentifier(); } else { FTI.Params[i].Param = Param; } break; } } } // If we don't have a comma, it is either the end of the list (a ';') or // an error, bail out. if (Tok.isNot(tok::comma)) break; ParmDeclarator.clear(); // Consume the comma. ParmDeclarator.setCommaLoc(ConsumeToken()); // Parse the next declarator. ParseDeclarator(ParmDeclarator); } // Consume ';' and continue parsing. if (!ExpectAndConsumeSemi(diag::err_expected_semi_declaration)) continue; // Otherwise recover by skipping to next semi or mandatory function body. if (SkipUntil(tok::l_brace, StopAtSemi | StopBeforeMatch)) break; TryConsumeToken(tok::semi); } // The actions module must verify that all arguments were declared. Actions.ActOnFinishKNRParamDeclarations(getCurScope(), D, Tok.getLocation()); } /// ParseAsmStringLiteral - This is just a normal string-literal, but is not /// allowed to be a wide string, and is not subject to character translation. /// /// [GNU] asm-string-literal: /// string-literal /// ExprResult Parser::ParseAsmStringLiteral() { assert(!getLangOpts().HLSL); // HLSL Change - this point should be unreachable if (!isTokenStringLiteral()) { Diag(Tok, diag::err_expected_string_literal) << /*Source='in...'*/0 << "'asm'"; return ExprError(); } ExprResult AsmString(ParseStringLiteralExpression()); if (!AsmString.isInvalid()) { const auto *SL = cast<StringLiteral>(AsmString.get()); if (!SL->isAscii()) { Diag(Tok, diag::err_asm_operand_wide_string_literal) << SL->isWide() << SL->getSourceRange(); return ExprError(); } } return AsmString; } /// ParseSimpleAsm /// /// [GNU] simple-asm-expr: /// 'asm' '(' asm-string-literal ')' /// ExprResult Parser::ParseSimpleAsm(SourceLocation *EndLoc) { assert(!getLangOpts().HLSL); // HLSL Change - this point should be unreachable assert(Tok.is(tok::kw_asm) && "Not an asm!"); SourceLocation Loc = ConsumeToken(); if (Tok.is(tok::kw_volatile)) { // Remove from the end of 'asm' to the end of 'volatile'. SourceRange RemovalRange(PP.getLocForEndOfToken(Loc), PP.getLocForEndOfToken(Tok.getLocation())); Diag(Tok, diag::warn_file_asm_volatile) << FixItHint::CreateRemoval(RemovalRange); ConsumeToken(); } BalancedDelimiterTracker T(*this, tok::l_paren); if (T.consumeOpen()) { Diag(Tok, diag::err_expected_lparen_after) << "asm"; return ExprError(); } ExprResult Result(ParseAsmStringLiteral()); if (!Result.isInvalid()) { // Close the paren and get the location of the end bracket T.consumeClose(); if (EndLoc) *EndLoc = T.getCloseLocation(); } else if (SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch)) { if (EndLoc) *EndLoc = Tok.getLocation(); ConsumeParen(); } return Result; } /// \brief Get the TemplateIdAnnotation from the token and put it in the /// cleanup pool so that it gets destroyed when parsing the current top level /// declaration is finished. TemplateIdAnnotation *Parser::takeTemplateIdAnnotation(const Token &tok) { assert(tok.is(tok::annot_template_id) && "Expected template-id token"); TemplateIdAnnotation * Id = static_cast<TemplateIdAnnotation *>(tok.getAnnotationValue()); return Id; } void Parser::AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation) { // Push the current token back into the token stream (or revert it if it is // cached) and use an annotation scope token for current token. if (PP.isBacktrackEnabled()) PP.RevertCachedTokens(1); else PP.EnterToken(Tok); Tok.setKind(tok::annot_cxxscope); Tok.setAnnotationValue(Actions.SaveNestedNameSpecifierAnnotation(SS)); Tok.setAnnotationRange(SS.getRange()); // In case the tokens were cached, have Preprocessor replace them // with the annotation token. We don't need to do this if we've // just reverted back to a prior state. if (IsNewAnnotation) PP.AnnotateCachedTokens(Tok); } /// \brief Attempt to classify the name at the current token position. This may /// form a type, scope or primary expression annotation, or replace the token /// with a typo-corrected keyword. This is only appropriate when the current /// name must refer to an entity which has already been declared. /// /// \param IsAddressOfOperand Must be \c true if the name is preceded by an '&' /// and might possibly have a dependent nested name specifier. /// \param CCC Indicates how to perform typo-correction for this name. If NULL, /// no typo correction will be performed. Parser::AnnotatedNameKind Parser::TryAnnotateName(bool IsAddressOfOperand, std::unique_ptr<CorrectionCandidateCallback> CCC) { assert(Tok.is(tok::identifier) || Tok.is(tok::annot_cxxscope)); const bool EnteringContext = false; const bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); CXXScopeSpec SS; if (getLangOpts().CPlusPlus && ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) return ANK_Error; if (Tok.isNot(tok::identifier) || SS.isInvalid()) { if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS, !WasScopeAnnotation)) return ANK_Error; return ANK_Unresolved; } IdentifierInfo *Name = Tok.getIdentifierInfo(); SourceLocation NameLoc = Tok.getLocation(); // FIXME: Move the tentative declaration logic into ClassifyName so we can // typo-correct to tentatively-declared identifiers. if (isTentativelyDeclared(Name)) { // Identifier has been tentatively declared, and thus cannot be resolved as // an expression. Fall back to annotating it as a type. if (TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, false, SS, !WasScopeAnnotation)) return ANK_Error; return Tok.is(tok::annot_typename) ? ANK_Success : ANK_TentativeDecl; } Token Next = NextToken(); // Look up and classify the identifier. We don't perform any typo-correction // after a scope specifier, because in general we can't recover from typos // there (eg, after correcting 'A::tempalte B<X>::C' [sic], we would need to // jump back into scope specifier parsing). Sema::NameClassification Classification = Actions.ClassifyName( getCurScope(), SS, Name, NameLoc, Next, IsAddressOfOperand, SS.isEmpty() ? std::move(CCC) : nullptr); switch (Classification.getKind()) { case Sema::NC_Error: return ANK_Error; case Sema::NC_Keyword: // The identifier was typo-corrected to a keyword. Tok.setIdentifierInfo(Name); Tok.setKind(Name->getTokenID()); PP.TypoCorrectToken(Tok); if (SS.isNotEmpty()) AnnotateScopeToken(SS, !WasScopeAnnotation); // We've "annotated" this as a keyword. return ANK_Success; case Sema::NC_Unknown: // It's not something we know about. Leave it unannotated. break; case Sema::NC_Type: { SourceLocation BeginLoc = NameLoc; if (SS.isNotEmpty()) BeginLoc = SS.getBeginLoc(); /// An Objective-C object type followed by '<' is a specialization of /// a parameterized class type or a protocol-qualified type. ParsedType Ty = Classification.getType(); if (getLangOpts().ObjC1 && NextToken().is(tok::less) && (Ty.get()->isObjCObjectType() || Ty.get()->isObjCObjectPointerType())) { // Consume the name. SourceLocation IdentifierLoc = ConsumeToken(); SourceLocation NewEndLoc; TypeResult NewType = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty, /*consumeLastToken=*/false, NewEndLoc); if (NewType.isUsable()) Ty = NewType.get(); } Tok.setKind(tok::annot_typename); setTypeAnnotation(Tok, Ty); Tok.setAnnotationEndLoc(Tok.getLocation()); Tok.setLocation(BeginLoc); PP.AnnotateCachedTokens(Tok); return ANK_Success; } case Sema::NC_Expression: Tok.setKind(tok::annot_primary_expr); setExprAnnotation(Tok, Classification.getExpression()); Tok.setAnnotationEndLoc(NameLoc); if (SS.isNotEmpty()) Tok.setLocation(SS.getBeginLoc()); PP.AnnotateCachedTokens(Tok); return ANK_Success; case Sema::NC_TypeTemplate: if (Next.isNot(tok::less)) { // This may be a type template being used as a template template argument. if (SS.isNotEmpty()) AnnotateScopeToken(SS, !WasScopeAnnotation); return ANK_TemplateName; } LLVM_FALLTHROUGH; // HLSL Change case Sema::NC_VarTemplate: case Sema::NC_FunctionTemplate: { // We have a type, variable or function template followed by '<'. ConsumeToken(); UnqualifiedId Id; Id.setIdentifier(Name, NameLoc); if (AnnotateTemplateIdToken( TemplateTy::make(Classification.getTemplateName()), Classification.getTemplateNameKind(), SS, SourceLocation(), Id)) return ANK_Error; return ANK_Success; } case Sema::NC_NestedNameSpecifier: llvm_unreachable("already parsed nested name specifier"); } // Unable to classify the name, but maybe we can annotate a scope specifier. if (SS.isNotEmpty()) AnnotateScopeToken(SS, !WasScopeAnnotation); return ANK_Unresolved; } bool Parser::TryKeywordIdentFallback(bool DisableKeyword) { assert(Tok.isNot(tok::identifier)); Diag(Tok, diag::ext_keyword_as_ident) << PP.getSpelling(Tok) << DisableKeyword; if (DisableKeyword) Tok.getIdentifierInfo()->RevertTokenIDToIdentifier(); Tok.setKind(tok::identifier); return true; } /// TryAnnotateTypeOrScopeToken - If the current token position is on a /// typename (possibly qualified in C++) or a C++ scope specifier not followed /// by a typename, TryAnnotateTypeOrScopeToken will replace one or more tokens /// with a single annotation token representing the typename or C++ scope /// respectively. /// This simplifies handling of C++ scope specifiers and allows efficient /// backtracking without the need to re-parse and resolve nested-names and /// typenames. /// It will mainly be called when we expect to treat identifiers as typenames /// (if they are typenames). For example, in C we do not expect identifiers /// inside expressions to be treated as typenames so it will not be called /// for expressions in C. /// The benefit for C/ObjC is that a typename will be annotated and /// Actions.getTypeName will not be needed to be called again (e.g. getTypeName /// will not be called twice, once to check whether we have a declaration /// specifier, and another one to get the actual type inside /// ParseDeclarationSpecifiers). /// /// This returns true if an error occurred. /// /// Note that this routine emits an error if you call it with ::new or ::delete /// as the current tokens, so only call it in contexts where these are invalid. bool Parser::TryAnnotateTypeOrScopeToken(bool EnteringContext, bool NeedType) { assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || Tok.is(tok::kw_typename) || Tok.is(tok::annot_cxxscope) || Tok.is(tok::kw_decltype) || Tok.is(tok::annot_template_id) || Tok.is(tok::kw___super)) && "Cannot be a type or scope token!"); if (Tok.is(tok::kw_typename)) { // MSVC lets you do stuff like: // typename typedef T_::D D; // // We will consume the typedef token here and put it back after we have // parsed the first identifier, transforming it into something more like: // typename T_::D typedef D; if (getLangOpts().MSVCCompat && NextToken().is(tok::kw_typedef)) { Token TypedefToken; PP.Lex(TypedefToken); bool Result = TryAnnotateTypeOrScopeToken(EnteringContext, NeedType); PP.EnterToken(Tok); Tok = TypedefToken; if (!Result) Diag(Tok.getLocation(), diag::warn_expected_qualified_after_typename); return Result; } // Parse a C++ typename-specifier, e.g., "typename T::type". // // typename-specifier: // 'typename' '::' [opt] nested-name-specifier identifier // 'typename' '::' [opt] nested-name-specifier template [opt] // simple-template-id SourceLocation TypenameLoc = ConsumeToken(); CXXScopeSpec SS; if (ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/ParsedType(), /*EnteringContext=*/false, nullptr, /*IsTypename*/ true)) return true; if (!SS.isSet()) { if (Tok.is(tok::identifier) || Tok.is(tok::annot_template_id) || Tok.is(tok::annot_decltype)) { // Attempt to recover by skipping the invalid 'typename' if (Tok.is(tok::annot_decltype) || (!TryAnnotateTypeOrScopeToken(EnteringContext, NeedType) && Tok.isAnnotation())) { unsigned DiagID = diag::err_expected_qualified_after_typename; // MS compatibility: MSVC permits using known types with typename. // e.g. "typedef typename T* pointer_type" if (getLangOpts().MicrosoftExt) DiagID = diag::warn_expected_qualified_after_typename; Diag(Tok.getLocation(), DiagID); return false; } } Diag(Tok.getLocation(), diag::err_expected_qualified_after_typename); return true; } TypeResult Ty; if (Tok.is(tok::identifier)) { // FIXME: check whether the next token is '<', first! Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, *Tok.getIdentifierInfo(), Tok.getLocation()); } else if (Tok.is(tok::annot_template_id)) { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); if (TemplateId->Kind != TNK_Type_template && TemplateId->Kind != TNK_Dependent_template_name) { Diag(Tok, diag::err_typename_refers_to_non_type_template) << Tok.getAnnotationRange(); return true; } ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), TemplateId->NumArgs); Ty = Actions.ActOnTypenameType(getCurScope(), TypenameLoc, SS, TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, TemplateId->RAngleLoc); } else { Diag(Tok, diag::err_expected_type_name_after_typename) << SS.getRange(); return true; } SourceLocation EndLoc = Tok.getLastLoc(); Tok.setKind(tok::annot_typename); setTypeAnnotation(Tok, Ty.isInvalid() ? ParsedType() : Ty.get()); Tok.setAnnotationEndLoc(EndLoc); Tok.setLocation(TypenameLoc); PP.AnnotateCachedTokens(Tok); return false; } // Remembers whether the token was originally a scope annotation. bool WasScopeAnnotation = Tok.is(tok::annot_cxxscope); CXXScopeSpec SS; if (getLangOpts().CPlusPlus) // HLSL Note - allowing scope qualification if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) return true; return TryAnnotateTypeOrScopeTokenAfterScopeSpec(EnteringContext, NeedType, SS, !WasScopeAnnotation); } /// \brief Try to annotate a type or scope token, having already parsed an /// optional scope specifier. \p IsNewScope should be \c true unless the scope /// specifier was extracted from an existing tok::annot_cxxscope annotation. bool Parser::TryAnnotateTypeOrScopeTokenAfterScopeSpec(bool EnteringContext, bool NeedType, CXXScopeSpec &SS, bool IsNewScope) { if (Tok.is(tok::identifier)) { IdentifierInfo *CorrectedII = nullptr; // Determine whether the identifier is a type name. if (ParsedType Ty = Actions.getTypeName(*Tok.getIdentifierInfo(), Tok.getLocation(), getCurScope(), &SS, false, NextToken().is(tok::period), ParsedType(), /*IsCtorOrDtorName=*/false, /*NonTrivialTypeSourceInfo*/ true, NeedType ? &CorrectedII : nullptr)) { // A FixIt was applied as a result of typo correction if (CorrectedII) Tok.setIdentifierInfo(CorrectedII); SourceLocation BeginLoc = Tok.getLocation(); if (SS.isNotEmpty()) // it was a C++ qualified type name. BeginLoc = SS.getBeginLoc(); /// An Objective-C object type followed by '<' is a specialization of /// a parameterized class type or a protocol-qualified type. if (getLangOpts().ObjC1 && NextToken().is(tok::less) && (Ty.get()->isObjCObjectType() || Ty.get()->isObjCObjectPointerType())) { // Consume the name. SourceLocation IdentifierLoc = ConsumeToken(); SourceLocation NewEndLoc; TypeResult NewType = parseObjCTypeArgsAndProtocolQualifiers(IdentifierLoc, Ty, /*consumeLastToken=*/false, NewEndLoc); if (NewType.isUsable()) Ty = NewType.get(); } // This is a typename. Replace the current token in-place with an // annotation type token. Tok.setKind(tok::annot_typename); setTypeAnnotation(Tok, Ty); Tok.setAnnotationEndLoc(Tok.getLocation()); Tok.setLocation(BeginLoc); // In case the tokens were cached, have Preprocessor replace // them with the annotation token. PP.AnnotateCachedTokens(Tok); return false; } if (!getLangOpts().CPlusPlus) { // HLSL Note - allow '::' qualification // If we're in C, we can't have :: tokens at all (the lexer won't return // them). If the identifier is not a type, then it can't be scope either, // just early exit. return false; } // If this is a template-id, annotate with a template-id or type token. if (NextToken().is(tok::less)) { TemplateTy Template; UnqualifiedId TemplateName; TemplateName.setIdentifier(Tok.getIdentifierInfo(), Tok.getLocation()); bool MemberOfUnknownSpecialization; if (TemplateNameKind TNK = Actions.isTemplateName(getCurScope(), SS, /*hasTemplateKeyword=*/false, TemplateName, /*ObjectType=*/ ParsedType(), EnteringContext, Template, MemberOfUnknownSpecialization)) { // Consume the identifier. ConsumeToken(); if (AnnotateTemplateIdToken(Template, TNK, SS, SourceLocation(), TemplateName)) { // If an unrecoverable error occurred, we need to return true here, // because the token stream is in a damaged state. We may not return // a valid identifier. return true; } } } // The current token, which is either an identifier or a // template-id, is not part of the annotation. Fall through to // push that token back into the stream and complete the C++ scope // specifier annotation. } if (Tok.is(tok::annot_template_id)) { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); if (TemplateId->Kind == TNK_Type_template) { // A template-id that refers to a type was parsed into a // template-id annotation in a context where we weren't allowed // to produce a type annotation token. Update the template-id // annotation token to a type annotation token now. AnnotateTemplateIdTokenAsType(); return false; } } if (SS.isEmpty()) return false; // A C++ scope specifier that isn't followed by a typename. AnnotateScopeToken(SS, IsNewScope); return false; } /// TryAnnotateScopeToken - Like TryAnnotateTypeOrScopeToken but only /// annotates C++ scope specifiers and template-ids. This returns /// true if there was an error that could not be recovered from. /// /// Note that this routine emits an error if you call it with ::new or ::delete /// as the current tokens, so only call it in contexts where these are invalid. bool Parser::TryAnnotateCXXScopeToken(bool EnteringContext) { assert(getLangOpts().CPlusPlus && "Call sites of this function should be guarded by checking for C++"); assert((Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super)) && "Cannot be a type or scope token!"); CXXScopeSpec SS; if (ParseOptionalCXXScopeSpecifier(SS, ParsedType(), EnteringContext)) return true; if (SS.isEmpty()) return false; AnnotateScopeToken(SS, true); return false; } bool Parser::isTokenEqualOrEqualTypo() { tok::TokenKind Kind = Tok.getKind(); switch (Kind) { default: return false; case tok::ampequal: // &= case tok::starequal: // *= case tok::plusequal: // += case tok::minusequal: // -= case tok::exclaimequal: // != case tok::slashequal: // /= case tok::percentequal: // %= case tok::lessequal: // <= case tok::lesslessequal: // <<= case tok::greaterequal: // >= case tok::greatergreaterequal: // >>= case tok::caretequal: // ^= case tok::pipeequal: // |= case tok::equalequal: // == Diag(Tok, diag::err_invalid_token_after_declarator_suggest_equal) << Kind << FixItHint::CreateReplacement(SourceRange(Tok.getLocation()), "="); LLVM_FALLTHROUGH; // HLSL Change case tok::equal: return true; } } SourceLocation Parser::handleUnexpectedCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); for (Scope *S = getCurScope(); S; S = S->getParent()) { if (S->getFlags() & Scope::FnScope) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_RecoveryInFunction); cutOffParsing(); return PrevTokLocation; } if (S->getFlags() & Scope::ClassScope) { Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Class); cutOffParsing(); return PrevTokLocation; } } Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Namespace); cutOffParsing(); return PrevTokLocation; } // Code-completion pass-through functions void Parser::CodeCompleteDirective(bool InConditional) { Actions.CodeCompletePreprocessorDirective(InConditional); } void Parser::CodeCompleteInConditionalExclusion() { Actions.CodeCompleteInPreprocessorConditionalExclusion(getCurScope()); } void Parser::CodeCompleteMacroName(bool IsDefinition) { Actions.CodeCompletePreprocessorMacroName(IsDefinition); } void Parser::CodeCompletePreprocessorExpression() { Actions.CodeCompletePreprocessorExpression(); } void Parser::CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) { Actions.CodeCompletePreprocessorMacroArgument(getCurScope(), Macro, MacroInfo, ArgumentIndex); } void Parser::CodeCompleteNaturalLanguage() { Actions.CodeCompleteNaturalLanguage(); } bool Parser::ParseMicrosoftIfExistsCondition(IfExistsCondition& Result) { assert((Tok.is(tok::kw___if_exists) || Tok.is(tok::kw___if_not_exists)) && "Expected '__if_exists' or '__if_not_exists'"); Result.IsIfExists = Tok.is(tok::kw___if_exists); Result.KeywordLoc = ConsumeToken(); BalancedDelimiterTracker T(*this, tok::l_paren); if (T.consumeOpen()) { Diag(Tok, diag::err_expected_lparen_after) << (Result.IsIfExists? "__if_exists" : "__if_not_exists"); return true; } // Parse nested-name-specifier. if (getLangOpts().CPlusPlus) ParseOptionalCXXScopeSpecifier(Result.SS, ParsedType(), /*EnteringContext=*/false); // Check nested-name specifier. if (Result.SS.isInvalid()) { T.skipToEnd(); return true; } // Parse the unqualified-id. SourceLocation TemplateKWLoc; // FIXME: parsed, but unused. if (ParseUnqualifiedId(Result.SS, false, true, true, ParsedType(), TemplateKWLoc, Result.Name)) { T.skipToEnd(); return true; } if (T.consumeClose()) return true; // Check if the symbol exists. switch (Actions.CheckMicrosoftIfExistsSymbol(getCurScope(), Result.KeywordLoc, Result.IsIfExists, Result.SS, Result.Name)) { case Sema::IER_Exists: Result.Behavior = Result.IsIfExists ? IEB_Parse : IEB_Skip; break; case Sema::IER_DoesNotExist: Result.Behavior = !Result.IsIfExists ? IEB_Parse : IEB_Skip; break; case Sema::IER_Dependent: Result.Behavior = IEB_Dependent; break; case Sema::IER_Error: return true; } return false; } void Parser::ParseMicrosoftIfExistsExternalDeclaration() { IfExistsCondition Result; if (ParseMicrosoftIfExistsCondition(Result)) return; BalancedDelimiterTracker Braces(*this, tok::l_brace); if (Braces.consumeOpen()) { Diag(Tok, diag::err_expected) << tok::l_brace; return; } switch (Result.Behavior) { case IEB_Parse: // Parse declarations below. break; case IEB_Dependent: llvm_unreachable("Cannot have a dependent external declaration"); case IEB_Skip: Braces.skipToEnd(); return; } // Parse the declarations. // FIXME: Support module import within __if_exists? while (Tok.isNot(tok::r_brace) && !isEofOrEom()) { ParsedAttributesWithRange attrs(AttrFactory); MaybeParseCXX11Attributes(attrs); assert(!getLangOpts().HLSL); // HLSL Change: in lieu of MaybeParseHLSLAttributes - if-exists not allowed MaybeParseMicrosoftAttributes(attrs); DeclGroupPtrTy Result = ParseExternalDeclaration(attrs); if (Result && !getCurScope()->getParent()) Actions.getASTConsumer().HandleTopLevelDecl(Result.get()); } Braces.consumeClose(); } Parser::DeclGroupPtrTy Parser::ParseModuleImport(SourceLocation AtLoc) { assert(Tok.isObjCAtKeyword(tok::objc_import) && "Improper start to module import"); SourceLocation ImportLoc = ConsumeToken(); SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path; // Parse the module path. do { if (!Tok.is(tok::identifier)) { if (Tok.is(tok::code_completion)) { Actions.CodeCompleteModuleImport(ImportLoc, Path); cutOffParsing(); return DeclGroupPtrTy(); } Diag(Tok, diag::err_module_expected_ident); SkipUntil(tok::semi); return DeclGroupPtrTy(); } // Record this part of the module path. Path.push_back(std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation())); ConsumeToken(); if (Tok.is(tok::period)) { ConsumeToken(); continue; } break; } while (true); if (PP.hadModuleLoaderFatalFailure()) { // With a fatal failure in the module loader, we abort parsing. cutOffParsing(); return DeclGroupPtrTy(); } DeclResult Import = Actions.ActOnModuleImport(AtLoc, ImportLoc, Path); ExpectAndConsumeSemi(diag::err_module_expected_semi); if (Import.isInvalid()) return DeclGroupPtrTy(); return Actions.ConvertDeclToDeclGroup(Import.get()); } bool BalancedDelimiterTracker::diagnoseOverflow() { P.Diag(P.Tok, diag::err_bracket_depth_exceeded) << P.getLangOpts().BracketDepth; P.Diag(P.Tok, diag::note_bracket_depth); P.cutOffParsing(); return true; } bool BalancedDelimiterTracker::expectAndConsume(unsigned DiagID, const char *Msg, tok::TokenKind SkipToTok) { LOpen = P.Tok.getLocation(); if (P.ExpectAndConsume(Kind, DiagID, Msg)) { if (SkipToTok != tok::unknown) P.SkipUntil(SkipToTok, Parser::StopAtSemi); return true; } if (getDepth() < MaxDepth) return false; return diagnoseOverflow(); } bool BalancedDelimiterTracker::diagnoseMissingClose() { assert(!P.Tok.is(Close) && "Should have consumed closing delimiter"); P.Diag(P.Tok, diag::err_expected) << Close; P.Diag(LOpen, diag::note_matching) << Kind; // If we're not already at some kind of closing bracket, skip to our closing // token. if (P.Tok.isNot(tok::r_paren) && P.Tok.isNot(tok::r_brace) && P.Tok.isNot(tok::r_square) && P.SkipUntil(Close, FinalToken, Parser::StopAtSemi | Parser::StopBeforeMatch) && P.Tok.is(Close)) LClose = P.ConsumeAnyToken(); return true; } void BalancedDelimiterTracker::skipToEnd() { P.SkipUntil(Close, Parser::StopBeforeMatch); consumeClose(); }
0
repos/DirectXShaderCompiler/tools/clang/lib
repos/DirectXShaderCompiler/tools/clang/lib/Parse/ParseTentative.cpp
//===--- ParseTentative.cpp - Ambiguity Resolution Parsing ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the tentative parsing portions of the Parser // interfaces, for ambiguity resolution. // //===----------------------------------------------------------------------===// #include "clang/Parse/Parser.h" #include "clang/Parse/ParseDiagnostic.h" #include "clang/Sema/ParsedTemplate.h" using namespace clang; /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. /// /// declaration-statement: /// block-declaration /// /// block-declaration: /// simple-declaration /// asm-definition /// namespace-alias-definition /// using-declaration /// using-directive /// [C++0x] static_assert-declaration /// /// asm-definition: /// 'asm' '(' string-literal ')' ';' /// /// namespace-alias-definition: /// 'namespace' identifier = qualified-namespace-specifier ';' /// /// using-declaration: /// 'using' typename[opt] '::'[opt] nested-name-specifier /// unqualified-id ';' /// 'using' '::' unqualified-id ; /// /// using-directive: /// 'using' 'namespace' '::'[opt] nested-name-specifier[opt] /// namespace-name ';' /// bool Parser::isCXXDeclarationStatement() { switch (Tok.getKind()) { // asm-definition case tok::kw_asm: // namespace-alias-definition case tok::kw_namespace: // using-declaration // using-directive case tok::kw_using: // static_assert-declaration case tok::kw_static_assert: case tok::kw__Static_assert: return true; // simple-declaration default: return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/false); } } /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. /// /// simple-declaration: /// decl-specifier-seq init-declarator-list[opt] ';' /// /// (if AllowForRangeDecl specified) /// for ( for-range-declaration : for-range-initializer ) statement /// for-range-declaration: /// attribute-specifier-seqopt type-specifier-seq declarator bool Parser::isCXXSimpleDeclaration(bool AllowForRangeDecl) { // C++ 6.8p1: // There is an ambiguity in the grammar involving expression-statements and // declarations: An expression-statement with a function-style explicit type // conversion (5.2.3) as its leftmost subexpression can be indistinguishable // from a declaration where the first declarator starts with a '('. In those // cases the statement is a declaration. [Note: To disambiguate, the whole // statement might have to be examined to determine if it is an // expression-statement or a declaration]. // C++ 6.8p3: // The disambiguation is purely syntactic; that is, the meaning of the names // occurring in such a statement, beyond whether they are type-names or not, // is not generally used in or changed by the disambiguation. Class // templates are instantiated as necessary to determine if a qualified name // is a type-name. Disambiguation precedes parsing, and a statement // disambiguated as a declaration may be an ill-formed declaration. // We don't have to parse all of the decl-specifier-seq part. There's only // an ambiguity if the first decl-specifier is // simple-type-specifier/typename-specifier followed by a '(', which may // indicate a function-style cast expression. // isCXXDeclarationSpecifier will return TPResult::Ambiguous only in such // a case. bool InvalidAsDeclaration = false; TPResult TPR = isCXXDeclarationSpecifier(TPResult::False, &InvalidAsDeclaration); if (TPR != TPResult::Ambiguous) return TPR != TPResult::False; // Returns true for TPResult::True or // TPResult::Error. // FIXME: TryParseSimpleDeclaration doesn't look past the first initializer, // and so gets some cases wrong. We can't carry on if we've already seen // something which makes this statement invalid as a declaration in this case, // since it can cause us to misparse valid code. Revisit this once // TryParseInitDeclaratorList is fixed. if (InvalidAsDeclaration) return false; // FIXME: Add statistics about the number of ambiguous statements encountered // and how they were resolved (number of declarations+number of expressions). // Ok, we have a simple-type-specifier/typename-specifier followed by a '(', // or an identifier which doesn't resolve as anything. We need tentative // parsing... TentativeParsingAction PA(*this); TPR = TryParseSimpleDeclaration(AllowForRangeDecl); PA.Revert(); // In case of an error, let the declaration parsing code handle it. if (TPR == TPResult::Error) return true; // Declarations take precedence over expressions. if (TPR == TPResult::Ambiguous) TPR = TPResult::True; assert(TPR == TPResult::True || TPR == TPResult::False); return TPR == TPResult::True; } /// Try to consume a token sequence that we've already identified as /// (potentially) starting a decl-specifier. Parser::TPResult Parser::TryConsumeDeclarationSpecifier() { switch (Tok.getKind()) { case tok::kw__Atomic: if (NextToken().isNot(tok::l_paren)) { ConsumeToken(); break; } LLVM_FALLTHROUGH; // HLSL Change case tok::kw_typeof: case tok::kw___attribute: case tok::kw___underlying_type: { ConsumeToken(); if (Tok.isNot(tok::l_paren)) return TPResult::Error; ConsumeParen(); if (!SkipUntil(tok::r_paren)) return TPResult::Error; break; } case tok::kw_class: case tok::kw_struct: case tok::kw_union: case tok::kw___interface: case tok::kw_enum: // elaborated-type-specifier: // class-key attribute-specifier-seq[opt] // nested-name-specifier[opt] identifier // class-key nested-name-specifier[opt] template[opt] simple-template-id // enum nested-name-specifier[opt] identifier // // FIXME: We don't support class-specifiers nor enum-specifiers here. ConsumeToken(); // Skip attributes. while (Tok.isOneOf(tok::l_square, tok::kw___attribute, tok::kw___declspec, tok::kw_alignas)) { if (Tok.is(tok::l_square)) { ConsumeBracket(); if (!SkipUntil(tok::r_square)) return TPResult::Error; } else { ConsumeToken(); if (Tok.isNot(tok::l_paren)) return TPResult::Error; ConsumeParen(); if (!SkipUntil(tok::r_paren)) return TPResult::Error; } } if (Tok.isOneOf(tok::identifier, tok::coloncolon, tok::kw_decltype, tok::annot_template_id) && TryAnnotateCXXScopeToken()) return TPResult::Error; if (Tok.is(tok::annot_cxxscope)) ConsumeToken(); if (Tok.isNot(tok::identifier) && Tok.isNot(tok::annot_template_id)) return TPResult::Error; ConsumeToken(); break; case tok::annot_cxxscope: ConsumeToken(); LLVM_FALLTHROUGH; // HLSL Change default: ConsumeToken(); if (getLangOpts().ObjC1 && Tok.is(tok::less)) return TryParseProtocolQualifiers(); break; } return TPResult::Ambiguous; } /// simple-declaration: /// decl-specifier-seq init-declarator-list[opt] ';' /// /// (if AllowForRangeDecl specified) /// for ( for-range-declaration : for-range-initializer ) statement /// for-range-declaration: /// attribute-specifier-seqopt type-specifier-seq declarator /// Parser::TPResult Parser::TryParseSimpleDeclaration(bool AllowForRangeDecl) { if (TryConsumeDeclarationSpecifier() == TPResult::Error) return TPResult::Error; // Two decl-specifiers in a row conclusively disambiguate this as being a // simple-declaration. Don't bother calling isCXXDeclarationSpecifier in the // overwhelmingly common case that the next token is a '('. if (Tok.isNot(tok::l_paren)) { TPResult TPR = isCXXDeclarationSpecifier(); if (TPR == TPResult::Ambiguous) return TPResult::True; if (TPR == TPResult::True || TPR == TPResult::Error) return TPR; assert(TPR == TPResult::False); } TPResult TPR = TryParseInitDeclaratorList(); if (TPR != TPResult::Ambiguous) return TPR; if (Tok.isNot(tok::semi) && (!AllowForRangeDecl || Tok.isNot(tok::colon))) return TPResult::False; return TPResult::Ambiguous; } /// Tentatively parse an init-declarator-list in order to disambiguate it from /// an expression. /// /// init-declarator-list: /// init-declarator /// init-declarator-list ',' init-declarator /// /// init-declarator: /// declarator initializer[opt] /// [GNU] declarator simple-asm-expr[opt] attributes[opt] initializer[opt] /// /// initializer: /// brace-or-equal-initializer /// '(' expression-list ')' /// /// brace-or-equal-initializer: /// '=' initializer-clause /// [C++11] braced-init-list /// /// initializer-clause: /// assignment-expression /// braced-init-list /// /// braced-init-list: /// '{' initializer-list ','[opt] '}' /// '{' '}' /// Parser::TPResult Parser::TryParseInitDeclaratorList() { while (1) { // declarator TPResult TPR = TryParseDeclarator(false/*mayBeAbstract*/); if (TPR != TPResult::Ambiguous) return TPR; // [GNU] simple-asm-expr[opt] attributes[opt] if (Tok.isOneOf(tok::kw_asm, tok::kw___attribute)) return TPResult::True; // initializer[opt] if (Tok.is(tok::l_paren)) { // Parse through the parens. ConsumeParen(); if (!SkipUntil(tok::r_paren, StopAtSemi)) return TPResult::Error; } else if (Tok.is(tok::l_brace)) { // A left-brace here is sufficient to disambiguate the parse; an // expression can never be followed directly by a braced-init-list. return TPResult::True; } else if (Tok.is(tok::equal) || isTokIdentifier_in()) { // MSVC and g++ won't examine the rest of declarators if '=' is // encountered; they just conclude that we have a declaration. // EDG parses the initializer completely, which is the proper behavior // for this case. // // At present, Clang follows MSVC and g++, since the parser does not have // the ability to parse an expression fully without recording the // results of that parse. // FIXME: Handle this case correctly. // // Also allow 'in' after an Objective-C declaration as in: // for (int (^b)(void) in array). Ideally this should be done in the // context of parsing for-init-statement of a foreach statement only. But, // in any other context 'in' is invalid after a declaration and parser // issues the error regardless of outcome of this decision. // FIXME: Change if above assumption does not hold. return TPResult::True; } if (!TryConsumeToken(tok::comma)) break; } return TPResult::Ambiguous; } /// isCXXConditionDeclaration - Disambiguates between a declaration or an /// expression for a condition of a if/switch/while/for statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// /// condition: /// expression /// type-specifier-seq declarator '=' assignment-expression /// [C++11] type-specifier-seq declarator '=' initializer-clause /// [C++11] type-specifier-seq declarator braced-init-list /// [GNU] type-specifier-seq declarator simple-asm-expr[opt] attributes[opt] /// '=' assignment-expression /// bool Parser::isCXXConditionDeclaration() { TPResult TPR = isCXXDeclarationSpecifier(); if (TPR != TPResult::Ambiguous) return TPR != TPResult::False; // Returns true for TPResult::True or // TPResult::Error. // FIXME: Add statistics about the number of ambiguous statements encountered // and how they were resolved (number of declarations+number of expressions). // Ok, we have a simple-type-specifier/typename-specifier followed by a '('. // We need tentative parsing... TentativeParsingAction PA(*this); // type-specifier-seq TryConsumeDeclarationSpecifier(); assert(Tok.is(tok::l_paren) && "Expected '('"); // declarator TPR = TryParseDeclarator(false/*mayBeAbstract*/); // In case of an error, let the declaration parsing code handle it. if (TPR == TPResult::Error) TPR = TPResult::True; if (TPR == TPResult::Ambiguous) { // '=' // [GNU] simple-asm-expr[opt] attributes[opt] if (Tok.isOneOf(tok::equal, tok::kw_asm, tok::kw___attribute)) TPR = TPResult::True; else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) TPR = TPResult::True; else TPR = TPResult::False; } PA.Revert(); assert(TPR == TPResult::True || TPR == TPResult::False); return TPR == TPResult::True; } /// \brief Determine whether the next set of tokens contains a type-id. /// /// The context parameter states what context we're parsing right /// now, which affects how this routine copes with the token /// following the type-id. If the context is TypeIdInParens, we have /// already parsed the '(' and we will cease lookahead when we hit /// the corresponding ')'. If the context is /// TypeIdAsTemplateArgument, we've already parsed the '<' or ',' /// before this template argument, and will cease lookahead when we /// hit a '>', '>>' (in C++0x), or ','. Returns true for a type-id /// and false for an expression. If during the disambiguation /// process a parsing error is encountered, the function returns /// true to let the declaration parsing code handle it. /// /// type-id: /// type-specifier-seq abstract-declarator[opt] /// bool Parser::isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous) { isAmbiguous = false; // C++ 8.2p2: // The ambiguity arising from the similarity between a function-style cast and // a type-id can occur in different contexts. The ambiguity appears as a // choice between a function-style cast expression and a declaration of a // type. The resolution is that any construct that could possibly be a type-id // in its syntactic context shall be considered a type-id. TPResult TPR = isCXXDeclarationSpecifier(); if (TPR != TPResult::Ambiguous) return TPR != TPResult::False; // Returns true for TPResult::True or // TPResult::Error. // FIXME: Add statistics about the number of ambiguous statements encountered // and how they were resolved (number of declarations+number of expressions). // Ok, we have a simple-type-specifier/typename-specifier followed by a '('. // We need tentative parsing... TentativeParsingAction PA(*this); // type-specifier-seq TryConsumeDeclarationSpecifier(); assert(Tok.is(tok::l_paren) && "Expected '('"); // declarator TPR = TryParseDeclarator(true/*mayBeAbstract*/, false/*mayHaveIdentifier*/); // In case of an error, let the declaration parsing code handle it. if (TPR == TPResult::Error) TPR = TPResult::True; if (TPR == TPResult::Ambiguous) { // We are supposed to be inside parens, so if after the abstract declarator // we encounter a ')' this is a type-id, otherwise it's an expression. if (Context == TypeIdInParens && Tok.is(tok::r_paren)) { TPR = TPResult::True; isAmbiguous = true; // We are supposed to be inside a template argument, so if after // the abstract declarator we encounter a '>', '>>' (in C++0x), or // ',', this is a type-id. Otherwise, it's an expression. } else if (Context == TypeIdAsTemplateArgument && (Tok.isOneOf(tok::greater, tok::comma) || (getLangOpts().CPlusPlus11 && Tok.is(tok::greatergreater)))) { TPR = TPResult::True; isAmbiguous = true; } else TPR = TPResult::False; } PA.Revert(); assert(TPR == TPResult::True || TPR == TPResult::False); return TPR == TPResult::True; } /// \brief Returns true if this is a C++11 attribute-specifier. Per /// C++11 [dcl.attr.grammar]p6, two consecutive left square bracket tokens /// always introduce an attribute. In Objective-C++11, this rule does not /// apply if either '[' begins a message-send. /// /// If Disambiguate is true, we try harder to determine whether a '[[' starts /// an attribute-specifier, and return CAK_InvalidAttributeSpecifier if not. /// /// If OuterMightBeMessageSend is true, we assume the outer '[' is either an /// Obj-C message send or the start of an attribute. Otherwise, we assume it /// is not an Obj-C message send. /// /// C++11 [dcl.attr.grammar]: /// /// attribute-specifier: /// '[' '[' attribute-list ']' ']' /// alignment-specifier /// /// attribute-list: /// attribute[opt] /// attribute-list ',' attribute[opt] /// attribute '...' /// attribute-list ',' attribute '...' /// /// attribute: /// attribute-token attribute-argument-clause[opt] /// /// attribute-token: /// identifier /// identifier '::' identifier /// /// attribute-argument-clause: /// '(' balanced-token-seq ')' Parser::CXX11AttributeKind Parser::isCXX11AttributeSpecifier(bool Disambiguate, bool OuterMightBeMessageSend) { if (Tok.is(tok::kw_alignas)) return CAK_AttributeSpecifier; if (Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) return CAK_NotAttributeSpecifier; // No tentative parsing if we don't need to look for ']]' or a lambda. if (!Disambiguate && !getLangOpts().ObjC1) return CAK_AttributeSpecifier; TentativeParsingAction PA(*this); // Opening brackets were checked for above. ConsumeBracket(); // Outside Obj-C++11, treat anything with a matching ']]' as an attribute. if (!getLangOpts().ObjC1) { ConsumeBracket(); bool IsAttribute = SkipUntil(tok::r_square); IsAttribute &= Tok.is(tok::r_square); PA.Revert(); return IsAttribute ? CAK_AttributeSpecifier : CAK_InvalidAttributeSpecifier; } // In Obj-C++11, we need to distinguish four situations: // 1a) int x[[attr]]; C++11 attribute. // 1b) [[attr]]; C++11 statement attribute. // 2) int x[[obj](){ return 1; }()]; Lambda in array size/index. // 3a) int x[[obj get]]; Message send in array size/index. // 3b) [[Class alloc] init]; Message send in message send. // 4) [[obj]{ return self; }() doStuff]; Lambda in message send. // (1) is an attribute, (2) is ill-formed, and (3) and (4) are accepted. // If we have a lambda-introducer, then this is definitely not a message send. // FIXME: If this disambiguation is too slow, fold the tentative lambda parse // into the tentative attribute parse below. LambdaIntroducer Intro; if (!TryParseLambdaIntroducer(Intro)) { // A lambda cannot end with ']]', and an attribute must. bool IsAttribute = Tok.is(tok::r_square); PA.Revert(); if (IsAttribute) // Case 1: C++11 attribute. return CAK_AttributeSpecifier; if (OuterMightBeMessageSend) // Case 4: Lambda in message send. return CAK_NotAttributeSpecifier; // Case 2: Lambda in array size / index. return CAK_InvalidAttributeSpecifier; } ConsumeBracket(); // If we don't have a lambda-introducer, then we have an attribute or a // message-send. bool IsAttribute = true; while (Tok.isNot(tok::r_square)) { if (Tok.is(tok::comma)) { // Case 1: Stray commas can only occur in attributes. PA.Revert(); return CAK_AttributeSpecifier; } // Parse the attribute-token, if present. // C++11 [dcl.attr.grammar]: // If a keyword or an alternative token that satisfies the syntactic // requirements of an identifier is contained in an attribute-token, // it is considered an identifier. SourceLocation Loc; if (!TryParseCXX11AttributeIdentifier(Loc)) { IsAttribute = false; break; } if (Tok.is(tok::coloncolon)) { ConsumeToken(); if (!TryParseCXX11AttributeIdentifier(Loc)) { IsAttribute = false; break; } } // Parse the attribute-argument-clause, if present. if (Tok.is(tok::l_paren)) { ConsumeParen(); if (!SkipUntil(tok::r_paren)) { IsAttribute = false; break; } } TryConsumeToken(tok::ellipsis); if (!TryConsumeToken(tok::comma)) break; } // An attribute must end ']]'. if (IsAttribute) { if (Tok.is(tok::r_square)) { ConsumeBracket(); IsAttribute = Tok.is(tok::r_square); } else { IsAttribute = false; } } PA.Revert(); if (IsAttribute) // Case 1: C++11 statement attribute. return CAK_AttributeSpecifier; // Case 3: Message send. return CAK_NotAttributeSpecifier; } Parser::TPResult Parser::TryParsePtrOperatorSeq() { while (true) { if (Tok.isOneOf(tok::coloncolon, tok::identifier)) if (TryAnnotateCXXScopeToken(true)) return TPResult::Error; if (Tok.isOneOf(tok::star, tok::amp, tok::caret, tok::ampamp) || (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::star))) { // ptr-operator ConsumeToken(); while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict, tok::kw__Nonnull, tok::kw__Nullable, tok::kw__Null_unspecified)) ConsumeToken(); } else { return TPResult::True; } } } /// operator-function-id: /// 'operator' operator /// /// operator: one of /// new delete new[] delete[] + - * / % ^ [...] /// /// conversion-function-id: /// 'operator' conversion-type-id /// /// conversion-type-id: /// type-specifier-seq conversion-declarator[opt] /// /// conversion-declarator: /// ptr-operator conversion-declarator[opt] /// /// literal-operator-id: /// 'operator' string-literal identifier /// 'operator' user-defined-string-literal Parser::TPResult Parser::TryParseOperatorId() { assert(Tok.is(tok::kw_operator)); ConsumeToken(); // Maybe this is an operator-function-id. switch (Tok.getKind()) { case tok::kw_new: case tok::kw_delete: ConsumeToken(); if (Tok.is(tok::l_square) && NextToken().is(tok::r_square)) { ConsumeBracket(); ConsumeBracket(); } return TPResult::True; #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemOnly) \ case tok::Token: #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemOnly) #include "clang/Basic/OperatorKinds.def" ConsumeToken(); return TPResult::True; case tok::l_square: if (NextToken().is(tok::r_square)) { ConsumeBracket(); ConsumeBracket(); return TPResult::True; } break; case tok::l_paren: if (NextToken().is(tok::r_paren)) { ConsumeParen(); ConsumeParen(); return TPResult::True; } break; default: break; } // Maybe this is a literal-operator-id. if (getLangOpts().CPlusPlus11 && isTokenStringLiteral()) { bool FoundUDSuffix = false; do { FoundUDSuffix |= Tok.hasUDSuffix(); ConsumeStringToken(); } while (isTokenStringLiteral()); if (!FoundUDSuffix) { if (Tok.is(tok::identifier)) ConsumeToken(); else return TPResult::Error; } return TPResult::True; } // Maybe this is a conversion-function-id. bool AnyDeclSpecifiers = false; while (true) { TPResult TPR = isCXXDeclarationSpecifier(); if (TPR == TPResult::Error) return TPR; if (TPR == TPResult::False) { if (!AnyDeclSpecifiers) return TPResult::Error; break; } if (TryConsumeDeclarationSpecifier() == TPResult::Error) return TPResult::Error; AnyDeclSpecifiers = true; } return TryParsePtrOperatorSeq(); } /// declarator: /// direct-declarator /// ptr-operator declarator /// /// direct-declarator: /// declarator-id /// direct-declarator '(' parameter-declaration-clause ')' /// cv-qualifier-seq[opt] exception-specification[opt] /// direct-declarator '[' constant-expression[opt] ']' /// '(' declarator ')' /// [GNU] '(' attributes declarator ')' /// /// abstract-declarator: /// ptr-operator abstract-declarator[opt] /// direct-abstract-declarator /// ... /// /// direct-abstract-declarator: /// direct-abstract-declarator[opt] /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] /// exception-specification[opt] /// direct-abstract-declarator[opt] '[' constant-expression[opt] ']' /// '(' abstract-declarator ')' /// /// ptr-operator: /// '*' cv-qualifier-seq[opt] /// '&' /// [C++0x] '&&' [TODO] /// '::'[opt] nested-name-specifier '*' cv-qualifier-seq[opt] /// /// cv-qualifier-seq: /// cv-qualifier cv-qualifier-seq[opt] /// /// cv-qualifier: /// 'const' /// 'volatile' /// /// declarator-id: /// '...'[opt] id-expression /// /// id-expression: /// unqualified-id /// qualified-id [TODO] /// /// unqualified-id: /// identifier /// operator-function-id /// conversion-function-id /// literal-operator-id /// '~' class-name [TODO] /// '~' decltype-specifier [TODO] /// template-id [TODO] /// Parser::TPResult Parser::TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier) { // declarator: // direct-declarator // ptr-operator declarator if (TryParsePtrOperatorSeq() == TPResult::Error) return TPResult::Error; // direct-declarator: // direct-abstract-declarator: if (Tok.is(tok::ellipsis)) ConsumeToken(); if ((Tok.isOneOf(tok::identifier, tok::kw_operator) || (Tok.is(tok::annot_cxxscope) && (NextToken().is(tok::identifier) || NextToken().is(tok::kw_operator)))) && mayHaveIdentifier) { // declarator-id if (Tok.is(tok::annot_cxxscope)) ConsumeToken(); else if (Tok.is(tok::identifier)) TentativelyDeclaredIdentifiers.push_back(Tok.getIdentifierInfo()); if (Tok.is(tok::kw_operator)) { if (TryParseOperatorId() == TPResult::Error) return TPResult::Error; } else ConsumeToken(); } else if (Tok.is(tok::l_paren)) { ConsumeParen(); if (mayBeAbstract && (Tok.is(tok::r_paren) || // 'int()' is a function. // 'int(...)' is a function. (Tok.is(tok::ellipsis) && NextToken().is(tok::r_paren)) || isDeclarationSpecifier())) { // 'int(int)' is a function. // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] // exception-specification[opt] TPResult TPR = TryParseFunctionDeclarator(); if (TPR != TPResult::Ambiguous) return TPR; } else { // '(' declarator ')' // '(' attributes declarator ')' // '(' abstract-declarator ')' if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec, tok::kw___cdecl, tok::kw___stdcall, tok::kw___fastcall, tok::kw___thiscall, tok::kw___vectorcall, tok::kw___unaligned)) return TPResult::True; // attributes indicate declaration TPResult TPR = TryParseDeclarator(mayBeAbstract, mayHaveIdentifier); if (TPR != TPResult::Ambiguous) return TPR; if (Tok.isNot(tok::r_paren)) return TPResult::False; ConsumeParen(); } } else if (!mayBeAbstract) { return TPResult::False; } while (1) { TPResult TPR(TPResult::Ambiguous); // abstract-declarator: ... if (Tok.is(tok::ellipsis)) ConsumeToken(); if (Tok.is(tok::l_paren)) { // Check whether we have a function declarator or a possible ctor-style // initializer that follows the declarator. Note that ctor-style // initializers are not possible in contexts where abstract declarators // are allowed. if (!mayBeAbstract && !isCXXFunctionDeclarator()) break; // direct-declarator '(' parameter-declaration-clause ')' // cv-qualifier-seq[opt] exception-specification[opt] ConsumeParen(); TPR = TryParseFunctionDeclarator(); } else if (Tok.is(tok::l_square)) { // direct-declarator '[' constant-expression[opt] ']' // direct-abstract-declarator[opt] '[' constant-expression[opt] ']' TPR = TryParseBracketDeclarator(); } else { break; } if (TPR != TPResult::Ambiguous) return TPR; } return TPResult::Ambiguous; } Parser::TPResult Parser::isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind) { switch (Kind) { // Obviously starts an expression. case tok::numeric_constant: case tok::char_constant: case tok::wide_char_constant: case tok::utf8_char_constant: case tok::utf16_char_constant: case tok::utf32_char_constant: case tok::string_literal: case tok::wide_string_literal: case tok::utf8_string_literal: case tok::utf16_string_literal: case tok::utf32_string_literal: case tok::l_square: case tok::l_paren: case tok::amp: case tok::ampamp: case tok::star: case tok::plus: case tok::plusplus: case tok::minus: case tok::minusminus: case tok::tilde: case tok::exclaim: case tok::kw_sizeof: case tok::kw___func__: case tok::kw_const_cast: case tok::kw_delete: case tok::kw_dynamic_cast: case tok::kw_false: case tok::kw_new: case tok::kw_operator: case tok::kw_reinterpret_cast: case tok::kw_static_cast: case tok::kw_this: case tok::kw_throw: case tok::kw_true: case tok::kw_typeid: case tok::kw_alignof: case tok::kw_noexcept: case tok::kw_nullptr: case tok::kw__Alignof: case tok::kw___null: case tok::kw___alignof: case tok::kw___builtin_choose_expr: case tok::kw___builtin_offsetof: case tok::kw___builtin_va_arg: case tok::kw___imag: case tok::kw___real: case tok::kw___FUNCTION__: case tok::kw___FUNCDNAME__: case tok::kw___FUNCSIG__: case tok::kw_L__FUNCTION__: case tok::kw___PRETTY_FUNCTION__: case tok::kw___uuidof: #define TYPE_TRAIT(N,Spelling,K) \ case tok::kw_##Spelling: #include "clang/Basic/TokenKinds.def" return TPResult::True; // Obviously starts a type-specifier-seq: case tok::kw_char: case tok::kw_const: case tok::kw_double: case tok::kw_enum: case tok::kw_half: case tok::kw_float: case tok::kw_int: case tok::kw_long: case tok::kw___int64: case tok::kw___int128: // HLSL Change Starts case tok::kw_column_major: case tok::kw_row_major: case tok::kw_snorm: case tok::kw_unorm: // HLSL Change Ends case tok::kw_restrict: case tok::kw_short: case tok::kw_signed: case tok::kw_struct: case tok::kw_union: case tok::kw_unsigned: case tok::kw_void: case tok::kw_volatile: case tok::kw__Bool: case tok::kw__Complex: case tok::kw_class: case tok::kw_typename: case tok::kw_wchar_t: case tok::kw_char16_t: case tok::kw_char32_t: case tok::kw__Decimal32: case tok::kw__Decimal64: case tok::kw__Decimal128: case tok::kw___interface: case tok::kw___thread: case tok::kw_thread_local: case tok::kw__Thread_local: case tok::kw_typeof: case tok::kw___underlying_type: case tok::kw___cdecl: case tok::kw___stdcall: case tok::kw___fastcall: case tok::kw___thiscall: case tok::kw___vectorcall: case tok::kw___unaligned: case tok::kw___vector: case tok::kw___pixel: case tok::kw___bool: case tok::kw__Atomic: case tok::kw___unknown_anytype: return TPResult::False; default: break; } return TPResult::Ambiguous; } bool Parser::isTentativelyDeclared(IdentifierInfo *II) { return std::find(TentativelyDeclaredIdentifiers.begin(), TentativelyDeclaredIdentifiers.end(), II) != TentativelyDeclaredIdentifiers.end(); } namespace { class TentativeParseCCC : public CorrectionCandidateCallback { public: TentativeParseCCC(const Token &Next) { WantRemainingKeywords = false; WantTypeSpecifiers = Next.isOneOf(tok::l_paren, tok::r_paren, tok::greater, tok::l_brace, tok::identifier); } bool ValidateCandidate(const TypoCorrection &Candidate) override { // Reject any candidate that only resolves to instance members since they // aren't viable as standalone identifiers instead of member references. if (Candidate.isResolved() && !Candidate.isKeyword() && std::all_of(Candidate.begin(), Candidate.end(), [](NamedDecl *ND) { return ND->isCXXInstanceMember(); })) return false; return CorrectionCandidateCallback::ValidateCandidate(Candidate); } }; } /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a declaration /// specifier, TPResult::False if it is not, TPResult::Ambiguous if it could /// be either a decl-specifier or a function-style cast, and TPResult::Error /// if a parsing error was found and reported. /// /// If HasMissingTypename is provided, a name with a dependent scope specifier /// will be treated as ambiguous if the 'typename' keyword is missing. If this /// happens, *HasMissingTypename will be set to 'true'. This will also be used /// as an indicator that undeclared identifiers (which will trigger a later /// parse error) should be treated as types. Returns TPResult::Ambiguous in /// such cases. /// /// decl-specifier: /// storage-class-specifier /// type-specifier /// function-specifier /// 'friend' /// 'typedef' /// [C++11] 'constexpr' /// [GNU] attributes declaration-specifiers[opt] /// /// storage-class-specifier: /// 'register' /// 'static' /// 'extern' /// 'mutable' /// 'auto' /// [GNU] '__thread' /// [C++11] 'thread_local' /// [C11] '_Thread_local' /// /// function-specifier: /// 'inline' /// 'virtual' /// 'explicit' /// /// typedef-name: /// identifier /// /// type-specifier: /// simple-type-specifier /// class-specifier /// enum-specifier /// elaborated-type-specifier /// typename-specifier /// cv-qualifier /// /// simple-type-specifier: /// '::'[opt] nested-name-specifier[opt] type-name /// '::'[opt] nested-name-specifier 'template' /// simple-template-id [TODO] /// 'char' /// 'wchar_t' /// 'bool' /// 'short' /// 'int' /// 'long' /// 'signed' /// 'unsigned' /// 'float' /// 'double' /// 'void' /// [GNU] typeof-specifier /// [GNU] '_Complex' /// [C++11] 'auto' /// [C++11] 'decltype' ( expression ) /// [C++1y] 'decltype' ( 'auto' ) /// /// type-name: /// class-name /// enum-name /// typedef-name /// /// elaborated-type-specifier: /// class-key '::'[opt] nested-name-specifier[opt] identifier /// class-key '::'[opt] nested-name-specifier[opt] 'template'[opt] /// simple-template-id /// 'enum' '::'[opt] nested-name-specifier[opt] identifier /// /// enum-name: /// identifier /// /// enum-specifier: /// 'enum' identifier[opt] '{' enumerator-list[opt] '}' /// 'enum' identifier[opt] '{' enumerator-list ',' '}' /// /// class-specifier: /// class-head '{' member-specification[opt] '}' /// /// class-head: /// class-key identifier[opt] base-clause[opt] /// class-key nested-name-specifier identifier base-clause[opt] /// class-key nested-name-specifier[opt] simple-template-id /// base-clause[opt] /// /// class-key: /// 'class' /// 'struct' /// 'union' /// /// cv-qualifier: /// 'const' /// 'volatile' /// [GNU] restrict /// Parser::TPResult Parser::isCXXDeclarationSpecifier(Parser::TPResult BracedCastResult, bool *HasMissingTypename) { switch (Tok.getKind()) { case tok::identifier: { // Check for need to substitute AltiVec __vector keyword // for "vector" identifier. if (TryAltiVecVectorToken()) return TPResult::True; const Token &Next = NextToken(); // In 'foo bar', 'foo' is always a type name outside of Objective-C. if (!getLangOpts().ObjC1 && Next.is(tok::identifier)) return TPResult::True; if (Next.isNot(tok::coloncolon) && Next.isNot(tok::less)) { // Determine whether this is a valid expression. If not, we will hit // a parse error one way or another. In that case, tell the caller that // this is ambiguous. Typo-correct to type and expression keywords and // to types and identifiers, in order to try to recover from errors. switch (TryAnnotateName(false /* no nested name specifier */, llvm::make_unique<TentativeParseCCC>(Next))) { case ANK_Error: return TPResult::Error; case ANK_TentativeDecl: return TPResult::False; case ANK_TemplateName: // A bare type template-name which can't be a template template // argument is an error, and was probably intended to be a type. return GreaterThanIsOperator ? TPResult::True : TPResult::False; case ANK_Unresolved: return HasMissingTypename ? TPResult::Ambiguous : TPResult::False; case ANK_Success: break; } assert(Tok.isNot(tok::identifier) && "TryAnnotateName succeeded without producing an annotation"); } else { // This might possibly be a type with a dependent scope specifier and // a missing 'typename' keyword. Don't use TryAnnotateName in this case, // since it will annotate as a primary expression, and we want to use the // "missing 'typename'" logic. if (TryAnnotateTypeOrScopeToken()) return TPResult::Error; // If annotation failed, assume it's a non-type. // FIXME: If this happens due to an undeclared identifier, treat it as // ambiguous. if (Tok.is(tok::identifier)) return TPResult::False; } // We annotated this token as something. Recurse to handle whatever we got. return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename); } case tok::kw_typename: // typename T::type // Annotate typenames and C++ scope specifiers. If we get one, just // recurse to handle whatever we get. if (TryAnnotateTypeOrScopeToken()) return TPResult::Error; return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename); case tok::coloncolon: { // ::foo::bar const Token &Next = NextToken(); if (Next.isOneOf(tok::kw_new, // ::new tok::kw_delete)) // ::delete return TPResult::False; } LLVM_FALLTHROUGH; // HLSL Change case tok::kw___super: case tok::kw_decltype: // Annotate typenames and C++ scope specifiers. If we get one, just // recurse to handle whatever we get. if (TryAnnotateTypeOrScopeToken()) return TPResult::Error; return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename); // decl-specifier: // storage-class-specifier // type-specifier // function-specifier // 'friend' // 'typedef' // 'constexpr' // 'concept' case tok::kw_friend: case tok::kw_typedef: case tok::kw_constexpr: case tok::kw_concept: // storage-class-specifier case tok::kw_register: case tok::kw_static: case tok::kw_extern: case tok::kw_mutable: case tok::kw_auto: case tok::kw___thread: case tok::kw_thread_local: case tok::kw__Thread_local: // function-specifier case tok::kw_inline: case tok::kw_virtual: case tok::kw_explicit: // Modules case tok::kw___module_private__: // Debugger support case tok::kw___unknown_anytype: // type-specifier: // simple-type-specifier // class-specifier // enum-specifier // elaborated-type-specifier // typename-specifier // cv-qualifier // class-specifier // elaborated-type-specifier case tok::kw_class: case tok::kw_struct: case tok::kw_union: case tok::kw___interface: // enum-specifier case tok::kw_enum: // cv-qualifier case tok::kw_const: case tok::kw_volatile: // GNU case tok::kw_restrict: case tok::kw__Complex: case tok::kw___attribute: return TPResult::True; // HLSL Change Starts case tok::kw_sample: case tok::kw_precise: case tok::kw_center: case tok::kw_globallycoherent: case tok::kw_indices: case tok::kw_vertices: case tok::kw_primitives: case tok::kw_payload: // FXC compatiblity: these are keywords when used as modifiers, but in // FXC they can also be used an identifiers. If the next token is a // punctuator, then we are using them as identifers. Need to change // the token type to tok::identifier and return false. // E.g., return (center); if (tok::isPunctuator(NextToken().getKind())) { Tok.setKind(tok::identifier); return TPResult::False; } else { return TPResult::True; } case tok::kw_in: case tok::kw_inout: case tok::kw_out: case tok::kw_linear: case tok::kw_centroid: case tok::kw_nointerpolation: case tok::kw_noperspective: case tok::kw_shared: case tok::kw_groupshared: case tok::kw_uniform: case tok::kw_row_major: case tok::kw_column_major: case tok::kw_snorm: case tok::kw_unorm: case tok::kw_point: case tok::kw_line: case tok::kw_lineadj: case tok::kw_triangle: case tok::kw_triangleadj: case tok::kw_export: return TPResult::True; // HLSL Change Ends // Microsoft case tok::kw___declspec: case tok::kw___cdecl: case tok::kw___stdcall: case tok::kw___fastcall: case tok::kw___thiscall: case tok::kw___vectorcall: case tok::kw___w64: case tok::kw___sptr: case tok::kw___uptr: case tok::kw___ptr64: case tok::kw___ptr32: case tok::kw___forceinline: case tok::kw___unaligned: case tok::kw__Nonnull: case tok::kw__Nullable: case tok::kw__Null_unspecified: case tok::kw___kindof: return TPResult::True; // Borland case tok::kw___pascal: return TPResult::True; // AltiVec case tok::kw___vector: return TPResult::True; case tok::annot_template_id: { TemplateIdAnnotation *TemplateId = takeTemplateIdAnnotation(Tok); if (TemplateId->Kind != TNK_Type_template) return TPResult::False; CXXScopeSpec SS; AnnotateTemplateIdTokenAsType(); assert(Tok.is(tok::annot_typename)); goto case_typename; } case tok::annot_cxxscope: // foo::bar or ::foo::bar, but already parsed // We've already annotated a scope; try to annotate a type. if (TryAnnotateTypeOrScopeToken()) return TPResult::Error; if (!Tok.is(tok::annot_typename)) { // If the next token is an identifier or a type qualifier, then this // can't possibly be a valid expression either. if (Tok.is(tok::annot_cxxscope) && NextToken().is(tok::identifier)) { CXXScopeSpec SS; Actions.RestoreNestedNameSpecifierAnnotation(Tok.getAnnotationValue(), Tok.getAnnotationRange(), SS); if (SS.getScopeRep() && SS.getScopeRep()->isDependent()) { TentativeParsingAction PA(*this); ConsumeToken(); ConsumeToken(); bool isIdentifier = Tok.is(tok::identifier); TPResult TPR = TPResult::False; if (!isIdentifier) TPR = isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename); PA.Revert(); if (isIdentifier || TPR == TPResult::True || TPR == TPResult::Error) return TPResult::Error; if (HasMissingTypename) { // We can't tell whether this is a missing 'typename' or a valid // expression. *HasMissingTypename = true; return TPResult::Ambiguous; } } else { // Try to resolve the name. If it doesn't exist, assume it was // intended to name a type and keep disambiguating. switch (TryAnnotateName(false /* SS is not dependent */)) { case ANK_Error: return TPResult::Error; case ANK_TentativeDecl: return TPResult::False; case ANK_TemplateName: // A bare type template-name which can't be a template template // argument is an error, and was probably intended to be a type. return GreaterThanIsOperator ? TPResult::True : TPResult::False; case ANK_Unresolved: return HasMissingTypename ? TPResult::Ambiguous : TPResult::False; case ANK_Success: // Annotated it, check again. assert(Tok.isNot(tok::annot_cxxscope) || NextToken().isNot(tok::identifier)); return isCXXDeclarationSpecifier(BracedCastResult, HasMissingTypename); } } } return TPResult::False; } // If that succeeded, fallthrough into the generic simple-type-id case. // The ambiguity resides in a simple-type-specifier/typename-specifier // followed by a '('. The '(' could either be the start of: // // direct-declarator: // '(' declarator ')' // // direct-abstract-declarator: // '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] // exception-specification[opt] // '(' abstract-declarator ')' // // or part of a function-style cast expression: // // simple-type-specifier '(' expression-list[opt] ')' // // simple-type-specifier: LLVM_FALLTHROUGH; // HLSL Change case tok::annot_typename: case_typename: // In Objective-C, we might have a protocol-qualified type. if (getLangOpts().ObjC1 && NextToken().is(tok::less)) { // Tentatively parse the protocol qualifiers. TentativeParsingAction PA(*this); ConsumeToken(); // The type token TPResult TPR = TryParseProtocolQualifiers(); bool isFollowedByParen = Tok.is(tok::l_paren); bool isFollowedByBrace = Tok.is(tok::l_brace); PA.Revert(); if (TPR == TPResult::Error) return TPResult::Error; if (isFollowedByParen) return TPResult::Ambiguous; if (getLangOpts().CPlusPlus11 && isFollowedByBrace) return BracedCastResult; return TPResult::True; } LLVM_FALLTHROUGH; // HLSL Change case tok::kw_char: case tok::kw_wchar_t: case tok::kw_char16_t: case tok::kw_char32_t: case tok::kw_bool: case tok::kw_short: case tok::kw_int: case tok::kw_long: case tok::kw___int64: case tok::kw___int128: case tok::kw_signed: case tok::kw_unsigned: case tok::kw_half: case tok::kw_float: case tok::kw_double: case tok::kw_void: case tok::annot_decltype: if (NextToken().is(tok::l_paren)) return TPResult::Ambiguous; // This is a function-style cast in all cases we disambiguate other than // one: // struct S { // enum E : int { a = 4 }; // enum // enum E : int { 4 }; // bit-field // }; if (getLangOpts().CPlusPlus11 && NextToken().is(tok::l_brace)) return BracedCastResult; if (isStartOfObjCClassMessageMissingOpenBracket()) return TPResult::False; return TPResult::True; // GNU typeof support. case tok::kw_typeof: { if (NextToken().isNot(tok::l_paren)) return TPResult::True; TentativeParsingAction PA(*this); TPResult TPR = TryParseTypeofSpecifier(); bool isFollowedByParen = Tok.is(tok::l_paren); bool isFollowedByBrace = Tok.is(tok::l_brace); PA.Revert(); if (TPR == TPResult::Error) return TPResult::Error; if (isFollowedByParen) return TPResult::Ambiguous; if (getLangOpts().CPlusPlus11 && isFollowedByBrace) return BracedCastResult; return TPResult::True; } // C++0x type traits support case tok::kw___underlying_type: return TPResult::True; // C11 _Atomic case tok::kw__Atomic: return TPResult::True; default: return TPResult::False; } } bool Parser::isCXXDeclarationSpecifierAType() { switch (Tok.getKind()) { // typename-specifier case tok::annot_decltype: case tok::annot_template_id: case tok::annot_typename: case tok::kw_typeof: case tok::kw___underlying_type: return true; // elaborated-type-specifier case tok::kw_class: case tok::kw_struct: case tok::kw_union: case tok::kw___interface: case tok::kw_enum: return true; // simple-type-specifier case tok::kw_char: case tok::kw_wchar_t: case tok::kw_char16_t: case tok::kw_char32_t: case tok::kw_bool: case tok::kw_short: case tok::kw_int: case tok::kw_long: case tok::kw___int64: case tok::kw___int128: case tok::kw_signed: case tok::kw_unsigned: case tok::kw_half: case tok::kw_float: case tok::kw_double: case tok::kw_void: case tok::kw___unknown_anytype: return true; case tok::kw_auto: return getLangOpts().CPlusPlus11; case tok::kw__Atomic: // "_Atomic foo" return NextToken().is(tok::l_paren); default: return false; } } /// [GNU] typeof-specifier: /// 'typeof' '(' expressions ')' /// 'typeof' '(' type-name ')' /// Parser::TPResult Parser::TryParseTypeofSpecifier() { assert(Tok.is(tok::kw_typeof) && "Expected 'typeof'!"); ConsumeToken(); assert(Tok.is(tok::l_paren) && "Expected '('"); // Parse through the parens after 'typeof'. ConsumeParen(); if (!SkipUntil(tok::r_paren, StopAtSemi)) return TPResult::Error; return TPResult::Ambiguous; } /// [ObjC] protocol-qualifiers: //// '<' identifier-list '>' Parser::TPResult Parser::TryParseProtocolQualifiers() { assert(Tok.is(tok::less) && "Expected '<' for qualifier list"); ConsumeToken(); do { if (Tok.isNot(tok::identifier)) return TPResult::Error; ConsumeToken(); if (Tok.is(tok::comma)) { ConsumeToken(); continue; } if (Tok.is(tok::greater)) { ConsumeToken(); return TPResult::Ambiguous; } } while (false); return TPResult::Error; } /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] /// exception-specification[opt] /// bool Parser::isCXXFunctionDeclarator(bool *IsAmbiguous) { // C++ 8.2p1: // The ambiguity arising from the similarity between a function-style cast and // a declaration mentioned in 6.8 can also occur in the context of a // declaration. In that context, the choice is between a function declaration // with a redundant set of parentheses around a parameter name and an object // declaration with a function-style cast as the initializer. Just as for the // ambiguities mentioned in 6.8, the resolution is to consider any construct // that could possibly be a declaration a declaration. TentativeParsingAction PA(*this); ConsumeParen(); bool InvalidAsDeclaration = false; TPResult TPR = TryParseParameterDeclarationClause(&InvalidAsDeclaration); if (TPR == TPResult::Ambiguous) { if (Tok.isNot(tok::r_paren)) TPR = TPResult::False; else { const Token &Next = NextToken(); if (Next.isOneOf(tok::amp, tok::ampamp, tok::kw_const, tok::kw_volatile, tok::kw_throw, tok::kw_noexcept, tok::l_square, tok::l_brace, tok::kw_try, tok::equal, tok::arrow) || isCXX11VirtSpecifier(Next)) // The next token cannot appear after a constructor-style initializer, // and can appear next in a function definition. This must be a function // declarator. TPR = TPResult::True; else if (InvalidAsDeclaration) // Use the absence of 'typename' as a tie-breaker. TPR = TPResult::False; } } PA.Revert(); if (IsAmbiguous && TPR == TPResult::Ambiguous) *IsAmbiguous = true; // In case of an error, let the declaration parsing code handle it. return TPR != TPResult::False; } /// parameter-declaration-clause: /// parameter-declaration-list[opt] '...'[opt] /// parameter-declaration-list ',' '...' /// /// parameter-declaration-list: /// parameter-declaration /// parameter-declaration-list ',' parameter-declaration /// /// parameter-declaration: /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt] /// attribute-specifier-seq[opt] decl-specifier-seq declarator attributes[opt] /// '=' assignment-expression /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt] /// attributes[opt] /// attribute-specifier-seq[opt] decl-specifier-seq abstract-declarator[opt] /// attributes[opt] '=' assignment-expression /// Parser::TPResult Parser::TryParseParameterDeclarationClause(bool *InvalidAsDeclaration, bool VersusTemplateArgument) { if (Tok.is(tok::r_paren)) return TPResult::Ambiguous; // parameter-declaration-list[opt] '...'[opt] // parameter-declaration-list ',' '...' // // parameter-declaration-list: // parameter-declaration // parameter-declaration-list ',' parameter-declaration // while (1) { // '...'[opt] if (Tok.is(tok::ellipsis)) { ConsumeToken(); if (Tok.is(tok::r_paren)) return TPResult::True; // '...)' is a sign of a function declarator. else return TPResult::False; } // An attribute-specifier-seq here is a sign of a function declarator. if (isCXX11AttributeSpecifier(/*Disambiguate*/false, /*OuterMightBeMessageSend*/true)) return TPResult::True; ParsedAttributes attrs(AttrFactory); MaybeParseMicrosoftAttributes(attrs); // decl-specifier-seq // A parameter-declaration's initializer must be preceded by an '=', so // decl-specifier-seq '{' is not a parameter in C++11. TPResult TPR = isCXXDeclarationSpecifier(TPResult::False, InvalidAsDeclaration); if (VersusTemplateArgument && TPR == TPResult::True) { // Consume the decl-specifier-seq. We have to look past it, since a // type-id might appear here in a template argument. bool SeenType = false; do { SeenType |= isCXXDeclarationSpecifierAType(); if (TryConsumeDeclarationSpecifier() == TPResult::Error) return TPResult::Error; // If we see a parameter name, this can't be a template argument. if (SeenType && Tok.is(tok::identifier)) return TPResult::True; TPR = isCXXDeclarationSpecifier(TPResult::False, InvalidAsDeclaration); if (TPR == TPResult::Error) return TPR; } while (TPR != TPResult::False); } else if (TPR == TPResult::Ambiguous) { // Disambiguate what follows the decl-specifier. if (TryConsumeDeclarationSpecifier() == TPResult::Error) return TPResult::Error; } else return TPR; // declarator // abstract-declarator[opt] TPR = TryParseDeclarator(true/*mayBeAbstract*/); if (TPR != TPResult::Ambiguous) return TPR; // [GNU] attributes[opt] if (Tok.is(tok::kw___attribute)) return TPResult::True; // If we're disambiguating a template argument in a default argument in // a class definition versus a parameter declaration, an '=' here // disambiguates the parse one way or the other. // If this is a parameter, it must have a default argument because // (a) the previous parameter did, and // (b) this must be the first declaration of the function, so we can't // inherit any default arguments from elsewhere. // If we see an ')', then we've reached the end of a // parameter-declaration-clause, and the last param is missing its default // argument. if (VersusTemplateArgument) return Tok.isOneOf(tok::equal, tok::r_paren) ? TPResult::True : TPResult::False; if (Tok.is(tok::equal)) { // '=' assignment-expression // Parse through assignment-expression. // FIXME: assignment-expression may contain an unparenthesized comma. if (!SkipUntil(tok::comma, tok::r_paren, StopAtSemi | StopBeforeMatch)) return TPResult::Error; } if (Tok.is(tok::ellipsis)) { ConsumeToken(); if (Tok.is(tok::r_paren)) return TPResult::True; // '...)' is a sign of a function declarator. else return TPResult::False; } if (!TryConsumeToken(tok::comma)) break; } return TPResult::Ambiguous; } /// TryParseFunctionDeclarator - We parsed a '(' and we want to try to continue /// parsing as a function declarator. /// If TryParseFunctionDeclarator fully parsed the function declarator, it will /// return TPResult::Ambiguous, otherwise it will return either False() or /// Error(). /// /// '(' parameter-declaration-clause ')' cv-qualifier-seq[opt] /// exception-specification[opt] /// /// exception-specification: /// 'throw' '(' type-id-list[opt] ')' /// Parser::TPResult Parser::TryParseFunctionDeclarator() { // The '(' is already parsed. TPResult TPR = TryParseParameterDeclarationClause(); if (TPR == TPResult::Ambiguous && Tok.isNot(tok::r_paren)) TPR = TPResult::False; if (TPR == TPResult::False || TPR == TPResult::Error) return TPR; // Parse through the parens. if (!SkipUntil(tok::r_paren, StopAtSemi)) return TPResult::Error; // cv-qualifier-seq while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict)) ConsumeToken(); // ref-qualifier[opt] if (Tok.isOneOf(tok::amp, tok::ampamp)) ConsumeToken(); // exception-specification if (Tok.is(tok::kw_throw)) { ConsumeToken(); if (Tok.isNot(tok::l_paren)) return TPResult::Error; // Parse through the parens after 'throw'. ConsumeParen(); if (!SkipUntil(tok::r_paren, StopAtSemi)) return TPResult::Error; } if (Tok.is(tok::kw_noexcept)) { ConsumeToken(); // Possibly an expression as well. if (Tok.is(tok::l_paren)) { // Find the matching rparen. ConsumeParen(); if (!SkipUntil(tok::r_paren, StopAtSemi)) return TPResult::Error; } } return TPResult::Ambiguous; } /// '[' constant-expression[opt] ']' /// Parser::TPResult Parser::TryParseBracketDeclarator() { ConsumeBracket(); if (!SkipUntil(tok::r_square, StopAtSemi)) return TPResult::Error; return TPResult::Ambiguous; }
0
repos/DirectXShaderCompiler/tools/clang
repos/DirectXShaderCompiler/tools/clang/examples/CMakeLists.txt
if(NOT CLANG_BUILD_EXAMPLES) set_property(DIRECTORY PROPERTY EXCLUDE_FROM_ALL ON) set(EXCLUDE_FROM_ALL ON) endif() if(CLANG_ENABLE_STATIC_ANALYZER) add_subdirectory(analyzer-plugin) endif() # add_subdirectory(clang-interpreter) // HLSL Change # add_subdirectory(PrintFunctionNames) // HLSL Change
0
repos/DirectXShaderCompiler/tools/clang/examples
repos/DirectXShaderCompiler/tools/clang/examples/analyzer-plugin/CMakeLists.txt
add_llvm_loadable_module(SampleAnalyzerPlugin MainCallChecker.cpp) if(LLVM_ENABLE_PLUGINS AND (WIN32 OR CYGWIN)) target_link_libraries(SampleAnalyzerPlugin ${cmake_2_8_12_PRIVATE} clangAnalysis clangAST clangStaticAnalyzerCore LLVMSupport ) endif()
0
repos/DirectXShaderCompiler/tools/clang/examples
repos/DirectXShaderCompiler/tools/clang/examples/analyzer-plugin/MainCallChecker.cpp
#include "clang/StaticAnalyzer/Core/Checker.h" #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" #include "clang/StaticAnalyzer/Core/CheckerRegistry.h" #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" using namespace clang; using namespace ento; namespace { class MainCallChecker : public Checker < check::PreStmt<CallExpr> > { mutable std::unique_ptr<BugType> BT; public: void checkPreStmt(const CallExpr *CE, CheckerContext &C) const; }; } // end anonymous namespace void MainCallChecker::checkPreStmt(const CallExpr *CE, CheckerContext &C) const { const ProgramStateRef state = C.getState(); const LocationContext *LC = C.getLocationContext(); const Expr *Callee = CE->getCallee(); const FunctionDecl *FD = state->getSVal(Callee, LC).getAsFunctionDecl(); if (!FD) return; // Get the name of the callee. IdentifierInfo *II = FD->getIdentifier(); if (!II) // if no identifier, not a simple C function return; if (II->isStr("main")) { ExplodedNode *N = C.generateSink(); if (!N) return; if (!BT) BT.reset(new BugType(this, "call to main", "example analyzer plugin")); std::unique_ptr<BugReport> report = llvm::make_unique<BugReport>(*BT, BT->getName(), N); report->addRange(Callee->getSourceRange()); C.emitReport(std::move(report)); } } // Register plugin! extern "C" void clang_registerCheckers (CheckerRegistry &registry) { registry.addChecker<MainCallChecker>("example.MainCallChecker", "Disallows calls to functions called main"); } extern "C" const char clang_analyzerAPIVersionString[] = CLANG_ANALYZER_API_VERSION_STRING;
0
repos/DirectXShaderCompiler/tools/clang
repos/DirectXShaderCompiler/tools/clang/docs/LibASTMatchersReference.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>AST Matcher Reference</title> <link type="text/css" rel="stylesheet" href="../menu.css" /> <link type="text/css" rel="stylesheet" href="../content.css" /> <style type="text/css"> td { padding: .33em; } td.doc { display: none; border-bottom: 1px solid black; } td.name:hover { color: blue; cursor: pointer; } </style> <script type="text/javascript"> function toggle(id) { if (!id) return; row = document.getElementById(id); if (row.style.display != 'table-cell') row.style.display = 'table-cell'; else row.style.display = 'none'; } </script> </head> <body onLoad="toggle(location.hash.substring(1, location.hash.length - 6))"> <!--#include virtual="../menu.html.incl"--> <div id="content"> <h1>AST Matcher Reference</h1> <p>This document shows all currently implemented matchers. The matchers are grouped by category and node type they match. You can click on matcher names to show the matcher's source documentation.</p> <p>There are three different basic categories of matchers: <ul> <li><a href="#decl-matchers">Node Matchers:</a> Matchers that match a specific type of AST node.</li> <li><a href="#narrowing-matchers">Narrowing Matchers:</a> Matchers that match attributes on AST nodes.</li> <li><a href="#traversal-matchers">Traversal Matchers:</a> Matchers that allow traversal between AST nodes.</li> </ul> </p> <p>Within each category the matchers are ordered by node type they match on. Note that if a matcher can match multiple node types, it will it will appear multiple times. This means that by searching for Matcher&lt;Stmt&gt; you can find all matchers that can be used to match on Stmt nodes.</p> <p>The exception to that rule are matchers that can match on any node. Those are marked with a * and are listed in the beginning of each category.</p> <p>Note that the categorization of matchers is a great help when you combine them into matcher expressions. You will usually want to form matcher expressions that read like english sentences by alternating between node matchers and narrowing or traversal matchers, like this: <pre> recordDecl(hasDescendant( ifStmt(hasTrueExpression( expr(hasDescendant( ifStmt())))))) </pre> </p> <!-- ======================================================================= --> <h2 id="decl-matchers">Node Matchers</h2> <!-- ======================================================================= --> <p>Node matchers are at the core of matcher expressions - they specify the type of node that is expected. Every match expression starts with a node matcher, which can then be further refined with a narrowing or traversal matcher. All traversal matchers take node matchers as their arguments.</p> <p>For convenience, all node matchers take an arbitrary number of arguments and implicitly act as allOf matchers.</p> <p>Node matchers are the only matchers that support the bind("id") call to bind the matched node to the given string, to be later retrieved from the match callback.</p> <p>It is important to remember that the arguments to node matchers are predicates on the same node, just with additional information about the type. This is often useful to make matcher expression more readable by inlining bind calls into redundant node matchers inside another node matcher: <pre> // This binds the CXXRecordDecl to "id", as the decl() matcher will stay on // the same node. recordDecl(decl().bind("id"), hasName("::MyClass")) </pre> </p> <table> <tr style="text-align:left"><th>Return type</th><th>Name</th><th>Parameters</th></tr> <!-- START_DECL_MATCHERS --> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html">CXXCtorInitializer</a>&gt;</td><td class="name" onclick="toggle('ctorInitializer0')"><a name="ctorInitializer0Anchor">ctorInitializer</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html">CXXCtorInitializer</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="ctorInitializer0"><pre>Matches constructor initializers. Examples matches i(42). class C { C() : i(42) {} int i; }; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('accessSpecDecl0')"><a name="accessSpecDecl0Anchor">accessSpecDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1AccessSpecDecl.html">AccessSpecDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="accessSpecDecl0"><pre>Matches C++ access specifier declarations. Given class C { public: int a; }; accessSpecDecl() matches 'public:' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('classTemplateDecl0')"><a name="classTemplateDecl0Anchor">classTemplateDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ClassTemplateDecl.html">ClassTemplateDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="classTemplateDecl0"><pre>Matches C++ class template declarations. Example matches Z template&lt;class T&gt; class Z {}; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('classTemplateSpecializationDecl0')"><a name="classTemplateSpecializationDecl0Anchor">classTemplateSpecializationDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ClassTemplateSpecializationDecl.html">ClassTemplateSpecializationDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="classTemplateSpecializationDecl0"><pre>Matches C++ class template specializations. Given template&lt;typename T&gt; class A {}; template&lt;&gt; class A&lt;double&gt; {}; A&lt;int&gt; a; classTemplateSpecializationDecl() matches the specializations A&lt;int&gt; and A&lt;double&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('constructorDecl0')"><a name="constructorDecl0Anchor">constructorDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructorDecl.html">CXXConstructorDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="constructorDecl0"><pre>Matches C++ constructor declarations. Example matches Foo::Foo() and Foo::Foo(int) class Foo { public: Foo(); Foo(int); int DoSomething(); }; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('decl0')"><a name="decl0Anchor">decl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="decl0"><pre>Matches declarations. Examples matches X, C, and the friend declaration inside C; void X(); class C { friend X; }; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('declaratorDecl0')"><a name="declaratorDecl0Anchor">declaratorDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclaratorDecl.html">DeclaratorDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="declaratorDecl0"><pre>Matches declarator declarations (field, variable, function and non-type template parameter declarations). Given class X { int y; }; declaratorDecl() matches int y. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('destructorDecl0')"><a name="destructorDecl0Anchor">destructorDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXDestructorDecl.html">CXXDestructorDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="destructorDecl0"><pre>Matches explicit C++ destructor declarations. Example matches Foo::~Foo() class Foo { public: virtual ~Foo(); }; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('enumConstantDecl0')"><a name="enumConstantDecl0Anchor">enumConstantDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumConstantDecl.html">EnumConstantDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="enumConstantDecl0"><pre>Matches enum constants. Example matches A, B, C enum X { A, B, C }; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('enumDecl0')"><a name="enumDecl0Anchor">enumDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumDecl.html">EnumDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="enumDecl0"><pre>Matches enum declarations. Example matches X enum X { A, B, C }; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('fieldDecl0')"><a name="fieldDecl0Anchor">fieldDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FieldDecl.html">FieldDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="fieldDecl0"><pre>Matches field declarations. Given class X { int m; }; fieldDecl() matches 'm'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('friendDecl0')"><a name="friendDecl0Anchor">friendDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FriendDecl.html">FriendDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="friendDecl0"><pre>Matches friend declarations. Given class X { friend void foo(); }; friendDecl() matches 'friend void foo()'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('functionDecl0')"><a name="functionDecl0Anchor">functionDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="functionDecl0"><pre>Matches function declarations. Example matches f void f(); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('functionTemplateDecl0')"><a name="functionTemplateDecl0Anchor">functionTemplateDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionTemplateDecl.html">FunctionTemplateDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="functionTemplateDecl0"><pre>Matches C++ function template declarations. Example matches f template&lt;class T&gt; void f(T t) {} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('linkageSpecDecl0')"><a name="linkageSpecDecl0Anchor">linkageSpecDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LinkageSpecDecl.html">LinkageSpecDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="linkageSpecDecl0"><pre>Matches a declaration of a linkage specification. Given extern "C" {} linkageSpecDecl() matches "extern "C" {}" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('methodDecl0')"><a name="methodDecl0Anchor">methodDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="methodDecl0"><pre>Matches method declarations. Example matches y class X { void y(); }; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('namedDecl0')"><a name="namedDecl0Anchor">namedDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NamedDecl.html">NamedDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="namedDecl0"><pre>Matches a declaration of anything that could have a name. Example matches X, S, the anonymous union type, i, and U; typedef int X; struct S { union { int i; } U; }; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('namespaceDecl0')"><a name="namespaceDecl0Anchor">namespaceDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NamespaceDecl.html">NamespaceDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="namespaceDecl0"><pre>Matches a declaration of a namespace. Given namespace {} namespace test {} namespaceDecl() matches "namespace {}" and "namespace test {}" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('parmVarDecl0')"><a name="parmVarDecl0Anchor">parmVarDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ParmVarDecl.html">ParmVarDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="parmVarDecl0"><pre>Matches parameter variable declarations. Given void f(int x); parmVarDecl() matches int x. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('recordDecl0')"><a name="recordDecl0Anchor">recordDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="recordDecl0"><pre>Matches C++ class declarations. Example matches X, Z class X; template&lt;class T&gt; class Z {}; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('translationUnitDecl0')"><a name="translationUnitDecl0Anchor">translationUnitDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TranslationUnitDecl.html">TranslationUnitDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="translationUnitDecl0"><pre>Matches the top declaration context. Given int X; namespace NS { int Y; } namespace NS decl(hasDeclContext(translationUnitDecl())) matches "int X", but not "int Y". </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('typedefDecl0')"><a name="typedefDecl0Anchor">typedefDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefDecl.html">TypedefDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="typedefDecl0"><pre>Matches typedef declarations. Given typedef int X; typedefDecl() matches "typedef int X" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('unresolvedUsingValueDecl0')"><a name="unresolvedUsingValueDecl0Anchor">unresolvedUsingValueDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingValueDecl.html">UnresolvedUsingValueDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="unresolvedUsingValueDecl0"><pre>Matches unresolved using value declarations. Given template&lt;typename X&gt; class C : private X { using X::x; }; unresolvedUsingValueDecl() matches using X::x </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('usingDecl0')"><a name="usingDecl0Anchor">usingDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UsingDecl.html">UsingDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="usingDecl0"><pre>Matches using declarations. Given namespace X { int x; } using X::x; usingDecl() matches using X::x </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('usingDirectiveDecl0')"><a name="usingDirectiveDecl0Anchor">usingDirectiveDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UsingDirectiveDecl.html">UsingDirectiveDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="usingDirectiveDecl0"><pre>Matches using namespace declarations. Given namespace X { int x; } using namespace X; usingDirectiveDecl() matches using namespace X </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('valueDecl0')"><a name="valueDecl0Anchor">valueDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html">ValueDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="valueDecl0"><pre>Matches any value declaration. Example matches A, B, C and F enum X { A, B, C }; void F(); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('varDecl0')"><a name="varDecl0Anchor">varDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="varDecl0"><pre>Matches variable declarations. Note: this does not match declarations of member variables, which are "field" declarations in Clang parlance. Example matches a int a; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifierLoc.html">NestedNameSpecifierLoc</a>&gt;</td><td class="name" onclick="toggle('nestedNameSpecifierLoc0')"><a name="nestedNameSpecifierLoc0Anchor">nestedNameSpecifierLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifierLoc.html">NestedNameSpecifierLoc</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="nestedNameSpecifierLoc0"><pre>Same as nestedNameSpecifier but matches NestedNameSpecifierLoc. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifier.html">NestedNameSpecifier</a>&gt;</td><td class="name" onclick="toggle('nestedNameSpecifier0')"><a name="nestedNameSpecifier0Anchor">nestedNameSpecifier</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifier.html">NestedNameSpecifier</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="nestedNameSpecifier0"><pre>Matches nested name specifiers. Given namespace ns { struct A { static void f(); }; void A::f() {} void g() { A::f(); } } ns::A a; nestedNameSpecifier() matches "ns::" and both "A::" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('qualType0')"><a name="qualType0Anchor">qualType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="qualType0"><pre>Matches QualTypes in the clang AST. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('CUDAKernelCallExpr0')"><a name="CUDAKernelCallExpr0Anchor">CUDAKernelCallExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CUDAKernelCallExpr.html">CUDAKernelCallExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="CUDAKernelCallExpr0"><pre>Matches CUDA kernel call expression. Example matches, kernel&lt;&lt;&lt;i,j&gt;&gt;&gt;(); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('arraySubscriptExpr0')"><a name="arraySubscriptExpr0Anchor">arraySubscriptExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArraySubscriptExpr.html">ArraySubscriptExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="arraySubscriptExpr0"><pre>Matches array subscript expressions. Given int i = a[1]; arraySubscriptExpr() matches "a[1]" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('asmStmt0')"><a name="asmStmt0Anchor">asmStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1AsmStmt.html">AsmStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="asmStmt0"><pre>Matches asm statements. int i = 100; __asm("mov al, 2"); asmStmt() matches '__asm("mov al, 2")' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('binaryOperator0')"><a name="binaryOperator0Anchor">binaryOperator</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BinaryOperator.html">BinaryOperator</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="binaryOperator0"><pre>Matches binary operator expressions. Example matches a || b !(a || b) </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('bindTemporaryExpr0')"><a name="bindTemporaryExpr0Anchor">bindTemporaryExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXBindTemporaryExpr.html">CXXBindTemporaryExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="bindTemporaryExpr0"><pre>Matches nodes where temporaries are created. Example matches FunctionTakesString(GetStringByValue()) (matcher = bindTemporaryExpr()) FunctionTakesString(GetStringByValue()); FunctionTakesStringByPointer(GetStringPointer()); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('boolLiteral0')"><a name="boolLiteral0Anchor">boolLiteral</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXBoolLiteralExpr.html">CXXBoolLiteralExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="boolLiteral0"><pre>Matches bool literals. Example matches true true </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('breakStmt0')"><a name="breakStmt0Anchor">breakStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BreakStmt.html">BreakStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="breakStmt0"><pre>Matches break statements. Given while (true) { break; } breakStmt() matches 'break' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('cStyleCastExpr0')"><a name="cStyleCastExpr0Anchor">cStyleCastExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CStyleCastExpr.html">CStyleCastExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="cStyleCastExpr0"><pre>Matches a C-style cast expression. Example: Matches (int*) 2.2f in int i = (int) 2.2f; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('callExpr0')"><a name="callExpr0Anchor">callExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="callExpr0"><pre>Matches call expressions. Example matches x.y() and y() X x; x.y(); y(); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('caseStmt0')"><a name="caseStmt0Anchor">caseStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CaseStmt.html">CaseStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="caseStmt0"><pre>Matches case statements inside switch statements. Given switch(a) { case 42: break; default: break; } caseStmt() matches 'case 42: break;'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('castExpr0')"><a name="castExpr0Anchor">castExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CastExpr.html">CastExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="castExpr0"><pre>Matches any cast nodes of Clang's AST. Example: castExpr() matches each of the following: (int) 3; const_cast&lt;Expr *&gt;(SubExpr); char c = 0; but does not match int i = (0); int k = 0; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('catchStmt0')"><a name="catchStmt0Anchor">catchStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXCatchStmt.html">CXXCatchStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="catchStmt0"><pre>Matches catch statements. try {} catch(int i) {} catchStmt() matches 'catch(int i)' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('characterLiteral0')"><a name="characterLiteral0Anchor">characterLiteral</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CharacterLiteral.html">CharacterLiteral</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="characterLiteral0"><pre>Matches character literals (also matches wchar_t). Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), though. Example matches 'a', L'a' char ch = 'a'; wchar_t chw = L'a'; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('compoundLiteralExpr0')"><a name="compoundLiteralExpr0Anchor">compoundLiteralExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CompoundLiteralExpr.html">CompoundLiteralExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="compoundLiteralExpr0"><pre>Matches compound (i.e. non-scalar) literals Example match: {1}, (1, 2) int array[4] = {1}; vector int myvec = (vector int)(1, 2); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('compoundStmt0')"><a name="compoundStmt0Anchor">compoundStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CompoundStmt.html">CompoundStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="compoundStmt0"><pre>Matches compound statements. Example matches '{}' and '{{}}'in 'for (;;) {{}}' for (;;) {{}} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('conditionalOperator0')"><a name="conditionalOperator0Anchor">conditionalOperator</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ConditionalOperator.html">ConditionalOperator</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="conditionalOperator0"><pre>Matches conditional operator expressions. Example matches a ? b : c (a ? b : c) + 42 </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('constCastExpr0')"><a name="constCastExpr0Anchor">constCastExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstCastExpr.html">CXXConstCastExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="constCastExpr0"><pre>Matches a const_cast expression. Example: Matches const_cast&lt;int*&gt;(&amp;r) in int n = 42; const int &amp;r(n); int* p = const_cast&lt;int*&gt;(&amp;r); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('constructExpr0')"><a name="constructExpr0Anchor">constructExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="constructExpr0"><pre>Matches constructor call expressions (including implicit ones). Example matches string(ptr, n) and ptr within arguments of f (matcher = constructExpr()) void f(const string &amp;a, const string &amp;b); char *ptr; int n; f(string(ptr, n), ptr); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('continueStmt0')"><a name="continueStmt0Anchor">continueStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ContinueStmt.html">ContinueStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="continueStmt0"><pre>Matches continue statements. Given while (true) { continue; } continueStmt() matches 'continue' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('declRefExpr0')"><a name="declRefExpr0Anchor">declRefExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="declRefExpr0"><pre>Matches expressions that refer to declarations. Example matches x in if (x) bool x; if (x) {} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('declStmt0')"><a name="declStmt0Anchor">declStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclStmt.html">DeclStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="declStmt0"><pre>Matches declaration statements. Given int a; declStmt() matches 'int a'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('defaultArgExpr0')"><a name="defaultArgExpr0Anchor">defaultArgExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXDefaultArgExpr.html">CXXDefaultArgExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="defaultArgExpr0"><pre>Matches the value of a default argument at the call site. Example matches the CXXDefaultArgExpr placeholder inserted for the default value of the second parameter in the call expression f(42) (matcher = defaultArgExpr()) void f(int x, int y = 0); f(42); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('defaultStmt0')"><a name="defaultStmt0Anchor">defaultStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DefaultStmt.html">DefaultStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="defaultStmt0"><pre>Matches default statements inside switch statements. Given switch(a) { case 42: break; default: break; } defaultStmt() matches 'default: break;'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('deleteExpr0')"><a name="deleteExpr0Anchor">deleteExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXDeleteExpr.html">CXXDeleteExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="deleteExpr0"><pre>Matches delete expressions. Given delete X; deleteExpr() matches 'delete X'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('doStmt0')"><a name="doStmt0Anchor">doStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DoStmt.html">DoStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="doStmt0"><pre>Matches do statements. Given do {} while (true); doStmt() matches 'do {} while(true)' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('dynamicCastExpr0')"><a name="dynamicCastExpr0Anchor">dynamicCastExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXDynamicCastExpr.html">CXXDynamicCastExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="dynamicCastExpr0"><pre>Matches a dynamic_cast expression. Example: dynamicCastExpr() matches dynamic_cast&lt;D*&gt;(&amp;b); in struct B { virtual ~B() {} }; struct D : B {}; B b; D* p = dynamic_cast&lt;D*&gt;(&amp;b); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('explicitCastExpr0')"><a name="explicitCastExpr0Anchor">explicitCastExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ExplicitCastExpr.html">ExplicitCastExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="explicitCastExpr0"><pre>Matches explicit cast expressions. Matches any cast expression written in user code, whether it be a C-style cast, a functional-style cast, or a keyword cast. Does not match implicit conversions. Note: the name "explicitCast" is chosen to match Clang's terminology, as Clang uses the term "cast" to apply to implicit conversions as well as to actual cast expressions. hasDestinationType. Example: matches all five of the casts in int((int)(reinterpret_cast&lt;int&gt;(static_cast&lt;int&gt;(const_cast&lt;int&gt;(42))))) but does not match the implicit conversion in long ell = 42; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('expr0')"><a name="expr0Anchor">expr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="expr0"><pre>Matches expressions. Example matches x() void f() { x(); } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('exprWithCleanups0')"><a name="exprWithCleanups0Anchor">exprWithCleanups</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ExprWithCleanups.html">ExprWithCleanups</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="exprWithCleanups0"><pre>Matches expressions that introduce cleanups to be run at the end of the sub-expression's evaluation. Example matches std::string() const std::string str = std::string(); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('floatLiteral0')"><a name="floatLiteral0Anchor">floatLiteral</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FloatingLiteral.html">FloatingLiteral</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="floatLiteral0"><pre>Matches float literals of all sizes encodings, e.g. 1.0, 1.0f, 1.0L and 1e10. Does not match implicit conversions such as float a = 10; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('forRangeStmt0')"><a name="forRangeStmt0Anchor">forRangeStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXForRangeStmt.html">CXXForRangeStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="forRangeStmt0"><pre>Matches range-based for statements. forRangeStmt() matches 'for (auto a : i)' int i[] = {1, 2, 3}; for (auto a : i); for(int j = 0; j &lt; 5; ++j); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('forStmt0')"><a name="forStmt0Anchor">forStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ForStmt.html">ForStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="forStmt0"><pre>Matches for statements. Example matches 'for (;;) {}' for (;;) {} int i[] = {1, 2, 3}; for (auto a : i); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('functionalCastExpr0')"><a name="functionalCastExpr0Anchor">functionalCastExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXFunctionalCastExpr.html">CXXFunctionalCastExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="functionalCastExpr0"><pre>Matches functional cast expressions Example: Matches Foo(bar); Foo f = bar; Foo g = (Foo) bar; Foo h = Foo(bar); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('gotoStmt0')"><a name="gotoStmt0Anchor">gotoStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1GotoStmt.html">GotoStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="gotoStmt0"><pre>Matches goto statements. Given goto FOO; FOO: bar(); gotoStmt() matches 'goto FOO' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('ifStmt0')"><a name="ifStmt0Anchor">ifStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IfStmt.html">IfStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="ifStmt0"><pre>Matches if statements. Example matches 'if (x) {}' if (x) {} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('implicitCastExpr0')"><a name="implicitCastExpr0Anchor">implicitCastExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ImplicitCastExpr.html">ImplicitCastExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="implicitCastExpr0"><pre>Matches the implicit cast nodes of Clang's AST. This matches many different places, including function call return value eliding, as well as any type conversions. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('initListExpr0')"><a name="initListExpr0Anchor">initListExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InitListExpr.html">InitListExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="initListExpr0"><pre>Matches init list expressions. Given int a[] = { 1, 2 }; struct B { int x, y; }; B b = { 5, 6 }; initListExpr() matches "{ 1, 2 }" and "{ 5, 6 }" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('integerLiteral0')"><a name="integerLiteral0Anchor">integerLiteral</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IntegerLiteral.html">IntegerLiteral</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="integerLiteral0"><pre>Matches integer literals of all sizes encodings, e.g. 1, 1L, 0x1 and 1U. Does not match character-encoded integers such as L'a'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('labelStmt0')"><a name="labelStmt0Anchor">labelStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="labelStmt0"><pre>Matches label statements. Given goto FOO; FOO: bar(); labelStmt() matches 'FOO:' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('lambdaExpr0')"><a name="lambdaExpr0Anchor">lambdaExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LambdaExpr.html">LambdaExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="lambdaExpr0"><pre>Matches lambda expressions. Example matches [&amp;](){return 5;} [&amp;](){return 5;} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('materializeTemporaryExpr0')"><a name="materializeTemporaryExpr0Anchor">materializeTemporaryExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MaterializeTemporaryExpr.html">MaterializeTemporaryExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="materializeTemporaryExpr0"><pre>Matches nodes where temporaries are materialized. Example: Given struct T {void func()}; T f(); void g(T); materializeTemporaryExpr() matches 'f()' in these statements T u(f()); g(f()); but does not match f(); f().func(); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('memberCallExpr0')"><a name="memberCallExpr0Anchor">memberCallExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMemberCallExpr.html">CXXMemberCallExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="memberCallExpr0"><pre>Matches member call expressions. Example matches x.y() X x; x.y(); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('memberExpr0')"><a name="memberExpr0Anchor">memberExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="memberExpr0"><pre>Matches member expressions. Given class Y { void x() { this-&gt;x(); x(); Y y; y.x(); a; this-&gt;b; Y::b; } int a; static int b; }; memberExpr() matches this-&gt;x, x, y.x, a, this-&gt;b </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('newExpr0')"><a name="newExpr0Anchor">newExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXNewExpr.html">CXXNewExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="newExpr0"><pre>Matches new expressions. Given new X; newExpr() matches 'new X'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('nullPtrLiteralExpr0')"><a name="nullPtrLiteralExpr0Anchor">nullPtrLiteralExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXNullPtrLiteralExpr.html">CXXNullPtrLiteralExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="nullPtrLiteralExpr0"><pre>Matches nullptr literal. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('nullStmt0')"><a name="nullStmt0Anchor">nullStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NullStmt.html">NullStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="nullStmt0"><pre>Matches null statements. foo();; nullStmt() matches the second ';' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('operatorCallExpr0')"><a name="operatorCallExpr0Anchor">operatorCallExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXOperatorCallExpr.html">CXXOperatorCallExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="operatorCallExpr0"><pre>Matches overloaded operator calls. Note that if an operator isn't overloaded, it won't match. Instead, use binaryOperator matcher. Currently it does not match operators such as new delete. FIXME: figure out why these do not match? Example matches both operator&lt;&lt;((o &lt;&lt; b), c) and operator&lt;&lt;(o, b) (matcher = operatorCallExpr()) ostream &amp;operator&lt;&lt; (ostream &amp;out, int i) { }; ostream &amp;o; int b = 1, c = 1; o &lt;&lt; b &lt;&lt; c; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('reinterpretCastExpr0')"><a name="reinterpretCastExpr0Anchor">reinterpretCastExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXReinterpretCastExpr.html">CXXReinterpretCastExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="reinterpretCastExpr0"><pre>Matches a reinterpret_cast expression. Either the source expression or the destination type can be matched using has(), but hasDestinationType() is more specific and can be more readable. Example matches reinterpret_cast&lt;char*&gt;(&amp;p) in void* p = reinterpret_cast&lt;char*&gt;(&amp;p); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('returnStmt0')"><a name="returnStmt0Anchor">returnStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReturnStmt.html">ReturnStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="returnStmt0"><pre>Matches return statements. Given return 1; returnStmt() matches 'return 1' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('staticCastExpr0')"><a name="staticCastExpr0Anchor">staticCastExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXStaticCastExpr.html">CXXStaticCastExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="staticCastExpr0"><pre>Matches a C++ static_cast expression. hasDestinationType reinterpretCast Example: staticCastExpr() matches static_cast&lt;long&gt;(8) in long eight(static_cast&lt;long&gt;(8)); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('stmt0')"><a name="stmt0Anchor">stmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="stmt0"><pre>Matches statements. Given { ++a; } stmt() matches both the compound statement '{ ++a; }' and '++a'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('stringLiteral0')"><a name="stringLiteral0Anchor">stringLiteral</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1StringLiteral.html">StringLiteral</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="stringLiteral0"><pre>Matches string literals (also matches wide string literals). Example matches "abcd", L"abcd" char *s = "abcd"; wchar_t *ws = L"abcd" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('substNonTypeTemplateParmExpr0')"><a name="substNonTypeTemplateParmExpr0Anchor">substNonTypeTemplateParmExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1SubstNonTypeTemplateParmExpr.html">SubstNonTypeTemplateParmExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="substNonTypeTemplateParmExpr0"><pre>Matches substitutions of non-type template parameters. Given template &lt;int N&gt; struct A { static const int n = N; }; struct B : public A&lt;42&gt; {}; substNonTypeTemplateParmExpr() matches "N" in the right-hand side of "static const int n = N;" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('switchCase0')"><a name="switchCase0Anchor">switchCase</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1SwitchCase.html">SwitchCase</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="switchCase0"><pre>Matches case and default statements inside switch statements. Given switch(a) { case 42: break; default: break; } switchCase() matches 'case 42: break;' and 'default: break;'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('switchStmt0')"><a name="switchStmt0Anchor">switchStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1SwitchStmt.html">SwitchStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="switchStmt0"><pre>Matches switch statements. Given switch(a) { case 42: break; default: break; } switchStmt() matches 'switch(a)'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('temporaryObjectExpr0')"><a name="temporaryObjectExpr0Anchor">temporaryObjectExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXTemporaryObjectExpr.html">CXXTemporaryObjectExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="temporaryObjectExpr0"><pre>Matches functional cast expressions having N != 1 arguments Example: Matches Foo(bar, bar) Foo h = Foo(bar, bar); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('thisExpr0')"><a name="thisExpr0Anchor">thisExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXThisExpr.html">CXXThisExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="thisExpr0"><pre>Matches implicit and explicit this expressions. Example matches the implicit this expression in "return i". (matcher = thisExpr()) struct foo { int i; int f() { return i; } }; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('throwExpr0')"><a name="throwExpr0Anchor">throwExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXThrowExpr.html">CXXThrowExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="throwExpr0"><pre>Matches throw expressions. try { throw 5; } catch(int i) {} throwExpr() matches 'throw 5' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('tryStmt0')"><a name="tryStmt0Anchor">tryStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXTryStmt.html">CXXTryStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="tryStmt0"><pre>Matches try statements. try {} catch(int i) {} tryStmt() matches 'try {}' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('unaryExprOrTypeTraitExpr0')"><a name="unaryExprOrTypeTraitExpr0Anchor">unaryExprOrTypeTraitExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnaryExprOrTypeTraitExpr.html">UnaryExprOrTypeTraitExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="unaryExprOrTypeTraitExpr0"><pre>Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) Given Foo x = bar; int y = sizeof(x) + alignof(x); unaryExprOrTypeTraitExpr() matches sizeof(x) and alignof(x) </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('unaryOperator0')"><a name="unaryOperator0Anchor">unaryOperator</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnaryOperator.html">UnaryOperator</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="unaryOperator0"><pre>Matches unary operator expressions. Example matches !a !a || b </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('unresolvedConstructExpr0')"><a name="unresolvedConstructExpr0Anchor">unresolvedConstructExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXUnresolvedConstructExpr.html">CXXUnresolvedConstructExpr</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="unresolvedConstructExpr0"><pre>Matches unresolved constructor call expressions. Example matches T(t) in return statement of f (matcher = unresolvedConstructExpr()) template &lt;typename T&gt; void f(const T&amp; t) { return T(t); } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('userDefinedLiteral0')"><a name="userDefinedLiteral0Anchor">userDefinedLiteral</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UserDefinedLiteral.html">UserDefinedLiteral</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="userDefinedLiteral0"><pre>Matches user defined literal operator call. Example match: "foo"_suffix </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('whileStmt0')"><a name="whileStmt0Anchor">whileStmt</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1WhileStmt.html">WhileStmt</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="whileStmt0"><pre>Matches while statements. Given while (true) {} whileStmt() matches 'while (true) {}'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('templateArgument0')"><a name="templateArgument0Anchor">templateArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="templateArgument0"><pre>Matches template arguments. Given template &lt;typename T&gt; struct C {}; C&lt;int&gt; c; templateArgument() matches 'int' in C&lt;int&gt;. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td><td class="name" onclick="toggle('typeLoc0')"><a name="typeLoc0Anchor">typeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="typeLoc0"><pre>Matches TypeLocs in the clang AST. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('arrayType0')"><a name="arrayType0Anchor">arrayType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArrayType.html">ArrayType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="arrayType0"><pre>Matches all kinds of arrays. Given int a[] = { 2, 3 }; int b[4]; void f() { int c[a[0]]; } arrayType() matches "int a[]", "int b[4]" and "int c[a[0]]"; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('atomicType0')"><a name="atomicType0Anchor">atomicType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1AtomicType.html">AtomicType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="atomicType0"><pre>Matches atomic types. Given _Atomic(int) i; atomicType() matches "_Atomic(int) i" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('autoType0')"><a name="autoType0Anchor">autoType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1AutoType.html">AutoType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="autoType0"><pre>Matches types nodes representing C++11 auto types. Given: auto n = 4; int v[] = { 2, 3 } for (auto i : v) { } autoType() matches "auto n" and "auto i" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('blockPointerType0')"><a name="blockPointerType0Anchor">blockPointerType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html">BlockPointerType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="blockPointerType0"><pre>Matches block pointer types, i.e. types syntactically represented as "void (^)(int)". The pointee is always required to be a FunctionType. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('builtinType0')"><a name="builtinType0Anchor">builtinType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BuiltinType.html">BuiltinType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="builtinType0"><pre>Matches builtin Types. Given struct A {}; A a; int b; float c; bool d; builtinType() matches "int b", "float c" and "bool d" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('complexType0')"><a name="complexType0Anchor">complexType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ComplexType.html">ComplexType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="complexType0"><pre>Matches C99 complex types. Given _Complex float f; complexType() matches "_Complex float f" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('constantArrayType0')"><a name="constantArrayType0Anchor">constantArrayType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ConstantArrayType.html">ConstantArrayType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="constantArrayType0"><pre>Matches C arrays with a specified constant size. Given void() { int a[2]; int b[] = { 2, 3 }; int c[b[0]]; } constantArrayType() matches "int a[2]" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('dependentSizedArrayType0')"><a name="dependentSizedArrayType0Anchor">dependentSizedArrayType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DependentSizedArrayType.html">DependentSizedArrayType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="dependentSizedArrayType0"><pre>Matches C++ arrays whose size is a value-dependent expression. Given template&lt;typename T, int Size&gt; class array { T data[Size]; }; dependentSizedArrayType matches "T data[Size]" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('elaboratedType0')"><a name="elaboratedType0Anchor">elaboratedType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ElaboratedType.html">ElaboratedType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="elaboratedType0"><pre>Matches types specified with an elaborated type keyword or with a qualified name. Given namespace N { namespace M { class D {}; } } class C {}; class C c; N::M::D d; elaboratedType() matches the type of the variable declarations of both c and d. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('functionType0')"><a name="functionType0Anchor">functionType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionType.html">FunctionType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="functionType0"><pre>Matches FunctionType nodes. Given int (*f)(int); void g(); functionType() matches "int (*f)(int)" and the type of "g". </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('incompleteArrayType0')"><a name="incompleteArrayType0Anchor">incompleteArrayType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IncompleteArrayType.html">IncompleteArrayType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="incompleteArrayType0"><pre>Matches C arrays with unspecified size. Given int a[] = { 2, 3 }; int b[42]; void f(int c[]) { int d[a[0]]; }; incompleteArrayType() matches "int a[]" and "int c[]" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('lValueReferenceType0')"><a name="lValueReferenceType0Anchor">lValueReferenceType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LValueReferenceType.html">LValueReferenceType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="lValueReferenceType0"><pre>Matches lvalue reference types. Given: int *a; int &amp;b = *a; int &amp;&amp;c = 1; auto &amp;d = b; auto &amp;&amp;e = c; auto &amp;&amp;f = 2; int g = 5; lValueReferenceType() matches the types of b, d, and e. e is matched since the type is deduced as int&amp; by reference collapsing rules. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('memberPointerType0')"><a name="memberPointerType0Anchor">memberPointerType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerType.html">MemberPointerType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="memberPointerType0"><pre>Matches member pointer types. Given struct A { int i; } A::* ptr = A::i; memberPointerType() matches "A::* ptr" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('parenType0')"><a name="parenType0Anchor">parenType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ParenType.html">ParenType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="parenType0"><pre>Matches ParenType nodes. Given int (*ptr_to_array)[4]; int *array_of_ptrs[4]; varDecl(hasType(pointsTo(parenType()))) matches ptr_to_array but not array_of_ptrs. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('pointerType0')"><a name="pointerType0Anchor">pointerType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerType.html">PointerType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="pointerType0"><pre>Matches pointer types. Given int *a; int &amp;b = *a; int c = 5; pointerType() matches "int *a" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('rValueReferenceType0')"><a name="rValueReferenceType0Anchor">rValueReferenceType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RValueReferenceType.html">RValueReferenceType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="rValueReferenceType0"><pre>Matches rvalue reference types. Given: int *a; int &amp;b = *a; int &amp;&amp;c = 1; auto &amp;d = b; auto &amp;&amp;e = c; auto &amp;&amp;f = 2; int g = 5; rValueReferenceType() matches the types of c and f. e is not matched as it is deduced to int&amp; by reference collapsing rules. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('recordType0')"><a name="recordType0Anchor">recordType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="recordType0"><pre>Matches record types (e.g. structs, classes). Given class C {}; struct S {}; C c; S s; recordType() matches the type of the variable declarations of both c and s. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('referenceType0')"><a name="referenceType0Anchor">referenceType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceType.html">ReferenceType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="referenceType0"><pre>Matches both lvalue and rvalue reference types. Given int *a; int &amp;b = *a; int &amp;&amp;c = 1; auto &amp;d = b; auto &amp;&amp;e = c; auto &amp;&amp;f = 2; int g = 5; referenceType() matches the types of b, c, d, e, and f. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('templateSpecializationType0')"><a name="templateSpecializationType0Anchor">templateSpecializationType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="templateSpecializationType0"><pre>Matches template specialization types. Given template &lt;typename T&gt; class C { }; template class C&lt;int&gt;; A C&lt;char&gt; var; B templateSpecializationType() matches the type of the explicit instantiation in A and the type of the variable declaration in B. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('type0')"><a name="type0Anchor">type</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="type0"><pre>Matches Types in the clang AST. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('typedefType0')"><a name="typedefType0Anchor">typedefType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="typedefType0"><pre>Matches typedef types. Given typedef int X; typedefType() matches "typedef int X" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('unaryTransformType0')"><a name="unaryTransformType0Anchor">unaryTransformType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnaryTransformType.html">UnaryTransformType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="unaryTransformType0"><pre>Matches types nodes representing unary type transformations. Given: typedef __underlying_type(T) type; unaryTransformType() matches "__underlying_type(T)" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('variableArrayType0')"><a name="variableArrayType0Anchor">variableArrayType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VariableArrayType.html">VariableArrayType</a>&gt;...</td></tr> <tr><td colspan="4" class="doc" id="variableArrayType0"><pre>Matches C arrays with a specified size that is not an integer-constant-expression. Given void f() { int a[] = { 2, 3 } int b[42]; int c[a[0]]; } variableArrayType() matches "int c[a[0]]" </pre></td></tr> <!--END_DECL_MATCHERS --> </table> <!-- ======================================================================= --> <h2 id="narrowing-matchers">Narrowing Matchers</h2> <!-- ======================================================================= --> <p>Narrowing matchers match certain attributes on the current node, thus narrowing down the set of nodes of the current type to match on.</p> <p>There are special logical narrowing matchers (allOf, anyOf, anything and unless) which allow users to create more powerful match expressions.</p> <table> <tr style="text-align:left"><th>Return type</th><th>Name</th><th>Parameters</th></tr> <!-- START_NARROWING_MATCHERS --> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('allOf0')"><a name="allOf0Anchor">allOf</a></td><td>Matcher&lt;*&gt;, ..., Matcher&lt;*&gt;</td></tr> <tr><td colspan="4" class="doc" id="allOf0"><pre>Matches if all given matchers match. Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('anyOf0')"><a name="anyOf0Anchor">anyOf</a></td><td>Matcher&lt;*&gt;, ..., Matcher&lt;*&gt;</td></tr> <tr><td colspan="4" class="doc" id="anyOf0"><pre>Matches if any of the given matchers matches. Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('anything0')"><a name="anything0Anchor">anything</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="anything0"><pre>Matches any node. Useful when another matcher requires a child matcher, but there's no additional constraint. This will often be used with an explicit conversion to an internal::Matcher&lt;&gt; type such as TypeMatcher. Example: DeclarationMatcher(anything()) matches all declarations, e.g., "int* p" and "void f()" in int* p; void f(); Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('unless0')"><a name="unless0Anchor">unless</a></td><td>Matcher&lt;*&gt;</td></tr> <tr><td colspan="4" class="doc" id="unless0"><pre>Matches if the provided matcher does not match. Example matches Y (matcher = recordDecl(unless(hasName("X")))) class X {}; class Y {}; Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BinaryOperator.html">BinaryOperator</a>&gt;</td><td class="name" onclick="toggle('hasOperatorName0')"><a name="hasOperatorName0Anchor">hasOperatorName</a></td><td>std::string Name</td></tr> <tr><td colspan="4" class="doc" id="hasOperatorName0"><pre>Matches the operator Name of operator expressions (binary or unary). Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) !(a || b) </pre></td></tr> <tr><td>Matcher&lt;CXXBoolLiteral&gt;</td><td class="name" onclick="toggle('equals2')"><a name="equals2Anchor">equals</a></td><td>ValueT Value</td></tr> <tr><td colspan="4" class="doc" id="equals2"><pre>Matches literals that are equal to the given value. Example matches true (matcher = boolLiteral(equals(true))) true Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CharacterLiteral.html">CharacterLiteral</a>&gt;, Matcher&lt;CXXBoolLiteral&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FloatingLiteral.html">FloatingLiteral</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IntegerLiteral.html">IntegerLiteral</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXCatchStmt.html">CXXCatchStmt</a>&gt;</td><td class="name" onclick="toggle('isCatchAll1')"><a name="isCatchAll1Anchor">isCatchAll</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isCatchAll1"><pre>Matches a C++ catch statement that has a handler that catches any exception type. Example matches catch(...) (matcher = catchStmt(isCatchAll())) try { // ... } catch(...) { } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;</td><td class="name" onclick="toggle('argumentCountIs1')"><a name="argumentCountIs1Anchor">argumentCountIs</a></td><td>unsigned N</td></tr> <tr><td colspan="4" class="doc" id="argumentCountIs1"><pre>Checks that a call expression or a constructor call expression has a specific number of arguments (including absent default arguments). Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) void f(int x, int y); f(0, 0); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;</td><td class="name" onclick="toggle('isListInitialization0')"><a name="isListInitialization0Anchor">isListInitialization</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isListInitialization0"><pre>Matches a constructor call expression which uses list initialization. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html">CXXCtorInitializer</a>&gt;</td><td class="name" onclick="toggle('isWritten0')"><a name="isWritten0Anchor">isWritten</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isWritten0"><pre>Matches a constructor initializer if it is explicitly written in code (as opposed to implicitly added by the compiler). Given struct Foo { Foo() { } Foo(int) : foo_("A") { } string foo_; }; constructorDecl(hasAnyConstructorInitializer(isWritten())) will match Foo(int), but not Foo() </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;</td><td class="name" onclick="toggle('isConst0')"><a name="isConst0Anchor">isConst</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isConst0"><pre>Matches if the given method declaration is const. Given struct A { void foo() const; void bar(); }; methodDecl(isConst()) matches A::foo() but not A::bar() </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;</td><td class="name" onclick="toggle('isOverride0')"><a name="isOverride0Anchor">isOverride</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isOverride0"><pre>Matches if the given method declaration overrides another method. Given class A { public: virtual void x(); }; class B : public A { public: virtual void x(); }; matches B::x </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;</td><td class="name" onclick="toggle('isPure0')"><a name="isPure0Anchor">isPure</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isPure0"><pre>Matches if the given method declaration is pure. Given class A { public: virtual void x() = 0; }; matches A::x </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;</td><td class="name" onclick="toggle('isVirtual0')"><a name="isVirtual0Anchor">isVirtual</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isVirtual0"><pre>Matches if the given method declaration is virtual. Given class A { public: virtual void x(); }; matches A::x </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXOperatorCallExpr.html">CXXOperatorCallExpr</a>&gt;</td><td class="name" onclick="toggle('hasOverloadedOperatorName1')"><a name="hasOverloadedOperatorName1Anchor">hasOverloadedOperatorName</a></td><td>StringRef Name</td></tr> <tr><td colspan="4" class="doc" id="hasOverloadedOperatorName1"><pre>Matches overloaded operator names. Matches overloaded operator names specified in strings without the "operator" prefix: e.g. "&lt;&lt;". Given: class A { int operator*(); }; const A &amp;operator&lt;&lt;(const A &amp;a, const A &amp;b); A a; a &lt;&lt; a; &lt;-- This matches operatorCallExpr(hasOverloadedOperatorName("&lt;&lt;"))) matches the specified line and recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches the declaration of A. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXOperatorCallExpr.html">CXXOperatorCallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('isDerivedFrom1')"><a name="isDerivedFrom1Anchor">isDerivedFrom</a></td><td>std::string BaseName</td></tr> <tr><td colspan="4" class="doc" id="isDerivedFrom1"><pre>Overloaded method as shortcut for isDerivedFrom(hasName(...)). </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('isExplicitTemplateSpecialization2')"><a name="isExplicitTemplateSpecialization2Anchor">isExplicitTemplateSpecialization</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isExplicitTemplateSpecialization2"><pre>Matches explicit template specializations of function, class, or static member variable template instantiations. Given template&lt;typename T&gt; void A(T t) { } template&lt;&gt; void A(int N) { } functionDecl(isExplicitTemplateSpecialization()) matches the specialization A&lt;int&gt;(). Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('isSameOrDerivedFrom1')"><a name="isSameOrDerivedFrom1Anchor">isSameOrDerivedFrom</a></td><td>std::string BaseName</td></tr> <tr><td colspan="4" class="doc" id="isSameOrDerivedFrom1"><pre>Overloaded method as shortcut for isSameOrDerivedFrom(hasName(...)). </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('isTemplateInstantiation2')"><a name="isTemplateInstantiation2Anchor">isTemplateInstantiation</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isTemplateInstantiation2"><pre>Matches template instantiations of function, class, or static member variable template instantiations. Given template &lt;typename T&gt; class X {}; class A {}; X&lt;A&gt; x; or template &lt;typename T&gt; class X {}; class A {}; template class X&lt;A&gt;; recordDecl(hasName("::X"), isTemplateInstantiation()) matches the template instantiation of X&lt;A&gt;. But given template &lt;typename T&gt; class X {}; class A {}; template &lt;&gt; class X&lt;A&gt; {}; X&lt;A&gt; x; recordDecl(hasName("::X"), isTemplateInstantiation()) does not match, as X&lt;A&gt; is an explicit template specialization. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;</td><td class="name" onclick="toggle('argumentCountIs0')"><a name="argumentCountIs0Anchor">argumentCountIs</a></td><td>unsigned N</td></tr> <tr><td colspan="4" class="doc" id="argumentCountIs0"><pre>Checks that a call expression or a constructor call expression has a specific number of arguments (including absent default arguments). Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) void f(int x, int y); f(0, 0); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CharacterLiteral.html">CharacterLiteral</a>&gt;</td><td class="name" onclick="toggle('equals3')"><a name="equals3Anchor">equals</a></td><td>ValueT Value</td></tr> <tr><td colspan="4" class="doc" id="equals3"><pre>Matches literals that are equal to the given value. Example matches true (matcher = boolLiteral(equals(true))) true Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CharacterLiteral.html">CharacterLiteral</a>&gt;, Matcher&lt;CXXBoolLiteral&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FloatingLiteral.html">FloatingLiteral</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IntegerLiteral.html">IntegerLiteral</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ClassTemplateSpecializationDecl.html">ClassTemplateSpecializationDecl</a>&gt;</td><td class="name" onclick="toggle('templateArgumentCountIs0')"><a name="templateArgumentCountIs0Anchor">templateArgumentCountIs</a></td><td>unsigned N</td></tr> <tr><td colspan="4" class="doc" id="templateArgumentCountIs0"><pre>Matches if the number of template arguments equals N. Given template&lt;typename T&gt; struct C {}; C&lt;int&gt; c; classTemplateSpecializationDecl(templateArgumentCountIs(1)) matches C&lt;int&gt;. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CompoundStmt.html">CompoundStmt</a>&gt;</td><td class="name" onclick="toggle('statementCountIs0')"><a name="statementCountIs0Anchor">statementCountIs</a></td><td>unsigned N</td></tr> <tr><td colspan="4" class="doc" id="statementCountIs0"><pre>Checks that a compound statement contains a specific number of child statements. Example: Given { for (;;) {} } compoundStmt(statementCountIs(0))) matches '{}' but does not match the outer compound statement. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ConstantArrayType.html">ConstantArrayType</a>&gt;</td><td class="name" onclick="toggle('hasSize0')"><a name="hasSize0Anchor">hasSize</a></td><td>unsigned N</td></tr> <tr><td colspan="4" class="doc" id="hasSize0"><pre>Matches ConstantArrayType nodes that have the specified size. Given int a[42]; int b[2 * 21]; int c[41], d[43]; constantArrayType(hasSize(42)) matches "int a[42]" and "int b[2 * 21]" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclStmt.html">DeclStmt</a>&gt;</td><td class="name" onclick="toggle('declCountIs0')"><a name="declCountIs0Anchor">declCountIs</a></td><td>unsigned N</td></tr> <tr><td colspan="4" class="doc" id="declCountIs0"><pre>Matches declaration statements that contain a specific number of declarations. Example: Given int a, b; int c; int d = 2, e; declCountIs(2) matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('equalsBoundNode1')"><a name="equalsBoundNode1Anchor">equalsBoundNode</a></td><td>std::string ID</td></tr> <tr><td colspan="4" class="doc" id="equalsBoundNode1"><pre>Matches if a node equals a previously bound node. Matches a node if it equals the node previously bound to ID. Given class X { int a; int b; }; recordDecl( has(fieldDecl(hasName("a"), hasType(type().bind("t")))), has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) matches the class X, as a and b have the same type. Note that when multiple matches are involved via forEach* matchers, equalsBoundNodes acts as a filter. For example: compoundStmt( forEachDescendant(varDecl().bind("d")), forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) will trigger a match for each combination of variable declaration and reference to that variable declaration within a compound statement. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('hasAttr0')"><a name="hasAttr0Anchor">hasAttr</a></td><td>attr::Kind AttrKind</td></tr> <tr><td colspan="4" class="doc" id="hasAttr0"><pre>Matches declaration that has a given attribute. Given __attribute__((device)) void f() { ... } decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of f. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isExpansionInFileMatching0')"><a name="isExpansionInFileMatching0Anchor">isExpansionInFileMatching</a></td><td>std::string RegExp</td></tr> <tr><td colspan="4" class="doc" id="isExpansionInFileMatching0"><pre>Matches AST nodes that were expanded within files whose name is partially matching a given regex. Example matches Y but not X (matcher = recordDecl(isExpansionInFileMatching("AST.*")) #include "ASTMatcher.h" class X {}; ASTMatcher.h: class Y {}; Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isExpansionInMainFile0')"><a name="isExpansionInMainFile0Anchor">isExpansionInMainFile</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isExpansionInMainFile0"><pre>Matches AST nodes that were expanded within the main-file. Example matches X but not Y (matcher = recordDecl(isExpansionInMainFile()) #include &lt;Y.h&gt; class X {}; Y.h: class Y {}; Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isExpansionInSystemHeader0')"><a name="isExpansionInSystemHeader0Anchor">isExpansionInSystemHeader</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isExpansionInSystemHeader0"><pre>Matches AST nodes that were expanded within system-header-files. Example matches Y but not X (matcher = recordDecl(isExpansionInSystemHeader()) #include &lt;SystemHeader.h&gt; class X {}; SystemHeader.h: class Y {}; Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isImplicit0')"><a name="isImplicit0Anchor">isImplicit</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isImplicit0"><pre>Matches a declaration that has been implicitly added by the compiler (eg. implicit defaultcopy constructors). </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isPrivate0')"><a name="isPrivate0Anchor">isPrivate</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isPrivate0"><pre>Matches private C++ declarations. Given class C { public: int a; protected: int b; private: int c; }; fieldDecl(isPrivate()) matches 'int c;' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isProtected0')"><a name="isProtected0Anchor">isProtected</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isProtected0"><pre>Matches protected C++ declarations. Given class C { public: int a; protected: int b; private: int c; }; fieldDecl(isProtected()) matches 'int b;' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('isPublic0')"><a name="isPublic0Anchor">isPublic</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isPublic0"><pre>Matches public C++ declarations. Given class C { public: int a; protected: int b; private: int c; }; fieldDecl(isPublic()) matches 'int a;' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FloatingLiteral.html">FloatingLiteral</a>&gt;</td><td class="name" onclick="toggle('equals1')"><a name="equals1Anchor">equals</a></td><td>ValueT Value</td></tr> <tr><td colspan="4" class="doc" id="equals1"><pre>Matches literals that are equal to the given value. Example matches true (matcher = boolLiteral(equals(true))) true Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CharacterLiteral.html">CharacterLiteral</a>&gt;, Matcher&lt;CXXBoolLiteral&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FloatingLiteral.html">FloatingLiteral</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IntegerLiteral.html">IntegerLiteral</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('hasOverloadedOperatorName0')"><a name="hasOverloadedOperatorName0Anchor">hasOverloadedOperatorName</a></td><td>StringRef Name</td></tr> <tr><td colspan="4" class="doc" id="hasOverloadedOperatorName0"><pre>Matches overloaded operator names. Matches overloaded operator names specified in strings without the "operator" prefix: e.g. "&lt;&lt;". Given: class A { int operator*(); }; const A &amp;operator&lt;&lt;(const A &amp;a, const A &amp;b); A a; a &lt;&lt; a; &lt;-- This matches operatorCallExpr(hasOverloadedOperatorName("&lt;&lt;"))) matches the specified line and recordDecl(hasMethod(hasOverloadedOperatorName("*"))) matches the declaration of A. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXOperatorCallExpr.html">CXXOperatorCallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('isDefinition2')"><a name="isDefinition2Anchor">isDefinition</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isDefinition2"><pre>Matches if a declaration has a body attached. Example matches A, va, fa class A {}; class B; Doesn't match, as it has no body. int va; extern int vb; Doesn't match, as it doesn't define the variable. void fa() {} void fb(); Doesn't match, as it has no body. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagDecl.html">TagDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('isDeleted0')"><a name="isDeleted0Anchor">isDeleted</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isDeleted0"><pre>Matches deleted function declarations. Given: void Func(); void DeletedFunc() = delete; functionDecl(isDeleted()) matches the declaration of DeletedFunc, but not Func. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('isExplicitTemplateSpecialization0')"><a name="isExplicitTemplateSpecialization0Anchor">isExplicitTemplateSpecialization</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isExplicitTemplateSpecialization0"><pre>Matches explicit template specializations of function, class, or static member variable template instantiations. Given template&lt;typename T&gt; void A(T t) { } template&lt;&gt; void A(int N) { } functionDecl(isExplicitTemplateSpecialization()) matches the specialization A&lt;int&gt;(). Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('isExternC0')"><a name="isExternC0Anchor">isExternC</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isExternC0"><pre>Matches extern "C" function declarations. Given: extern "C" void f() {} extern "C" { void g() {} } void h() {} functionDecl(isExternC()) matches the declaration of f and g, but not the declaration h </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('isTemplateInstantiation0')"><a name="isTemplateInstantiation0Anchor">isTemplateInstantiation</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isTemplateInstantiation0"><pre>Matches template instantiations of function, class, or static member variable template instantiations. Given template &lt;typename T&gt; class X {}; class A {}; X&lt;A&gt; x; or template &lt;typename T&gt; class X {}; class A {}; template class X&lt;A&gt;; recordDecl(hasName("::X"), isTemplateInstantiation()) matches the template instantiation of X&lt;A&gt;. But given template &lt;typename T&gt; class X {}; class A {}; template &lt;&gt; class X&lt;A&gt; {}; X&lt;A&gt; x; recordDecl(hasName("::X"), isTemplateInstantiation()) does not match, as X&lt;A&gt; is an explicit template specialization. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('parameterCountIs0')"><a name="parameterCountIs0Anchor">parameterCountIs</a></td><td>unsigned N</td></tr> <tr><td colspan="4" class="doc" id="parameterCountIs0"><pre>Matches FunctionDecls that have a specific parameter count. Given void f(int i) {} void g(int i, int j) {} functionDecl(parameterCountIs(2)) matches g(int i, int j) {} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IntegerLiteral.html">IntegerLiteral</a>&gt;</td><td class="name" onclick="toggle('equals0')"><a name="equals0Anchor">equals</a></td><td>ValueT Value</td></tr> <tr><td colspan="4" class="doc" id="equals0"><pre>Matches literals that are equal to the given value. Example matches true (matcher = boolLiteral(equals(true))) true Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CharacterLiteral.html">CharacterLiteral</a>&gt;, Matcher&lt;CXXBoolLiteral&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FloatingLiteral.html">FloatingLiteral</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IntegerLiteral.html">IntegerLiteral</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;</td><td class="name" onclick="toggle('isArrow0')"><a name="isArrow0Anchor">isArrow</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isArrow0"><pre>Matches member expressions that are called with '-&gt;' as opposed to '.'. Member calls on the implicit this pointer match as called with '-&gt;'. Given class Y { void x() { this-&gt;x(); x(); Y y; y.x(); a; this-&gt;b; Y::b; } int a; static int b; }; memberExpr(isArrow()) matches this-&gt;x, x, y.x, a, this-&gt;b </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NamedDecl.html">NamedDecl</a>&gt;</td><td class="name" onclick="toggle('hasName0')"><a name="hasName0Anchor">hasName</a></td><td>std::string Name</td></tr> <tr><td colspan="4" class="doc" id="hasName0"><pre>Matches NamedDecl nodes that have the specified name. Supports specifying enclosing namespaces or classes by prefixing the name with '&lt;enclosing&gt;::'. Does not match typedefs of an underlying type with the given name. Example matches X (Name == "X") class X; Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") namespace a { namespace b { class X; } } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NamedDecl.html">NamedDecl</a>&gt;</td><td class="name" onclick="toggle('matchesName0')"><a name="matchesName0Anchor">matchesName</a></td><td>std::string RegExp</td></tr> <tr><td colspan="4" class="doc" id="matchesName0"><pre>Matches NamedDecl nodes whose fully qualified names contain a substring matched by the given RegExp. Supports specifying enclosing namespaces or classes by prefixing the name with '&lt;enclosing&gt;::'. Does not match typedefs of an underlying type with the given name. Example matches X (regexp == "::X") class X; Example matches X (regexp is one of "::X", "^foo::.*X", among others) namespace foo { namespace bar { class X; } } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('asString0')"><a name="asString0Anchor">asString</a></td><td>std::string Name</td></tr> <tr><td colspan="4" class="doc" id="asString0"><pre>Matches if the matched type is represented by the given string. Given class Y { public: void x(); }; void z() { Y* y; y-&gt;x(); } callExpr(on(hasType(asString("class Y *")))) matches y-&gt;x() </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('equalsBoundNode3')"><a name="equalsBoundNode3Anchor">equalsBoundNode</a></td><td>std::string ID</td></tr> <tr><td colspan="4" class="doc" id="equalsBoundNode3"><pre>Matches if a node equals a previously bound node. Matches a node if it equals the node previously bound to ID. Given class X { int a; int b; }; recordDecl( has(fieldDecl(hasName("a"), hasType(type().bind("t")))), has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) matches the class X, as a and b have the same type. Note that when multiple matches are involved via forEach* matchers, equalsBoundNodes acts as a filter. For example: compoundStmt( forEachDescendant(varDecl().bind("d")), forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) will trigger a match for each combination of variable declaration and reference to that variable declaration within a compound statement. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('hasLocalQualifiers0')"><a name="hasLocalQualifiers0Anchor">hasLocalQualifiers</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="hasLocalQualifiers0"><pre>Matches QualType nodes that have local CV-qualifiers attached to the node, not hidden within a typedef. Given typedef const int const_int; const_int i; int *const j; int *volatile k; int m; varDecl(hasType(hasLocalQualifiers())) matches only j and k. i is const-qualified but the qualifier is not local. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('isConstQualified0')"><a name="isConstQualified0Anchor">isConstQualified</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isConstQualified0"><pre>Matches QualType nodes that are const-qualified, i.e., that include "top-level" const. Given void a(int); void b(int const); void c(const int); void d(const int*); void e(int const) {}; functionDecl(hasAnyParameter(hasType(isConstQualified()))) matches "void b(int const)", "void c(const int)" and "void e(int const) {}". It does not match d as there is no top-level const on the parameter type "const int *". </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('isInteger0')"><a name="isInteger0Anchor">isInteger</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isInteger0"><pre>Matches QualType nodes that are of integer type. Given void a(int); void b(long); void c(double); functionDecl(hasAnyParameter(hasType(isInteger()))) matches "a(int)", "b(long)", but not "c(double)". </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('equalsBoundNode0')"><a name="equalsBoundNode0Anchor">equalsBoundNode</a></td><td>std::string ID</td></tr> <tr><td colspan="4" class="doc" id="equalsBoundNode0"><pre>Matches if a node equals a previously bound node. Matches a node if it equals the node previously bound to ID. Given class X { int a; int b; }; recordDecl( has(fieldDecl(hasName("a"), hasType(type().bind("t")))), has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) matches the class X, as a and b have the same type. Note that when multiple matches are involved via forEach* matchers, equalsBoundNodes acts as a filter. For example: compoundStmt( forEachDescendant(varDecl().bind("d")), forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) will trigger a match for each combination of variable declaration and reference to that variable declaration within a compound statement. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('isExpansionInFileMatching1')"><a name="isExpansionInFileMatching1Anchor">isExpansionInFileMatching</a></td><td>std::string RegExp</td></tr> <tr><td colspan="4" class="doc" id="isExpansionInFileMatching1"><pre>Matches AST nodes that were expanded within files whose name is partially matching a given regex. Example matches Y but not X (matcher = recordDecl(isExpansionInFileMatching("AST.*")) #include "ASTMatcher.h" class X {}; ASTMatcher.h: class Y {}; Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('isExpansionInMainFile1')"><a name="isExpansionInMainFile1Anchor">isExpansionInMainFile</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isExpansionInMainFile1"><pre>Matches AST nodes that were expanded within the main-file. Example matches X but not Y (matcher = recordDecl(isExpansionInMainFile()) #include &lt;Y.h&gt; class X {}; Y.h: class Y {}; Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('isExpansionInSystemHeader1')"><a name="isExpansionInSystemHeader1Anchor">isExpansionInSystemHeader</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isExpansionInSystemHeader1"><pre>Matches AST nodes that were expanded within system-header-files. Example matches Y but not X (matcher = recordDecl(isExpansionInSystemHeader()) #include &lt;SystemHeader.h&gt; class X {}; SystemHeader.h: class Y {}; Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagDecl.html">TagDecl</a>&gt;</td><td class="name" onclick="toggle('isDefinition0')"><a name="isDefinition0Anchor">isDefinition</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isDefinition0"><pre>Matches if a declaration has a body attached. Example matches A, va, fa class A {}; class B; Doesn't match, as it has no body. int va; extern int vb; Doesn't match, as it doesn't define the variable. void fa() {} void fb(); Doesn't match, as it has no body. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagDecl.html">TagDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('equalsIntegralValue0')"><a name="equalsIntegralValue0Anchor">equalsIntegralValue</a></td><td>std::string Value</td></tr> <tr><td colspan="4" class="doc" id="equalsIntegralValue0"><pre>Matches a TemplateArgument of integral type with a given value. Note that 'Value' is a string as the template argument's value is an arbitrary precision integer. 'Value' must be euqal to the canonical representation of that integral value in base 10. Given template&lt;int T&gt; struct A {}; C&lt;42&gt; c; classTemplateSpecializationDecl( hasAnyTemplateArgument(equalsIntegralValue("42"))) matches the implicit instantiation of C in C&lt;42&gt;. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('isIntegral0')"><a name="isIntegral0Anchor">isIntegral</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isIntegral0"><pre>Matches a TemplateArgument that is an integral value. Given template&lt;int T&gt; struct A {}; C&lt;42&gt; c; classTemplateSpecializationDecl( hasAnyTemplateArgument(isIntegral())) matches the implicit instantiation of C in C&lt;42&gt; with isIntegral() matching 42. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;</td><td class="name" onclick="toggle('templateArgumentCountIs1')"><a name="templateArgumentCountIs1Anchor">templateArgumentCountIs</a></td><td>unsigned N</td></tr> <tr><td colspan="4" class="doc" id="templateArgumentCountIs1"><pre>Matches if the number of template arguments equals N. Given template&lt;typename T&gt; struct C {}; C&lt;int&gt; c; classTemplateSpecializationDecl(templateArgumentCountIs(1)) matches C&lt;int&gt;. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td><td class="name" onclick="toggle('isExpansionInFileMatching2')"><a name="isExpansionInFileMatching2Anchor">isExpansionInFileMatching</a></td><td>std::string RegExp</td></tr> <tr><td colspan="4" class="doc" id="isExpansionInFileMatching2"><pre>Matches AST nodes that were expanded within files whose name is partially matching a given regex. Example matches Y but not X (matcher = recordDecl(isExpansionInFileMatching("AST.*")) #include "ASTMatcher.h" class X {}; ASTMatcher.h: class Y {}; Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td><td class="name" onclick="toggle('isExpansionInMainFile2')"><a name="isExpansionInMainFile2Anchor">isExpansionInMainFile</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isExpansionInMainFile2"><pre>Matches AST nodes that were expanded within the main-file. Example matches X but not Y (matcher = recordDecl(isExpansionInMainFile()) #include &lt;Y.h&gt; class X {}; Y.h: class Y {}; Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td><td class="name" onclick="toggle('isExpansionInSystemHeader2')"><a name="isExpansionInSystemHeader2Anchor">isExpansionInSystemHeader</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isExpansionInSystemHeader2"><pre>Matches AST nodes that were expanded within system-header-files. Example matches Y but not X (matcher = recordDecl(isExpansionInSystemHeader()) #include &lt;SystemHeader.h&gt; class X {}; SystemHeader.h: class Y {}; Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('equalsBoundNode2')"><a name="equalsBoundNode2Anchor">equalsBoundNode</a></td><td>std::string ID</td></tr> <tr><td colspan="4" class="doc" id="equalsBoundNode2"><pre>Matches if a node equals a previously bound node. Matches a node if it equals the node previously bound to ID. Given class X { int a; int b; }; recordDecl( has(fieldDecl(hasName("a"), hasType(type().bind("t")))), has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) matches the class X, as a and b have the same type. Note that when multiple matches are involved via forEach* matchers, equalsBoundNodes acts as a filter. For example: compoundStmt( forEachDescendant(varDecl().bind("d")), forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) will trigger a match for each combination of variable declaration and reference to that variable declaration within a compound statement. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td><td class="name" onclick="toggle('voidType0')"><a name="voidType0Anchor">voidType</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="voidType0"><pre>Matches type void. Given struct S { void func(); }; functionDecl(returns(voidType())) matches "void func();" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnaryExprOrTypeTraitExpr.html">UnaryExprOrTypeTraitExpr</a>&gt;</td><td class="name" onclick="toggle('ofKind0')"><a name="ofKind0Anchor">ofKind</a></td><td>UnaryExprOrTypeTrait Kind</td></tr> <tr><td colspan="4" class="doc" id="ofKind0"><pre>Matches unary expressions of a certain kind. Given int x; int s = sizeof(x) + alignof(x) unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) matches sizeof(x) </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnaryOperator.html">UnaryOperator</a>&gt;</td><td class="name" onclick="toggle('hasOperatorName1')"><a name="hasOperatorName1Anchor">hasOperatorName</a></td><td>std::string Name</td></tr> <tr><td colspan="4" class="doc" id="hasOperatorName1"><pre>Matches the operator Name of operator expressions (binary or unary). Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) !(a || b) </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;</td><td class="name" onclick="toggle('hasGlobalStorage0')"><a name="hasGlobalStorage0Anchor">hasGlobalStorage</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="hasGlobalStorage0"><pre>Matches a variable declaration that does not have local storage. Example matches y and z (matcher = varDecl(hasGlobalStorage()) void f() { int x; static int y; } int z; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;</td><td class="name" onclick="toggle('hasLocalStorage0')"><a name="hasLocalStorage0Anchor">hasLocalStorage</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="hasLocalStorage0"><pre>Matches a variable declaration that has function scope and is a non-static local variable. Example matches x (matcher = varDecl(hasLocalStorage()) void f() { int x; static int y; } int z; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;</td><td class="name" onclick="toggle('isDefinition1')"><a name="isDefinition1Anchor">isDefinition</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isDefinition1"><pre>Matches if a declaration has a body attached. Example matches A, va, fa class A {}; class B; Doesn't match, as it has no body. int va; extern int vb; Doesn't match, as it doesn't define the variable. void fa() {} void fb(); Doesn't match, as it has no body. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagDecl.html">TagDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;</td><td class="name" onclick="toggle('isExplicitTemplateSpecialization1')"><a name="isExplicitTemplateSpecialization1Anchor">isExplicitTemplateSpecialization</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isExplicitTemplateSpecialization1"><pre>Matches explicit template specializations of function, class, or static member variable template instantiations. Given template&lt;typename T&gt; void A(T t) { } template&lt;&gt; void A(int N) { } functionDecl(isExplicitTemplateSpecialization()) matches the specialization A&lt;int&gt;(). Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;</td><td class="name" onclick="toggle('isTemplateInstantiation1')"><a name="isTemplateInstantiation1Anchor">isTemplateInstantiation</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isTemplateInstantiation1"><pre>Matches template instantiations of function, class, or static member variable template instantiations. Given template &lt;typename T&gt; class X {}; class A {}; X&lt;A&gt; x; or template &lt;typename T&gt; class X {}; class A {}; template class X&lt;A&gt;; recordDecl(hasName("::X"), isTemplateInstantiation()) matches the template instantiation of X&lt;A&gt;. But given template &lt;typename T&gt; class X {}; class A {}; template &lt;&gt; class X&lt;A&gt; {}; X&lt;A&gt; x; recordDecl(hasName("::X"), isTemplateInstantiation()) does not match, as X&lt;A&gt; is an explicit template specialization. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt;internal::Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;&gt;</td><td class="name" onclick="toggle('isInstantiated0')"><a name="isInstantiated0Anchor">isInstantiated</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isInstantiated0"><pre>Matches declarations that are template instantiations or are inside template instantiations. Given template&lt;typename T&gt; void A(T t) { T i; } A(0); A(0U); functionDecl(isInstantiated()) matches 'A(int) {...};' and 'A(unsigned) {...}'. </pre></td></tr> <tr><td>Matcher&lt;internal::Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;&gt;</td><td class="name" onclick="toggle('isInTemplateInstantiation0')"><a name="isInTemplateInstantiation0Anchor">isInTemplateInstantiation</a></td><td></td></tr> <tr><td colspan="4" class="doc" id="isInTemplateInstantiation0"><pre>Matches statements inside of a template instantiation. Given int j; template&lt;typename T&gt; void A(T t) { T i; j += 42;} A(0); A(0U); declStmt(isInTemplateInstantiation()) matches 'int i;' and 'unsigned i'. unless(stmt(isInTemplateInstantiation())) will NOT match j += 42; as it's shared between the template definition and instantiation. </pre></td></tr> <!--END_NARROWING_MATCHERS --> </table> <!-- ======================================================================= --> <h2 id="traversal-matchers">AST Traversal Matchers</h2> <!-- ======================================================================= --> <p>Traversal matchers specify the relationship to other nodes that are reachable from the current node.</p> <p>Note that there are special traversal matchers (has, hasDescendant, forEach and forEachDescendant) which work on all nodes and allow users to write more generic match expressions.</p> <table> <tr style="text-align:left"><th>Return type</th><th>Name</th><th>Parameters</th></tr> <!-- START_TRAVERSAL_MATCHERS --> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('eachOf0')"><a name="eachOf0Anchor">eachOf</a></td><td>Matcher&lt;*&gt;, ..., Matcher&lt;*&gt;</td></tr> <tr><td colspan="4" class="doc" id="eachOf0"><pre>Matches if any of the given matchers matches. Unlike anyOf, eachOf will generate a match result for each matching submatcher. For example, in: class A { int a; int b; }; The matcher: recordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), has(fieldDecl(hasName("b")).bind("v")))) will generate two results binding "v", the first of which binds the field declaration of a, the second the field declaration of b. Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('forEachDescendant0')"><a name="forEachDescendant0Anchor">forEachDescendant</a></td><td>Matcher&lt;*&gt;</td></tr> <tr><td colspan="4" class="doc" id="forEachDescendant0"><pre>Matches AST nodes that have descendant AST nodes that match the provided matcher. Example matches X, A, B, C (matcher = recordDecl(forEachDescendant(recordDecl(hasName("X"))))) class X {}; Matches X, because X::X is a class of name X inside X. class A { class X {}; }; class B { class C { class X {}; }; }; DescendantT must be an AST base type. As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for each result that matches instead of only on the first one. Note: Recursively combined ForEachDescendant can cause many matches: recordDecl(forEachDescendant(recordDecl(forEachDescendant(recordDecl())))) will match 10 times (plus injected class name matches) on: class A { class B { class C { class D { class E {}; }; }; }; }; Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('forEach0')"><a name="forEach0Anchor">forEach</a></td><td>Matcher&lt;*&gt;</td></tr> <tr><td colspan="4" class="doc" id="forEach0"><pre>Matches AST nodes that have child AST nodes that match the provided matcher. Example matches X, Y (matcher = recordDecl(forEach(recordDecl(hasName("X"))) class X {}; Matches X, because X::X is a class of name X inside X. class Y { class X {}; }; class Z { class Y { class X {}; }; }; Does not match Z. ChildT must be an AST base type. As opposed to 'has', 'forEach' will cause a match for each result that matches instead of only on the first one. Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('hasAncestor0')"><a name="hasAncestor0Anchor">hasAncestor</a></td><td>Matcher&lt;*&gt;</td></tr> <tr><td colspan="4" class="doc" id="hasAncestor0"><pre>Matches AST nodes that have an ancestor that matches the provided matcher. Given void f() { if (true) { int x = 42; } } void g() { for (;;) { int x = 43; } } expr(integerLiteral(hasAncestor(ifStmt()))) matches 42, but not 43. Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('hasDescendant0')"><a name="hasDescendant0Anchor">hasDescendant</a></td><td>Matcher&lt;*&gt;</td></tr> <tr><td colspan="4" class="doc" id="hasDescendant0"><pre>Matches AST nodes that have descendant AST nodes that match the provided matcher. Example matches X, Y, Z (matcher = recordDecl(hasDescendant(recordDecl(hasName("X"))))) class X {}; Matches X, because X::X is a class of name X inside X. class Y { class X {}; }; class Z { class Y { class X {}; }; }; DescendantT must be an AST base type. Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('has0')"><a name="has0Anchor">has</a></td><td>Matcher&lt;*&gt;</td></tr> <tr><td colspan="4" class="doc" id="has0"><pre>Matches AST nodes that have child AST nodes that match the provided matcher. Example matches X, Y (matcher = recordDecl(has(recordDecl(hasName("X"))) class X {}; Matches X, because X::X is a class of name X inside X. class Y { class X {}; }; class Z { class Y { class X {}; }; }; Does not match Z. ChildT must be an AST base type. Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt;*&gt;</td><td class="name" onclick="toggle('hasParent0')"><a name="hasParent0Anchor">hasParent</a></td><td>Matcher&lt;*&gt;</td></tr> <tr><td colspan="4" class="doc" id="hasParent0"><pre>Matches AST nodes that have a parent that matches the provided matcher. Given void f() { for (;;) { int x = 42; if (true) { int x = 43; } } } compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }". Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArraySubscriptExpr.html">ArraySubscriptExpr</a>&gt;</td><td class="name" onclick="toggle('hasBase0')"><a name="hasBase0Anchor">hasBase</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasBase0"><pre>Matches the base expression of an array subscript expression. Given int i[5]; void f() { i[1] = 42; } arraySubscriptExpression(hasBase(implicitCastExpr( hasSourceExpression(declRefExpr())))) matches i[1] with the declRefExpr() matching i </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArraySubscriptExpr.html">ArraySubscriptExpr</a>&gt;</td><td class="name" onclick="toggle('hasIndex0')"><a name="hasIndex0Anchor">hasIndex</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasIndex0"><pre>Matches the index expression of an array subscript expression. Given int i[5]; void f() { i[1] = 42; } arraySubscriptExpression(hasIndex(integerLiteral())) matches i[1] with the integerLiteral() matching 1 </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArrayTypeLoc.html">ArrayTypeLoc</a>&gt;</td><td class="name" onclick="toggle('hasElementTypeLoc0')"><a name="hasElementTypeLoc0Anchor">hasElementTypeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="hasElementTypeLoc0"><pre>Matches arrays and C99 complex types that have a specific element type. Given struct A {}; A a[7]; int b[7]; arrayType(hasElementType(builtinType())) matches "int b[7]" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArrayType.html">ArrayType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ComplexType.html">ComplexType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArrayType.html">ArrayType</a>&gt;</td><td class="name" onclick="toggle('hasElementType0')"><a name="hasElementType0Anchor">hasElementType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="hasElementType0"><pre>Matches arrays and C99 complex types that have a specific element type. Given struct A {}; A a[7]; int b[7]; arrayType(hasElementType(builtinType())) matches "int b[7]" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArrayType.html">ArrayType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ComplexType.html">ComplexType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1AtomicTypeLoc.html">AtomicTypeLoc</a>&gt;</td><td class="name" onclick="toggle('hasValueTypeLoc0')"><a name="hasValueTypeLoc0Anchor">hasValueTypeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="hasValueTypeLoc0"><pre>Matches atomic types with a specific value type. Given _Atomic(int) i; _Atomic(float) f; atomicType(hasValueType(isInteger())) matches "_Atomic(int) i" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1AtomicType.html">AtomicType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1AtomicType.html">AtomicType</a>&gt;</td><td class="name" onclick="toggle('hasValueType0')"><a name="hasValueType0Anchor">hasValueType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="hasValueType0"><pre>Matches atomic types with a specific value type. Given _Atomic(int) i; _Atomic(float) f; atomicType(hasValueType(isInteger())) matches "_Atomic(int) i" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1AtomicType.html">AtomicType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1AutoType.html">AutoType</a>&gt;</td><td class="name" onclick="toggle('hasDeducedType0')"><a name="hasDeducedType0Anchor">hasDeducedType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="hasDeducedType0"><pre>Matches AutoType nodes where the deduced type is a specific type. Note: There is no TypeLoc for the deduced type and thus no getDeducedLoc() matcher. Given auto a = 1; auto b = 2.0; autoType(hasDeducedType(isInteger())) matches "auto a" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1AutoType.html">AutoType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BinaryOperator.html">BinaryOperator</a>&gt;</td><td class="name" onclick="toggle('hasEitherOperand0')"><a name="hasEitherOperand0Anchor">hasEitherOperand</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasEitherOperand0"><pre>Matches if either the left hand side or the right hand side of a binary operator matches. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BinaryOperator.html">BinaryOperator</a>&gt;</td><td class="name" onclick="toggle('hasLHS0')"><a name="hasLHS0Anchor">hasLHS</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasLHS0"><pre>Matches the left hand side of binary operator expressions. Example matches a (matcher = binaryOperator(hasLHS())) a || b </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BinaryOperator.html">BinaryOperator</a>&gt;</td><td class="name" onclick="toggle('hasRHS0')"><a name="hasRHS0Anchor">hasRHS</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasRHS0"><pre>Matches the right hand side of binary operator expressions. Example matches b (matcher = binaryOperator(hasRHS())) a || b </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerTypeLoc.html">BlockPointerTypeLoc</a>&gt;</td><td class="name" onclick="toggle('pointeeLoc0')"><a name="pointeeLoc0Anchor">pointeeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="pointeeLoc0"><pre>Narrows PointerType (and similar) matchers to those where the pointee matches a given matcher. Given int *a; int const *b; float const *f; pointerType(pointee(isConstQualified(), isInteger())) matches "int const *b" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html">BlockPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerType.html">MemberPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerType.html">PointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceType.html">ReferenceType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html">BlockPointerType</a>&gt;</td><td class="name" onclick="toggle('pointee0')"><a name="pointee0Anchor">pointee</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="pointee0"><pre>Narrows PointerType (and similar) matchers to those where the pointee matches a given matcher. Given int *a; int const *b; float const *f; pointerType(pointee(isConstQualified(), isInteger())) matches "int const *b" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html">BlockPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerType.html">MemberPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerType.html">PointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceType.html">ReferenceType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;</td><td class="name" onclick="toggle('hasAnyArgument1')"><a name="hasAnyArgument1Anchor">hasAnyArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasAnyArgument1"><pre>Matches any argument of a call expression or a constructor call expression. Given void x(int, int, int) { int y; x(1, y, 42); } callExpr(hasAnyArgument(declRefExpr())) matches x(1, y, 42) with hasAnyArgument(...) matching y FIXME: Currently this will ignore parentheses and implicit casts on the argument before applying the inner matcher. We'll want to remove this to allow for greater control by the user once ignoreImplicit() has been implemented. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;</td><td class="name" onclick="toggle('hasArgument1')"><a name="hasArgument1Anchor">hasArgument</a></td><td>unsigned N, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasArgument1"><pre>Matches the n'th argument of a call expression or a constructor call expression. Example matches y in x(y) (matcher = callExpr(hasArgument(0, declRefExpr()))) void x(int) { int y; x(y); } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration12')"><a name="hasDeclaration12Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration12"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructorDecl.html">CXXConstructorDecl</a>&gt;</td><td class="name" onclick="toggle('forEachConstructorInitializer0')"><a name="forEachConstructorInitializer0Anchor">forEachConstructorInitializer</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html">CXXCtorInitializer</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="forEachConstructorInitializer0"><pre>Matches each constructor initializer in a constructor definition. Given class A { A() : i(42), j(42) {} int i; int j; }; constructorDecl(forEachConstructorInitializer(forField(decl().bind("x")))) will trigger two matches, binding for 'i' and 'j' respectively. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructorDecl.html">CXXConstructorDecl</a>&gt;</td><td class="name" onclick="toggle('hasAnyConstructorInitializer0')"><a name="hasAnyConstructorInitializer0Anchor">hasAnyConstructorInitializer</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html">CXXCtorInitializer</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasAnyConstructorInitializer0"><pre>Matches a constructor initializer. Given struct Foo { Foo() : foo_(1) { } int foo_; }; recordDecl(has(constructorDecl(hasAnyConstructorInitializer(anything())))) record matches Foo, hasAnyConstructorInitializer matches foo_(1) </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html">CXXCtorInitializer</a>&gt;</td><td class="name" onclick="toggle('forField0')"><a name="forField0Anchor">forField</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FieldDecl.html">FieldDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="forField0"><pre>Matches the field declaration of a constructor initializer. Given struct Foo { Foo() : foo_(1) { } int foo_; }; recordDecl(has(constructorDecl(hasAnyConstructorInitializer( forField(hasName("foo_")))))) matches Foo with forField matching foo_ </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXCtorInitializer.html">CXXCtorInitializer</a>&gt;</td><td class="name" onclick="toggle('withInitializer0')"><a name="withInitializer0Anchor">withInitializer</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="withInitializer0"><pre>Matches the initializer expression of a constructor initializer. Given struct Foo { Foo() : foo_(1) { } int foo_; }; recordDecl(has(constructorDecl(hasAnyConstructorInitializer( withInitializer(integerLiteral(equals(1))))))) matches Foo with withInitializer matching (1) </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXForRangeStmt.html">CXXForRangeStmt</a>&gt;</td><td class="name" onclick="toggle('hasBody3')"><a name="hasBody3Anchor">hasBody</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasBody3"><pre>Matches a 'for', 'while', or 'do while' statement that has a given body. Given for (;;) {} hasBody(compoundStmt()) matches 'for (;;) {}' with compoundStmt() matching '{}' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXForRangeStmt.html">CXXForRangeStmt</a>&gt;</td><td class="name" onclick="toggle('hasLoopVariable0')"><a name="hasLoopVariable0Anchor">hasLoopVariable</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasLoopVariable0"><pre>Matches the initialization statement of a for loop. Example: forStmt(hasLoopVariable(anything())) matches 'int x' in for (int x : a) { } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXForRangeStmt.html">CXXForRangeStmt</a>&gt;</td><td class="name" onclick="toggle('hasRangeInit0')"><a name="hasRangeInit0Anchor">hasRangeInit</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasRangeInit0"><pre>Matches the range initialization statement of a for loop. Example: forStmt(hasRangeInit(anything())) matches 'a' in for (int x : a) { } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMemberCallExpr.html">CXXMemberCallExpr</a>&gt;</td><td class="name" onclick="toggle('onImplicitObjectArgument0')"><a name="onImplicitObjectArgument0Anchor">onImplicitObjectArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="onImplicitObjectArgument0"><pre></pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMemberCallExpr.html">CXXMemberCallExpr</a>&gt;</td><td class="name" onclick="toggle('on0')"><a name="on0Anchor">on</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="on0"><pre>Matches on the implicit object argument of a member call expression. Example matches y.x() (matcher = callExpr(on(hasType(recordDecl(hasName("Y")))))) class Y { public: void x(); }; void z() { Y y; y.x(); }", FIXME: Overload to allow directly matching types? </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMemberCallExpr.html">CXXMemberCallExpr</a>&gt;</td><td class="name" onclick="toggle('thisPointerType1')"><a name="thisPointerType1Anchor">thisPointerType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="thisPointerType1"><pre>Overloaded to match the type's declaration. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMemberCallExpr.html">CXXMemberCallExpr</a>&gt;</td><td class="name" onclick="toggle('thisPointerType0')"><a name="thisPointerType0Anchor">thisPointerType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="thisPointerType0"><pre>Matches if the expression's type either matches the specified matcher, or is a pointer to a type that matches the InnerMatcher. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt;</td><td class="name" onclick="toggle('ofClass0')"><a name="ofClass0Anchor">ofClass</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="ofClass0"><pre>Matches the class declaration that the given method declaration belongs to. FIXME: Generalize this for other kinds of declarations. FIXME: What other kind of declarations would we need to generalize this to? Example matches A() in the last line (matcher = constructExpr(hasDeclaration(methodDecl( ofClass(hasName("A")))))) class A { public: A(); }; A a = A(); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('hasMethod0')"><a name="hasMethod0Anchor">hasMethod</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXMethodDecl.html">CXXMethodDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasMethod0"><pre>Matches the first method of a class or struct that satisfies InnerMatcher. Given: class A { void func(); }; class B { void member(); }; recordDecl(hasMethod(hasName("func"))) matches the declaration of A but not B. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('isDerivedFrom0')"><a name="isDerivedFrom0Anchor">isDerivedFrom</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NamedDecl.html">NamedDecl</a>&gt; Base</td></tr> <tr><td colspan="4" class="doc" id="isDerivedFrom0"><pre>Matches C++ classes that are directly or indirectly derived from a class matching Base. Note that a class is not considered to be derived from itself. Example matches Y, Z, C (Base == hasName("X")) class X; class Y : public X {}; directly derived class Z : public Y {}; indirectly derived typedef X A; typedef A B; class C : public B {}; derived from a typedef of X In the following example, Bar matches isDerivedFrom(hasName("X")): class Foo; typedef Foo X; class Bar : public Foo {}; derived from a type that X is a typedef of </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXRecordDecl.html">CXXRecordDecl</a>&gt;</td><td class="name" onclick="toggle('isSameOrDerivedFrom0')"><a name="isSameOrDerivedFrom0Anchor">isSameOrDerivedFrom</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NamedDecl.html">NamedDecl</a>&gt; Base</td></tr> <tr><td colspan="4" class="doc" id="isSameOrDerivedFrom0"><pre>Similar to isDerivedFrom(), but also matches classes that directly match Base. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;</td><td class="name" onclick="toggle('callee1')"><a name="callee1Anchor">callee</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="callee1"><pre>Matches if the call expression's callee's declaration matches the given matcher. Example matches y.x() (matcher = callExpr(callee(methodDecl(hasName("x"))))) class Y { public: void x(); }; void z() { Y y; y.x(); } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;</td><td class="name" onclick="toggle('callee0')"><a name="callee0Anchor">callee</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="callee0"><pre>Matches if the call expression's callee expression matches. Given class Y { void x() { this-&gt;x(); x(); Y y; y.x(); } }; void f() { f(); } callExpr(callee(expr())) matches this-&gt;x(), x(), y.x(), f() with callee(...) matching this-&gt;x, x, y.x, f respectively Note: Callee cannot take the more general internal::Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; because this introduces ambiguous overloads with calls to Callee taking a internal::Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;, as the matcher hierarchy is purely implemented in terms of implicit casts. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;</td><td class="name" onclick="toggle('hasAnyArgument0')"><a name="hasAnyArgument0Anchor">hasAnyArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasAnyArgument0"><pre>Matches any argument of a call expression or a constructor call expression. Given void x(int, int, int) { int y; x(1, y, 42); } callExpr(hasAnyArgument(declRefExpr())) matches x(1, y, 42) with hasAnyArgument(...) matching y FIXME: Currently this will ignore parentheses and implicit casts on the argument before applying the inner matcher. We'll want to remove this to allow for greater control by the user once ignoreImplicit() has been implemented. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;</td><td class="name" onclick="toggle('hasArgument0')"><a name="hasArgument0Anchor">hasArgument</a></td><td>unsigned N, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasArgument0"><pre>Matches the n'th argument of a call expression or a constructor call expression. Example matches y in x(y) (matcher = callExpr(hasArgument(0, declRefExpr()))) void x(int) { int y; x(y); } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration13')"><a name="hasDeclaration13Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration13"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CaseStmt.html">CaseStmt</a>&gt;</td><td class="name" onclick="toggle('hasCaseConstant0')"><a name="hasCaseConstant0Anchor">hasCaseConstant</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasCaseConstant0"><pre>If the given case statement does not use the GNU case range extension, matches the constant given in the statement. Given switch (1) { case 1: case 1+1: case 3 ... 4: ; } caseStmt(hasCaseConstant(integerLiteral())) matches "case 1:" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CastExpr.html">CastExpr</a>&gt;</td><td class="name" onclick="toggle('hasSourceExpression0')"><a name="hasSourceExpression0Anchor">hasSourceExpression</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasSourceExpression0"><pre>Matches if the cast's source expression matches the given matcher. Example: matches "a string" (matcher = hasSourceExpression(constructExpr())) class URL { URL(string); }; URL url = "a string"; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ClassTemplateSpecializationDecl.html">ClassTemplateSpecializationDecl</a>&gt;</td><td class="name" onclick="toggle('hasAnyTemplateArgument0')"><a name="hasAnyTemplateArgument0Anchor">hasAnyTemplateArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasAnyTemplateArgument0"><pre>Matches classTemplateSpecializations that have at least one TemplateArgument matching the given InnerMatcher. Given template&lt;typename T&gt; class A {}; template&lt;&gt; class A&lt;double&gt; {}; A&lt;int&gt; a; classTemplateSpecializationDecl(hasAnyTemplateArgument( refersToType(asString("int")))) matches the specialization A&lt;int&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ClassTemplateSpecializationDecl.html">ClassTemplateSpecializationDecl</a>&gt;</td><td class="name" onclick="toggle('hasTemplateArgument0')"><a name="hasTemplateArgument0Anchor">hasTemplateArgument</a></td><td>unsigned N, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasTemplateArgument0"><pre>Matches classTemplateSpecializations where the n'th TemplateArgument matches the given InnerMatcher. Given template&lt;typename T, typename U&gt; class A {}; A&lt;bool, int&gt; b; A&lt;int, bool&gt; c; classTemplateSpecializationDecl(hasTemplateArgument( 1, refersToType(asString("int")))) matches the specialization A&lt;bool, int&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ComplexTypeLoc.html">ComplexTypeLoc</a>&gt;</td><td class="name" onclick="toggle('hasElementTypeLoc1')"><a name="hasElementTypeLoc1Anchor">hasElementTypeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="hasElementTypeLoc1"><pre>Matches arrays and C99 complex types that have a specific element type. Given struct A {}; A a[7]; int b[7]; arrayType(hasElementType(builtinType())) matches "int b[7]" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArrayType.html">ArrayType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ComplexType.html">ComplexType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ComplexType.html">ComplexType</a>&gt;</td><td class="name" onclick="toggle('hasElementType1')"><a name="hasElementType1Anchor">hasElementType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="hasElementType1"><pre>Matches arrays and C99 complex types that have a specific element type. Given struct A {}; A a[7]; int b[7]; arrayType(hasElementType(builtinType())) matches "int b[7]" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ArrayType.html">ArrayType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ComplexType.html">ComplexType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CompoundStmt.html">CompoundStmt</a>&gt;</td><td class="name" onclick="toggle('hasAnySubstatement0')"><a name="hasAnySubstatement0Anchor">hasAnySubstatement</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasAnySubstatement0"><pre>Matches compound statements where at least one substatement matches a given matcher. Given { {}; 1+2; } hasAnySubstatement(compoundStmt()) matches '{ {}; 1+2; }' with compoundStmt() matching '{}' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ConditionalOperator.html">ConditionalOperator</a>&gt;</td><td class="name" onclick="toggle('hasCondition4')"><a name="hasCondition4Anchor">hasCondition</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasCondition4"><pre>Matches the condition expression of an if statement, for loop, or conditional operator. Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) if (true) {} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ConditionalOperator.html">ConditionalOperator</a>&gt;</td><td class="name" onclick="toggle('hasFalseExpression0')"><a name="hasFalseExpression0Anchor">hasFalseExpression</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasFalseExpression0"><pre>Matches the false branch expression of a conditional operator. Example matches b condition ? a : b </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ConditionalOperator.html">ConditionalOperator</a>&gt;</td><td class="name" onclick="toggle('hasTrueExpression0')"><a name="hasTrueExpression0Anchor">hasTrueExpression</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasTrueExpression0"><pre>Matches the true branch expression of a conditional operator. Example matches a condition ? a : b </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration11')"><a name="hasDeclaration11Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration11"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;</td><td class="name" onclick="toggle('throughUsingDecl0')"><a name="throughUsingDecl0Anchor">throughUsingDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UsingShadowDecl.html">UsingShadowDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="throughUsingDecl0"><pre>Matches a DeclRefExpr that refers to a declaration through a specific using shadow declaration. FIXME: This currently only works for functions. Fix. Given namespace a { void f() {} } using a::f; void g() { f(); Matches this .. a::f(); .. but not this. } declRefExpr(throughUsingDeclaration(anything())) matches f() </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;</td><td class="name" onclick="toggle('to0')"><a name="to0Anchor">to</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="to0"><pre>Matches a DeclRefExpr that refers to a declaration that matches the specified matcher. Example matches x in if(x) (matcher = declRefExpr(to(varDecl(hasName("x"))))) bool x; if (x) {} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclStmt.html">DeclStmt</a>&gt;</td><td class="name" onclick="toggle('containsDeclaration0')"><a name="containsDeclaration0Anchor">containsDeclaration</a></td><td>unsigned N, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="containsDeclaration0"><pre>Matches the n'th declaration of a declaration statement. Note that this does not work for global declarations because the AST breaks up multiple-declaration DeclStmt's into multiple single-declaration DeclStmt's. Example: Given non-global declarations int a, b = 0; int c; int d = 2, e; declStmt(containsDeclaration( 0, varDecl(hasInitializer(anything())))) matches only 'int d = 2, e;', and declStmt(containsDeclaration(1, varDecl())) matches 'int a, b = 0' as well as 'int d = 2, e;' but 'int c;' is not matched. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclStmt.html">DeclStmt</a>&gt;</td><td class="name" onclick="toggle('hasSingleDecl0')"><a name="hasSingleDecl0Anchor">hasSingleDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasSingleDecl0"><pre>Matches the Decl of a DeclStmt which has a single declaration. Given int a, b; int c; declStmt(hasSingleDecl(anything())) matches 'int c;' but not 'int a, b;'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclaratorDecl.html">DeclaratorDecl</a>&gt;</td><td class="name" onclick="toggle('hasTypeLoc0')"><a name="hasTypeLoc0Anchor">hasTypeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; Inner</td></tr> <tr><td colspan="4" class="doc" id="hasTypeLoc0"><pre>Matches if the type location of the declarator decl's type matches the inner matcher. Given int x; declaratorDecl(hasTypeLoc(loc(asString("int")))) matches int x </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt;</td><td class="name" onclick="toggle('hasDeclContext0')"><a name="hasDeclContext0Anchor">hasDeclContext</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclContext0"><pre>Matches declarations whose declaration context, interpreted as a Decl, matches InnerMatcher. Given namespace N { namespace M { class D {}; } } recordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the declaration of class D. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DoStmt.html">DoStmt</a>&gt;</td><td class="name" onclick="toggle('hasBody0')"><a name="hasBody0Anchor">hasBody</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasBody0"><pre>Matches a 'for', 'while', or 'do while' statement that has a given body. Given for (;;) {} hasBody(compoundStmt()) matches 'for (;;) {}' with compoundStmt() matching '{}' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DoStmt.html">DoStmt</a>&gt;</td><td class="name" onclick="toggle('hasCondition3')"><a name="hasCondition3Anchor">hasCondition</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasCondition3"><pre>Matches the condition expression of an if statement, for loop, or conditional operator. Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) if (true) {} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ElaboratedType.html">ElaboratedType</a>&gt;</td><td class="name" onclick="toggle('hasQualifier0')"><a name="hasQualifier0Anchor">hasQualifier</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifier.html">NestedNameSpecifier</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasQualifier0"><pre>Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier, matches InnerMatcher if the qualifier exists. Given namespace N { namespace M { class D {}; } } N::M::D d; elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))) matches the type of the variable declaration of d. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ElaboratedType.html">ElaboratedType</a>&gt;</td><td class="name" onclick="toggle('namesType0')"><a name="namesType0Anchor">namesType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="namesType0"><pre>Matches ElaboratedTypes whose named type matches InnerMatcher. Given namespace N { namespace M { class D {}; } } N::M::D d; elaboratedType(namesType(recordType( hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable declaration of d. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration10')"><a name="hasDeclaration10Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration10"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ExplicitCastExpr.html">ExplicitCastExpr</a>&gt;</td><td class="name" onclick="toggle('hasDestinationType0')"><a name="hasDestinationType0Anchor">hasDestinationType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDestinationType0"><pre>Matches casts whose destination type matches a given matcher. (Note: Clang's AST refers to other conversions as "casts" too, and calls actual casts "explicit" casts.) </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;</td><td class="name" onclick="toggle('hasType2')"><a name="hasType2Anchor">hasType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasType2"><pre>Overloaded to match the declaration of the expression's or value declaration's type. In case of a value declaration (for example a variable declaration), this resolves one layer of indirection. For example, in the value declaration "X x;", recordDecl(hasName("X")) matches the declaration of X, while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration of x." Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) class X {}; void y(X &amp;x) { x; X z; } Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html">ValueDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;</td><td class="name" onclick="toggle('hasType0')"><a name="hasType0Anchor">hasType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasType0"><pre>Matches if the expression's or declaration's type matches a type matcher. Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) class X {}; void y(X &amp;x) { x; X z; } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;</td><td class="name" onclick="toggle('ignoringImpCasts0')"><a name="ignoringImpCasts0Anchor">ignoringImpCasts</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="ignoringImpCasts0"><pre>Matches expressions that match InnerMatcher after any implicit casts are stripped off. Parentheses and explicit casts are not discarded. Given int arr[5]; int a = 0; char b = 0; const int c = a; int *d = arr; long e = (long) 0l; The matchers varDecl(hasInitializer(ignoringImpCasts(integerLiteral()))) varDecl(hasInitializer(ignoringImpCasts(declRefExpr()))) would match the declarations for a, b, c, and d, but not e. While varDecl(hasInitializer(integerLiteral())) varDecl(hasInitializer(declRefExpr())) only match the declarations for b, c, and d. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;</td><td class="name" onclick="toggle('ignoringParenCasts0')"><a name="ignoringParenCasts0Anchor">ignoringParenCasts</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="ignoringParenCasts0"><pre>Matches expressions that match InnerMatcher after parentheses and casts are stripped off. Implicit and non-C Style casts are also discarded. Given int a = 0; char b = (0); void* c = reinterpret_cast&lt;char*&gt;(0); char d = char(0); The matcher varDecl(hasInitializer(ignoringParenCasts(integerLiteral()))) would match the declarations for a, b, c, and d. while varDecl(hasInitializer(integerLiteral())) only match the declaration for a. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;</td><td class="name" onclick="toggle('ignoringParenImpCasts0')"><a name="ignoringParenImpCasts0Anchor">ignoringParenImpCasts</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="ignoringParenImpCasts0"><pre>Matches expressions that match InnerMatcher after implicit casts and parentheses are stripped off. Explicit casts are not discarded. Given int arr[5]; int a = 0; char b = (0); const int c = a; int *d = (arr); long e = ((long) 0l); The matchers varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral()))) varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr()))) would match the declarations for a, b, c, and d, but not e. while varDecl(hasInitializer(integerLiteral())) varDecl(hasInitializer(declRefExpr())) would only match the declaration for a. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ForStmt.html">ForStmt</a>&gt;</td><td class="name" onclick="toggle('hasBody1')"><a name="hasBody1Anchor">hasBody</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasBody1"><pre>Matches a 'for', 'while', or 'do while' statement that has a given body. Given for (;;) {} hasBody(compoundStmt()) matches 'for (;;) {}' with compoundStmt() matching '{}' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ForStmt.html">ForStmt</a>&gt;</td><td class="name" onclick="toggle('hasCondition1')"><a name="hasCondition1Anchor">hasCondition</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasCondition1"><pre>Matches the condition expression of an if statement, for loop, or conditional operator. Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) if (true) {} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ForStmt.html">ForStmt</a>&gt;</td><td class="name" onclick="toggle('hasIncrement0')"><a name="hasIncrement0Anchor">hasIncrement</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasIncrement0"><pre>Matches the increment statement of a for loop. Example: forStmt(hasIncrement(unaryOperator(hasOperatorName("++")))) matches '++x' in for (x; x &lt; N; ++x) { } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ForStmt.html">ForStmt</a>&gt;</td><td class="name" onclick="toggle('hasLoopInit0')"><a name="hasLoopInit0Anchor">hasLoopInit</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasLoopInit0"><pre>Matches the initialization statement of a for loop. Example: forStmt(hasLoopInit(declStmt())) matches 'int x = 0' in for (int x = 0; x &lt; N; ++x) { } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('hasAnyParameter0')"><a name="hasAnyParameter0Anchor">hasAnyParameter</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ParmVarDecl.html">ParmVarDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasAnyParameter0"><pre>Matches any parameter of a function declaration. Does not match the 'this' parameter of a method. Given class X { void f(int x, int y, int z) {} }; methodDecl(hasAnyParameter(hasName("y"))) matches f(int x, int y, int z) {} with hasAnyParameter(...) matching int y </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('hasParameter0')"><a name="hasParameter0Anchor">hasParameter</a></td><td>unsigned N, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ParmVarDecl.html">ParmVarDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasParameter0"><pre>Matches the n'th parameter of a function declaration. Given class X { void f(int x) {} }; methodDecl(hasParameter(0, hasType(varDecl()))) matches f(int x) {} with hasParameter(...) matching int x </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1FunctionDecl.html">FunctionDecl</a>&gt;</td><td class="name" onclick="toggle('returns0')"><a name="returns0Anchor">returns</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="returns0"><pre>Matches the return type of a function declaration. Given: class X { int f() { return 1; } }; methodDecl(returns(asString("int"))) matches int f() { return 1; } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IfStmt.html">IfStmt</a>&gt;</td><td class="name" onclick="toggle('hasCondition0')"><a name="hasCondition0Anchor">hasCondition</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasCondition0"><pre>Matches the condition expression of an if statement, for loop, or conditional operator. Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) if (true) {} </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IfStmt.html">IfStmt</a>&gt;</td><td class="name" onclick="toggle('hasConditionVariableStatement0')"><a name="hasConditionVariableStatement0Anchor">hasConditionVariableStatement</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclStmt.html">DeclStmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasConditionVariableStatement0"><pre>Matches the condition variable statement in an if statement. Given if (A* a = GetAPointer()) {} hasConditionVariableStatement(...) matches 'A* a = GetAPointer()'. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IfStmt.html">IfStmt</a>&gt;</td><td class="name" onclick="toggle('hasElse0')"><a name="hasElse0Anchor">hasElse</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasElse0"><pre>Matches the else-statement of an if statement. Examples matches the if statement (matcher = ifStmt(hasElse(boolLiteral(equals(true))))) if (false) false; else true; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1IfStmt.html">IfStmt</a>&gt;</td><td class="name" onclick="toggle('hasThen0')"><a name="hasThen0Anchor">hasThen</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasThen0"><pre>Matches the then-statement of an if statement. Examples matches the if statement (matcher = ifStmt(hasThen(boolLiteral(equals(true))))) if (false) true; else false; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ImplicitCastExpr.html">ImplicitCastExpr</a>&gt;</td><td class="name" onclick="toggle('hasImplicitDestinationType0')"><a name="hasImplicitDestinationType0Anchor">hasImplicitDestinationType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasImplicitDestinationType0"><pre>Matches implicit casts whose destination type matches a given matcher. FIXME: Unit test this matcher </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration9')"><a name="hasDeclaration9Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration9"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration8')"><a name="hasDeclaration8Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration8"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration7')"><a name="hasDeclaration7Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration7"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;</td><td class="name" onclick="toggle('hasObjectExpression0')"><a name="hasObjectExpression0Anchor">hasObjectExpression</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasObjectExpression0"><pre>Matches a member expression where the object expression is matched by a given matcher. Given struct X { int m; }; void f(X x) { x.m; m; } memberExpr(hasObjectExpression(hasType(recordDecl(hasName("X"))))))) matches "x.m" and "m" with hasObjectExpression(...) matching "x" and the implicit object expression of "m" which has type X*. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;</td><td class="name" onclick="toggle('member0')"><a name="member0Anchor">member</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html">ValueDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="member0"><pre>Matches a member expression where the member is matched by a given matcher. Given struct { int first, second; } first, second; int i(second.first); int j(first.second); memberExpr(member(hasName("first"))) matches second.first but not first.second (because the member name there is "second"). </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerTypeLoc.html">MemberPointerTypeLoc</a>&gt;</td><td class="name" onclick="toggle('pointeeLoc1')"><a name="pointeeLoc1Anchor">pointeeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="pointeeLoc1"><pre>Narrows PointerType (and similar) matchers to those where the pointee matches a given matcher. Given int *a; int const *b; float const *f; pointerType(pointee(isConstQualified(), isInteger())) matches "int const *b" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html">BlockPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerType.html">MemberPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerType.html">PointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceType.html">ReferenceType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerType.html">MemberPointerType</a>&gt;</td><td class="name" onclick="toggle('pointee1')"><a name="pointee1Anchor">pointee</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="pointee1"><pre>Narrows PointerType (and similar) matchers to those where the pointee matches a given matcher. Given int *a; int const *b; float const *f; pointerType(pointee(isConstQualified(), isInteger())) matches "int const *b" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html">BlockPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerType.html">MemberPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerType.html">PointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceType.html">ReferenceType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifierLoc.html">NestedNameSpecifierLoc</a>&gt;</td><td class="name" onclick="toggle('hasPrefix1')"><a name="hasPrefix1Anchor">hasPrefix</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifierLoc.html">NestedNameSpecifierLoc</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasPrefix1"><pre>Matches on the prefix of a NestedNameSpecifierLoc. Given struct A { struct B { struct C {}; }; }; A::B::C c; nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A"))))) matches "A::" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifierLoc.html">NestedNameSpecifierLoc</a>&gt;</td><td class="name" onclick="toggle('specifiesTypeLoc0')"><a name="specifiesTypeLoc0Anchor">specifiesTypeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="specifiesTypeLoc0"><pre>Matches nested name specifier locs that specify a type matching the given TypeLoc. Given struct A { struct B { struct C {}; }; }; A::B::C c; nestedNameSpecifierLoc(specifiesTypeLoc(loc(type( hasDeclaration(recordDecl(hasName("A"))))))) matches "A::" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifier.html">NestedNameSpecifier</a>&gt;</td><td class="name" onclick="toggle('hasPrefix0')"><a name="hasPrefix0Anchor">hasPrefix</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifier.html">NestedNameSpecifier</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasPrefix0"><pre>Matches on the prefix of a NestedNameSpecifier. Given struct A { struct B { struct C {}; }; }; A::B::C c; nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and matches "A::" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifier.html">NestedNameSpecifier</a>&gt;</td><td class="name" onclick="toggle('specifiesNamespace0')"><a name="specifiesNamespace0Anchor">specifiesNamespace</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NamespaceDecl.html">NamespaceDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="specifiesNamespace0"><pre>Matches nested name specifiers that specify a namespace matching the given namespace matcher. Given namespace ns { struct A {}; } ns::A a; nestedNameSpecifier(specifiesNamespace(hasName("ns"))) matches "ns::" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifier.html">NestedNameSpecifier</a>&gt;</td><td class="name" onclick="toggle('specifiesType0')"><a name="specifiesType0Anchor">specifiesType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="specifiesType0"><pre>Matches nested name specifiers that specify a type matching the given QualType matcher without qualifiers. Given struct A { struct B { struct C {}; }; }; A::B::C c; nestedNameSpecifier(specifiesType(hasDeclaration(recordDecl(hasName("A"))))) matches "A::" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ParenType.html">ParenType</a>&gt;</td><td class="name" onclick="toggle('innerType0')"><a name="innerType0Anchor">innerType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="innerType0"><pre>Matches ParenType nodes where the inner type is a specific type. Given int (*ptr_to_array)[4]; int (*ptr_to_func)(int); varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches ptr_to_func but not ptr_to_array. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ParenType.html">ParenType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerTypeLoc.html">PointerTypeLoc</a>&gt;</td><td class="name" onclick="toggle('pointeeLoc2')"><a name="pointeeLoc2Anchor">pointeeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="pointeeLoc2"><pre>Narrows PointerType (and similar) matchers to those where the pointee matches a given matcher. Given int *a; int const *b; float const *f; pointerType(pointee(isConstQualified(), isInteger())) matches "int const *b" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html">BlockPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerType.html">MemberPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerType.html">PointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceType.html">ReferenceType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerType.html">PointerType</a>&gt;</td><td class="name" onclick="toggle('pointee2')"><a name="pointee2Anchor">pointee</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="pointee2"><pre>Narrows PointerType (and similar) matchers to those where the pointee matches a given matcher. Given int *a; int const *b; float const *f; pointerType(pointee(isConstQualified(), isInteger())) matches "int const *b" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html">BlockPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerType.html">MemberPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerType.html">PointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceType.html">ReferenceType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('hasCanonicalType0')"><a name="hasCanonicalType0Anchor">hasCanonicalType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasCanonicalType0"><pre>Matches QualTypes whose canonical type matches InnerMatcher. Given: typedef int &amp;int_ref; int a; int_ref b = a; varDecl(hasType(qualType(referenceType()))))) will not match the declaration of b but varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration6')"><a name="hasDeclaration6Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration6"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('pointsTo1')"><a name="pointsTo1Anchor">pointsTo</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="pointsTo1"><pre>Overloaded to match the pointee type's declaration. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('pointsTo0')"><a name="pointsTo0Anchor">pointsTo</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="pointsTo0"><pre>Matches if the matched type is a pointer type and the pointee type matches the specified matcher. Example matches y-&gt;x() (matcher = callExpr(on(hasType(pointsTo(recordDecl(hasName("Y"))))))) class Y { public: void x(); }; void z() { Y *y; y-&gt;x(); } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('references1')"><a name="references1Anchor">references</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="references1"><pre>Overloaded to match the referenced type's declaration. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;</td><td class="name" onclick="toggle('references0')"><a name="references0Anchor">references</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="references0"><pre>Matches if the matched type is a reference type and the referenced type matches the specified matcher. Example matches X &amp;x and const X &amp;y (matcher = varDecl(hasType(references(recordDecl(hasName("X")))))) class X { void a(X b) { X &amp;x = b; const X &amp;y = b; } }; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration5')"><a name="hasDeclaration5Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration5"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceTypeLoc.html">ReferenceTypeLoc</a>&gt;</td><td class="name" onclick="toggle('pointeeLoc3')"><a name="pointeeLoc3Anchor">pointeeLoc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="pointeeLoc3"><pre>Narrows PointerType (and similar) matchers to those where the pointee matches a given matcher. Given int *a; int const *b; float const *f; pointerType(pointee(isConstQualified(), isInteger())) matches "int const *b" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html">BlockPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerType.html">MemberPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerType.html">PointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceType.html">ReferenceType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceType.html">ReferenceType</a>&gt;</td><td class="name" onclick="toggle('pointee3')"><a name="pointee3Anchor">pointee</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Type.html">Type</a>&gt;</td></tr> <tr><td colspan="4" class="doc" id="pointee3"><pre>Narrows PointerType (and similar) matchers to those where the pointee matches a given matcher. Given int *a; int const *b; float const *f; pointerType(pointee(isConstQualified(), isInteger())) matches "int const *b" Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1BlockPointerType.html">BlockPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberPointerType.html">MemberPointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1PointerType.html">PointerType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ReferenceType.html">ReferenceType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('alignOfExpr0')"><a name="alignOfExpr0Anchor">alignOfExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnaryExprOrTypeTraitExpr.html">UnaryExprOrTypeTraitExpr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="alignOfExpr0"><pre>Same as unaryExprOrTypeTraitExpr, but only matching alignof. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt;</td><td class="name" onclick="toggle('sizeOfExpr0')"><a name="sizeOfExpr0Anchor">sizeOfExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnaryExprOrTypeTraitExpr.html">UnaryExprOrTypeTraitExpr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="sizeOfExpr0"><pre>Same as unaryExprOrTypeTraitExpr, but only matching sizeof. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1SwitchStmt.html">SwitchStmt</a>&gt;</td><td class="name" onclick="toggle('forEachSwitchCase0')"><a name="forEachSwitchCase0Anchor">forEachSwitchCase</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1SwitchCase.html">SwitchCase</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="forEachSwitchCase0"><pre>Matches each case or default statement belonging to the given switch statement. This matcher may produce multiple matches. Given switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } } switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s") matches four times, with "c" binding each of "case 1:", "case 2:", "case 3:" and "case 4:", and "s" respectively binding "switch (1)", "switch (1)", "switch (2)" and "switch (2)". </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration4')"><a name="hasDeclaration4Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration4"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('isExpr0')"><a name="isExpr0Anchor">isExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="isExpr0"><pre>Matches a sugar TemplateArgument that refers to a certain expression. Given template&lt;typename T&gt; struct A {}; struct B { B* next; }; A&lt;&amp;B::next&gt; a; templateSpecializationType(hasAnyTemplateArgument( isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next")))))))) matches the specialization A&lt;&amp;B::next&gt; with fieldDecl(...) matching B::next </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('refersToDeclaration0')"><a name="refersToDeclaration0Anchor">refersToDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="refersToDeclaration0"><pre>Matches a canonical TemplateArgument that refers to a certain declaration. Given template&lt;typename T&gt; struct A {}; struct B { B* next; }; A&lt;&amp;B::next&gt; a; classTemplateSpecializationDecl(hasAnyTemplateArgument( refersToDeclaration(fieldDecl(hasName("next")))) matches the specialization A&lt;&amp;B::next&gt; with fieldDecl(...) matching B::next </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('refersToIntegralType0')"><a name="refersToIntegralType0Anchor">refersToIntegralType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="refersToIntegralType0"><pre>Matches a TemplateArgument that referes to an integral type. Given template&lt;int T&gt; struct A {}; C&lt;42&gt; c; classTemplateSpecializationDecl( hasAnyTemplateArgument(refersToIntegralType(asString("int")))) matches the implicit instantiation of C in C&lt;42&gt;. </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt;</td><td class="name" onclick="toggle('refersToType0')"><a name="refersToType0Anchor">refersToType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="refersToType0"><pre>Matches a TemplateArgument that refers to a certain type. Given struct X {}; template&lt;typename T&gt; struct A {}; A&lt;X&gt; a; classTemplateSpecializationDecl(hasAnyTemplateArgument( refersToType(class(hasName("X"))))) matches the specialization A&lt;X&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;</td><td class="name" onclick="toggle('hasAnyTemplateArgument1')"><a name="hasAnyTemplateArgument1Anchor">hasAnyTemplateArgument</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasAnyTemplateArgument1"><pre>Matches classTemplateSpecializations that have at least one TemplateArgument matching the given InnerMatcher. Given template&lt;typename T&gt; class A {}; template&lt;&gt; class A&lt;double&gt; {}; A&lt;int&gt; a; classTemplateSpecializationDecl(hasAnyTemplateArgument( refersToType(asString("int")))) matches the specialization A&lt;int&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration3')"><a name="hasDeclaration3Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration3"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;</td><td class="name" onclick="toggle('hasTemplateArgument1')"><a name="hasTemplateArgument1Anchor">hasTemplateArgument</a></td><td>unsigned N, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateArgument.html">TemplateArgument</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasTemplateArgument1"><pre>Matches classTemplateSpecializations where the n'th TemplateArgument matches the given InnerMatcher. Given template&lt;typename T, typename U&gt; class A {}; A&lt;bool, int&gt; b; A&lt;int, bool&gt; c; classTemplateSpecializationDecl(hasTemplateArgument( 1, refersToType(asString("int")))) matches the specialization A&lt;bool, int&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration2')"><a name="hasDeclaration2Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration2"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt;T&gt;</td><td class="name" onclick="toggle('findAll0')"><a name="findAll0Anchor">findAll</a></td><td>Matcher&lt;T&gt; Matcher</td></tr> <tr><td colspan="4" class="doc" id="findAll0"><pre>Matches if the node or any descendant matches. Generates results for each match. For example, in: class A { class B {}; class C {}; }; The matcher: recordDecl(hasName("::A"), findAll(recordDecl(isDefinition()).bind("m"))) will generate results for A, B and C. Usable as: Any Matcher </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration1')"><a name="hasDeclaration1Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration1"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnaryExprOrTypeTraitExpr.html">UnaryExprOrTypeTraitExpr</a>&gt;</td><td class="name" onclick="toggle('hasArgumentOfType0')"><a name="hasArgumentOfType0Anchor">hasArgumentOfType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasArgumentOfType0"><pre>Matches unary expressions that have a specific type of argument. Given int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) matches sizeof(a) and alignof(c) </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnaryOperator.html">UnaryOperator</a>&gt;</td><td class="name" onclick="toggle('hasUnaryOperand0')"><a name="hasUnaryOperand0Anchor">hasUnaryOperand</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasUnaryOperand0"><pre>Matches if the operand of a unary operator matches. Example matches true (matcher = hasUnaryOperand(boolLiteral(equals(true)))) !true </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt;</td><td class="name" onclick="toggle('hasDeclaration0')"><a name="hasDeclaration0Anchor">hasDeclaration</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasDeclaration0"><pre>Matches a node if the declaration associated with that node matches the given matcher. The associated declaration is: - for type nodes, the declaration of the underlying type - for CallExpr, the declaration of the callee - for MemberExpr, the declaration of the referenced member - for CXXConstructExpr, the declaration of the constructor Also usable as Matcher&lt;T&gt; for any T supporting the getDecl() member function. e.g. various subtypes of clang::Type and various expressions. Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CallExpr.html">CallExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1CXXConstructExpr.html">CXXConstructExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1DeclRefExpr.html">DeclRefExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1EnumType.html">EnumType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1InjectedClassNameType.html">InjectedClassNameType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1LabelStmt.html">LabelStmt</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1MemberExpr.html">MemberExpr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1RecordType.html">RecordType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TagType.html">TagType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateSpecializationType.html">TemplateSpecializationType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TemplateTypeParmType.html">TemplateTypeParmType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypedefType.html">TypedefType</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UnresolvedUsingType.html">UnresolvedUsingType</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UsingDecl.html">UsingDecl</a>&gt;</td><td class="name" onclick="toggle('hasAnyUsingShadowDecl0')"><a name="hasAnyUsingShadowDecl0Anchor">hasAnyUsingShadowDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UsingShadowDecl.html">UsingShadowDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasAnyUsingShadowDecl0"><pre>Matches any using shadow declaration. Given namespace X { void b(); } using X::b; usingDecl(hasAnyUsingShadowDecl(hasName("b")))) matches using X::b </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1UsingShadowDecl.html">UsingShadowDecl</a>&gt;</td><td class="name" onclick="toggle('hasTargetDecl0')"><a name="hasTargetDecl0Anchor">hasTargetDecl</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NamedDecl.html">NamedDecl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasTargetDecl0"><pre>Matches a using shadow declaration where the target declaration is matched by the given matcher. Given namespace X { int a; void b(); } using X::a; using X::b; usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) matches using X::b but not using X::a </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html">ValueDecl</a>&gt;</td><td class="name" onclick="toggle('hasType3')"><a name="hasType3Anchor">hasType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Decl.html">Decl</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasType3"><pre>Overloaded to match the declaration of the expression's or value declaration's type. In case of a value declaration (for example a variable declaration), this resolves one layer of indirection. For example, in the value declaration "X x;", recordDecl(hasName("X")) matches the declaration of X, while varDecl(hasType(recordDecl(hasName("X")))) matches the declaration of x." Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) class X {}; void y(X &amp;x) { x; X z; } Usable as: Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt;, Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html">ValueDecl</a>&gt; </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1ValueDecl.html">ValueDecl</a>&gt;</td><td class="name" onclick="toggle('hasType1')"><a name="hasType1Anchor">hasType</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasType1"><pre>Matches if the expression's or declaration's type matches a type matcher. Example matches x (matcher = expr(hasType(recordDecl(hasName("X"))))) and z (matcher = varDecl(hasType(recordDecl(hasName("X"))))) class X {}; void y(X &amp;x) { x; X z; } </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VarDecl.html">VarDecl</a>&gt;</td><td class="name" onclick="toggle('hasInitializer0')"><a name="hasInitializer0Anchor">hasInitializer</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasInitializer0"><pre>Matches a variable declaration that has an initializer expression that matches the given matcher. Example matches x (matcher = varDecl(hasInitializer(callExpr()))) bool y() { return true; } bool x = y(); </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1VariableArrayType.html">VariableArrayType</a>&gt;</td><td class="name" onclick="toggle('hasSizeExpr0')"><a name="hasSizeExpr0Anchor">hasSizeExpr</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasSizeExpr0"><pre>Matches VariableArrayType nodes that have a specific size expression. Given void f(int b) { int a[b]; } variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( varDecl(hasName("b"))))))) matches "int a[b]" </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1WhileStmt.html">WhileStmt</a>&gt;</td><td class="name" onclick="toggle('hasBody2')"><a name="hasBody2Anchor">hasBody</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Stmt.html">Stmt</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasBody2"><pre>Matches a 'for', 'while', or 'do while' statement that has a given body. Given for (;;) {} hasBody(compoundStmt()) matches 'for (;;) {}' with compoundStmt() matching '{}' </pre></td></tr> <tr><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1WhileStmt.html">WhileStmt</a>&gt;</td><td class="name" onclick="toggle('hasCondition2')"><a name="hasCondition2Anchor">hasCondition</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1Expr.html">Expr</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="hasCondition2"><pre>Matches the condition expression of an if statement, for loop, or conditional operator. Example matches true (matcher = hasCondition(boolLiteral(equals(true)))) if (true) {} </pre></td></tr> <tr><td>Matcher&lt;internal::BindableMatcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifierLoc.html">NestedNameSpecifierLoc</a>&gt;&gt;</td><td class="name" onclick="toggle('loc1')"><a name="loc1Anchor">loc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1NestedNameSpecifier.html">NestedNameSpecifier</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="loc1"><pre>Matches NestedNameSpecifierLocs for which the given inner NestedNameSpecifier-matcher matches. </pre></td></tr> <tr><td>Matcher&lt;internal::BindableMatcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1TypeLoc.html">TypeLoc</a>&gt;&gt;</td><td class="name" onclick="toggle('loc0')"><a name="loc0Anchor">loc</a></td><td>Matcher&lt<a href="http://clang.llvm.org/doxygen/classclang_1_1QualType.html">QualType</a>&gt; InnerMatcher</td></tr> <tr><td colspan="4" class="doc" id="loc0"><pre>Matches TypeLocs for which the given inner QualType-matcher matches. </pre></td></tr> <!--END_TRAVERSAL_MATCHERS --> </table> </div> </body> </html>
0
repos/DirectXShaderCompiler/tools/clang
repos/DirectXShaderCompiler/tools/clang/docs/make.bat
@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^<target^>` where ^<target^> is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Clang.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Clang.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end
0
repos/DirectXShaderCompiler/tools/clang
repos/DirectXShaderCompiler/tools/clang/docs/CMakeLists.txt
if (DOXYGEN_FOUND) if (LLVM_ENABLE_DOXYGEN) set(abs_srcdir ${CMAKE_CURRENT_SOURCE_DIR}) set(abs_builddir ${CMAKE_CURRENT_BINARY_DIR}) if (HAVE_DOT) set(DOT ${LLVM_PATH_DOT}) endif() if (LLVM_DOXYGEN_EXTERNAL_SEARCH) set(enable_searchengine "YES") set(searchengine_url "${LLVM_DOXYGEN_SEARCHENGINE_URL}") set(enable_server_based_search "YES") set(enable_external_search "YES") set(extra_search_mappings "${LLVM_DOXYGEN_SEARCH_MAPPINGS}") else() set(enable_searchengine "NO") set(searchengine_url "") set(enable_server_based_search "NO") set(enable_external_search "NO") set(extra_search_mappings "") endif() # If asked, configure doxygen for the creation of a Qt Compressed Help file. if (LLVM_ENABLE_DOXYGEN_QT_HELP) set(CLANG_DOXYGEN_QCH_FILENAME "org.llvm.clang.qch" CACHE STRING "Filename of the Qt Compressed help file") set(CLANG_DOXYGEN_QHP_NAMESPACE "org.llvm.clang" CACHE STRING "Namespace under which the intermediate Qt Help Project file lives") set(CLANG_DOXYGEN_QHP_CUST_FILTER_NAME "Clang ${CLANG_VERSION}" CACHE STRING "See http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-filters") set(CLANG_DOXYGEN_QHP_CUST_FILTER_ATTRS "Clang,${CLANG_VERSION}" CACHE STRING "See http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes") set(clang_doxygen_generate_qhp "YES") set(clang_doxygen_qch_filename "${CLANG_DOXYGEN_QCH_FILENAME}") set(clang_doxygen_qhp_namespace "${CLANG_DOXYGEN_QHP_NAMESPACE}") set(clang_doxygen_qhelpgenerator_path "${LLVM_DOXYGEN_QHELPGENERATOR_PATH}") set(clang_doxygen_qhp_cust_filter_name "${CLANG_DOXYGEN_QHP_CUST_FILTER_NAME}") set(clang_doxygen_qhp_cust_filter_attrs "${CLANG_DOXYGEN_QHP_CUST_FILTER_ATTRS}") else() set(clang_doxygen_generate_qhp "NO") set(clang_doxygen_qch_filename "") set(clang_doxygen_qhp_namespace "") set(clang_doxygen_qhelpgenerator_path "") set(clang_doxygen_qhp_cust_filter_name "") set(clang_doxygen_qhp_cust_filter_attrs "") endif() option(LLVM_DOXYGEN_SVG "Use svg instead of png files for doxygen graphs." OFF) if (LLVM_DOXYGEN_SVG) set(DOT_IMAGE_FORMAT "svg") else() set(DOT_IMAGE_FORMAT "png") endif() configure_file(${CMAKE_CURRENT_SOURCE_DIR}/doxygen.cfg.in ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg @ONLY) set(abs_top_srcdir) set(abs_top_builddir) set(DOT) set(enable_searchengine) set(searchengine_url) set(enable_server_based_search) set(enable_external_search) set(extra_search_mappings) set(clang_doxygen_generate_qhp) set(clang_doxygen_qch_filename) set(clang_doxygen_qhp_namespace) set(clang_doxygen_qhelpgenerator_path) set(clang_doxygen_qhp_cust_filter_name) set(clang_doxygen_qhp_cust_filter_attrs) set(DOT_IMAGE_FORMAT) add_custom_target(doxygen-clang COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/doxygen.cfg WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} COMMENT "Generating clang doxygen documentation." VERBATIM) if (LLVM_BUILD_DOCS) add_dependencies(doxygen doxygen-clang) endif() if (NOT LLVM_INSTALL_TOOLCHAIN_ONLY) install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/doxygen/html DESTINATION docs/html) endif() endif() endif() if (LLVM_ENABLE_SPHINX) if (SPHINX_FOUND) include(AddSphinxTarget) if (${SPHINX_OUTPUT_HTML}) add_sphinx_target(html clang) endif() if (${SPHINX_OUTPUT_MAN}) add_sphinx_target(man clang) endif() endif() endif()
0
repos/DirectXShaderCompiler/tools/clang
repos/DirectXShaderCompiler/tools/clang/docs/conf.py
# -*- coding: utf-8 -*- # # Clang documentation build configuration file, created by # sphinx-quickstart on Sun Dec 9 20:01:55 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.todo', 'sphinx.ext.mathjax'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'DirectX HLSL Compiler' copyright = u'2016, Microsoft Corporation' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build', 'analyzer'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'friendly' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'haiku' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. html_show_sourcelink = False # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'dxcdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'dxc.tex', u'DirectX HLSL Compiler', u'Microsoft Corporation', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [] # Automatically derive the list of man pages from the contents of the command # guide subdirectory. This was copied from llvm/docs/conf.py. basedir = os.path.dirname(__file__) man_page_authors = u'Maintained by Microsoft Corporation' command_guide_subpath = 'CommandGuide' command_guide_path = os.path.join(basedir, command_guide_subpath) for name in os.listdir(command_guide_path): # Ignore non-ReST files and the index page. if not name.endswith('.rst') or name in ('index.rst',): continue # Otherwise, automatically extract the description. file_subpath = os.path.join(command_guide_subpath, name) with open(os.path.join(command_guide_path, name)) as f: title = f.readline().rstrip('\n') header = f.readline().rstrip('\n') if len(header) != len(title): print >>sys.stderr, ( "error: invalid header in %r (does not match title)" % ( file_subpath,)) if ' - ' not in title: print >>sys.stderr, ( ("error: invalid title in %r " "(expected '<name> - <description>')") % ( file_subpath,)) # Split the name out of the title. name,description = title.split(' - ', 1) man_pages.append((file_subpath.replace('.rst',''), name, description, man_page_authors, 1)) # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'DirectX HLSL Compiler', u'DirectX HLSL Compiler Documentation', u'Microsoft Corporation', 'DirectX HLSL Compiler', 'Compiler for HLSL language.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
0
repos/DirectXShaderCompiler/tools/clang/docs
repos/DirectXShaderCompiler/tools/clang/docs/analyzer/make.bat
@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^<target^>` where ^<target^> is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\ClangStaticAnalyzer.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\ClangStaticAnalyzer.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end
0
repos/DirectXShaderCompiler/tools/clang/docs
repos/DirectXShaderCompiler/tools/clang/docs/analyzer/conf.py
# -*- coding: utf-8 -*- # # Clang Static Analyzer documentation build configuration file, created by # sphinx-quickstart on Wed Jan 2 15:54:28 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.todo', 'sphinx.ext.mathjax'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Clang Static Analyzer' copyright = u'2013-2014, Analyzer Team' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '3.4' # The full version, including alpha/beta/rc tags. release = '3.4' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'haiku' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'ClangStaticAnalyzerdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'ClangStaticAnalyzer.tex', u'Clang Static Analyzer Documentation', u'Analyzer Team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'clangstaticanalyzer', u'Clang Static Analyzer Documentation', [u'Analyzer Team'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'ClangStaticAnalyzer', u'Clang Static Analyzer Documentation', u'Analyzer Team', 'ClangStaticAnalyzer', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None}
0
repos/DirectXShaderCompiler/tools/clang/docs
repos/DirectXShaderCompiler/tools/clang/docs/analyzer/RegionStore.txt
The analyzer "Store" represents the contents of memory regions. It is an opaque functional data structure stored in each ProgramState; the only class that can modify the store is its associated StoreManager. Currently (Feb. 2013), the only StoreManager implementation being used is RegionStoreManager. This store records bindings to memory regions using a "base region + offset" key. (This allows `*p` and `p[0]` to map to the same location, among other benefits.) Regions are grouped into "clusters", which roughly correspond to "regions with the same base region". This allows certain operations to be more efficient, such as invalidation. Regions that do not have a known offset use a special "symbolic" offset. These keys store both the original region, and the "concrete offset region" -- the last region whose offset is entirely concrete. (For example, in the expression `foo.bar[1][i].baz`, the concrete offset region is the array `foo.bar[1]`, since that has a known offset from the start of the top-level `foo` struct.) Binding Invalidation ==================== Supporting both concrete and symbolic offsets makes things a bit tricky. Here's an example: foo[0] = 0; foo[1] = 1; foo[i] = i; After the third assignment, nothing can be said about the value of `foo[0]`, because `foo[i]` may have overwritten it! Thus, *binding to a region with a symbolic offset invalidates the entire concrete offset region.* We know `foo[i]` is somewhere within `foo`, so we don't have to invalidate anything else, but we do have to be conservative about all other bindings within `foo`. Continuing the example: foo[i] = i; foo[0] = 0; After this latest assignment, nothing can be said about the value of `foo[i]`, because `foo[0]` may have overwritten it! *Binding to a region R with a concrete offset invalidates any symbolic offset bindings whose concrete offset region is a super-region **or** sub-region of R.* All we know about `foo[i]` is that it is somewhere within `foo`, so changing *anything* within `foo` might change `foo[i]`, and changing *all* of `foo` (or its base region) will *definitely* change `foo[i]`. This logic could be improved by using the current constraints on `i`, at the cost of speed. The latter case could also be improved by matching region kinds, i.e. changing `foo[0].a` is unlikely to affect `foo[i].b`, no matter what `i` is. For more detail, read through RegionStoreManager::removeSubRegionBindings in RegionStore.cpp. ObjCIvarRegions =============== Objective-C instance variables require a bit of special handling. Like struct fields, they are not base regions, and when their parent object region is invalidated, all the instance variables must be invalidated as well. However, they have no concrete compile-time offsets (in the modern, "non-fragile" runtime), and so cannot easily be represented as an offset from the start of the object in the analyzer. Moreover, this means that invalidating a single instance variable should *not* invalidate the rest of the object, since unlike struct fields or array elements there is no way to perform pointer arithmetic to access another instance variable. Consequently, although the base region of an ObjCIvarRegion is the entire object, RegionStore offsets are computed from the start of the instance variable. Thus it is not valid to assume that all bindings with non-symbolic offsets start from the base region! Region Invalidation =================== Unlike binding invalidation, region invalidation occurs when the entire contents of a region may have changed---say, because it has been passed to a function the analyzer can model, like memcpy, or because its address has escaped, usually as an argument to an opaque function call. In these cases we need to throw away not just all bindings within the region itself, but within its entire cluster, since neighboring regions may be accessed via pointer arithmetic. Region invalidation typically does even more than this, however. Because it usually represents the complete escape of a region from the analyzer's model, its *contents* must also be transitively invalidated. (For example, if a region 'p' of type 'int **' is invalidated, the contents of '*p' and '**p' may have changed as well.) The algorithm that traverses this transitive closure of accessible regions is known as ClusterAnalysis, and is also used for finding all live bindings in the store (in order to throw away the dead ones). The name "ClusterAnalysis" predates the cluster-based organization of bindings, but refers to the same concept: during invalidation and liveness analysis, all bindings within a cluster must be treated in the same way for a conservative model of program behavior. Default Bindings ================ Most bindings in RegionStore are simple scalar values -- integers and pointers. These are known as "Direct" bindings. However, RegionStore supports a second type of binding called a "Default" binding. These are used to provide values to all the elements of an aggregate type (struct or array) without having to explicitly specify a binding for each individual element. When there is no Direct binding for a particular region, the store manager looks at each super-region in turn to see if there is a Default binding. If so, this value is used as the value of the original region. The search ends when the base region is reached, at which point the RegionStore will pick an appropriate default value for the region (usually a symbolic value, but sometimes zero, for static data, or "uninitialized", for stack variables). int manyInts[10]; manyInts[1] = 42; // Creates a Direct binding for manyInts[1]. print(manyInts[1]); // Retrieves the Direct binding for manyInts[1]; print(manyInts[0]); // There is no Direct binding for manyInts[1]. // Is there a Default binding for the entire array? // There is not, but it is a stack variable, so we use // "uninitialized" as the default value (and emit a // diagnostic!). NOTE: The fact that bindings are stored as a base region plus an offset limits the Default Binding strategy, because in C aggregates can contain other aggregates. In the current implementation of RegionStore, there is no way to distinguish a Default binding for an entire aggregate from a Default binding for the sub-aggregate at offset 0. Lazy Bindings (LazyCompoundVal) =============================== RegionStore implements an optimization for copying aggregates (structs and arrays) called "lazy bindings", implemented using a special SVal called LazyCompoundVal. When the store is asked for the "binding" for an entire aggregate (i.e. for an lvalue-to-rvalue conversion), it returns a LazyCompoundVal instead. When this value is then stored into a variable, it is bound as a Default value. This makes copying arrays and structs much cheaper than if they had required memberwise access. Under the hood, a LazyCompoundVal is implemented as a uniqued pair of (region, store), representing "the value of the region during this 'snapshot' of the store". This has important implications for any sort of liveness or reachability analysis, which must take the bindings in the old store into account. Retrieving a value from a lazy binding happens in the same way as any other Default binding: since there is no direct binding, the store manager falls back to super-regions to look for an appropriate default binding. LazyCompoundVal differs from a normal default binding, however, in that it contains several different values, instead of one value that will appear several times. Because of this, the store manager has to reconstruct the subregion chain on top of the LazyCompoundVal region, and look up *that* region in the previous store. Here's a concrete example: CGPoint p; p.x = 42; // A Direct binding is made to the FieldRegion 'p.x'. CGPoint p2 = p; // A LazyCompoundVal is created for 'p', along with a // snapshot of the current store state. This value is then // used as a Default binding for the VarRegion 'p2'. return p2.x; // The binding for FieldRegion 'p2.x' is requested. // There is no Direct binding, so we look for a Default // binding to 'p2' and find the LCV. // Because it's an LCV, we look at our requested region // and see that it's the '.x' field. We ask for the value // of 'p.x' within the snapshot, and get back 42.
0
repos/DirectXShaderCompiler/tools/clang/docs
repos/DirectXShaderCompiler/tools/clang/docs/analyzer/IPA.txt
Inlining ======== NOTE: this document applies to the original Clang project, not the DirectX Compiler. It's made available for informational purposes only. There are several options that control which calls the analyzer will consider for inlining. The major one is -analyzer-config ipa: -analyzer-config ipa=none - All inlining is disabled. This is the only mode available in LLVM 3.1 and earlier and in Xcode 4.3 and earlier. -analyzer-config ipa=basic-inlining - Turns on inlining for C functions, C++ static member functions, and blocks -- essentially, the calls that behave like simple C function calls. This is essentially the mode used in Xcode 4.4. -analyzer-config ipa=inlining - Turns on inlining when we can confidently find the function/method body corresponding to the call. (C functions, static functions, devirtualized C++ methods, Objective-C class methods, Objective-C instance methods when ExprEngine is confident about the dynamic type of the instance). -analyzer-config ipa=dynamic - Inline instance methods for which the type is determined at runtime and we are not 100% sure that our type info is correct. For virtual calls, inline the most plausible definition. -analyzer-config ipa=dynamic-bifurcate - Same as -analyzer-config ipa=dynamic, but the path is split. We inline on one branch and do not inline on the other. This mode does not drop the coverage in cases when the parent class has code that is only exercised when some of its methods are overridden. Currently, -analyzer-config ipa=dynamic-bifurcate is the default mode. While -analyzer-config ipa determines in general how aggressively the analyzer will try to inline functions, several additional options control which types of functions can inlined, in an all-or-nothing way. These options use the analyzer's configuration table, so they are all specified as follows: -analyzer-config OPTION=VALUE ### c++-inlining ### This option controls which C++ member functions may be inlined. -analyzer-config c++-inlining=[none | methods | constructors | destructors] Each of these modes implies that all the previous member function kinds will be inlined as well; it doesn't make sense to inline destructors without inlining constructors, for example. The default c++-inlining mode is 'destructors', meaning that all member functions with visible definitions will be considered for inlining. In some cases the analyzer may still choose not to inline the function. Note that under 'constructors', constructors for types with non-trivial destructors will not be inlined. Additionally, no C++ member functions will be inlined under -analyzer-config ipa=none or -analyzer-config ipa=basic-inlining, regardless of the setting of the c++-inlining mode. ### c++-template-inlining ### This option controls whether C++ templated functions may be inlined. -analyzer-config c++-template-inlining=[true | false] Currently, template functions are considered for inlining by default. The motivation behind this option is that very generic code can be a source of false positives, either by considering paths that the caller considers impossible (by some unstated precondition), or by inlining some but not all of a deep implementation of a function. ### c++-stdlib-inlining ### This option controls whether functions from the C++ standard library, including methods of the container classes in the Standard Template Library, should be considered for inlining. -analyzer-config c++-stdlib-inlining=[true | false] Currently, C++ standard library functions are considered for inlining by default. The standard library functions and the STL in particular are used ubiquitously enough that our tolerance for false positives is even lower here. A false positive due to poor modeling of the STL leads to a poor user experience, since most users would not be comfortable adding assertions to system headers in order to silence analyzer warnings. ### c++-container-inlining ### This option controls whether constructors and destructors of "container" types should be considered for inlining. -analyzer-config c++-container-inlining=[true | false] Currently, these constructors and destructors are NOT considered for inlining by default. The current implementation of this setting checks whether a type has a member named 'iterator' or a member named 'begin'; these names are idiomatic in C++, with the latter specified in the C++11 standard. The analyzer currently does a fairly poor job of modeling certain data structure invariants of container-like objects. For example, these three expressions should be equivalent: std::distance(c.begin(), c.end()) == 0 c.begin() == c.end() c.empty()) Many of these issues are avoided if containers always have unknown, symbolic state, which is what happens when their constructors are treated as opaque. In the future, we may decide specific containers are "safe" to model through inlining, or choose to model them directly using checkers instead. Basics of Implementation ----------------------- The low-level mechanism of inlining a function is handled in ExprEngine::inlineCall and ExprEngine::processCallExit. If the conditions are right for inlining, a CallEnter node is created and added to the analysis work list. The CallEnter node marks the change to a new LocationContext representing the called function, and its state includes the contents of the new stack frame. When the CallEnter node is actually processed, its single successor will be a edge to the first CFG block in the function. Exiting an inlined function is a bit more work, fortunately broken up into reasonable steps: 1. The CoreEngine realizes we're at the end of an inlined call and generates a CallExitBegin node. 2. ExprEngine takes over (in processCallExit) and finds the return value of the function, if it has one. This is bound to the expression that triggered the call. (In the case of calls without origin expressions, such as destructors, this step is skipped.) 3. Dead symbols and bindings are cleaned out from the state, including any local bindings. 4. A CallExitEnd node is generated, which marks the transition back to the caller's LocationContext. 5. Custom post-call checks are processed and the final nodes are pushed back onto the work list, so that evaluation of the caller can continue. Retry Without Inlining ---------------------- In some cases, we would like to retry analysis without inlining a particular call. Currently, we use this technique to recover coverage in case we stop analyzing a path due to exceeding the maximum block count inside an inlined function. When this situation is detected, we walk up the path to find the first node before inlining was started and enqueue it on the WorkList with a special ReplayWithoutInlining bit added to it (ExprEngine::replayWithoutInlining). The path is then re-analyzed from that point without inlining that particular call. Deciding When to Inline ----------------------- In general, the analyzer attempts to inline as much as possible, since it provides a better summary of what actually happens in the program. There are some cases, however, where the analyzer chooses not to inline: - If there is no definition available for the called function or method. In this case, there is no opportunity to inline. - If the CFG cannot be constructed for a called function, or the liveness cannot be computed. These are prerequisites for analyzing a function body, with or without inlining. - If the LocationContext chain for a given ExplodedNode reaches a maximum cutoff depth. This prevents unbounded analysis due to infinite recursion, but also serves as a useful cutoff for performance reasons. - If the function is variadic. This is not a hard limitation, but an engineering limitation. Tracked by: <rdar://problem/12147064> Support inlining of variadic functions - In C++, constructors are not inlined unless the destructor call will be processed by the ExprEngine. Thus, if the CFG was built without nodes for implicit destructors, or if the destructors for the given object are not represented in the CFG, the constructor will not be inlined. (As an exception, constructors for objects with trivial constructors can still be inlined.) See "C++ Caveats" below. - In C++, ExprEngine does not inline custom implementations of operator 'new' or operator 'delete', nor does it inline the constructors and destructors associated with these. See "C++ Caveats" below. - Calls resulting in "dynamic dispatch" are specially handled. See more below. - The FunctionSummaries map stores additional information about declarations, some of which is collected at runtime based on previous analyses. We do not inline functions which were not profitable to inline in a different context (for example, if the maximum block count was exceeded; see "Retry Without Inlining"). Dynamic Calls and Devirtualization ---------------------------------- "Dynamic" calls are those that are resolved at runtime, such as C++ virtual method calls and Objective-C message sends. Due to the path-sensitive nature of the analysis, the analyzer may be able to reason about the dynamic type of the object whose method is being called and thus "devirtualize" the call. This path-sensitive devirtualization occurs when the analyzer can determine what method would actually be called at runtime. This is possible when the type information is constrained enough for a simulated C++/Objective-C object that the analyzer can make such a decision. == DynamicTypeInfo == As the analyzer analyzes a path, it may accrue information to refine the knowledge about the type of an object. This can then be used to make better decisions about the target method of a call. Such type information is tracked as DynamicTypeInfo. This is path-sensitive data that is stored in ProgramState, which defines a mapping from MemRegions to an (optional) DynamicTypeInfo. If no DynamicTypeInfo has been explicitly set for a MemRegion, it will be lazily inferred from the region's type or associated symbol. Information from symbolic regions is weaker than from true typed regions. EXAMPLE: A C++ object declared "A obj" is known to have the class 'A', but a reference "A &ref" may dynamically be a subclass of 'A'. The DynamicTypePropagation checker gathers and propagates DynamicTypeInfo, updating it as information is observed along a path that can refine that type information for a region. WARNING: Not all of the existing analyzer code has been retrofitted to use DynamicTypeInfo, nor is it universally appropriate. In particular, DynamicTypeInfo always applies to a region with all casts stripped off, but sometimes the information provided by casts can be useful. == RuntimeDefinition == The basis of devirtualization is CallEvent's getRuntimeDefinition() method, which returns a RuntimeDefinition object. When asked to provide a definition, the CallEvents for dynamic calls will use the DynamicTypeInfo in their ProgramState to attempt to devirtualize the call. In the case of no dynamic dispatch, or perfectly constrained devirtualization, the resulting RuntimeDefinition contains a Decl corresponding to the definition of the called function, and RuntimeDefinition::mayHaveOtherDefinitions will return FALSE. In the case of dynamic dispatch where our information is not perfect, CallEvent can make a guess, but RuntimeDefinition::mayHaveOtherDefinitions will return TRUE. The RuntimeDefinition object will then also include a MemRegion corresponding to the object being called (i.e., the "receiver" in Objective-C parlance), which ExprEngine uses to decide whether or not the call should be inlined. == Inlining Dynamic Calls == The -analyzer-config ipa option has five different modes: none, basic-inlining, inlining, dynamic, and dynamic-bifurcate. Under -analyzer-config ipa=dynamic, all dynamic calls are inlined, whether we are certain or not that this will actually be the definition used at runtime. Under -analyzer-config ipa=inlining, only "near-perfect" devirtualized calls are inlined*, and other dynamic calls are evaluated conservatively (as if no definition were available). * Currently, no Objective-C messages are not inlined under -analyzer-config ipa=inlining, even if we are reasonably confident of the type of the receiver. We plan to enable this once we have tested our heuristics more thoroughly. The last option, -analyzer-config ipa=dynamic-bifurcate, behaves similarly to "dynamic", but performs a conservative invalidation in the general virtual case in *addition* to inlining. The details of this are discussed below. As stated above, -analyzer-config ipa=basic-inlining does not inline any C++ member functions or Objective-C method calls, even if they are non-virtual or can be safely devirtualized. Bifurcation ----------- ExprEngine::BifurcateCall implements the -analyzer-config ipa=dynamic-bifurcate mode. When a call is made on an object with imprecise dynamic type information (RuntimeDefinition::mayHaveOtherDefinitions() evaluates to TRUE), ExprEngine bifurcates the path and marks the object's region (retrieved from the RuntimeDefinition object) with a path-sensitive "mode" in the ProgramState. Currently, there are 2 modes: DynamicDispatchModeInlined - Models the case where the dynamic type information of the receiver (MemoryRegion) is assumed to be perfectly constrained so that a given definition of a method is expected to be the code actually called. When this mode is set, ExprEngine uses the Decl from RuntimeDefinition to inline any dynamically dispatched call sent to this receiver because the function definition is considered to be fully resolved. DynamicDispatchModeConservative - Models the case where the dynamic type information is assumed to be incorrect, for example, implies that the method definition is overriden in a subclass. In such cases, ExprEngine does not inline the methods sent to the receiver (MemoryRegion), even if a candidate definition is available. This mode is conservative about simulating the effects of a call. Going forward along the symbolic execution path, ExprEngine consults the mode of the receiver's MemRegion to make decisions on whether the calls should be inlined or not, which ensures that there is at most one split per region. At a high level, "bifurcation mode" allows for increased semantic coverage in cases where the parent method contains code which is only executed when the class is subclassed. The disadvantages of this mode are a (considerable?) performance hit and the possibility of false positives on the path where the conservative mode is used. Objective-C Message Heuristics ------------------------------ ExprEngine relies on a set of heuristics to partition the set of Objective-C method calls into those that require bifurcation and those that do not. Below are the cases when the DynamicTypeInfo of the object is considered precise (cannot be a subclass): - If the object was created with +alloc or +new and initialized with an -init method. - If the calls are property accesses using dot syntax. This is based on the assumption that children rarely override properties, or do so in an essentially compatible way. - If the class interface is declared inside the main source file. In this case it is unlikely that it will be subclassed. - If the method is not declared outside of main source file, either by the receiver's class or by any superclasses. C++ Caveats -------------------- C++11 [class.cdtor]p4 describes how the vtable of an object is modified as it is being constructed or destructed; that is, the type of the object depends on which base constructors have been completed. This is tracked using DynamicTypeInfo in the DynamicTypePropagation checker. There are several limitations in the current implementation: - Temporaries are poorly modeled right now because we're not confident in the placement of their destructors in the CFG. We currently won't inline their constructors unless the destructor is trivial, and don't process their destructors at all, not even to invalidate the region. - 'new' is poorly modeled due to some nasty CFG/design issues. This is tracked in PR12014. 'delete' is not modeled at all. - Arrays of objects are modeled very poorly right now. ExprEngine currently only simulates the first constructor and first destructor. Because of this, ExprEngine does not inline any constructors or destructors for arrays. CallEvent ========= A CallEvent represents a specific call to a function, method, or other body of code. It is path-sensitive, containing both the current state (ProgramStateRef) and stack space (LocationContext), and provides uniform access to the argument values and return type of a call, no matter how the call is written in the source or what sort of code body is being invoked. NOTE: For those familiar with Cocoa, CallEvent is roughly equivalent to NSInvocation. CallEvent should be used whenever there is logic dealing with function calls that does not care how the call occurred. Examples include checking that arguments satisfy preconditions (such as __attribute__((nonnull))), and attempting to inline a call. CallEvents are reference-counted objects managed by a CallEventManager. While there is no inherent issue with persisting them (say, in a ProgramState's GDM), they are intended for short-lived use, and can be recreated from CFGElements or non-top-level StackFrameContexts fairly easily.
0
repos/DirectXShaderCompiler/tools/clang/docs
repos/DirectXShaderCompiler/tools/clang/docs/tools/dump_format_style.py
#!/usr/bin/env python # A tool to parse the FormatStyle struct from Format.h and update the # documentation in ../ClangFormatStyleOptions.rst automatically. # Run from the directory in which this file is located to update the docs. import collections import re import urllib2 FORMAT_STYLE_FILE = '../../include/clang/Format/Format.h' DOC_FILE = '../ClangFormatStyleOptions.rst' def substitute(text, tag, contents): replacement = '\n.. START_%s\n\n%s\n\n.. END_%s\n' % (tag, contents, tag) pattern = r'\n\.\. START_%s\n.*\n\.\. END_%s\n' % (tag, tag) return re.sub(pattern, '%s', text, flags=re.S) % replacement def doxygen2rst(text): text = re.sub(r'([^/\*])\*', r'\1\\*', text) text = re.sub(r'<tt>\s*(.*?)\s*<\/tt>', r'``\1``', text) text = re.sub(r'\\c ([^ ,;\.]+)', r'``\1``', text) text = re.sub(r'\\\w+ ', '', text) return text def indent(text, columns): indent = ' ' * columns s = re.sub(r'\n([^\n])', '\n' + indent + '\\1', text, flags=re.S) if s.startswith('\n'): return s return indent + s class Option: def __init__(self, name, type, comment): self.name = name self.type = type self.comment = comment.strip() self.enum = None def __str__(self): s = '**%s** (``%s``)\n%s' % (self.name, self.type, doxygen2rst(indent(self.comment, 2))) if self.enum: s += indent('\n\nPossible values:\n\n%s\n' % self.enum, 2) return s class Enum: def __init__(self, name, comment): self.name = name self.comment = comment.strip() self.values = [] def __str__(self): return '\n'.join(map(str, self.values)) class EnumValue: def __init__(self, name, comment): self.name = name self.comment = comment.strip() def __str__(self): return '* ``%s`` (in configuration: ``%s``)\n%s' % ( self.name, re.sub('.*_', '', self.name), doxygen2rst(indent(self.comment, 2))) def clean_comment_line(line): return line[3:].strip() + '\n' def read_options(header): class State: BeforeStruct, Finished, InStruct, InFieldComment, InEnum, \ InEnumMemberComment = range(6) state = State.BeforeStruct options = [] enums = {} comment = '' enum = None for line in header: line = line.strip() if state == State.BeforeStruct: if line == 'struct FormatStyle {': state = State.InStruct elif state == State.InStruct: if line.startswith('///'): state = State.InFieldComment comment = clean_comment_line(line) elif line == '};': state = State.Finished break elif state == State.InFieldComment: if line.startswith('///'): comment += clean_comment_line(line) elif line.startswith('enum'): state = State.InEnum name = re.sub(r'enum\s+(\w+)\s*\{', '\\1', line) enum = Enum(name, comment) elif line.endswith(';'): state = State.InStruct field_type, field_name = re.match(r'([<>:\w]+)\s+(\w+);', line).groups() option = Option(str(field_name), str(field_type), comment) options.append(option) else: raise Exception('Invalid format, expected comment, field or enum') elif state == State.InEnum: if line.startswith('///'): state = State.InEnumMemberComment comment = clean_comment_line(line) elif line == '};': state = State.InStruct enums[enum.name] = enum else: raise Exception('Invalid format, expected enum field comment or };') elif state == State.InEnumMemberComment: if line.startswith('///'): comment += clean_comment_line(line) else: state = State.InEnum enum.values.append(EnumValue(line.replace(',', ''), comment)) if state != State.Finished: raise Exception('Not finished by the end of file') for option in options: if not option.type in ['bool', 'unsigned', 'int', 'std::string', 'std::vector<std::string>']: if enums.has_key(option.type): option.enum = enums[option.type] else: raise Exception('Unknown type: %s' % option.type) return options options = read_options(open(FORMAT_STYLE_FILE)) options = sorted(options, key=lambda x: x.name) options_text = '\n\n'.join(map(str, options)) contents = open(DOC_FILE).read() contents = substitute(contents, 'FORMAT_STYLE_OPTIONS', options_text) with open(DOC_FILE, 'w') as output: output.write(contents)
0
repos/DirectXShaderCompiler/tools/clang/docs
repos/DirectXShaderCompiler/tools/clang/docs/tools/dump_ast_matchers.py
#!/usr/bin/env python # A tool to parse ASTMatchers.h and update the documentation in # ../LibASTMatchersReference.html automatically. Run from the # directory in which this file is located to update the docs. import collections import re import urllib2 MATCHERS_FILE = '../../include/clang/ASTMatchers/ASTMatchers.h' # Each matcher is documented in one row of the form: # result | name | argA # The subsequent row contains the documentation and is hidden by default, # becoming visible via javascript when the user clicks the matcher name. TD_TEMPLATE=""" <tr><td>%(result)s</td><td class="name" onclick="toggle('%(id)s')"><a name="%(id)sAnchor">%(name)s</a></td><td>%(args)s</td></tr> <tr><td colspan="4" class="doc" id="%(id)s"><pre>%(comment)s</pre></td></tr> """ # We categorize the matchers into these three categories in the reference: node_matchers = {} narrowing_matchers = {} traversal_matchers = {} # We output multiple rows per matcher if the matcher can be used on multiple # node types. Thus, we need a new id per row to control the documentation # pop-up. ids[name] keeps track of those ids. ids = collections.defaultdict(int) # Cache for doxygen urls we have already verified. doxygen_probes = {} def esc(text): """Escape any html in the given text.""" text = re.sub(r'&', '&amp;', text) text = re.sub(r'<', '&lt;', text) text = re.sub(r'>', '&gt;', text) def link_if_exists(m): name = m.group(1) url = 'http://clang.llvm.org/doxygen/classclang_1_1%s.html' % name if url not in doxygen_probes: try: print 'Probing %s...' % url urllib2.urlopen(url) doxygen_probes[url] = True except: doxygen_probes[url] = False if doxygen_probes[url]: return r'Matcher&lt<a href="%s">%s</a>&gt;' % (url, name) else: return m.group(0) text = re.sub( r'Matcher&lt;([^\*&]+)&gt;', link_if_exists, text) return text def extract_result_types(comment): """Extracts a list of result types from the given comment. We allow annotations in the comment of the matcher to specify what nodes a matcher can match on. Those comments have the form: Usable as: Any Matcher | (Matcher<T1>[, Matcher<t2>[, ...]]) Returns ['*'] in case of 'Any Matcher', or ['T1', 'T2', ...]. Returns the empty list if no 'Usable as' specification could be parsed. """ result_types = [] m = re.search(r'Usable as: Any Matcher[\s\n]*$', comment, re.S) if m: return ['*'] while True: m = re.match(r'^(.*)Matcher<([^>]+)>\s*,?[\s\n]*$', comment, re.S) if not m: if re.search(r'Usable as:\s*$', comment): return result_types else: return None result_types += [m.group(2)] comment = m.group(1) def strip_doxygen(comment): """Returns the given comment without \-escaped words.""" # If there is only a doxygen keyword in the line, delete the whole line. comment = re.sub(r'^\\[^\s]+\n', r'', comment, flags=re.M) # Delete the doxygen command and the following whitespace. comment = re.sub(r'\\[^\s]+\s+', r'', comment) return comment def unify_arguments(args): """Gets rid of anything the user doesn't care about in the argument list.""" args = re.sub(r'internal::', r'', args) args = re.sub(r'const\s+', r'', args) args = re.sub(r'&', r' ', args) args = re.sub(r'(^|\s)M\d?(\s)', r'\1Matcher<*>\2', args) return args def add_matcher(result_type, name, args, comment, is_dyncast=False): """Adds a matcher to one of our categories.""" if name == 'id': # FIXME: Figure out whether we want to support the 'id' matcher. return matcher_id = '%s%d' % (name, ids[name]) ids[name] += 1 args = unify_arguments(args) matcher_html = TD_TEMPLATE % { 'result': esc('Matcher<%s>' % result_type), 'name': name, 'args': esc(args), 'comment': esc(strip_doxygen(comment)), 'id': matcher_id, } if is_dyncast: node_matchers[result_type + name] = matcher_html # Use a heuristic to figure out whether a matcher is a narrowing or # traversal matcher. By default, matchers that take other matchers as # arguments (and are not node matchers) do traversal. We specifically # exclude known narrowing matchers that also take other matchers as # arguments. elif ('Matcher<' not in args or name in ['allOf', 'anyOf', 'anything', 'unless']): narrowing_matchers[result_type + name + esc(args)] = matcher_html else: traversal_matchers[result_type + name + esc(args)] = matcher_html def act_on_decl(declaration, comment, allowed_types): """Parse the matcher out of the given declaration and comment. If 'allowed_types' is set, it contains a list of node types the matcher can match on, as extracted from the static type asserts in the matcher definition. """ if declaration.strip(): # Node matchers are defined by writing: # VariadicDynCastAllOfMatcher<ResultType, ArgumentType> name; m = re.match(r""".*Variadic(?:DynCast)?AllOfMatcher\s*< \s*([^\s,]+)\s*(?:, \s*([^\s>]+)\s*)?> \s*([^\s;]+)\s*;\s*$""", declaration, flags=re.X) if m: result, inner, name = m.groups() if not inner: inner = result add_matcher(result, name, 'Matcher<%s>...' % inner, comment, is_dyncast=True) return # Parse the various matcher definition macros. m = re.match(""".*AST_TYPE_MATCHER\( \s*([^\s,]+\s*), \s*([^\s,]+\s*) \)\s*;\s*$""", declaration, flags=re.X) if m: inner, name = m.groups() add_matcher('Type', name, 'Matcher<%s>...' % inner, comment, is_dyncast=True) # FIXME: re-enable once we have implemented casting on the TypeLoc # hierarchy. # add_matcher('TypeLoc', '%sLoc' % name, 'Matcher<%sLoc>...' % inner, # comment, is_dyncast=True) return m = re.match(""".*AST_TYPE(LOC)?_TRAVERSE_MATCHER\( \s*([^\s,]+\s*), \s*(?:[^\s,]+\s*), \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\) \)\s*;\s*$""", declaration, flags=re.X) if m: loc, name, n_results, results = m.groups()[0:4] result_types = [r.strip() for r in results.split(',')] comment_result_types = extract_result_types(comment) if (comment_result_types and sorted(result_types) != sorted(comment_result_types)): raise Exception('Inconsistent documentation for: %s' % name) for result_type in result_types: add_matcher(result_type, name, 'Matcher<Type>', comment) if loc: add_matcher('%sLoc' % result_type, '%sLoc' % name, 'Matcher<TypeLoc>', comment) return m = re.match(r"""^\s*AST_POLYMORPHIC_MATCHER(_P)?(.?)(?:_OVERLOAD)?\( \s*([^\s,]+)\s*, \s*AST_POLYMORPHIC_SUPPORTED_TYPES\(([^)]*)\) (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*\d+\s*)? \)\s*{\s*$""", declaration, flags=re.X) if m: p, n, name, n_results, results = m.groups()[0:5] args = m.groups()[5:] result_types = [r.strip() for r in results.split(',')] if allowed_types and allowed_types != result_types: raise Exception('Inconsistent documentation for: %s' % name) if n not in ['', '2']: raise Exception('Cannot parse "%s"' % declaration) args = ', '.join('%s %s' % (args[i], args[i+1]) for i in range(0, len(args), 2) if args[i]) for result_type in result_types: add_matcher(result_type, name, args, comment) return m = re.match(r"""^\s*AST_MATCHER_FUNCTION(_P)?(.?)(?:_OVERLOAD)?\( (?:\s*([^\s,]+)\s*,)? \s*([^\s,]+)\s* (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*\d+\s*)? \)\s*{\s*$""", declaration, flags=re.X) if m: p, n, result, name = m.groups()[0:4] args = m.groups()[4:] if n not in ['', '2']: raise Exception('Cannot parse "%s"' % declaration) args = ', '.join('%s %s' % (args[i], args[i+1]) for i in range(0, len(args), 2) if args[i]) add_matcher(result, name, args, comment) return m = re.match(r"""^\s*AST_MATCHER(_P)?(.?)(?:_OVERLOAD)?\( (?:\s*([^\s,]+)\s*,)? \s*([^\s,]+)\s* (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*([^\s,]+)\s* ,\s*([^\s,]+)\s*)? (?:,\s*\d+\s*)? \)\s*{\s*$""", declaration, flags=re.X) if m: p, n, result, name = m.groups()[0:4] args = m.groups()[4:] if not result: if not allowed_types: raise Exception('Did not find allowed result types for: %s' % name) result_types = allowed_types else: result_types = [result] if n not in ['', '2']: raise Exception('Cannot parse "%s"' % declaration) args = ', '.join('%s %s' % (args[i], args[i+1]) for i in range(0, len(args), 2) if args[i]) for result_type in result_types: add_matcher(result_type, name, args, comment) return # Parse ArgumentAdapting matchers. m = re.match( r"""^.*ArgumentAdaptingMatcherFunc<.*>\s*(?:LLVM_ATTRIBUTE_UNUSED\s*) ([a-zA-Z]*)\s*=\s*{};$""", declaration, flags=re.X) if m: name = m.groups()[0] add_matcher('*', name, 'Matcher<*>', comment) return # Parse Variadic operator matchers. m = re.match( r"""^.*VariadicOperatorMatcherFunc\s*<\s*([^,]+),\s*([^\s>]+)\s*>\s* ([a-zA-Z]*)\s*=\s*{.*};$""", declaration, flags=re.X) if m: min_args, max_args, name = m.groups()[:3] if max_args == '1': add_matcher('*', name, 'Matcher<*>', comment) return elif max_args == 'UINT_MAX': add_matcher('*', name, 'Matcher<*>, ..., Matcher<*>', comment) return # Parse free standing matcher functions, like: # Matcher<ResultType> Name(Matcher<ArgumentType> InnerMatcher) { m = re.match(r"""^\s*(.*)\s+ ([^\s\(]+)\s*\( (.*) \)\s*{""", declaration, re.X) if m: result, name, args = m.groups() args = ', '.join(p.strip() for p in args.split(',')) m = re.match(r'.*\s+internal::(Bindable)?Matcher<([^>]+)>$', result) if m: result_types = [m.group(2)] else: result_types = extract_result_types(comment) if not result_types: if not comment: # Only overloads don't have their own doxygen comments; ignore those. print 'Ignoring "%s"' % name else: print 'Cannot determine result type for "%s"' % name else: for result_type in result_types: add_matcher(result_type, name, args, comment) else: print '*** Unparsable: "' + declaration + '" ***' def sort_table(matcher_type, matcher_map): """Returns the sorted html table for the given row map.""" table = '' for key in sorted(matcher_map.keys()): table += matcher_map[key] + '\n' return ('<!-- START_%(type)s_MATCHERS -->\n' + '%(table)s' + '<!--END_%(type)s_MATCHERS -->') % { 'type': matcher_type, 'table': table, } # Parse the ast matchers. # We alternate between two modes: # body = True: We parse the definition of a matcher. We need # to parse the full definition before adding a matcher, as the # definition might contain static asserts that specify the result # type. # body = False: We parse the comments and declaration of the matcher. comment = '' declaration = '' allowed_types = [] body = False for line in open(MATCHERS_FILE).read().splitlines(): if body: if line.strip() and line[0] == '}': if declaration: act_on_decl(declaration, comment, allowed_types) comment = '' declaration = '' allowed_types = [] body = False else: m = re.search(r'is_base_of<([^,]+), NodeType>', line) if m and m.group(1): allowed_types += [m.group(1)] continue if line.strip() and line.lstrip()[0] == '/': comment += re.sub(r'/+\s?', '', line) + '\n' else: declaration += ' ' + line if ((not line.strip()) or line.rstrip()[-1] == ';' or (line.rstrip()[-1] == '{' and line.rstrip()[-3:] != '= {')): if line.strip() and line.rstrip()[-1] == '{': body = True else: act_on_decl(declaration, comment, allowed_types) comment = '' declaration = '' allowed_types = [] node_matcher_table = sort_table('DECL', node_matchers) narrowing_matcher_table = sort_table('NARROWING', narrowing_matchers) traversal_matcher_table = sort_table('TRAVERSAL', traversal_matchers) reference = open('../LibASTMatchersReference.html').read() reference = re.sub(r'<!-- START_DECL_MATCHERS.*END_DECL_MATCHERS -->', '%s', reference, flags=re.S) % node_matcher_table reference = re.sub(r'<!-- START_NARROWING_MATCHERS.*END_NARROWING_MATCHERS -->', '%s', reference, flags=re.S) % narrowing_matcher_table reference = re.sub(r'<!-- START_TRAVERSAL_MATCHERS.*END_TRAVERSAL_MATCHERS -->', '%s', reference, flags=re.S) % traversal_matcher_table with open('../LibASTMatchersReference.html', 'w') as output: output.write(reference)
0
repos/DirectXShaderCompiler/tools/clang
repos/DirectXShaderCompiler/tools/clang/utils/find-unused-diagnostics.sh
#!/usr/bin/env bash # # This script produces a list of all diagnostics that are defined # in Diagnostic*.td files but not used in sources. # # Gather all diagnostic identifiers from the .td files. ALL_DIAGS=$(grep -E --only-matching --no-filename '(err_|warn_|ext_|note_)[a-z_]+' ./include/clang/Basic/Diagnostic*.td) # Now look for all potential identifiers in the source files. ALL_SOURCES=$(find lib include tools -name \*.cpp -or -name \*.h) DIAGS_IN_SOURCES=$(grep -E --only-matching --no-filename '(err_|warn_|ext_|note_)[a-z_]+' $ALL_SOURCES) # Print all diags that occur in the .td files but not in the source. comm -23 <(sort -u <<< "$ALL_DIAGS") <(sort -u <<< "$DIAGS_IN_SOURCES")
0
repos/DirectXShaderCompiler/tools/clang
repos/DirectXShaderCompiler/tools/clang/utils/builtin-defines.c
/* This is a clang style test case for checking that preprocessor defines match gcc. */ /* RUN: for arch in -m32 -m64; do \ RUN: for lang in -std=gnu89 -ansi -std=c99 -std=gnu99; do \ RUN: for input in c objective-c; do \ RUN: for opts in "-O0" "-O1 -dynamic" "-O2 -static" "-Os"; do \ RUN: echo "-- $arch, $lang, $input, $opts --"; \ RUN: for cc in 0 1; do \ RUN: if [ "$cc" == 0 ]; then \ RUN: cc_prog=clang; \ RUN: output=%t0; \ RUN: else \ RUN: cc_prog=gcc; \ RUN: output=%t1; \ RUN: fi; \ RUN: $cc_prog $arch $lang $opts -march=core2 -dM -E -x $input %s | sort > $output; \ RUN: done; \ RUN: if (! diff %t0 %t1); then exit 1; fi; \ RUN: done; \ RUN: done; \ RUN: done; \ RUN: done; */ /* We don't care about this difference */ #ifdef __PIC__ #if __PIC__ == 1 #undef __PIC__ #undef __pic__ #define __PIC__ 2 #define __pic__ 2 #endif #endif /* Undefine things we don't expect to match. */ #undef __core2 #undef __core2__ #undef __SSSE3__ /* Undefine things we don't expect to match. */ #undef __DEC_EVAL_METHOD__ #undef __INT16_TYPE__ #undef __INT32_TYPE__ #undef __INT64_TYPE__ #undef __INT8_TYPE__ #undef __SSP__ #undef __APPLE_CC__ #undef __VERSION__ #undef __clang__ #undef __llvm__ #undef __nocona #undef __nocona__ #undef __k8 #undef __k8__ #undef __tune_nocona__ #undef __tune_core2__ #undef __POINTER_WIDTH__ #undef __INTPTR_TYPE__ #undef __NO_MATH_INLINES #undef __DEC128_DEN__ #undef __DEC128_EPSILON__ #undef __DEC128_MANT_DIG__ #undef __DEC128_MAX_EXP__ #undef __DEC128_MAX__ #undef __DEC128_MIN_EXP__ #undef __DEC128_MIN__ #undef __DEC32_DEN__ #undef __DEC32_EPSILON__ #undef __DEC32_MANT_DIG__ #undef __DEC32_MAX_EXP__ #undef __DEC32_MAX__ #undef __DEC32_MIN_EXP__ #undef __DEC32_MIN__ #undef __DEC64_DEN__ #undef __DEC64_EPSILON__ #undef __DEC64_MANT_DIG__ #undef __DEC64_MAX_EXP__ #undef __DEC64_MAX__ #undef __DEC64_MIN_EXP__ #undef __DEC64_MIN__
0
repos/DirectXShaderCompiler/tools/clang
repos/DirectXShaderCompiler/tools/clang/utils/token-delta.py
#!/usr/bin/env python import os import re import subprocess import sys import tempfile ### class DeltaAlgorithm(object): def __init__(self): self.cache = set() def test(self, changes): abstract ### def getTestResult(self, changes): # There is no reason to cache successful tests because we will # always reduce the changeset when we see one. changeset = frozenset(changes) if changeset in self.cache: return False elif not self.test(changes): self.cache.add(changeset) return False else: return True def run(self, changes, force=False): # Make sure the initial test passes, if not then (a) either # the user doesn't expect monotonicity, and we may end up # doing O(N^2) tests, or (b) the test is wrong. Avoid the # O(N^2) case unless user requests it. if not force: if not self.getTestResult(changes): raise ValueError,'Initial test passed to delta fails.' # Check empty set first to quickly find poor test functions. if self.getTestResult(set()): return set() else: return self.delta(changes, self.split(changes)) def split(self, S): """split(set) -> [sets] Partition a set into one or two pieces. """ # There are many ways to split, we could do a better job with more # context information (but then the API becomes grosser). L = list(S) mid = len(L)//2 if mid==0: return L, else: return L[:mid],L[mid:] def delta(self, c, sets): # assert(reduce(set.union, sets, set()) == c) # If there is nothing left we can remove, we are done. if len(sets) <= 1: return c # Look for a passing subset. res = self.search(c, sets) if res is not None: return res # Otherwise, partition sets if possible; if not we are done. refined = sum(map(list, map(self.split, sets)), []) if len(refined) == len(sets): return c return self.delta(c, refined) def search(self, c, sets): for i,S in enumerate(sets): # If test passes on this subset alone, recurse. if self.getTestResult(S): return self.delta(S, self.split(S)) # Otherwise if we have more than two sets, see if test # pases without this subset. if len(sets) > 2: complement = sum(sets[:i] + sets[i+1:],[]) if self.getTestResult(complement): return self.delta(complement, sets[:i] + sets[i+1:]) ### class Token: def __init__(self, type, data, flags, file, line, column): self.type = type self.data = data self.flags = flags self.file = file self.line = line self.column = column kTokenRE = re.compile(r"""([a-z_]+) '(.*)'\t(.*)\tLoc=<(.*):(.*):(.*)>""", re.DOTALL | re.MULTILINE) def getTokens(path): p = subprocess.Popen(['clang','-dump-raw-tokens',path], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = p.communicate() tokens = [] collect = None for ln in err.split('\n'): # Silly programmers refuse to print in simple machine readable # formats. Whatever. if collect is None: collect = ln else: collect = collect + '\n' + ln if 'Loc=<' in ln and ln.endswith('>'): ln,collect = collect,None tokens.append(Token(*kTokenRE.match(ln).groups())) return tokens ### class TMBDDelta(DeltaAlgorithm): def __init__(self, testProgram, tokenLists, log): def patchName(name, suffix): base,ext = os.path.splitext(name) return base + '.' + suffix + ext super(TMBDDelta, self).__init__() self.testProgram = testProgram self.tokenLists = tokenLists self.tempFiles = [patchName(f,'tmp') for f,_ in self.tokenLists] self.targetFiles = [patchName(f,'ok') for f,_ in self.tokenLists] self.log = log self.numTests = 0 def writeFiles(self, changes, fileNames): assert len(fileNames) == len(self.tokenLists) byFile = [[] for i in self.tokenLists] for i,j in changes: byFile[i].append(j) for i,(file,tokens) in enumerate(self.tokenLists): f = open(fileNames[i],'w') for j in byFile[i]: f.write(tokens[j]) f.close() return byFile def test(self, changes): self.numTests += 1 byFile = self.writeFiles(changes, self.tempFiles) if self.log: print >>sys.stderr, 'TEST - ', if self.log > 1: for i,(file,_) in enumerate(self.tokenLists): indices = byFile[i] if i: sys.stderr.write('\n ') sys.stderr.write('%s:%d tokens: [' % (file,len(byFile[i]))) prev = None for j in byFile[i]: if prev is None or j != prev + 1: if prev: sys.stderr.write('%d][' % prev) sys.stderr.write(str(j)) sys.stderr.write(':') prev = j if byFile[i]: sys.stderr.write(str(byFile[i][-1])) sys.stderr.write('] ') else: print >>sys.stderr, ', '.join(['%s:%d tokens' % (file, len(byFile[i])) for i,(file,_) in enumerate(self.tokenLists)]), p = subprocess.Popen([self.testProgram] + self.tempFiles) res = p.wait() == 0 if res: self.writeFiles(changes, self.targetFiles) if self.log: print >>sys.stderr, '=> %s' % res else: if res: print '\nSUCCESS (%d tokens)' % len(changes) else: sys.stderr.write('.') return res def run(self): res = super(TMBDDelta, self).run([(i,j) for i,(file,tokens) in enumerate(self.tokenLists) for j in range(len(tokens))]) self.writeFiles(res, self.targetFiles) if not self.log: print >>sys.stderr return res def tokenBasedMultiDelta(program, files, log): # Read in the lists of tokens. tokenLists = [(file, [t.data for t in getTokens(file)]) for file in files] numTokens = sum([len(tokens) for _,tokens in tokenLists]) print "Delta on %s with %d tokens." % (', '.join(files), numTokens) tbmd = TMBDDelta(program, tokenLists, log) res = tbmd.run() print "Finished %s with %d tokens (in %d tests)." % (', '.join(tbmd.targetFiles), len(res), tbmd.numTests) def main(): from optparse import OptionParser, OptionGroup parser = OptionParser("%prog <test program> {files+}") parser.add_option("", "--debug", dest="debugLevel", help="set debug level [default %default]", action="store", type=int, default=0) (opts, args) = parser.parse_args() if len(args) <= 1: parser.error('Invalid number of arguments.') program,files = args[0],args[1:] md = tokenBasedMultiDelta(program, files, log=opts.debugLevel) if __name__ == '__main__': try: main() except KeyboardInterrupt: print >>sys.stderr,'Interrupted.' os._exit(1) # Avoid freeing our giant cache.
0
repos/DirectXShaderCompiler/tools/clang
repos/DirectXShaderCompiler/tools/clang/utils/ClangDataFormat.py
"""lldb data formatters for clang classes. Usage -- import this file in your ~/.lldbinit by adding this line: command script import /path/to/ClangDataFormat.py After that, instead of getting this: (lldb) p Tok.Loc (clang::SourceLocation) $0 = { (unsigned int) ID = 123582 } you'll get: (lldb) p Tok.Loc (clang::SourceLocation) $4 = "/usr/include/i386/_types.h:37:1" (offset: 123582, file, local) """ import lldb def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand("type summary add -F ClangDataFormat.SourceLocation_summary clang::SourceLocation") debugger.HandleCommand("type summary add -F ClangDataFormat.QualType_summary clang::QualType") debugger.HandleCommand("type summary add -F ClangDataFormat.StringRef_summary llvm::StringRef") def SourceLocation_summary(srcloc, internal_dict): return SourceLocation(srcloc).summary() def QualType_summary(qualty, internal_dict): return QualType(qualty).summary() def StringRef_summary(strref, internal_dict): return StringRef(strref).summary() class SourceLocation(object): def __init__(self, srcloc): self.srcloc = srcloc self.ID = srcloc.GetChildAtIndex(0).GetValueAsUnsigned() self.frame = srcloc.GetFrame() def offset(self): return getValueFromExpression(self.srcloc, ".getOffset()").GetValueAsUnsigned() def isInvalid(self): return self.ID == 0 def isMacro(self): return getValueFromExpression(self.srcloc, ".isMacroID()").GetValueAsUnsigned() def isLocal(self, srcmgr_path): return self.frame.EvaluateExpression("(%s).isLocalSourceLocation(%s)" % (srcmgr_path, getExpressionPath(self.srcloc))).GetValueAsUnsigned() def getPrint(self, srcmgr_path): print_str = getValueFromExpression(self.srcloc, ".printToString(%s)" % srcmgr_path) return print_str.GetSummary() def summary(self): if self.isInvalid(): return "<invalid loc>" srcmgr_path = findObjectExpressionPath("clang::SourceManager", self.frame) if srcmgr_path: return "%s (offset: %d, %s, %s)" % (self.getPrint(srcmgr_path), self.offset(), "macro" if self.isMacro() else "file", "local" if self.isLocal(srcmgr_path) else "loaded") return "(offset: %d, %s)" % (self.offset(), "macro" if self.isMacro() else "file") class QualType(object): def __init__(self, qualty): self.qualty = qualty def getAsString(self): std_str = getValueFromExpression(self.qualty, ".getAsString()") return std_str.GetSummary() def summary(self): desc = self.getAsString() if desc == '"NULL TYPE"': return "<NULL TYPE>" return desc class StringRef(object): def __init__(self, strref): self.strref = strref self.Data_value = strref.GetChildAtIndex(0) self.Length = strref.GetChildAtIndex(1).GetValueAsUnsigned() def summary(self): if self.Length == 0: return '""' data = self.Data_value.GetPointeeData(0, self.Length) error = lldb.SBError() string = data.ReadRawData(error, 0, data.GetByteSize()) if error.Fail(): return None return '"%s"' % string # Key is a (function address, type name) tuple, value is the expression path for # an object with such a type name from inside that function. FramePathMapCache = {} def findObjectExpressionPath(typename, frame): func_addr = frame.GetFunction().GetStartAddress().GetFileAddress() key = (func_addr, typename) try: return FramePathMapCache[key] except KeyError: #print "CACHE MISS" path = None obj = findObject(typename, frame) if obj: path = getExpressionPath(obj) FramePathMapCache[key] = path return path def findObject(typename, frame): def getTypename(value): # FIXME: lldb should provide something like getBaseType ty = value.GetType() if ty.IsPointerType() or ty.IsReferenceType(): return ty.GetPointeeType().GetName() return ty.GetName() def searchForType(value, searched): tyname = getTypename(value) #print "SEARCH:", getExpressionPath(value), value.GetType().GetName() if tyname == typename: return value ty = value.GetType() if not (ty.IsPointerType() or ty.IsReferenceType() or # FIXME: lldb should provide something like getCanonicalType tyname.startswith("llvm::IntrusiveRefCntPtr<") or tyname.startswith("llvm::OwningPtr<")): return None # FIXME: Hashing for SBTypes does not seem to work correctly, uses the typename instead, # and not the canonical one unfortunately. if tyname in searched: return None searched.add(tyname) for i in range(value.GetNumChildren()): child = value.GetChildAtIndex(i, 0, False) found = searchForType(child, searched) if found: return found searched = set() value_list = frame.GetVariables(True, True, True, True) for val in value_list: found = searchForType(val, searched) if found: return found if not found.TypeIsPointerType() else found.Dereference() def getValueFromExpression(val, expr): return val.GetFrame().EvaluateExpression(getExpressionPath(val) + expr) def getExpressionPath(val): stream = lldb.SBStream() val.GetExpressionPath(stream) return stream.GetData()
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/ABITest/summarize.sh
#!/bin/sh set -eu if [ $# != 1 ]; then echo "usage: $0 <num-tests>" exit 1 fi for i in $(seq 0 $1); do if (! make test.$i.report &> /dev/null); then echo "FAIL: $i"; fi; done
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/ABITest/Enumeration.py
"""Utilities for enumeration of finite and countably infinite sets. """ ### # Countable iteration # Simplifies some calculations class Aleph0(int): _singleton = None def __new__(type): if type._singleton is None: type._singleton = int.__new__(type) return type._singleton def __repr__(self): return '<aleph0>' def __str__(self): return 'inf' def __cmp__(self, b): return 1 def __sub__(self, b): raise ValueError,"Cannot subtract aleph0" __rsub__ = __sub__ def __add__(self, b): return self __radd__ = __add__ def __mul__(self, b): if b == 0: return b return self __rmul__ = __mul__ def __floordiv__(self, b): if b == 0: raise ZeroDivisionError return self __rfloordiv__ = __floordiv__ __truediv__ = __floordiv__ __rtuediv__ = __floordiv__ __div__ = __floordiv__ __rdiv__ = __floordiv__ def __pow__(self, b): if b == 0: return 1 return self aleph0 = Aleph0() def base(line): return line*(line+1)//2 def pairToN((x,y)): line,index = x+y,y return base(line)+index def getNthPairInfo(N): # Avoid various singularities if N==0: return (0,0) # Gallop to find bounds for line line = 1 next = 2 while base(next)<=N: line = next next = line << 1 # Binary search for starting line lo = line hi = line<<1 while lo + 1 != hi: #assert base(lo) <= N < base(hi) mid = (lo + hi)>>1 if base(mid)<=N: lo = mid else: hi = mid line = lo return line, N - base(line) def getNthPair(N): line,index = getNthPairInfo(N) return (line - index, index) def getNthPairBounded(N,W=aleph0,H=aleph0,useDivmod=False): """getNthPairBounded(N, W, H) -> (x, y) Return the N-th pair such that 0 <= x < W and 0 <= y < H.""" if W <= 0 or H <= 0: raise ValueError,"Invalid bounds" elif N >= W*H: raise ValueError,"Invalid input (out of bounds)" # Simple case... if W is aleph0 and H is aleph0: return getNthPair(N) # Otherwise simplify by assuming W < H if H < W: x,y = getNthPairBounded(N,H,W,useDivmod=useDivmod) return y,x if useDivmod: return N%W,N//W else: # Conceptually we want to slide a diagonal line across a # rectangle. This gives more interesting results for large # bounds than using divmod. # If in lower left, just return as usual cornerSize = base(W) if N < cornerSize: return getNthPair(N) # Otherwise if in upper right, subtract from corner if H is not aleph0: M = W*H - N - 1 if M < cornerSize: x,y = getNthPair(M) return (W-1-x,H-1-y) # Otherwise, compile line and index from number of times we # wrap. N = N - cornerSize index,offset = N%W,N//W # p = (W-1, 1+offset) + (-1,1)*index return (W-1-index, 1+offset+index) def getNthPairBoundedChecked(N,W=aleph0,H=aleph0,useDivmod=False,GNP=getNthPairBounded): x,y = GNP(N,W,H,useDivmod) assert 0 <= x < W and 0 <= y < H return x,y def getNthNTuple(N, W, H=aleph0, useLeftToRight=False): """getNthNTuple(N, W, H) -> (x_0, x_1, ..., x_W) Return the N-th W-tuple, where for 0 <= x_i < H.""" if useLeftToRight: elts = [None]*W for i in range(W): elts[i],N = getNthPairBounded(N, H) return tuple(elts) else: if W==0: return () elif W==1: return (N,) elif W==2: return getNthPairBounded(N, H, H) else: LW,RW = W//2, W - (W//2) L,R = getNthPairBounded(N, H**LW, H**RW) return (getNthNTuple(L,LW,H=H,useLeftToRight=useLeftToRight) + getNthNTuple(R,RW,H=H,useLeftToRight=useLeftToRight)) def getNthNTupleChecked(N, W, H=aleph0, useLeftToRight=False, GNT=getNthNTuple): t = GNT(N,W,H,useLeftToRight) assert len(t) == W for i in t: assert i < H return t def getNthTuple(N, maxSize=aleph0, maxElement=aleph0, useDivmod=False, useLeftToRight=False): """getNthTuple(N, maxSize, maxElement) -> x Return the N-th tuple where len(x) < maxSize and for y in x, 0 <= y < maxElement.""" # All zero sized tuples are isomorphic, don't ya know. if N == 0: return () N -= 1 if maxElement is not aleph0: if maxSize is aleph0: raise NotImplementedError,'Max element size without max size unhandled' bounds = [maxElement**i for i in range(1, maxSize+1)] S,M = getNthPairVariableBounds(N, bounds) else: S,M = getNthPairBounded(N, maxSize, useDivmod=useDivmod) return getNthNTuple(M, S+1, maxElement, useLeftToRight=useLeftToRight) def getNthTupleChecked(N, maxSize=aleph0, maxElement=aleph0, useDivmod=False, useLeftToRight=False, GNT=getNthTuple): # FIXME: maxsize is inclusive t = GNT(N,maxSize,maxElement,useDivmod,useLeftToRight) assert len(t) <= maxSize for i in t: assert i < maxElement return t def getNthPairVariableBounds(N, bounds): """getNthPairVariableBounds(N, bounds) -> (x, y) Given a finite list of bounds (which may be finite or aleph0), return the N-th pair such that 0 <= x < len(bounds) and 0 <= y < bounds[x].""" if not bounds: raise ValueError,"Invalid bounds" if not (0 <= N < sum(bounds)): raise ValueError,"Invalid input (out of bounds)" level = 0 active = range(len(bounds)) active.sort(key=lambda i: bounds[i]) prevLevel = 0 for i,index in enumerate(active): level = bounds[index] W = len(active) - i if level is aleph0: H = aleph0 else: H = level - prevLevel levelSize = W*H if N<levelSize: # Found the level idelta,delta = getNthPairBounded(N, W, H) return active[i+idelta],prevLevel+delta else: N -= levelSize prevLevel = level else: raise RuntimError,"Unexpected loop completion" def getNthPairVariableBoundsChecked(N, bounds, GNVP=getNthPairVariableBounds): x,y = GNVP(N,bounds) assert 0 <= x < len(bounds) and 0 <= y < bounds[x] return (x,y) ### def testPairs(): W = 3 H = 6 a = [[' ' for x in range(10)] for y in range(10)] b = [[' ' for x in range(10)] for y in range(10)] for i in range(min(W*H,40)): x,y = getNthPairBounded(i,W,H) x2,y2 = getNthPairBounded(i,W,H,useDivmod=True) print i,(x,y),(x2,y2) a[y][x] = '%2d'%i b[y2][x2] = '%2d'%i print '-- a --' for ln in a[::-1]: if ''.join(ln).strip(): print ' '.join(ln) print '-- b --' for ln in b[::-1]: if ''.join(ln).strip(): print ' '.join(ln) def testPairsVB(): bounds = [2,2,4,aleph0,5,aleph0] a = [[' ' for x in range(15)] for y in range(15)] b = [[' ' for x in range(15)] for y in range(15)] for i in range(min(sum(bounds),40)): x,y = getNthPairVariableBounds(i, bounds) print i,(x,y) a[y][x] = '%2d'%i print '-- a --' for ln in a[::-1]: if ''.join(ln).strip(): print ' '.join(ln) ### # Toggle to use checked versions of enumeration routines. if False: getNthPairVariableBounds = getNthPairVariableBoundsChecked getNthPairBounded = getNthPairBoundedChecked getNthNTuple = getNthNTupleChecked getNthTuple = getNthTupleChecked if __name__ == '__main__': testPairs() testPairsVB()
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/ABITest/build.sh
#!/bin/sh set -eu if [ $# != 1 ]; then echo "usage: $0 <num-tests>" exit 1 fi CPUS=2 make -j $CPUS \ $(for i in $(seq 0 $1); do echo test.$i.report; done) -k
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/ABITest/build-and-summarize-all.sh
#!/bin/sh set -eu if [ $# != 1 ]; then echo "usage: $0 <num-tests>" exit 1 fi for bits in 32 64; do for kind in return-types single-args; do echo "-- $kind-$bits --" (cd $kind-$bits && ../build-and-summarize.sh $1) done done
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/ABITest/build-and-summarize.sh
#!/bin/sh set -eu if [ $# != 1 ]; then echo "usage: $0 <num-tests>" exit 1 fi dir=$(dirname $0) $dir/build.sh $1 &> /dev/null || true ../summarize.sh $1 &> fails-x.txt cat fails-x.txt wc -l fails-x.txt
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/ABITest/TypeGen.py
"""Flexible enumeration of C types.""" from Enumeration import * # TODO: # - struct improvements (flexible arrays, packed & # unpacked, alignment) # - objective-c qualified id # - anonymous / transparent unions # - VLAs # - block types # - K&R functions # - pass arguments of different types (test extension, transparent union) # - varargs ### # Actual type types class Type: def isBitField(self): return False def isPaddingBitField(self): return False def getTypeName(self, printer): name = 'T%d' % len(printer.types) typedef = self.getTypedefDef(name, printer) printer.addDeclaration(typedef) return name class BuiltinType(Type): def __init__(self, name, size, bitFieldSize=None): self.name = name self.size = size self.bitFieldSize = bitFieldSize def isBitField(self): return self.bitFieldSize is not None def isPaddingBitField(self): return self.bitFieldSize is 0 def getBitFieldSize(self): assert self.isBitField() return self.bitFieldSize def getTypeName(self, printer): return self.name def sizeof(self): return self.size def __str__(self): return self.name class EnumType(Type): unique_id = 0 def __init__(self, index, enumerators): self.index = index self.enumerators = enumerators self.unique_id = self.__class__.unique_id self.__class__.unique_id += 1 def getEnumerators(self): result = '' for i, init in enumerate(self.enumerators): if i > 0: result = result + ', ' result = result + 'enum%dval%d_%d' % (self.index, i, self.unique_id) if init: result = result + ' = %s' % (init) return result def __str__(self): return 'enum { %s }' % (self.getEnumerators()) def getTypedefDef(self, name, printer): return 'typedef enum %s { %s } %s;'%(name, self.getEnumerators(), name) class RecordType(Type): def __init__(self, index, isUnion, fields): self.index = index self.isUnion = isUnion self.fields = fields self.name = None def __str__(self): def getField(t): if t.isBitField(): return "%s : %d;" % (t, t.getBitFieldSize()) else: return "%s;" % t return '%s { %s }'%(('struct','union')[self.isUnion], ' '.join(map(getField, self.fields))) def getTypedefDef(self, name, printer): def getField((i, t)): if t.isBitField(): if t.isPaddingBitField(): return '%s : 0;'%(printer.getTypeName(t),) else: return '%s field%d : %d;'%(printer.getTypeName(t),i, t.getBitFieldSize()) else: return '%s field%d;'%(printer.getTypeName(t),i) fields = map(getField, enumerate(self.fields)) # Name the struct for more readable LLVM IR. return 'typedef %s %s { %s } %s;'%(('struct','union')[self.isUnion], name, ' '.join(fields), name) class ArrayType(Type): def __init__(self, index, isVector, elementType, size): if isVector: # Note that for vectors, this is the size in bytes. assert size > 0 else: assert size is None or size >= 0 self.index = index self.isVector = isVector self.elementType = elementType self.size = size if isVector: eltSize = self.elementType.sizeof() assert not (self.size % eltSize) self.numElements = self.size // eltSize else: self.numElements = self.size def __str__(self): if self.isVector: return 'vector (%s)[%d]'%(self.elementType,self.size) elif self.size is not None: return '(%s)[%d]'%(self.elementType,self.size) else: return '(%s)[]'%(self.elementType,) def getTypedefDef(self, name, printer): elementName = printer.getTypeName(self.elementType) if self.isVector: return 'typedef %s %s __attribute__ ((vector_size (%d)));'%(elementName, name, self.size) else: if self.size is None: sizeStr = '' else: sizeStr = str(self.size) return 'typedef %s %s[%s];'%(elementName, name, sizeStr) class ComplexType(Type): def __init__(self, index, elementType): self.index = index self.elementType = elementType def __str__(self): return '_Complex (%s)'%(self.elementType) def getTypedefDef(self, name, printer): return 'typedef _Complex %s %s;'%(printer.getTypeName(self.elementType), name) class FunctionType(Type): def __init__(self, index, returnType, argTypes): self.index = index self.returnType = returnType self.argTypes = argTypes def __str__(self): if self.returnType is None: rt = 'void' else: rt = str(self.returnType) if not self.argTypes: at = 'void' else: at = ', '.join(map(str, self.argTypes)) return '%s (*)(%s)'%(rt, at) def getTypedefDef(self, name, printer): if self.returnType is None: rt = 'void' else: rt = str(self.returnType) if not self.argTypes: at = 'void' else: at = ', '.join(map(str, self.argTypes)) return 'typedef %s (*%s)(%s);'%(rt, name, at) ### # Type enumerators class TypeGenerator(object): def __init__(self): self.cache = {} def setCardinality(self): abstract def get(self, N): T = self.cache.get(N) if T is None: assert 0 <= N < self.cardinality T = self.cache[N] = self.generateType(N) return T def generateType(self, N): abstract class FixedTypeGenerator(TypeGenerator): def __init__(self, types): TypeGenerator.__init__(self) self.types = types self.setCardinality() def setCardinality(self): self.cardinality = len(self.types) def generateType(self, N): return self.types[N] # Factorial def fact(n): result = 1 while n > 0: result = result * n n = n - 1 return result # Compute the number of combinations (n choose k) def num_combinations(n, k): return fact(n) / (fact(k) * fact(n - k)) # Enumerate the combinations choosing k elements from the list of values def combinations(values, k): # From ActiveState Recipe 190465: Generator for permutations, # combinations, selections of a sequence if k==0: yield [] else: for i in xrange(len(values)-k+1): for cc in combinations(values[i+1:],k-1): yield [values[i]]+cc class EnumTypeGenerator(TypeGenerator): def __init__(self, values, minEnumerators, maxEnumerators): TypeGenerator.__init__(self) self.values = values self.minEnumerators = minEnumerators self.maxEnumerators = maxEnumerators self.setCardinality() def setCardinality(self): self.cardinality = 0 for num in range(self.minEnumerators, self.maxEnumerators + 1): self.cardinality += num_combinations(len(self.values), num) def generateType(self, n): # Figure out the number of enumerators in this type numEnumerators = self.minEnumerators valuesCovered = 0 while numEnumerators < self.maxEnumerators: comb = num_combinations(len(self.values), numEnumerators) if valuesCovered + comb > n: break numEnumerators = numEnumerators + 1 valuesCovered += comb # Find the requested combination of enumerators and build a # type from it. i = 0 for enumerators in combinations(self.values, numEnumerators): if i == n - valuesCovered: return EnumType(n, enumerators) i = i + 1 assert False class ComplexTypeGenerator(TypeGenerator): def __init__(self, typeGen): TypeGenerator.__init__(self) self.typeGen = typeGen self.setCardinality() def setCardinality(self): self.cardinality = self.typeGen.cardinality def generateType(self, N): return ComplexType(N, self.typeGen.get(N)) class VectorTypeGenerator(TypeGenerator): def __init__(self, typeGen, sizes): TypeGenerator.__init__(self) self.typeGen = typeGen self.sizes = tuple(map(int,sizes)) self.setCardinality() def setCardinality(self): self.cardinality = len(self.sizes)*self.typeGen.cardinality def generateType(self, N): S,T = getNthPairBounded(N, len(self.sizes), self.typeGen.cardinality) return ArrayType(N, True, self.typeGen.get(T), self.sizes[S]) class FixedArrayTypeGenerator(TypeGenerator): def __init__(self, typeGen, sizes): TypeGenerator.__init__(self) self.typeGen = typeGen self.sizes = tuple(size) self.setCardinality() def setCardinality(self): self.cardinality = len(self.sizes)*self.typeGen.cardinality def generateType(self, N): S,T = getNthPairBounded(N, len(self.sizes), self.typeGen.cardinality) return ArrayType(N, false, self.typeGen.get(T), self.sizes[S]) class ArrayTypeGenerator(TypeGenerator): def __init__(self, typeGen, maxSize, useIncomplete=False, useZero=False): TypeGenerator.__init__(self) self.typeGen = typeGen self.useIncomplete = useIncomplete self.useZero = useZero self.maxSize = int(maxSize) self.W = useIncomplete + useZero + self.maxSize self.setCardinality() def setCardinality(self): self.cardinality = self.W * self.typeGen.cardinality def generateType(self, N): S,T = getNthPairBounded(N, self.W, self.typeGen.cardinality) if self.useIncomplete: if S==0: size = None S = None else: S = S - 1 if S is not None: if self.useZero: size = S else: size = S + 1 return ArrayType(N, False, self.typeGen.get(T), size) class RecordTypeGenerator(TypeGenerator): def __init__(self, typeGen, useUnion, maxSize): TypeGenerator.__init__(self) self.typeGen = typeGen self.useUnion = bool(useUnion) self.maxSize = int(maxSize) self.setCardinality() def setCardinality(self): M = 1 + self.useUnion if self.maxSize is aleph0: S = aleph0 * self.typeGen.cardinality else: S = 0 for i in range(self.maxSize+1): S += M * (self.typeGen.cardinality ** i) self.cardinality = S def generateType(self, N): isUnion,I = False,N if self.useUnion: isUnion,I = (I&1),I>>1 fields = map(self.typeGen.get,getNthTuple(I,self.maxSize,self.typeGen.cardinality)) return RecordType(N, isUnion, fields) class FunctionTypeGenerator(TypeGenerator): def __init__(self, typeGen, useReturn, maxSize): TypeGenerator.__init__(self) self.typeGen = typeGen self.useReturn = useReturn self.maxSize = maxSize self.setCardinality() def setCardinality(self): if self.maxSize is aleph0: S = aleph0 * self.typeGen.cardinality() elif self.useReturn: S = 0 for i in range(1,self.maxSize+1+1): S += self.typeGen.cardinality ** i else: S = 0 for i in range(self.maxSize+1): S += self.typeGen.cardinality ** i self.cardinality = S def generateType(self, N): if self.useReturn: # Skip the empty tuple argIndices = getNthTuple(N+1, self.maxSize+1, self.typeGen.cardinality) retIndex,argIndices = argIndices[0],argIndices[1:] retTy = self.typeGen.get(retIndex) else: retTy = None argIndices = getNthTuple(N, self.maxSize, self.typeGen.cardinality) args = map(self.typeGen.get, argIndices) return FunctionType(N, retTy, args) class AnyTypeGenerator(TypeGenerator): def __init__(self): TypeGenerator.__init__(self) self.generators = [] self.bounds = [] self.setCardinality() self._cardinality = None def getCardinality(self): if self._cardinality is None: return aleph0 else: return self._cardinality def setCardinality(self): self.bounds = [g.cardinality for g in self.generators] self._cardinality = sum(self.bounds) cardinality = property(getCardinality, None) def addGenerator(self, g): self.generators.append(g) for i in range(100): prev = self._cardinality self._cardinality = None for g in self.generators: g.setCardinality() self.setCardinality() if (self._cardinality is aleph0) or prev==self._cardinality: break else: raise RuntimeError,"Infinite loop in setting cardinality" def generateType(self, N): index,M = getNthPairVariableBounds(N, self.bounds) return self.generators[index].get(M) def test(): fbtg = FixedTypeGenerator([BuiltinType('char', 4), BuiltinType('char', 4, 0), BuiltinType('int', 4, 5)]) fields1 = AnyTypeGenerator() fields1.addGenerator( fbtg ) fields0 = AnyTypeGenerator() fields0.addGenerator( fbtg ) # fields0.addGenerator( RecordTypeGenerator(fields1, False, 4) ) btg = FixedTypeGenerator([BuiltinType('char', 4), BuiltinType('int', 4)]) etg = EnumTypeGenerator([None, '-1', '1', '1u'], 0, 3) atg = AnyTypeGenerator() atg.addGenerator( btg ) atg.addGenerator( RecordTypeGenerator(fields0, False, 4) ) atg.addGenerator( etg ) print 'Cardinality:',atg.cardinality for i in range(100): if i == atg.cardinality: try: atg.get(i) raise RuntimeError,"Cardinality was wrong" except AssertionError: break print '%4d: %s'%(i, atg.get(i)) if __name__ == '__main__': test()
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/ABITest/ABITestGen.py
#!/usr/bin/env python from pprint import pprint import random, atexit, time from random import randrange import re from Enumeration import * from TypeGen import * #### class TypePrinter: def __init__(self, output, outputHeader=None, outputTests=None, outputDriver=None, headerName=None, info=None): self.output = output self.outputHeader = outputHeader self.outputTests = outputTests self.outputDriver = outputDriver self.writeBody = outputHeader or outputTests or outputDriver self.types = {} self.testValues = {} self.testReturnValues = {} self.layoutTests = [] self.declarations = set() if info: for f in (self.output,self.outputHeader,self.outputTests,self.outputDriver): if f: print >>f,info if self.writeBody: print >>self.output, '#include <stdio.h>\n' if self.outputTests: print >>self.outputTests, '#include <stdio.h>' print >>self.outputTests, '#include <string.h>' print >>self.outputTests, '#include <assert.h>\n' if headerName: for f in (self.output,self.outputTests,self.outputDriver): if f is not None: print >>f, '#include "%s"\n'%(headerName,) if self.outputDriver: print >>self.outputDriver, '#include <stdio.h>' print >>self.outputDriver, '#include <stdlib.h>\n' print >>self.outputDriver, 'int main(int argc, char **argv) {' print >>self.outputDriver, ' int index = -1;' print >>self.outputDriver, ' if (argc > 1) index = atoi(argv[1]);' def finish(self): if self.layoutTests: print >>self.output, 'int main(int argc, char **argv) {' print >>self.output, ' int index = -1;' print >>self.output, ' if (argc > 1) index = atoi(argv[1]);' for i,f in self.layoutTests: print >>self.output, ' if (index == -1 || index == %d)' % i print >>self.output, ' %s();' % f print >>self.output, ' return 0;' print >>self.output, '}' if self.outputDriver: print >>self.outputDriver, ' printf("DONE\\n");' print >>self.outputDriver, ' return 0;' print >>self.outputDriver, '}' def addDeclaration(self, decl): if decl in self.declarations: return False self.declarations.add(decl) if self.outputHeader: print >>self.outputHeader, decl else: print >>self.output, decl if self.outputTests: print >>self.outputTests, decl return True def getTypeName(self, T): name = self.types.get(T) if name is None: # Reserve slot self.types[T] = None self.types[T] = name = T.getTypeName(self) return name def writeLayoutTest(self, i, ty): tyName = self.getTypeName(ty) tyNameClean = tyName.replace(' ','_').replace('*','star') fnName = 'test_%s' % tyNameClean print >>self.output,'void %s(void) {' % fnName self.printSizeOfType(' %s'%fnName, tyName, ty, self.output) self.printAlignOfType(' %s'%fnName, tyName, ty, self.output) self.printOffsetsOfType(' %s'%fnName, tyName, ty, self.output) print >>self.output,'}' print >>self.output self.layoutTests.append((i,fnName)) def writeFunction(self, i, FT): args = ', '.join(['%s arg%d'%(self.getTypeName(t),i) for i,t in enumerate(FT.argTypes)]) if not args: args = 'void' if FT.returnType is None: retvalName = None retvalTypeName = 'void' else: retvalTypeName = self.getTypeName(FT.returnType) if self.writeBody or self.outputTests: retvalName = self.getTestReturnValue(FT.returnType) fnName = 'fn%d'%(FT.index,) if self.outputHeader: print >>self.outputHeader,'%s %s(%s);'%(retvalTypeName, fnName, args) elif self.outputTests: print >>self.outputTests,'%s %s(%s);'%(retvalTypeName, fnName, args) print >>self.output,'%s %s(%s)'%(retvalTypeName, fnName, args), if self.writeBody: print >>self.output, '{' for i,t in enumerate(FT.argTypes): self.printValueOfType(' %s'%fnName, 'arg%d'%i, t) if retvalName is not None: print >>self.output, ' return %s;'%(retvalName,) print >>self.output, '}' else: print >>self.output, '{}' print >>self.output if self.outputDriver: print >>self.outputDriver, ' if (index == -1 || index == %d) {' % i print >>self.outputDriver, ' extern void test_%s(void);' % fnName print >>self.outputDriver, ' test_%s();' % fnName print >>self.outputDriver, ' }' if self.outputTests: if self.outputHeader: print >>self.outputHeader, 'void test_%s(void);'%(fnName,) if retvalName is None: retvalTests = None else: retvalTests = self.getTestValuesArray(FT.returnType) tests = map(self.getTestValuesArray, FT.argTypes) print >>self.outputTests, 'void test_%s(void) {'%(fnName,) if retvalTests is not None: print >>self.outputTests, ' printf("%s: testing return.\\n");'%(fnName,) print >>self.outputTests, ' for (int i=0; i<%d; ++i) {'%(retvalTests[1],) args = ', '.join(['%s[%d]'%(t,randrange(l)) for t,l in tests]) print >>self.outputTests, ' %s RV;'%(retvalTypeName,) print >>self.outputTests, ' %s = %s[i];'%(retvalName, retvalTests[0]) print >>self.outputTests, ' RV = %s(%s);'%(fnName, args) self.printValueOfType(' %s_RV'%fnName, 'RV', FT.returnType, output=self.outputTests, indent=4) self.checkTypeValues('RV', '%s[i]' % retvalTests[0], FT.returnType, output=self.outputTests, indent=4) print >>self.outputTests, ' }' if tests: print >>self.outputTests, ' printf("%s: testing arguments.\\n");'%(fnName,) for i,(array,length) in enumerate(tests): for j in range(length): args = ['%s[%d]'%(t,randrange(l)) for t,l in tests] args[i] = '%s[%d]'%(array,j) print >>self.outputTests, ' %s(%s);'%(fnName, ', '.join(args),) print >>self.outputTests, '}' def getTestReturnValue(self, type): typeName = self.getTypeName(type) info = self.testReturnValues.get(typeName) if info is None: name = '%s_retval'%(typeName.replace(' ','_').replace('*','star'),) print >>self.output, '%s %s;'%(typeName,name) if self.outputHeader: print >>self.outputHeader, 'extern %s %s;'%(typeName,name) elif self.outputTests: print >>self.outputTests, 'extern %s %s;'%(typeName,name) info = self.testReturnValues[typeName] = name return info def getTestValuesArray(self, type): typeName = self.getTypeName(type) info = self.testValues.get(typeName) if info is None: name = '%s_values'%(typeName.replace(' ','_').replace('*','star'),) print >>self.outputTests, 'static %s %s[] = {'%(typeName,name) length = 0 for item in self.getTestValues(type): print >>self.outputTests, '\t%s,'%(item,) length += 1 print >>self.outputTests,'};' info = self.testValues[typeName] = (name,length) return info def getTestValues(self, t): if isinstance(t, BuiltinType): if t.name=='float': for i in ['0.0','-1.0','1.0']: yield i+'f' elif t.name=='double': for i in ['0.0','-1.0','1.0']: yield i elif t.name in ('void *'): yield '(void*) 0' yield '(void*) -1' else: yield '(%s) 0'%(t.name,) yield '(%s) -1'%(t.name,) yield '(%s) 1'%(t.name,) elif isinstance(t, EnumType): for i in range(0, len(t.enumerators)): yield 'enum%dval%d_%d' % (t.index, i, t.unique_id) elif isinstance(t, RecordType): nonPadding = [f for f in t.fields if not f.isPaddingBitField()] if not nonPadding: yield '{ }' return # FIXME: Use designated initializers to access non-first # fields of unions. if t.isUnion: for v in self.getTestValues(nonPadding[0]): yield '{ %s }' % v return fieldValues = map(list, map(self.getTestValues, nonPadding)) for i,values in enumerate(fieldValues): for v in values: elements = map(random.choice,fieldValues) elements[i] = v yield '{ %s }'%(', '.join(elements)) elif isinstance(t, ComplexType): for t in self.getTestValues(t.elementType): yield '%s + %s * 1i'%(t,t) elif isinstance(t, ArrayType): values = list(self.getTestValues(t.elementType)) if not values: yield '{ }' for i in range(t.numElements): for v in values: elements = [random.choice(values) for i in range(t.numElements)] elements[i] = v yield '{ %s }'%(', '.join(elements)) else: raise NotImplementedError,'Cannot make tests values of type: "%s"'%(t,) def printSizeOfType(self, prefix, name, t, output=None, indent=2): print >>output, '%*sprintf("%s: sizeof(%s) = %%ld\\n", (long)sizeof(%s));'%(indent, '', prefix, name, name) def printAlignOfType(self, prefix, name, t, output=None, indent=2): print >>output, '%*sprintf("%s: __alignof__(%s) = %%ld\\n", (long)__alignof__(%s));'%(indent, '', prefix, name, name) def printOffsetsOfType(self, prefix, name, t, output=None, indent=2): if isinstance(t, RecordType): for i,f in enumerate(t.fields): if f.isBitField(): continue fname = 'field%d' % i print >>output, '%*sprintf("%s: __builtin_offsetof(%s, %s) = %%ld\\n", (long)__builtin_offsetof(%s, %s));'%(indent, '', prefix, name, fname, name, fname) def printValueOfType(self, prefix, name, t, output=None, indent=2): if output is None: output = self.output if isinstance(t, BuiltinType): value_expr = name if t.name.split(' ')[-1] == '_Bool': # Hack to work around PR5579. value_expr = "%s ? 2 : 0" % name if t.name.endswith('long long'): code = 'lld' elif t.name.endswith('long'): code = 'ld' elif t.name.split(' ')[-1] in ('_Bool','char','short', 'int','unsigned'): code = 'd' elif t.name in ('float','double'): code = 'f' elif t.name == 'long double': code = 'Lf' else: code = 'p' print >>output, '%*sprintf("%s: %s = %%%s\\n", %s);'%( indent, '', prefix, name, code, value_expr) elif isinstance(t, EnumType): print >>output, '%*sprintf("%s: %s = %%d\\n", %s);'%(indent, '', prefix, name, name) elif isinstance(t, RecordType): if not t.fields: print >>output, '%*sprintf("%s: %s (empty)\\n");'%(indent, '', prefix, name) for i,f in enumerate(t.fields): if f.isPaddingBitField(): continue fname = '%s.field%d'%(name,i) self.printValueOfType(prefix, fname, f, output=output, indent=indent) elif isinstance(t, ComplexType): self.printValueOfType(prefix, '(__real %s)'%name, t.elementType, output=output,indent=indent) self.printValueOfType(prefix, '(__imag %s)'%name, t.elementType, output=output,indent=indent) elif isinstance(t, ArrayType): for i in range(t.numElements): # Access in this fashion as a hackish way to portably # access vectors. if t.isVector: self.printValueOfType(prefix, '((%s*) &%s)[%d]'%(t.elementType,name,i), t.elementType, output=output,indent=indent) else: self.printValueOfType(prefix, '%s[%d]'%(name,i), t.elementType, output=output,indent=indent) else: raise NotImplementedError,'Cannot print value of type: "%s"'%(t,) def checkTypeValues(self, nameLHS, nameRHS, t, output=None, indent=2): prefix = 'foo' if output is None: output = self.output if isinstance(t, BuiltinType): print >>output, '%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS) elif isinstance(t, EnumType): print >>output, '%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS) elif isinstance(t, RecordType): for i,f in enumerate(t.fields): if f.isPaddingBitField(): continue self.checkTypeValues('%s.field%d'%(nameLHS,i), '%s.field%d'%(nameRHS,i), f, output=output, indent=indent) if t.isUnion: break elif isinstance(t, ComplexType): self.checkTypeValues('(__real %s)'%nameLHS, '(__real %s)'%nameRHS, t.elementType, output=output,indent=indent) self.checkTypeValues('(__imag %s)'%nameLHS, '(__imag %s)'%nameRHS, t.elementType, output=output,indent=indent) elif isinstance(t, ArrayType): for i in range(t.numElements): # Access in this fashion as a hackish way to portably # access vectors. if t.isVector: self.checkTypeValues('((%s*) &%s)[%d]'%(t.elementType,nameLHS,i), '((%s*) &%s)[%d]'%(t.elementType,nameRHS,i), t.elementType, output=output,indent=indent) else: self.checkTypeValues('%s[%d]'%(nameLHS,i), '%s[%d]'%(nameRHS,i), t.elementType, output=output,indent=indent) else: raise NotImplementedError,'Cannot print value of type: "%s"'%(t,) import sys def main(): from optparse import OptionParser, OptionGroup parser = OptionParser("%prog [options] {indices}") parser.add_option("", "--mode", dest="mode", help="autogeneration mode (random or linear) [default %default]", type='choice', choices=('random','linear'), default='linear') parser.add_option("", "--count", dest="count", help="autogenerate COUNT functions according to MODE", type=int, default=0) parser.add_option("", "--min", dest="minIndex", metavar="N", help="start autogeneration with the Nth function type [default %default]", type=int, default=0) parser.add_option("", "--max", dest="maxIndex", metavar="N", help="maximum index for random autogeneration [default %default]", type=int, default=10000000) parser.add_option("", "--seed", dest="seed", help="random number generator seed [default %default]", type=int, default=1) parser.add_option("", "--use-random-seed", dest="useRandomSeed", help="use random value for initial random number generator seed", action='store_true', default=False) parser.add_option("", "--skip", dest="skipTests", help="add a test index to skip", type=int, action='append', default=[]) parser.add_option("-o", "--output", dest="output", metavar="FILE", help="write output to FILE [default %default]", type=str, default='-') parser.add_option("-O", "--output-header", dest="outputHeader", metavar="FILE", help="write header file for output to FILE [default %default]", type=str, default=None) parser.add_option("-T", "--output-tests", dest="outputTests", metavar="FILE", help="write function tests to FILE [default %default]", type=str, default=None) parser.add_option("-D", "--output-driver", dest="outputDriver", metavar="FILE", help="write test driver to FILE [default %default]", type=str, default=None) parser.add_option("", "--test-layout", dest="testLayout", metavar="FILE", help="test structure layout", action='store_true', default=False) group = OptionGroup(parser, "Type Enumeration Options") # Builtins - Ints group.add_option("", "--no-char", dest="useChar", help="do not generate char types", action="store_false", default=True) group.add_option("", "--no-short", dest="useShort", help="do not generate short types", action="store_false", default=True) group.add_option("", "--no-int", dest="useInt", help="do not generate int types", action="store_false", default=True) group.add_option("", "--no-long", dest="useLong", help="do not generate long types", action="store_false", default=True) group.add_option("", "--no-long-long", dest="useLongLong", help="do not generate long long types", action="store_false", default=True) group.add_option("", "--no-unsigned", dest="useUnsigned", help="do not generate unsigned integer types", action="store_false", default=True) # Other builtins group.add_option("", "--no-bool", dest="useBool", help="do not generate bool types", action="store_false", default=True) group.add_option("", "--no-float", dest="useFloat", help="do not generate float types", action="store_false", default=True) group.add_option("", "--no-double", dest="useDouble", help="do not generate double types", action="store_false", default=True) group.add_option("", "--no-long-double", dest="useLongDouble", help="do not generate long double types", action="store_false", default=True) group.add_option("", "--no-void-pointer", dest="useVoidPointer", help="do not generate void* types", action="store_false", default=True) # Enumerations group.add_option("", "--no-enums", dest="useEnum", help="do not generate enum types", action="store_false", default=True) # Derived types group.add_option("", "--no-array", dest="useArray", help="do not generate record types", action="store_false", default=True) group.add_option("", "--no-complex", dest="useComplex", help="do not generate complex types", action="store_false", default=True) group.add_option("", "--no-record", dest="useRecord", help="do not generate record types", action="store_false", default=True) group.add_option("", "--no-union", dest="recordUseUnion", help="do not generate union types", action="store_false", default=True) group.add_option("", "--no-vector", dest="useVector", help="do not generate vector types", action="store_false", default=True) group.add_option("", "--no-bit-field", dest="useBitField", help="do not generate bit-field record members", action="store_false", default=True) group.add_option("", "--no-builtins", dest="useBuiltins", help="do not use any types", action="store_false", default=True) # Tuning group.add_option("", "--no-function-return", dest="functionUseReturn", help="do not generate return types for functions", action="store_false", default=True) group.add_option("", "--vector-types", dest="vectorTypes", help="comma separated list of vector types (e.g., v2i32) [default %default]", action="store", type=str, default='v2i16, v1i64, v2i32, v4i16, v8i8, v2f32, v2i64, v4i32, v8i16, v16i8, v2f64, v4f32, v16f32', metavar="N") group.add_option("", "--bit-fields", dest="bitFields", help="comma separated list 'type:width' bit-field specifiers [default %default]", action="store", type=str, default=( "char:0,char:4,int:0,unsigned:1,int:1,int:4,int:13,int:24")) group.add_option("", "--max-args", dest="functionMaxArgs", help="maximum number of arguments per function [default %default]", action="store", type=int, default=4, metavar="N") group.add_option("", "--max-array", dest="arrayMaxSize", help="maximum array size [default %default]", action="store", type=int, default=4, metavar="N") group.add_option("", "--max-record", dest="recordMaxSize", help="maximum number of fields per record [default %default]", action="store", type=int, default=4, metavar="N") group.add_option("", "--max-record-depth", dest="recordMaxDepth", help="maximum nested structure depth [default %default]", action="store", type=int, default=None, metavar="N") parser.add_option_group(group) (opts, args) = parser.parse_args() if not opts.useRandomSeed: random.seed(opts.seed) # Construct type generator builtins = [] if opts.useBuiltins: ints = [] if opts.useChar: ints.append(('char',1)) if opts.useShort: ints.append(('short',2)) if opts.useInt: ints.append(('int',4)) # FIXME: Wrong size. if opts.useLong: ints.append(('long',4)) if opts.useLongLong: ints.append(('long long',8)) if opts.useUnsigned: ints = ([('unsigned %s'%i,s) for i,s in ints] + [('signed %s'%i,s) for i,s in ints]) builtins.extend(ints) if opts.useBool: builtins.append(('_Bool',1)) if opts.useFloat: builtins.append(('float',4)) if opts.useDouble: builtins.append(('double',8)) if opts.useLongDouble: builtins.append(('long double',16)) # FIXME: Wrong size. if opts.useVoidPointer: builtins.append(('void*',4)) btg = FixedTypeGenerator([BuiltinType(n,s) for n,s in builtins]) bitfields = [] for specifier in opts.bitFields.split(','): if not specifier.strip(): continue name,width = specifier.strip().split(':', 1) bitfields.append(BuiltinType(name,None,int(width))) bftg = FixedTypeGenerator(bitfields) charType = BuiltinType('char',1) shortType = BuiltinType('short',2) intType = BuiltinType('int',4) longlongType = BuiltinType('long long',8) floatType = BuiltinType('float',4) doubleType = BuiltinType('double',8) sbtg = FixedTypeGenerator([charType, intType, floatType, doubleType]) atg = AnyTypeGenerator() artg = AnyTypeGenerator() def makeGenerator(atg, subgen, subfieldgen, useRecord, useArray, useBitField): atg.addGenerator(btg) if useBitField and opts.useBitField: atg.addGenerator(bftg) if useRecord and opts.useRecord: assert subgen atg.addGenerator(RecordTypeGenerator(subfieldgen, opts.recordUseUnion, opts.recordMaxSize)) if opts.useComplex: # FIXME: Allow overriding builtins here atg.addGenerator(ComplexTypeGenerator(sbtg)) if useArray and opts.useArray: assert subgen atg.addGenerator(ArrayTypeGenerator(subgen, opts.arrayMaxSize)) if opts.useVector: vTypes = [] for i,t in enumerate(opts.vectorTypes.split(',')): m = re.match('v([1-9][0-9]*)([if][1-9][0-9]*)', t.strip()) if not m: parser.error('Invalid vector type: %r' % t) count,kind = m.groups() count = int(count) type = { 'i8' : charType, 'i16' : shortType, 'i32' : intType, 'i64' : longlongType, 'f32' : floatType, 'f64' : doubleType, }.get(kind) if not type: parser.error('Invalid vector type: %r' % t) vTypes.append(ArrayType(i, True, type, count * type.size)) atg.addGenerator(FixedTypeGenerator(vTypes)) if opts.useEnum: atg.addGenerator(EnumTypeGenerator([None, '-1', '1', '1u'], 1, 4)) if opts.recordMaxDepth is None: # Fully recursive, just avoid top-level arrays. subFTG = AnyTypeGenerator() subTG = AnyTypeGenerator() atg = AnyTypeGenerator() makeGenerator(subFTG, atg, atg, True, True, True) makeGenerator(subTG, atg, subFTG, True, True, False) makeGenerator(atg, subTG, subFTG, True, False, False) else: # Make a chain of type generators, each builds smaller # structures. base = AnyTypeGenerator() fbase = AnyTypeGenerator() makeGenerator(base, None, None, False, False, False) makeGenerator(fbase, None, None, False, False, True) for i in range(opts.recordMaxDepth): n = AnyTypeGenerator() fn = AnyTypeGenerator() makeGenerator(n, base, fbase, True, True, False) makeGenerator(fn, base, fbase, True, True, True) base = n fbase = fn atg = AnyTypeGenerator() makeGenerator(atg, base, fbase, True, False, False) if opts.testLayout: ftg = atg else: ftg = FunctionTypeGenerator(atg, opts.functionUseReturn, opts.functionMaxArgs) # Override max,min,count if finite if opts.maxIndex is None: if ftg.cardinality is aleph0: opts.maxIndex = 10000000 else: opts.maxIndex = ftg.cardinality opts.maxIndex = min(opts.maxIndex, ftg.cardinality) opts.minIndex = max(0,min(opts.maxIndex-1, opts.minIndex)) if not opts.mode=='random': opts.count = min(opts.count, opts.maxIndex-opts.minIndex) if opts.output=='-': output = sys.stdout else: output = open(opts.output,'w') atexit.register(lambda: output.close()) outputHeader = None if opts.outputHeader: outputHeader = open(opts.outputHeader,'w') atexit.register(lambda: outputHeader.close()) outputTests = None if opts.outputTests: outputTests = open(opts.outputTests,'w') atexit.register(lambda: outputTests.close()) outputDriver = None if opts.outputDriver: outputDriver = open(opts.outputDriver,'w') atexit.register(lambda: outputDriver.close()) info = '' info += '// %s\n'%(' '.join(sys.argv),) info += '// Generated: %s\n'%(time.strftime('%Y-%m-%d %H:%M'),) info += '// Cardinality of function generator: %s\n'%(ftg.cardinality,) info += '// Cardinality of type generator: %s\n'%(atg.cardinality,) if opts.testLayout: info += '\n#include <stdio.h>' P = TypePrinter(output, outputHeader=outputHeader, outputTests=outputTests, outputDriver=outputDriver, headerName=opts.outputHeader, info=info) def write(N): try: FT = ftg.get(N) except RuntimeError,e: if e.args[0]=='maximum recursion depth exceeded': print >>sys.stderr,'WARNING: Skipped %d, recursion limit exceeded (bad arguments?)'%(N,) return raise if opts.testLayout: P.writeLayoutTest(N, FT) else: P.writeFunction(N, FT) if args: [write(int(a)) for a in args] skipTests = set(opts.skipTests) for i in range(opts.count): if opts.mode=='linear': index = opts.minIndex + i else: index = opts.minIndex + int((opts.maxIndex-opts.minIndex) * random.random()) if index in skipTests: continue write(index) P.finish() if __name__=='__main__': main()
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/check_cfc/setup.py
"""For use on Windows. Run with: python.exe setup.py py2exe """ from distutils.core import setup try: import py2exe except ImportError: import platform import sys if platform.system() == 'Windows': print "Could not find py2exe. Please install then run setup.py py2exe." raise else: print "setup.py only required on Windows." sys.exit(1) setup( console=['check_cfc.py'], name="Check CFC", description='Check Compile Flow Consistency' )
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/check_cfc/test_check_cfc.py
#!/usr/bin/env python2.7 """Test internal functions within check_cfc.py.""" import check_cfc import os import platform import unittest class TestCheckCFC(unittest.TestCase): def test_flip_dash_g(self): self.assertIn('-g', check_cfc.flip_dash_g(['clang', '-c'])) self.assertNotIn('-g', check_cfc.flip_dash_g(['clang', '-c', '-g'])) self.assertNotIn( '-g', check_cfc.flip_dash_g(['clang', '-g', '-c', '-g'])) def test_remove_dir_from_path(self): bin_path = r'/usr/bin' space_path = r'/home/user/space in path' superstring_path = r'/usr/bin/local' # Test removing last thing in path self.assertNotIn( bin_path, check_cfc.remove_dir_from_path(bin_path, bin_path)) # Test removing one entry and leaving others # Also tests removing repeated path path_var = os.pathsep.join( [superstring_path, bin_path, space_path, bin_path]) stripped_path_var = check_cfc.remove_dir_from_path(path_var, bin_path) self.assertIn(superstring_path, stripped_path_var) self.assertNotIn(bin_path, stripped_path_var.split(os.pathsep)) self.assertIn(space_path, stripped_path_var) # Test removing non-canonical path self.assertNotIn(r'/usr//bin', check_cfc.remove_dir_from_path(r'/usr//bin', bin_path)) if platform == 'Windows': # Windows is case insensitive so should remove a different case # path self.assertNotIn( bin_path, check_cfc.remove_dir_from_path(path_var, r'/USR/BIN')) else: # Case sensitive so will not remove different case path self.assertIn( bin_path, check_cfc.remove_dir_from_path(path_var, r'/USR/BIN')) def test_is_output_specified(self): self.assertTrue( check_cfc.is_output_specified(['clang', '-o', 'test.o'])) self.assertTrue(check_cfc.is_output_specified(['clang', '-otest.o'])) self.assertFalse( check_cfc.is_output_specified(['clang', '-gline-tables-only'])) # Not specified for implied output file name self.assertFalse(check_cfc.is_output_specified(['clang', 'test.c'])) def test_get_output_file(self): self.assertEqual( check_cfc.get_output_file(['clang', '-o', 'test.o']), 'test.o') self.assertEqual( check_cfc.get_output_file(['clang', '-otest.o']), 'test.o') self.assertIsNone( check_cfc.get_output_file(['clang', '-gline-tables-only'])) # Can't get output file if more than one input file self.assertIsNone( check_cfc.get_output_file(['clang', '-c', 'test.cpp', 'test2.cpp'])) # No output file specified self.assertIsNone(check_cfc.get_output_file(['clang', '-c', 'test.c'])) def test_derive_output_file(self): # Test getting implicit output file self.assertEqual( check_cfc.derive_output_file(['clang', '-c', 'test.c']), 'test.o') self.assertEqual( check_cfc.derive_output_file(['clang', '-c', 'test.cpp']), 'test.o') self.assertIsNone(check_cfc.derive_output_file(['clang', '--version'])) def test_is_normal_compile(self): self.assertTrue(check_cfc.is_normal_compile( ['clang', '-c', 'test.cpp', '-o', 'test2.o'])) self.assertTrue( check_cfc.is_normal_compile(['clang', '-c', 'test.cpp'])) # Outputting bitcode is not a normal compile self.assertFalse( check_cfc.is_normal_compile(['clang', '-c', 'test.cpp', '-flto'])) self.assertFalse( check_cfc.is_normal_compile(['clang', '-c', 'test.cpp', '-emit-llvm'])) # Outputting preprocessed output or assembly is not a normal compile self.assertFalse( check_cfc.is_normal_compile(['clang', '-E', 'test.cpp', '-o', 'test.ii'])) self.assertFalse( check_cfc.is_normal_compile(['clang', '-S', 'test.cpp', '-o', 'test.s'])) # Input of preprocessed or assembly is not a "normal compile" self.assertFalse( check_cfc.is_normal_compile(['clang', '-c', 'test.s', '-o', 'test.o'])) self.assertFalse( check_cfc.is_normal_compile(['clang', '-c', 'test.ii', '-o', 'test.o'])) # Specifying --version and -c is not a normal compile self.assertFalse( check_cfc.is_normal_compile(['clang', '-c', 'test.cpp', '--version'])) self.assertFalse( check_cfc.is_normal_compile(['clang', '-c', 'test.cpp', '--help'])) # Outputting dependency files is not a normal compile self.assertFalse( check_cfc.is_normal_compile(['clang', '-c', '-M', 'test.cpp'])) self.assertFalse( check_cfc.is_normal_compile(['clang', '-c', '-MM', 'test.cpp'])) # Creating a dependency file as a side effect still outputs an object file self.assertTrue( check_cfc.is_normal_compile(['clang', '-c', '-MD', 'test.cpp'])) self.assertTrue( check_cfc.is_normal_compile(['clang', '-c', '-MMD', 'test.cpp'])) def test_replace_output_file(self): self.assertEqual(check_cfc.replace_output_file( ['clang', '-o', 'test.o'], 'testg.o'), ['clang', '-o', 'testg.o']) self.assertEqual(check_cfc.replace_output_file( ['clang', '-otest.o'], 'testg.o'), ['clang', '-otestg.o']) with self.assertRaises(Exception): check_cfc.replace_output_file(['clang'], 'testg.o') def test_add_output_file(self): self.assertEqual(check_cfc.add_output_file( ['clang'], 'testg.o'), ['clang', '-o', 'testg.o']) def test_set_output_file(self): # Test output not specified self.assertEqual( check_cfc.set_output_file(['clang'], 'test.o'), ['clang', '-o', 'test.o']) # Test output is specified self.assertEqual(check_cfc.set_output_file( ['clang', '-o', 'test.o'], 'testb.o'), ['clang', '-o', 'testb.o']) def test_get_input_file(self): # No input file self.assertIsNone(check_cfc.get_input_file(['clang'])) # Input C file self.assertEqual( check_cfc.get_input_file(['clang', 'test.c']), 'test.c') # Input C++ file self.assertEqual( check_cfc.get_input_file(['clang', 'test.cpp']), 'test.cpp') # Multiple input files self.assertIsNone( check_cfc.get_input_file(['clang', 'test.c', 'test2.cpp'])) self.assertIsNone( check_cfc.get_input_file(['clang', 'test.c', 'test2.c'])) # Don't handle preprocessed files self.assertIsNone(check_cfc.get_input_file(['clang', 'test.i'])) self.assertIsNone(check_cfc.get_input_file(['clang', 'test.ii'])) # Test identifying input file with quotes self.assertEqual( check_cfc.get_input_file(['clang', '"test.c"']), '"test.c"') self.assertEqual( check_cfc.get_input_file(['clang', "'test.c'"]), "'test.c'") # Test multiple quotes self.assertEqual( check_cfc.get_input_file(['clang', "\"'test.c'\""]), "\"'test.c'\"") def test_set_input_file(self): self.assertEqual(check_cfc.set_input_file( ['clang', 'test.c'], 'test.s'), ['clang', 'test.s']) if __name__ == '__main__': unittest.main()
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/check_cfc/check_cfc.py
#!/usr/bin/env python2.7 """Check CFC - Check Compile Flow Consistency This is a compiler wrapper for testing that code generation is consistent with different compilation processes. It checks that code is not unduly affected by compiler options or other changes which should not have side effects. To use: -Ensure that the compiler under test (i.e. clang, clang++) is on the PATH -On Linux copy this script to the name of the compiler e.g. cp check_cfc.py clang && cp check_cfc.py clang++ -On Windows use setup.py to generate check_cfc.exe and copy that to clang.exe and clang++.exe -Enable the desired checks in check_cfc.cfg (in the same directory as the wrapper) e.g. [Checks] dash_g_no_change = true dash_s_no_change = false -The wrapper can be run using its absolute path or added to PATH before the compiler under test e.g. export PATH=<path to check_cfc>:$PATH -Compile as normal. The wrapper intercepts normal -c compiles and will return non-zero if the check fails. e.g. $ clang -c test.cpp Code difference detected with -g --- /tmp/tmp5nv893.o +++ /tmp/tmp6Vwjnc.o @@ -1 +1 @@ - 0: 48 8b 05 51 0b 20 00 mov 0x200b51(%rip),%rax + 0: 48 39 3d 51 0b 20 00 cmp %rdi,0x200b51(%rip) -To run LNT with Check CFC specify the absolute path to the wrapper to the --cc and --cxx options e.g. lnt runtest nt --cc <path to check_cfc>/clang \\ --cxx <path to check_cfc>/clang++ ... To add a new check: -Create a new subclass of WrapperCheck -Implement the perform_check() method. This should perform the alternate compile and do the comparison. -Add the new check to check_cfc.cfg. The check has the same name as the subclass. """ from __future__ import print_function import imp import os import platform import shutil import subprocess import sys import tempfile import ConfigParser import io import obj_diff def is_windows(): """Returns True if running on Windows.""" return platform.system() == 'Windows' class WrapperStepException(Exception): """Exception type to be used when a step other than the original compile fails.""" def __init__(self, msg, stdout, stderr): self.msg = msg self.stdout = stdout self.stderr = stderr class WrapperCheckException(Exception): """Exception type to be used when a comparison check fails.""" def __init__(self, msg): self.msg = msg def main_is_frozen(): """Returns True when running as a py2exe executable.""" return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") or # old py2exe imp.is_frozen("__main__")) # tools/freeze def get_main_dir(): """Get the directory that the script or executable is located in.""" if main_is_frozen(): return os.path.dirname(sys.executable) return os.path.dirname(sys.argv[0]) def remove_dir_from_path(path_var, directory): """Remove the specified directory from path_var, a string representing PATH""" pathlist = path_var.split(os.pathsep) norm_directory = os.path.normpath(os.path.normcase(directory)) pathlist = filter(lambda x: os.path.normpath( os.path.normcase(x)) != norm_directory, pathlist) return os.pathsep.join(pathlist) def path_without_wrapper(): """Returns the PATH variable modified to remove the path to this program.""" scriptdir = get_main_dir() path = os.environ['PATH'] return remove_dir_from_path(path, scriptdir) def flip_dash_g(args): """Search for -g in args. If it exists then return args without. If not then add it.""" if '-g' in args: # Return args without any -g return [x for x in args if x != '-g'] else: # No -g, add one return args + ['-g'] def derive_output_file(args): """Derive output file from the input file (if just one) or None otherwise.""" infile = get_input_file(args) if infile is None: return None else: return '{}.o'.format(os.path.splitext(infile)[0]) def get_output_file(args): """Return the output file specified by this command or None if not specified.""" grabnext = False for arg in args: if grabnext: return arg if arg == '-o': # Specified as a separate arg grabnext = True elif arg.startswith('-o'): # Specified conjoined with -o return arg[2:] assert grabnext == False return None def is_output_specified(args): """Return true is output file is specified in args.""" return get_output_file(args) is not None def replace_output_file(args, new_name): """Replaces the specified name of an output file with the specified name. Assumes that the output file name is specified in the command line args.""" replaceidx = None attached = False for idx, val in enumerate(args): if val == '-o': replaceidx = idx + 1 attached = False elif val.startswith('-o'): replaceidx = idx attached = True if replaceidx is None: raise Exception replacement = new_name if attached == True: replacement = '-o' + new_name args[replaceidx] = replacement return args def add_output_file(args, output_file): """Append an output file to args, presuming not already specified.""" return args + ['-o', output_file] def set_output_file(args, output_file): """Set the output file within the arguments. Appends or replaces as appropriate.""" if is_output_specified(args): args = replace_output_file(args, output_file) else: args = add_output_file(args, output_file) return args gSrcFileSuffixes = ('.c', '.cpp', '.cxx', '.c++', '.cp', '.cc') def get_input_file(args): """Return the input file string if it can be found (and there is only one).""" inputFiles = list() for arg in args: testarg = arg quotes = ('"', "'") while testarg.endswith(quotes): testarg = testarg[:-1] testarg = os.path.normcase(testarg) # Test if it is a source file if testarg.endswith(gSrcFileSuffixes): inputFiles.append(arg) if len(inputFiles) == 1: return inputFiles[0] else: return None def set_input_file(args, input_file): """Replaces the input file with that specified.""" infile = get_input_file(args) if infile: infile_idx = args.index(infile) args[infile_idx] = input_file return args else: # Could not find input file assert False def is_normal_compile(args): """Check if this is a normal compile which will output an object file rather than a preprocess or link. args is a list of command line arguments.""" compile_step = '-c' in args # Bitcode cannot be disassembled in the same way bitcode = '-flto' in args or '-emit-llvm' in args # Version and help are queries of the compiler and override -c if specified query = '--version' in args or '--help' in args # Options to output dependency files for make dependency = '-M' in args or '-MM' in args # Check if the input is recognised as a source file (this may be too # strong a restriction) input_is_valid = bool(get_input_file(args)) return compile_step and not bitcode and not query and not dependency and input_is_valid def run_step(command, my_env, error_on_failure): """Runs a step of the compilation. Reports failure as exception.""" # Need to use shell=True on Windows as Popen won't use PATH otherwise. p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env, shell=is_windows()) (stdout, stderr) = p.communicate() if p.returncode != 0: raise WrapperStepException(error_on_failure, stdout, stderr) def get_temp_file_name(suffix): """Get a temporary file name with a particular suffix. Let the caller be reponsible for deleting it.""" tf = tempfile.NamedTemporaryFile(suffix=suffix, delete=False) tf.close() return tf.name class WrapperCheck(object): """Base class for a check. Subclass this to add a check.""" def __init__(self, output_file_a): """Record the base output file that will be compared against.""" self._output_file_a = output_file_a def perform_check(self, arguments, my_env): """Override this to perform the modified compilation and required checks.""" raise NotImplementedError("Please Implement this method") class dash_g_no_change(WrapperCheck): def perform_check(self, arguments, my_env): """Check if different code is generated with/without the -g flag.""" output_file_b = get_temp_file_name('.o') alternate_command = list(arguments) alternate_command = flip_dash_g(alternate_command) alternate_command = set_output_file(alternate_command, output_file_b) run_step(alternate_command, my_env, "Error compiling with -g") # Compare disassembly (returns first diff if differs) difference = obj_diff.compare_object_files(self._output_file_a, output_file_b) if difference: raise WrapperCheckException( "Code difference detected with -g\n{}".format(difference)) # Clean up temp file if comparison okay os.remove(output_file_b) class dash_s_no_change(WrapperCheck): def perform_check(self, arguments, my_env): """Check if compiling to asm then assembling in separate steps results in different code than compiling to object directly.""" output_file_b = get_temp_file_name('.o') alternate_command = arguments + ['-via-file-asm'] alternate_command = set_output_file(alternate_command, output_file_b) run_step(alternate_command, my_env, "Error compiling with -via-file-asm") # Compare if object files are exactly the same exactly_equal = obj_diff.compare_exact(self._output_file_a, output_file_b) if not exactly_equal: # Compare disassembly (returns first diff if differs) difference = obj_diff.compare_object_files(self._output_file_a, output_file_b) if difference: raise WrapperCheckException( "Code difference detected with -S\n{}".format(difference)) # Code is identical, compare debug info dbgdifference = obj_diff.compare_debug_info(self._output_file_a, output_file_b) if dbgdifference: raise WrapperCheckException( "Debug info difference detected with -S\n{}".format(dbgdifference)) raise WrapperCheckException("Object files not identical with -S\n") # Clean up temp file if comparison okay os.remove(output_file_b) if __name__ == '__main__': # Create configuration defaults from list of checks default_config = """ [Checks] """ # Find all subclasses of WrapperCheck checks = [cls.__name__ for cls in vars()['WrapperCheck'].__subclasses__()] for c in checks: default_config += "{} = false\n".format(c) config = ConfigParser.RawConfigParser() config.readfp(io.BytesIO(default_config)) scriptdir = get_main_dir() config_path = os.path.join(scriptdir, 'check_cfc.cfg') try: config.read(os.path.join(config_path)) except: print("Could not read config from {}, " "using defaults.".format(config_path)) my_env = os.environ.copy() my_env['PATH'] = path_without_wrapper() arguments_a = list(sys.argv) # Prevent infinite loop if called with absolute path. arguments_a[0] = os.path.basename(arguments_a[0]) # Sanity check enabled_checks = [check_name for check_name in checks if config.getboolean('Checks', check_name)] checks_comma_separated = ', '.join(enabled_checks) print("Check CFC, checking: {}".format(checks_comma_separated)) # A - original compilation output_file_orig = get_output_file(arguments_a) if output_file_orig is None: output_file_orig = derive_output_file(arguments_a) p = subprocess.Popen(arguments_a, env=my_env, shell=is_windows()) p.communicate() if p.returncode != 0: sys.exit(p.returncode) if not is_normal_compile(arguments_a) or output_file_orig is None: # Bail out here if we can't apply checks in this case. # Does not indicate an error. # Maybe not straight compilation (e.g. -S or --version or -flto) # or maybe > 1 input files. sys.exit(0) # Sometimes we generate files which have very long names which can't be # read/disassembled. This will exit early if we can't find the file we # expected to be output. if not os.path.isfile(output_file_orig): sys.exit(0) # Copy output file to a temp file temp_output_file_orig = get_temp_file_name('.o') shutil.copyfile(output_file_orig, temp_output_file_orig) # Run checks, if they are enabled in config and if they are appropriate for # this command line. current_module = sys.modules[__name__] for check_name in checks: if config.getboolean('Checks', check_name): class_ = getattr(current_module, check_name) checker = class_(temp_output_file_orig) try: checker.perform_check(arguments_a, my_env) except WrapperCheckException as e: # Check failure print("{} {}".format(get_input_file(arguments_a), e.msg), file=sys.stderr) # Remove file to comply with build system expectations (no # output file if failed) os.remove(output_file_orig) sys.exit(1) except WrapperStepException as e: # Compile step failure print(e.msg, file=sys.stderr) print("*** stdout ***", file=sys.stderr) print(e.stdout, file=sys.stderr) print("*** stderr ***", file=sys.stderr) print(e.stderr, file=sys.stderr) # Remove file to comply with build system expectations (no # output file if failed) os.remove(output_file_orig) sys.exit(1)
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/check_cfc/obj_diff.py
#!/usr/bin/env python2.7 from __future__ import print_function import argparse import difflib import filecmp import os import subprocess import sys disassembler = 'objdump' def keep_line(line): """Returns true for lines that should be compared in the disassembly output.""" return "file format" not in line def disassemble(objfile): """Disassemble object to a file.""" p = subprocess.Popen([disassembler, '-d', objfile], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() if p.returncode or err: print("Disassemble failed: {}".format(objfile)) sys.exit(1) return filter(keep_line, out.split(os.linesep)) def dump_debug(objfile): """Dump all of the debug info from a file.""" p = subprocess.Popen([disassembler, '-WliaprmfsoRt', objfile], stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() if p.returncode or err: print("Dump debug failed: {}".format(objfile)) sys.exit(1) return filter(keep_line, out.split(os.linesep)) def first_diff(a, b, fromfile, tofile): """Returns the first few lines of a difference, if there is one. Python diff can be very slow with large objects and the most interesting changes are the first ones. Truncate data before sending to difflib. Returns None is there is no difference.""" # Find first diff first_diff_idx = None for idx, val in enumerate(a): if val != b[idx]: first_diff_idx = idx break if first_diff_idx == None: # No difference return None # Diff to first line of diff plus some lines context = 3 diff = difflib.unified_diff(a[:first_diff_idx+context], b[:first_diff_idx+context], fromfile, tofile) difference = "\n".join(diff) if first_diff_idx + context < len(a): difference += "\n*** Diff truncated ***" return difference def compare_object_files(objfilea, objfileb): """Compare disassembly of two different files. Allowing unavoidable differences, such as filenames. Return the first difference if the disassembly differs, or None. """ disa = disassemble(objfilea) disb = disassemble(objfileb) return first_diff(disa, disb, objfilea, objfileb) def compare_debug_info(objfilea, objfileb): """Compare debug info of two different files. Allowing unavoidable differences, such as filenames. Return the first difference if the debug info differs, or None. If there are differences in the code, there will almost certainly be differences in the debug info too. """ dbga = dump_debug(objfilea) dbgb = dump_debug(objfileb) return first_diff(dbga, dbgb, objfilea, objfileb) def compare_exact(objfilea, objfileb): """Byte for byte comparison between object files. Returns True if equal, False otherwise. """ return filecmp.cmp(objfilea, objfileb) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('objfilea', nargs=1) parser.add_argument('objfileb', nargs=1) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() diff = compare_object_files(args.objfilea[0], args.objfileb[0]) if diff: print("Difference detected") if args.verbose: print(diff) sys.exit(1) else: print("The same")
0
repos/DirectXShaderCompiler/tools/clang/utils
repos/DirectXShaderCompiler/tools/clang/utils/analyzer/reducer.pl
#!/usr/bin/perl -w use strict; use File::Temp qw/ tempdir /; my $prog = "reducer"; die "$prog <code file> <error string> [optional command]\n" if ($#ARGV < 0); my $file = shift @ARGV; die "$prog: [error] cannot read file $file\n" if (! -r $file); my $magic = shift @ARGV; die "$prog: [error] no error string specified\n" if (! defined $magic); # Create a backup of the file. my $dir = tempdir( CLEANUP => 1 ); print "$prog: created temporary directory '$dir'\n"; my $srcFile = "$dir/$file"; `cp $file $srcFile`; # Create the script. my $scriptFile = "$dir/script"; open(OUT, ">$scriptFile") or die "$prog: cannot create '$scriptFile'\n"; my $reduceOut = "$dir/reduceOut"; my $command; if (scalar(@ARGV) > 0) { $command = \@ARGV; } else { my $compiler = "clang"; $command = [$compiler, "-fsyntax-only", "-Wfatal-errors", "-Wno-deprecated-declarations", "-Wimplicit-function-declaration"]; } push @$command, $srcFile; my $commandStr = "@$command"; print OUT <<ENDTEXT; #!/usr/bin/perl -w use strict; my \$BAD = 1; my \$GOOD = 0; `rm -f $reduceOut`; my \$command = "$commandStr > $reduceOut 2>&1"; system(\$command); open(IN, "$reduceOut") or exit(\$BAD); my \$found = 0; while(<IN>) { if (/$magic/) { exit \$GOOD; } } exit \$BAD; ENDTEXT close(OUT); `chmod +x $scriptFile`; print "$prog: starting reduction\n"; sub multidelta($) { my ($level) = @_; system("multidelta -level=$level $scriptFile $srcFile"); } for (my $i = 1 ; $i <= 5; $i++) { foreach my $level (0,0,1,1,2,2,10) { multidelta($level); } } # Copy the final file. `cp $srcFile $file.reduced`; print "$prog: generated '$file.reduced";