Preprocessor.cpp revision cf29e0716bb3ecbbc15b74cd648367d6b075fdf0
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 "clang/Lex/HeaderSearch.h" 30#include "clang/Lex/MacroInfo.h" 31#include "clang/Lex/Pragma.h" 32#include "clang/Lex/ScratchBuffer.h" 33#include "clang/Lex/LexDiagnostic.h" 34#include "clang/Basic/SourceManager.h" 35#include "clang/Basic/FileManager.h" 36#include "clang/Basic/TargetInfo.h" 37#include "llvm/ADT/APFloat.h" 38#include "llvm/ADT/SmallVector.h" 39#include "llvm/Support/MemoryBuffer.h" 40#include "llvm/Support/Streams.h" 41using namespace clang; 42 43//===----------------------------------------------------------------------===// 44 45PreprocessorFactory::~PreprocessorFactory() {} 46 47Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts, 48 TargetInfo &target, SourceManager &SM, 49 HeaderSearch &Headers, 50 IdentifierInfoLookup* IILookup) 51 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()), 52 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts, IILookup), 53 CurPPLexer(0), CurDirLookup(0), Callbacks(0) { 54 ScratchBuf = new ScratchBuffer(SourceMgr); 55 56 // Clear stats. 57 NumDirectives = NumDefined = NumUndefined = NumPragma = 0; 58 NumIf = NumElse = NumEndif = 0; 59 NumEnteredSourceFiles = 0; 60 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0; 61 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0; 62 MaxIncludeStackDepth = 0; 63 NumSkipped = 0; 64 65 // Default to discarding comments. 66 KeepComments = false; 67 KeepMacroComments = false; 68 69 // Macro expansion is enabled. 70 DisableMacroExpansion = false; 71 InMacroArgs = false; 72 NumCachedTokenLexers = 0; 73 74 CachedLexPos = 0; 75 76 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. 77 // This gets unpoisoned where it is allowed. 78 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned(); 79 80 // Initialize the pragma handlers. 81 PragmaHandlers = new PragmaNamespace(0); 82 RegisterBuiltinPragmas(); 83 84 // Initialize builtin macros like __LINE__ and friends. 85 RegisterBuiltinMacros(); 86} 87 88Preprocessor::~Preprocessor() { 89 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!"); 90 91 while (!IncludeMacroStack.empty()) { 92 delete IncludeMacroStack.back().TheLexer; 93 delete IncludeMacroStack.back().TheTokenLexer; 94 IncludeMacroStack.pop_back(); 95 } 96 97 // Free any macro definitions. 98 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I = 99 Macros.begin(), E = Macros.end(); I != E; ++I) { 100 // We don't need to free the MacroInfo objects directly. These 101 // will be released when the BumpPtrAllocator 'BP' object gets 102 // destroyed. We still need to run the dstor, however, to free 103 // memory alocated by MacroInfo. 104 I->second->Destroy(); 105 I->first->setHasMacroDefinition(false); 106 } 107 108 // Free any cached macro expanders. 109 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i) 110 delete TokenLexerCache[i]; 111 112 // Release pragma information. 113 delete PragmaHandlers; 114 115 // Delete the scratch buffer info. 116 delete ScratchBuf; 117 118 delete Callbacks; 119} 120 121void Preprocessor::setPTHManager(PTHManager* pm) { 122 PTH.reset(pm); 123 FileMgr.setStatCache(PTH->createStatCache()); 124} 125 126void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { 127 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '" 128 << getSpelling(Tok) << "'"; 129 130 if (!DumpFlags) return; 131 132 llvm::cerr << "\t"; 133 if (Tok.isAtStartOfLine()) 134 llvm::cerr << " [StartOfLine]"; 135 if (Tok.hasLeadingSpace()) 136 llvm::cerr << " [LeadingSpace]"; 137 if (Tok.isExpandDisabled()) 138 llvm::cerr << " [ExpandDisabled]"; 139 if (Tok.needsCleaning()) { 140 const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); 141 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength()) 142 << "']"; 143 } 144 145 llvm::cerr << "\tLoc=<"; 146 DumpLocation(Tok.getLocation()); 147 llvm::cerr << ">"; 148} 149 150void Preprocessor::DumpLocation(SourceLocation Loc) const { 151 Loc.dump(SourceMgr); 152} 153 154void Preprocessor::DumpMacro(const MacroInfo &MI) const { 155 llvm::cerr << "MACRO: "; 156 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { 157 DumpToken(MI.getReplacementToken(i)); 158 llvm::cerr << " "; 159 } 160 llvm::cerr << "\n"; 161} 162 163void Preprocessor::PrintStats() { 164 llvm::cerr << "\n*** Preprocessor Stats:\n"; 165 llvm::cerr << NumDirectives << " directives found:\n"; 166 llvm::cerr << " " << NumDefined << " #define.\n"; 167 llvm::cerr << " " << NumUndefined << " #undef.\n"; 168 llvm::cerr << " #include/#include_next/#import:\n"; 169 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n"; 170 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n"; 171 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n"; 172 llvm::cerr << " " << NumElse << " #else/#elif.\n"; 173 llvm::cerr << " " << NumEndif << " #endif.\n"; 174 llvm::cerr << " " << NumPragma << " #pragma.\n"; 175 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; 176 177 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" 178 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " 179 << NumFastMacroExpanded << " on the fast path.\n"; 180 llvm::cerr << (NumFastTokenPaste+NumTokenPaste) 181 << " token paste (##) operations performed, " 182 << NumFastTokenPaste << " on the fast path.\n"; 183} 184 185//===----------------------------------------------------------------------===// 186// Token Spelling 187//===----------------------------------------------------------------------===// 188 189 190/// getSpelling() - Return the 'spelling' of this token. The spelling of a 191/// token are the characters used to represent the token in the source file 192/// after trigraph expansion and escaped-newline folding. In particular, this 193/// wants to get the true, uncanonicalized, spelling of things like digraphs 194/// UCNs, etc. 195std::string Preprocessor::getSpelling(const Token &Tok) const { 196 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!"); 197 198 // If this token contains nothing interesting, return it directly. 199 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation()); 200 if (!Tok.needsCleaning()) 201 return std::string(TokStart, TokStart+Tok.getLength()); 202 203 std::string Result; 204 Result.reserve(Tok.getLength()); 205 206 // Otherwise, hard case, relex the characters into the string. 207 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength(); 208 Ptr != End; ) { 209 unsigned CharSize; 210 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features)); 211 Ptr += CharSize; 212 } 213 assert(Result.size() != unsigned(Tok.getLength()) && 214 "NeedsCleaning flag set on something that didn't need cleaning!"); 215 return Result; 216} 217 218/// getSpelling - This method is used to get the spelling of a token into a 219/// preallocated buffer, instead of as an std::string. The caller is required 220/// to allocate enough space for the token, which is guaranteed to be at least 221/// Tok.getLength() bytes long. The actual length of the token is returned. 222/// 223/// Note that this method may do two possible things: it may either fill in 224/// the buffer specified with characters, or it may *change the input pointer* 225/// to point to a constant buffer with the data already in it (avoiding a 226/// copy). The caller is not allowed to modify the returned buffer pointer 227/// if an internal buffer is returned. 228unsigned Preprocessor::getSpelling(const Token &Tok, 229 const char *&Buffer) const { 230 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!"); 231 232 // If this token is an identifier, just return the string from the identifier 233 // table, which is very quick. 234 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) { 235 Buffer = II->getName(); 236 return II->getLength(); 237 } 238 239 // Otherwise, compute the start of the token in the input lexer buffer. 240 const char *TokStart = 0; 241 242 if (Tok.isLiteral()) 243 TokStart = Tok.getLiteralData(); 244 245 if (TokStart == 0) 246 TokStart = SourceMgr.getCharacterData(Tok.getLocation()); 247 248 // If this token contains nothing interesting, return it directly. 249 if (!Tok.needsCleaning()) { 250 Buffer = TokStart; 251 return Tok.getLength(); 252 } 253 254 // Otherwise, hard case, relex the characters into the string. 255 char *OutBuf = const_cast<char*>(Buffer); 256 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength(); 257 Ptr != End; ) { 258 unsigned CharSize; 259 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features); 260 Ptr += CharSize; 261 } 262 assert(unsigned(OutBuf-Buffer) != Tok.getLength() && 263 "NeedsCleaning flag set on something that didn't need cleaning!"); 264 265 return OutBuf-Buffer; 266} 267 268 269/// CreateString - Plop the specified string into a scratch buffer and return a 270/// location for it. If specified, the source location provides a source 271/// location for the token. 272void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok, 273 SourceLocation InstantiationLoc) { 274 Tok.setLength(Len); 275 276 const char *DestPtr; 277 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr); 278 279 if (InstantiationLoc.isValid()) 280 Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc, 281 InstantiationLoc, Len); 282 Tok.setLocation(Loc); 283 284 // If this is a literal token, set the pointer data. 285 if (Tok.isLiteral()) 286 Tok.setLiteralData(DestPtr); 287} 288 289 290/// AdvanceToTokenCharacter - Given a location that specifies the start of a 291/// token, return a new location that specifies a character within the token. 292SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart, 293 unsigned CharNo) { 294 // If they request the first char of the token, we're trivially done. 295 if (CharNo == 0) return TokStart; 296 297 // Figure out how many physical characters away the specified instantiation 298 // character is. This needs to take into consideration newlines and 299 // trigraphs. 300 const char *TokPtr = SourceMgr.getCharacterData(TokStart); 301 unsigned PhysOffset = 0; 302 303 // The usual case is that tokens don't contain anything interesting. Skip 304 // over the uninteresting characters. If a token only consists of simple 305 // chars, this method is extremely fast. 306 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr)) 307 ++TokPtr, --CharNo, ++PhysOffset; 308 309 // If we have a character that may be a trigraph or escaped newline, use a 310 // lexer to parse it correctly. 311 if (CharNo != 0) { 312 // Skip over characters the remaining characters. 313 for (; CharNo; --CharNo) { 314 unsigned Size; 315 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features); 316 TokPtr += Size; 317 PhysOffset += Size; 318 } 319 } 320 321 return TokStart.getFileLocWithOffset(PhysOffset); 322} 323 324 325//===----------------------------------------------------------------------===// 326// Preprocessor Initialization Methods 327//===----------------------------------------------------------------------===// 328 329// Append a #define line to Buf for Macro. Macro should be of the form XXX, 330// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit 331// "#define XXX Y z W". To get a #define with no value, use "XXX=". 332static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro, 333 const char *Command = "#define ") { 334 Buf.insert(Buf.end(), Command, Command+strlen(Command)); 335 if (const char *Equal = strchr(Macro, '=')) { 336 // Turn the = into ' '. 337 Buf.insert(Buf.end(), Macro, Equal); 338 Buf.push_back(' '); 339 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal)); 340 } else { 341 // Push "macroname 1". 342 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro)); 343 Buf.push_back(' '); 344 Buf.push_back('1'); 345 } 346 Buf.push_back('\n'); 347} 348 349/// PickFP - This is used to pick a value based on the FP semantics of the 350/// specified FP model. 351template <typename T> 352static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal, 353 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) { 354 if (Sem == &llvm::APFloat::IEEEsingle) 355 return IEEESingleVal; 356 if (Sem == &llvm::APFloat::IEEEdouble) 357 return IEEEDoubleVal; 358 if (Sem == &llvm::APFloat::x87DoubleExtended) 359 return X87DoubleExtendedVal; 360 assert(Sem == &llvm::APFloat::PPCDoubleDouble); 361 return PPCDoubleDoubleVal; 362} 363 364static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix, 365 const llvm::fltSemantics *Sem) { 366 const char *DenormMin, *Epsilon, *Max, *Min; 367 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324", 368 "3.64519953188247460253e-4951L", 369 "4.94065645841246544176568792868221e-324L"); 370 int Digits = PickFP(Sem, 6, 15, 18, 31); 371 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16", 372 "1.08420217248550443401e-19L", 373 "4.94065645841246544176568792868221e-324L"); 374 int HasInifinity = 1, HasQuietNaN = 1; 375 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106); 376 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291); 377 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308); 378 int MinExp = PickFP(Sem, -125, -1021, -16381, -968); 379 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024); 380 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308", 381 "3.36210314311209350626e-4932L", 382 "2.00416836000897277799610805135016e-292L"); 383 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308", 384 "1.18973149535723176502e+4932L", 385 "1.79769313486231580793728971405301e+308L"); 386 387 char MacroBuf[60]; 388 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin); 389 DefineBuiltinMacro(Buf, MacroBuf); 390 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits); 391 DefineBuiltinMacro(Buf, MacroBuf); 392 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon); 393 DefineBuiltinMacro(Buf, MacroBuf); 394 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity); 395 DefineBuiltinMacro(Buf, MacroBuf); 396 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN); 397 DefineBuiltinMacro(Buf, MacroBuf); 398 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits); 399 DefineBuiltinMacro(Buf, MacroBuf); 400 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp); 401 DefineBuiltinMacro(Buf, MacroBuf); 402 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp); 403 DefineBuiltinMacro(Buf, MacroBuf); 404 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max); 405 DefineBuiltinMacro(Buf, MacroBuf); 406 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp); 407 DefineBuiltinMacro(Buf, MacroBuf); 408 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp); 409 DefineBuiltinMacro(Buf, MacroBuf); 410 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min); 411 DefineBuiltinMacro(Buf, MacroBuf); 412 sprintf(MacroBuf, "__%s_HAS_DENORM__=1", Prefix); 413 DefineBuiltinMacro(Buf, MacroBuf); 414} 415 416 417/// DefineTypeSize - Emit a macro to the predefines buffer that declares a macro 418/// named MacroName with the max value for a type with width 'TypeWidth' a 419/// signedness of 'isSigned' and with a value suffix of 'ValSuffix' (e.g. LL). 420static void DefineTypeSize(const char *MacroName, unsigned TypeWidth, 421 const char *ValSuffix, bool isSigned, 422 std::vector<char> &Buf) { 423 char MacroBuf[60]; 424 uint64_t MaxVal; 425 if (isSigned) 426 MaxVal = (1LL << (TypeWidth - 1)) - 1; 427 else 428 MaxVal = ~0LL >> (64-TypeWidth); 429 430 sprintf(MacroBuf, "%s=%llu%s", MacroName, MaxVal, ValSuffix); 431 DefineBuiltinMacro(Buf, MacroBuf); 432} 433 434static void DefineType(const char *MacroName, TargetInfo::IntType Ty, 435 std::vector<char> &Buf) { 436 char MacroBuf[60]; 437 sprintf(MacroBuf, "%s=%s", MacroName, TargetInfo::getTypeName(Ty)); 438 DefineBuiltinMacro(Buf, MacroBuf); 439} 440 441 442static void InitializePredefinedMacros(Preprocessor &PP, 443 std::vector<char> &Buf) { 444 char MacroBuf[60]; 445 // Compiler version introspection macros. 446 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend 447 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend 448 449 // Currently claim to be compatible with GCC 4.2.1-5621. 450 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621"); 451 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2"); 452 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1"); 453 DefineBuiltinMacro(Buf, "__GNUC__=4"); 454 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002"); 455 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 (Apple Computer, Inc. " 456 "build 5621) (dot 3)\""); 457 458 459 // Initialize language-specific preprocessor defines. 460 461 // These should all be defined in the preprocessor according to the 462 // current language configuration. 463 if (!PP.getLangOptions().Microsoft) 464 DefineBuiltinMacro(Buf, "__STDC__=1"); 465 if (PP.getLangOptions().AsmPreprocessor) 466 DefineBuiltinMacro(Buf, "__ASSEMBLER__=1"); 467 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus) 468 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L"); 469 else if (0) // STDC94 ? 470 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L"); 471 472 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1"); 473 if (PP.getLangOptions().ObjC1) { 474 DefineBuiltinMacro(Buf, "__OBJC__=1"); 475 if (PP.getLangOptions().ObjCNonFragileABI) 476 DefineBuiltinMacro(Buf, "__OBJC2__=1"); 477 478 if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) { 479 DefineBuiltinMacro(Buf, "__weak="); 480 DefineBuiltinMacro(Buf, "__strong="); 481 } else { 482 DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))"); 483 DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))"); 484 DefineBuiltinMacro(Buf, "__OBJC_GC__=1"); 485 } 486 487 if (PP.getLangOptions().NeXTRuntime) 488 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1"); 489 } 490 491 // darwin_constant_cfstrings controls this. This is also dependent 492 // on other things like the runtime I believe. This is set even for C code. 493 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1"); 494 495 if (PP.getLangOptions().ObjC2) 496 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES"); 497 498 if (PP.getLangOptions().PascalStrings) 499 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__"); 500 501 if (PP.getLangOptions().Blocks) { 502 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))"); 503 DefineBuiltinMacro(Buf, "__BLOCKS__=1"); 504 } 505 506 if (PP.getLangOptions().CPlusPlus) { 507 DefineBuiltinMacro(Buf, "__DEPRECATED=1"); 508 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1"); 509 DefineBuiltinMacro(Buf, "__GNUG__=4"); 510 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1"); 511 DefineBuiltinMacro(Buf, "__cplusplus=1"); 512 DefineBuiltinMacro(Buf, "__private_extern__=extern"); 513 } 514 515 // Filter out some microsoft extensions when trying to parse in ms-compat 516 // mode. 517 if (PP.getLangOptions().Microsoft) { 518 DefineBuiltinMacro(Buf, "_cdecl=__cdecl"); 519 DefineBuiltinMacro(Buf, "__int8=__INT8_TYPE__"); 520 DefineBuiltinMacro(Buf, "__int16=__INT16_TYPE__"); 521 DefineBuiltinMacro(Buf, "__int32=__INT32_TYPE__"); 522 DefineBuiltinMacro(Buf, "__int64=__INT64_TYPE__"); 523 } 524 525 // Initialize target-specific preprocessor defines. 526 const TargetInfo &TI = PP.getTargetInfo(); 527 528 // Define type sizing macros based on the target properties. 529 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far"); 530 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8"); 531 532 unsigned IntMaxWidth; 533 const char *IntMaxSuffix; 534 if (TI.getIntMaxType() == TargetInfo::SignedLongLong) { 535 IntMaxWidth = TI.getLongLongWidth(); 536 IntMaxSuffix = "LL"; 537 } else if (TI.getIntMaxType() == TargetInfo::SignedLong) { 538 IntMaxWidth = TI.getLongWidth(); 539 IntMaxSuffix = "L"; 540 } else { 541 assert(TI.getIntMaxType() == TargetInfo::SignedInt); 542 IntMaxWidth = TI.getIntWidth(); 543 IntMaxSuffix = ""; 544 } 545 546 DefineTypeSize("__SCHAR_MAX__", TI.getCharWidth(), "", true, Buf); 547 DefineTypeSize("__SHRT_MAX__", TI.getShortWidth(), "", true, Buf); 548 DefineTypeSize("__INT_MAX__", TI.getIntWidth(), "", true, Buf); 549 DefineTypeSize("__LONG_MAX__", TI.getLongWidth(), "L", true, Buf); 550 DefineTypeSize("__LONG_LONG_MAX__", TI.getLongLongWidth(), "LL", true, Buf); 551 DefineTypeSize("__WCHAR_MAX__", TI.getWCharWidth(), "", true, Buf); 552 DefineTypeSize("__INTMAX_MAX__", IntMaxWidth, IntMaxSuffix, true, Buf); 553 554 DefineType("__INTMAX_TYPE__", TI.getIntMaxType(), Buf); 555 DefineType("__UINTMAX_TYPE__", TI.getUIntMaxType(), Buf); 556 DefineType("__PTRDIFF_TYPE__", TI.getPtrDiffType(0), Buf); 557 DefineType("__INTPTR_TYPE__", TI.getIntPtrType(), Buf); 558 DefineType("__SIZE_TYPE__", TI.getSizeType(), Buf); 559 DefineType("__WCHAR_TYPE__", TI.getWCharType(), Buf); 560 // FIXME: TargetInfo hookize __WINT_TYPE__. 561 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int"); 562 563 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat()); 564 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat()); 565 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat()); 566 567 // Define a __POINTER_WIDTH__ macro for stdint.h. 568 sprintf(MacroBuf, "__POINTER_WIDTH__=%d", (int)TI.getPointerWidth(0)); 569 DefineBuiltinMacro(Buf, MacroBuf); 570 571 if (!TI.isCharSigned()) 572 DefineBuiltinMacro(Buf, "__CHAR_UNSIGNED__"); 573 574 // Define fixed-sized integer types for stdint.h 575 assert(TI.getCharWidth() == 8 && "unsupported target types"); 576 assert(TI.getShortWidth() == 16 && "unsupported target types"); 577 DefineBuiltinMacro(Buf, "__INT8_TYPE__=char"); 578 DefineBuiltinMacro(Buf, "__INT16_TYPE__=short"); 579 580 if (TI.getIntWidth() == 32) 581 DefineBuiltinMacro(Buf, "__INT32_TYPE__=int"); 582 else { 583 assert(TI.getLongLongWidth() == 32 && "unsupported target types"); 584 DefineBuiltinMacro(Buf, "__INT32_TYPE__=long long"); 585 } 586 587 // 16-bit targets doesn't necessarily have a 64-bit type. 588 if (TI.getLongLongWidth() == 64) 589 DefineBuiltinMacro(Buf, "__INT64_TYPE__=long long"); 590 591 // Add __builtin_va_list typedef. 592 { 593 const char *VAList = TI.getVAListDeclaration(); 594 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList)); 595 Buf.push_back('\n'); 596 } 597 598 if (const char *Prefix = TI.getUserLabelPrefix()) { 599 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix); 600 DefineBuiltinMacro(Buf, MacroBuf); 601 } 602 603 // Build configuration options. FIXME: these should be controlled by 604 // command line options or something. 605 DefineBuiltinMacro(Buf, "__DYNAMIC__=1"); 606 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0"); 607 DefineBuiltinMacro(Buf, "__NO_INLINE__=1"); 608 DefineBuiltinMacro(Buf, "__PIC__=1"); 609 610 // Macros to control C99 numerics and <float.h> 611 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0"); 612 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2"); 613 sprintf(MacroBuf, "__DECIMAL_DIG__=%d", 614 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33)); 615 DefineBuiltinMacro(Buf, MacroBuf); 616 617 // Get other target #defines. 618 TI.getTargetDefines(Buf); 619 620 // FIXME: Should emit a #line directive here. 621} 622 623 624/// EnterMainSourceFile - Enter the specified FileID as the main source file, 625/// which implicitly adds the builtin defines etc. 626void Preprocessor::EnterMainSourceFile() { 627 // We do not allow the preprocessor to reenter the main file. Doing so will 628 // cause FileID's to accumulate information from both runs (e.g. #line 629 // information) and predefined macros aren't guaranteed to be set properly. 630 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!"); 631 FileID MainFileID = SourceMgr.getMainFileID(); 632 633 // Enter the main file source buffer. 634 EnterSourceFile(MainFileID, 0); 635 636 // Tell the header info that the main file was entered. If the file is later 637 // #imported, it won't be re-entered. 638 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) 639 HeaderInfo.IncrementIncludeCount(FE); 640 641 std::vector<char> PrologFile; 642 PrologFile.reserve(4080); 643 644 // Install things like __POWERPC__, __GNUC__, etc into the macro table. 645 InitializePredefinedMacros(*this, PrologFile); 646 647 // Add on the predefines from the driver. 648 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end()); 649 650 // Memory buffer must end with a null byte! 651 PrologFile.push_back(0); 652 653 // Now that we have emitted the predefined macros, #includes, etc into 654 // PrologFile, preprocess it to populate the initial preprocessor state. 655 llvm::MemoryBuffer *SB = 656 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(), 657 "<predefines>"); 658 assert(SB && "Cannot fail to create predefined source buffer"); 659 FileID FID = SourceMgr.createFileIDForMemBuffer(SB); 660 assert(!FID.isInvalid() && "Could not create FileID for predefines?"); 661 662 // Start parsing the predefines. 663 EnterSourceFile(FID, 0); 664} 665 666 667//===----------------------------------------------------------------------===// 668// Lexer Event Handling. 669//===----------------------------------------------------------------------===// 670 671/// LookUpIdentifierInfo - Given a tok::identifier token, look up the 672/// identifier information for the token and install it into the token. 673IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier, 674 const char *BufPtr) { 675 assert(Identifier.is(tok::identifier) && "Not an identifier!"); 676 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!"); 677 678 // Look up this token, see if it is a macro, or if it is a language keyword. 679 IdentifierInfo *II; 680 if (BufPtr && !Identifier.needsCleaning()) { 681 // No cleaning needed, just use the characters from the lexed buffer. 682 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength()); 683 } else { 684 // Cleaning needed, alloca a buffer, clean into it, then use the buffer. 685 llvm::SmallVector<char, 64> IdentifierBuffer; 686 IdentifierBuffer.resize(Identifier.getLength()); 687 const char *TmpBuf = &IdentifierBuffer[0]; 688 unsigned Size = getSpelling(Identifier, TmpBuf); 689 II = getIdentifierInfo(TmpBuf, TmpBuf+Size); 690 } 691 Identifier.setIdentifierInfo(II); 692 return II; 693} 694 695 696/// HandleIdentifier - This callback is invoked when the lexer reads an 697/// identifier. This callback looks up the identifier in the map and/or 698/// potentially macro expands it or turns it into a named token (like 'for'). 699/// 700/// Note that callers of this method are guarded by checking the 701/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the 702/// IdentifierInfo methods that compute these properties will need to change to 703/// match. 704void Preprocessor::HandleIdentifier(Token &Identifier) { 705 assert(Identifier.getIdentifierInfo() && 706 "Can't handle identifiers without identifier info!"); 707 708 IdentifierInfo &II = *Identifier.getIdentifierInfo(); 709 710 // If this identifier was poisoned, and if it was not produced from a macro 711 // expansion, emit an error. 712 if (II.isPoisoned() && CurPPLexer) { 713 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning. 714 Diag(Identifier, diag::err_pp_used_poisoned_id); 715 else 716 Diag(Identifier, diag::ext_pp_bad_vaargs_use); 717 } 718 719 // If this is a macro to be expanded, do it. 720 if (MacroInfo *MI = getMacroInfo(&II)) { 721 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) { 722 if (MI->isEnabled()) { 723 if (!HandleMacroExpandedIdentifier(Identifier, MI)) 724 return; 725 } else { 726 // C99 6.10.3.4p2 says that a disabled macro may never again be 727 // expanded, even if it's in a context where it could be expanded in the 728 // future. 729 Identifier.setFlag(Token::DisableExpand); 730 } 731 } 732 } 733 734 // C++ 2.11p2: If this is an alternative representation of a C++ operator, 735 // then we act as if it is the actual operator and not the textual 736 // representation of it. 737 if (II.isCPlusPlusOperatorKeyword()) 738 Identifier.setIdentifierInfo(0); 739 740 // If this is an extension token, diagnose its use. 741 // We avoid diagnosing tokens that originate from macro definitions. 742 if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion) 743 Diag(Identifier, diag::ext_token_used); 744} 745