1 //===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Preprocessor interface. 11 // 12 //===----------------------------------------------------------------------===// 13 // 14 // Options to support: 15 // -H - Print the name of each header file used. 16 // -d[DNI] - Dump various things. 17 // -fworking-directory - #line's with preprocessor's working dir. 18 // -fpreprocessed 19 // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD 20 // -W* 21 // -w 22 // 23 // Messages to emit: 24 // "Multiple include guards may be useful for:\n" 25 // 26 //===----------------------------------------------------------------------===// 27 28 #include "clang/Lex/Preprocessor.h" 29 #include "MacroArgs.h" 30 #include "clang/Lex/ExternalPreprocessorSource.h" 31 #include "clang/Lex/HeaderSearch.h" 32 #include "clang/Lex/MacroInfo.h" 33 #include "clang/Lex/Pragma.h" 34 #include "clang/Lex/PreprocessingRecord.h" 35 #include "clang/Lex/ScratchBuffer.h" 36 #include "clang/Lex/LexDiagnostic.h" 37 #include "clang/Lex/CodeCompletionHandler.h" 38 #include "clang/Basic/SourceManager.h" 39 #include "clang/Basic/FileManager.h" 40 #include "clang/Basic/TargetInfo.h" 41 #include "llvm/ADT/APFloat.h" 42 #include "llvm/ADT/SmallVector.h" 43 #include "llvm/Support/MemoryBuffer.h" 44 #include "llvm/Support/raw_ostream.h" 45 using namespace clang; 46 47 //===----------------------------------------------------------------------===// 48 ExternalPreprocessorSource::~ExternalPreprocessorSource() { } 49 50 Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts, 51 const TargetInfo &target, SourceManager &SM, 52 HeaderSearch &Headers, 53 IdentifierInfoLookup* IILookup, 54 bool OwnsHeaders) 55 : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()), 56 SourceMgr(SM), 57 HeaderInfo(Headers), ExternalSource(0), 58 Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0), 59 CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0), 60 CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0), 61 MICache(0) { 62 ScratchBuf = new ScratchBuffer(SourceMgr); 63 CounterValue = 0; // __COUNTER__ starts at 0. 64 OwnsHeaderSearch = OwnsHeaders; 65 66 // Clear stats. 67 NumDirectives = NumDefined = NumUndefined = NumPragma = 0; 68 NumIf = NumElse = NumEndif = 0; 69 NumEnteredSourceFiles = 0; 70 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0; 71 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0; 72 MaxIncludeStackDepth = 0; 73 NumSkipped = 0; 74 75 // Default to discarding comments. 76 KeepComments = false; 77 KeepMacroComments = false; 78 79 // Macro expansion is enabled. 80 DisableMacroExpansion = false; 81 InMacroArgs = false; 82 NumCachedTokenLexers = 0; 83 84 CachedLexPos = 0; 85 86 // We haven't read anything from the external source. 87 ReadMacrosFromExternalSource = false; 88 89 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. 90 // This gets unpoisoned where it is allowed. 91 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned(); 92 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use); 93 94 // Initialize the pragma handlers. 95 PragmaHandlers = new PragmaNamespace(llvm::StringRef()); 96 RegisterBuiltinPragmas(); 97 98 // Initialize builtin macros like __LINE__ and friends. 99 RegisterBuiltinMacros(); 100 101 if(Features.Borland) { 102 Ident__exception_info = getIdentifierInfo("_exception_info"); 103 Ident___exception_info = getIdentifierInfo("__exception_info"); 104 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation"); 105 Ident__exception_code = getIdentifierInfo("_exception_code"); 106 Ident___exception_code = getIdentifierInfo("__exception_code"); 107 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode"); 108 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination"); 109 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination"); 110 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination"); 111 } else { 112 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0; 113 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0; 114 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0; 115 } 116 117 } 118 119 Preprocessor::~Preprocessor() { 120 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!"); 121 assert(MacroExpandingLexersStack.empty() && MacroExpandedTokens.empty() && 122 "Preprocessor::HandleEndOfTokenLexer should have cleared those"); 123 124 while (!IncludeMacroStack.empty()) { 125 delete IncludeMacroStack.back().TheLexer; 126 delete IncludeMacroStack.back().TheTokenLexer; 127 IncludeMacroStack.pop_back(); 128 } 129 130 // Free any macro definitions. 131 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next) 132 I->MI.Destroy(); 133 134 // Free any cached macro expanders. 135 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i) 136 delete TokenLexerCache[i]; 137 138 // Free any cached MacroArgs. 139 for (MacroArgs *ArgList = MacroArgCache; ArgList; ) 140 ArgList = ArgList->deallocate(); 141 142 // Release pragma information. 143 delete PragmaHandlers; 144 145 // Delete the scratch buffer info. 146 delete ScratchBuf; 147 148 // Delete the header search info, if we own it. 149 if (OwnsHeaderSearch) 150 delete &HeaderInfo; 151 152 delete Callbacks; 153 } 154 155 void Preprocessor::setPTHManager(PTHManager* pm) { 156 PTH.reset(pm); 157 FileMgr.addStatCache(PTH->createStatCache()); 158 } 159 160 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { 161 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '" 162 << getSpelling(Tok) << "'"; 163 164 if (!DumpFlags) return; 165 166 llvm::errs() << "\t"; 167 if (Tok.isAtStartOfLine()) 168 llvm::errs() << " [StartOfLine]"; 169 if (Tok.hasLeadingSpace()) 170 llvm::errs() << " [LeadingSpace]"; 171 if (Tok.isExpandDisabled()) 172 llvm::errs() << " [ExpandDisabled]"; 173 if (Tok.needsCleaning()) { 174 const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); 175 llvm::errs() << " [UnClean='" << llvm::StringRef(Start, Tok.getLength()) 176 << "']"; 177 } 178 179 llvm::errs() << "\tLoc=<"; 180 DumpLocation(Tok.getLocation()); 181 llvm::errs() << ">"; 182 } 183 184 void Preprocessor::DumpLocation(SourceLocation Loc) const { 185 Loc.dump(SourceMgr); 186 } 187 188 void Preprocessor::DumpMacro(const MacroInfo &MI) const { 189 llvm::errs() << "MACRO: "; 190 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { 191 DumpToken(MI.getReplacementToken(i)); 192 llvm::errs() << " "; 193 } 194 llvm::errs() << "\n"; 195 } 196 197 void Preprocessor::PrintStats() { 198 llvm::errs() << "\n*** Preprocessor Stats:\n"; 199 llvm::errs() << NumDirectives << " directives found:\n"; 200 llvm::errs() << " " << NumDefined << " #define.\n"; 201 llvm::errs() << " " << NumUndefined << " #undef.\n"; 202 llvm::errs() << " #include/#include_next/#import:\n"; 203 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n"; 204 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n"; 205 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n"; 206 llvm::errs() << " " << NumElse << " #else/#elif.\n"; 207 llvm::errs() << " " << NumEndif << " #endif.\n"; 208 llvm::errs() << " " << NumPragma << " #pragma.\n"; 209 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; 210 211 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" 212 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " 213 << NumFastMacroExpanded << " on the fast path.\n"; 214 llvm::errs() << (NumFastTokenPaste+NumTokenPaste) 215 << " token paste (##) operations performed, " 216 << NumFastTokenPaste << " on the fast path.\n"; 217 } 218 219 Preprocessor::macro_iterator 220 Preprocessor::macro_begin(bool IncludeExternalMacros) const { 221 if (IncludeExternalMacros && ExternalSource && 222 !ReadMacrosFromExternalSource) { 223 ReadMacrosFromExternalSource = true; 224 ExternalSource->ReadDefinedMacros(); 225 } 226 227 return Macros.begin(); 228 } 229 230 size_t Preprocessor::getTotalMemory() const { 231 return BP.getTotalMemory() + MacroExpandedTokens.capacity()*sizeof(Token); 232 } 233 234 Preprocessor::macro_iterator 235 Preprocessor::macro_end(bool IncludeExternalMacros) const { 236 if (IncludeExternalMacros && ExternalSource && 237 !ReadMacrosFromExternalSource) { 238 ReadMacrosFromExternalSource = true; 239 ExternalSource->ReadDefinedMacros(); 240 } 241 242 return Macros.end(); 243 } 244 245 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File, 246 unsigned TruncateAtLine, 247 unsigned TruncateAtColumn) { 248 using llvm::MemoryBuffer; 249 250 CodeCompletionFile = File; 251 252 // Okay to clear out the code-completion point by passing NULL. 253 if (!CodeCompletionFile) 254 return false; 255 256 // Load the actual file's contents. 257 bool Invalid = false; 258 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid); 259 if (Invalid) 260 return true; 261 262 // Find the byte position of the truncation point. 263 const char *Position = Buffer->getBufferStart(); 264 for (unsigned Line = 1; Line < TruncateAtLine; ++Line) { 265 for (; *Position; ++Position) { 266 if (*Position != '\r' && *Position != '\n') 267 continue; 268 269 // Eat \r\n or \n\r as a single line. 270 if ((Position[1] == '\r' || Position[1] == '\n') && 271 Position[0] != Position[1]) 272 ++Position; 273 ++Position; 274 break; 275 } 276 } 277 278 Position += TruncateAtColumn - 1; 279 280 // Truncate the buffer. 281 if (Position < Buffer->getBufferEnd()) { 282 llvm::StringRef Data(Buffer->getBufferStart(), 283 Position-Buffer->getBufferStart()); 284 MemoryBuffer *TruncatedBuffer 285 = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier()); 286 SourceMgr.overrideFileContents(File, TruncatedBuffer); 287 } 288 289 return false; 290 } 291 292 bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const { 293 return CodeCompletionFile && FileLoc.isFileID() && 294 SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc)) 295 == CodeCompletionFile; 296 } 297 298 void Preprocessor::CodeCompleteNaturalLanguage() { 299 SetCodeCompletionPoint(0, 0, 0); 300 getDiagnostics().setSuppressAllDiagnostics(true); 301 if (CodeComplete) 302 CodeComplete->CodeCompleteNaturalLanguage(); 303 } 304 305 /// getSpelling - This method is used to get the spelling of a token into a 306 /// SmallVector. Note that the returned StringRef may not point to the 307 /// supplied buffer if a copy can be avoided. 308 llvm::StringRef Preprocessor::getSpelling(const Token &Tok, 309 llvm::SmallVectorImpl<char> &Buffer, 310 bool *Invalid) const { 311 // NOTE: this has to be checked *before* testing for an IdentifierInfo. 312 if (Tok.isNot(tok::raw_identifier)) { 313 // Try the fast path. 314 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) 315 return II->getName(); 316 } 317 318 // Resize the buffer if we need to copy into it. 319 if (Tok.needsCleaning()) 320 Buffer.resize(Tok.getLength()); 321 322 const char *Ptr = Buffer.data(); 323 unsigned Len = getSpelling(Tok, Ptr, Invalid); 324 return llvm::StringRef(Ptr, Len); 325 } 326 327 /// CreateString - Plop the specified string into a scratch buffer and return a 328 /// location for it. If specified, the source location provides a source 329 /// location for the token. 330 void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok, 331 SourceLocation InstantiationLoc) { 332 Tok.setLength(Len); 333 334 const char *DestPtr; 335 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr); 336 337 if (InstantiationLoc.isValid()) 338 Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc, 339 InstantiationLoc, Len); 340 Tok.setLocation(Loc); 341 342 // If this is a raw identifier or a literal token, set the pointer data. 343 if (Tok.is(tok::raw_identifier)) 344 Tok.setRawIdentifierData(DestPtr); 345 else if (Tok.isLiteral()) 346 Tok.setLiteralData(DestPtr); 347 } 348 349 350 351 //===----------------------------------------------------------------------===// 352 // Preprocessor Initialization Methods 353 //===----------------------------------------------------------------------===// 354 355 356 /// EnterMainSourceFile - Enter the specified FileID as the main source file, 357 /// which implicitly adds the builtin defines etc. 358 void Preprocessor::EnterMainSourceFile() { 359 // We do not allow the preprocessor to reenter the main file. Doing so will 360 // cause FileID's to accumulate information from both runs (e.g. #line 361 // information) and predefined macros aren't guaranteed to be set properly. 362 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!"); 363 FileID MainFileID = SourceMgr.getMainFileID(); 364 365 // Enter the main file source buffer. 366 EnterSourceFile(MainFileID, 0, SourceLocation()); 367 368 // If we've been asked to skip bytes in the main file (e.g., as part of a 369 // precompiled preamble), do so now. 370 if (SkipMainFilePreamble.first > 0) 371 CurLexer->SkipBytes(SkipMainFilePreamble.first, 372 SkipMainFilePreamble.second); 373 374 // Tell the header info that the main file was entered. If the file is later 375 // #imported, it won't be re-entered. 376 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) 377 HeaderInfo.IncrementIncludeCount(FE); 378 379 // Preprocess Predefines to populate the initial preprocessor state. 380 llvm::MemoryBuffer *SB = 381 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>"); 382 assert(SB && "Cannot create predefined source buffer"); 383 FileID FID = SourceMgr.createFileIDForMemBuffer(SB); 384 assert(!FID.isInvalid() && "Could not create FileID for predefines?"); 385 386 // Start parsing the predefines. 387 EnterSourceFile(FID, 0, SourceLocation()); 388 } 389 390 void Preprocessor::EndSourceFile() { 391 // Notify the client that we reached the end of the source file. 392 if (Callbacks) 393 Callbacks->EndOfMainFile(); 394 } 395 396 //===----------------------------------------------------------------------===// 397 // Lexer Event Handling. 398 //===----------------------------------------------------------------------===// 399 400 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the 401 /// identifier information for the token and install it into the token, 402 /// updating the token kind accordingly. 403 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const { 404 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!"); 405 406 // Look up this token, see if it is a macro, or if it is a language keyword. 407 IdentifierInfo *II; 408 if (!Identifier.needsCleaning()) { 409 // No cleaning needed, just use the characters from the lexed buffer. 410 II = getIdentifierInfo(llvm::StringRef(Identifier.getRawIdentifierData(), 411 Identifier.getLength())); 412 } else { 413 // Cleaning needed, alloca a buffer, clean into it, then use the buffer. 414 llvm::SmallString<64> IdentifierBuffer; 415 llvm::StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer); 416 II = getIdentifierInfo(CleanedStr); 417 } 418 419 // Update the token info (identifier info and appropriate token kind). 420 Identifier.setIdentifierInfo(II); 421 Identifier.setKind(II->getTokenID()); 422 423 return II; 424 } 425 426 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) { 427 PoisonReasons[II] = DiagID; 428 } 429 430 void Preprocessor::PoisonSEHIdentifiers(bool Poison) { 431 assert(Ident__exception_code && Ident__exception_info); 432 assert(Ident___exception_code && Ident___exception_info); 433 Ident__exception_code->setIsPoisoned(Poison); 434 Ident___exception_code->setIsPoisoned(Poison); 435 Ident_GetExceptionCode->setIsPoisoned(Poison); 436 Ident__exception_info->setIsPoisoned(Poison); 437 Ident___exception_info->setIsPoisoned(Poison); 438 Ident_GetExceptionInfo->setIsPoisoned(Poison); 439 Ident__abnormal_termination->setIsPoisoned(Poison); 440 Ident___abnormal_termination->setIsPoisoned(Poison); 441 Ident_AbnormalTermination->setIsPoisoned(Poison); 442 } 443 444 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) { 445 assert(Identifier.getIdentifierInfo() && 446 "Can't handle identifiers without identifier info!"); 447 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it = 448 PoisonReasons.find(Identifier.getIdentifierInfo()); 449 if(it == PoisonReasons.end()) 450 Diag(Identifier, diag::err_pp_used_poisoned_id); 451 else 452 Diag(Identifier,it->second) << Identifier.getIdentifierInfo(); 453 } 454 455 /// HandleIdentifier - This callback is invoked when the lexer reads an 456 /// identifier. This callback looks up the identifier in the map and/or 457 /// potentially macro expands it or turns it into a named token (like 'for'). 458 /// 459 /// Note that callers of this method are guarded by checking the 460 /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the 461 /// IdentifierInfo methods that compute these properties will need to change to 462 /// match. 463 void Preprocessor::HandleIdentifier(Token &Identifier) { 464 assert(Identifier.getIdentifierInfo() && 465 "Can't handle identifiers without identifier info!"); 466 467 IdentifierInfo &II = *Identifier.getIdentifierInfo(); 468 469 // If this identifier was poisoned, and if it was not produced from a macro 470 // expansion, emit an error. 471 if (II.isPoisoned() && CurPPLexer) { 472 HandlePoisonedIdentifier(Identifier); 473 } 474 475 // If this is a macro to be expanded, do it. 476 if (MacroInfo *MI = getMacroInfo(&II)) { 477 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) { 478 if (MI->isEnabled()) { 479 if (!HandleMacroExpandedIdentifier(Identifier, MI)) 480 return; 481 } else { 482 // C99 6.10.3.4p2 says that a disabled macro may never again be 483 // expanded, even if it's in a context where it could be expanded in the 484 // future. 485 Identifier.setFlag(Token::DisableExpand); 486 } 487 } 488 } 489 490 // C++ 2.11p2: If this is an alternative representation of a C++ operator, 491 // then we act as if it is the actual operator and not the textual 492 // representation of it. 493 if (II.isCPlusPlusOperatorKeyword()) 494 Identifier.setIdentifierInfo(0); 495 496 // If this is an extension token, diagnose its use. 497 // We avoid diagnosing tokens that originate from macro definitions. 498 // FIXME: This warning is disabled in cases where it shouldn't be, 499 // like "#define TY typeof", "TY(1) x". 500 if (II.isExtensionToken() && !DisableMacroExpansion) 501 Diag(Identifier, diag::ext_token_used); 502 } 503 504 void Preprocessor::AddCommentHandler(CommentHandler *Handler) { 505 assert(Handler && "NULL comment handler"); 506 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) == 507 CommentHandlers.end() && "Comment handler already registered"); 508 CommentHandlers.push_back(Handler); 509 } 510 511 void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) { 512 std::vector<CommentHandler *>::iterator Pos 513 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler); 514 assert(Pos != CommentHandlers.end() && "Comment handler not registered"); 515 CommentHandlers.erase(Pos); 516 } 517 518 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) { 519 bool AnyPendingTokens = false; 520 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(), 521 HEnd = CommentHandlers.end(); 522 H != HEnd; ++H) { 523 if ((*H)->HandleComment(*this, Comment)) 524 AnyPendingTokens = true; 525 } 526 if (!AnyPendingTokens || getCommentRetentionState()) 527 return false; 528 Lex(result); 529 return true; 530 } 531 532 CommentHandler::~CommentHandler() { } 533 534 CodeCompletionHandler::~CodeCompletionHandler() { } 535 536 void Preprocessor::createPreprocessingRecord( 537 bool IncludeNestedMacroInstantiations) { 538 if (Record) 539 return; 540 541 Record = new PreprocessingRecord(IncludeNestedMacroInstantiations); 542 addPPCallbacks(Record); 543 } 544