blob: 18b106ad84127fe13ed597dddfbe486d8e35a58e [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
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[MDNI] - 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"
Chris Lattner4b009652007-07-25 00:24:17 +000031#include "clang/Lex/Pragma.h"
32#include "clang/Lex/ScratchBuffer.h"
33#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000034#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
36#include "llvm/ADT/SmallVector.h"
37#include "llvm/Support/MemoryBuffer.h"
Ted Kremenekce4c64e2008-01-14 16:44:48 +000038#include "llvm/Support/Streams.h"
Chris Lattner4b009652007-07-25 00:24:17 +000039using namespace clang;
40
41//===----------------------------------------------------------------------===//
42
Ted Kremenek5ab36b02008-04-17 21:23:07 +000043PreprocessorFactory::~PreprocessorFactory() {}
44
Chris Lattner4b009652007-07-25 00:24:17 +000045Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
46 TargetInfo &target, SourceManager &SM,
47 HeaderSearch &Headers)
48 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
49 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattner5b54ed92008-03-09 02:26:03 +000050 CurLexer(0), CurDirLookup(0), CurTokenLexer(0), Callbacks(0) {
Chris Lattner4b009652007-07-25 00:24:17 +000051 ScratchBuf = new ScratchBuffer(SourceMgr);
52
53 // Clear stats.
54 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
55 NumIf = NumElse = NumEndif = 0;
56 NumEnteredSourceFiles = 0;
57 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
58 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
59 MaxIncludeStackDepth = 0;
60 NumSkipped = 0;
61
62 // Default to discarding comments.
63 KeepComments = false;
64 KeepMacroComments = false;
65
66 // Macro expansion is enabled.
67 DisableMacroExpansion = false;
68 InMacroArgs = false;
Chris Lattner5b54ed92008-03-09 02:26:03 +000069 NumCachedTokenLexers = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000070
Argiris Kirtzidisf55b1102008-08-10 13:15:22 +000071 CacheTokens = false;
72 CachedLexPos = 0;
73
Chris Lattner4b009652007-07-25 00:24:17 +000074 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
75 // This gets unpoisoned where it is allowed.
76 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
77
78 // Initialize the pragma handlers.
79 PragmaHandlers = new PragmaNamespace(0);
80 RegisterBuiltinPragmas();
81
82 // Initialize builtin macros like __LINE__ and friends.
83 RegisterBuiltinMacros();
84}
85
86Preprocessor::~Preprocessor() {
Argiris Kirtzidis1370cf12008-08-23 12:12:06 +000087 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
88
Chris Lattner4b009652007-07-25 00:24:17 +000089 // Free any active lexers.
90 delete CurLexer;
91
92 while (!IncludeMacroStack.empty()) {
93 delete IncludeMacroStack.back().TheLexer;
Chris Lattner5b54ed92008-03-09 02:26:03 +000094 delete IncludeMacroStack.back().TheTokenLexer;
Chris Lattner4b009652007-07-25 00:24:17 +000095 IncludeMacroStack.pop_back();
96 }
Chris Lattner7a1b0882007-10-07 08:44:20 +000097
98 // Free any macro definitions.
99 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
100 Macros.begin(), E = Macros.end(); I != E; ++I) {
101 // Free the macro definition.
102 delete I->second;
103 I->second = 0;
104 I->first->setHasMacroDefinition(false);
105 }
Chris Lattner4b009652007-07-25 00:24:17 +0000106
107 // Free any cached macro expanders.
Chris Lattner5b54ed92008-03-09 02:26:03 +0000108 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
109 delete TokenLexerCache[i];
Chris Lattner4b009652007-07-25 00:24:17 +0000110
111 // Release pragma information.
112 delete PragmaHandlers;
113
114 // Delete the scratch buffer info.
115 delete ScratchBuf;
Chris Lattner65829812008-03-14 06:07:05 +0000116
117 delete Callbacks;
Chris Lattner4b009652007-07-25 00:24:17 +0000118}
119
Nico Weberd2a6ac92008-08-10 19:59:06 +0000120bool Preprocessor::isSystemHeader(const FileEntry* F) const {
121 if (F) {
122 DirectoryLookup::DirType DirInfo = HeaderInfo.getFileDirFlavor(F);
123 if (DirInfo == DirectoryLookup::SystemHeaderDir ||
124 DirInfo == DirectoryLookup::ExternCSystemHeaderDir)
125 return true;
126 }
127 return false;
128}
129
130
Chris Lattner4b009652007-07-25 00:24:17 +0000131/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
132/// the specified Token's location, translating the token's start
133/// position in the current buffer into a SourcePosition object for rendering.
134void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000135 Diags.Report(getFullLoc(Loc), DiagID);
Chris Lattner4b009652007-07-25 00:24:17 +0000136}
137
138void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
139 const std::string &Msg) {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000140 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000141}
142
Chris Lattnerbef45c52008-05-05 06:45:50 +0000143void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
144 const std::string &Msg,
145 const SourceRange &R1, const SourceRange &R2) {
146 SourceRange R[] = {R1, R2};
147 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1, R, 2);
148}
149
150
151void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
152 const SourceRange &R) {
153 Diags.Report(getFullLoc(Loc), DiagID, 0, 0, &R, 1);
154}
155
156void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
157 const SourceRange &R1, const SourceRange &R2) {
158 SourceRange R[] = {R1, R2};
159 Diags.Report(getFullLoc(Loc), DiagID, 0, 0, R, 2);
160}
161
162
Chris Lattner4b009652007-07-25 00:24:17 +0000163void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000164 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
165 << getSpelling(Tok) << "'";
Chris Lattner4b009652007-07-25 00:24:17 +0000166
167 if (!DumpFlags) return;
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000168
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000169 llvm::cerr << "\t";
Chris Lattner4b009652007-07-25 00:24:17 +0000170 if (Tok.isAtStartOfLine())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000171 llvm::cerr << " [StartOfLine]";
Chris Lattner4b009652007-07-25 00:24:17 +0000172 if (Tok.hasLeadingSpace())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000173 llvm::cerr << " [LeadingSpace]";
Chris Lattner4b009652007-07-25 00:24:17 +0000174 if (Tok.isExpandDisabled())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000175 llvm::cerr << " [ExpandDisabled]";
Chris Lattner4b009652007-07-25 00:24:17 +0000176 if (Tok.needsCleaning()) {
177 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000178 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
179 << "']";
Chris Lattner4b009652007-07-25 00:24:17 +0000180 }
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000181
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000182 llvm::cerr << "\tLoc=<";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000183 DumpLocation(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000184 llvm::cerr << ">";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000185}
186
187void Preprocessor::DumpLocation(SourceLocation Loc) const {
188 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000189 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
190 << SourceMgr.getLineNumber(LogLoc) << ':'
Ted Kremenek79882742008-07-19 19:10:04 +0000191 << SourceMgr.getColumnNumber(LogLoc);
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000192
193 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
194 if (PhysLoc != LogLoc) {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000195 llvm::cerr << " <PhysLoc=";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000196 DumpLocation(PhysLoc);
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000197 llvm::cerr << ">";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000198 }
Chris Lattner4b009652007-07-25 00:24:17 +0000199}
200
201void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000202 llvm::cerr << "MACRO: ";
Chris Lattner4b009652007-07-25 00:24:17 +0000203 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
204 DumpToken(MI.getReplacementToken(i));
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000205 llvm::cerr << " ";
Chris Lattner4b009652007-07-25 00:24:17 +0000206 }
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000207 llvm::cerr << "\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000208}
209
210void Preprocessor::PrintStats() {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000211 llvm::cerr << "\n*** Preprocessor Stats:\n";
212 llvm::cerr << NumDirectives << " directives found:\n";
213 llvm::cerr << " " << NumDefined << " #define.\n";
214 llvm::cerr << " " << NumUndefined << " #undef.\n";
215 llvm::cerr << " #include/#include_next/#import:\n";
216 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
217 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
218 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
219 llvm::cerr << " " << NumElse << " #else/#elif.\n";
220 llvm::cerr << " " << NumEndif << " #endif.\n";
221 llvm::cerr << " " << NumPragma << " #pragma.\n";
222 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000223
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000224 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
225 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
226 << NumFastMacroExpanded << " on the fast path.\n";
227 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
228 << " token paste (##) operations performed, "
229 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000230}
231
232//===----------------------------------------------------------------------===//
233// Token Spelling
234//===----------------------------------------------------------------------===//
235
236
237/// getSpelling() - Return the 'spelling' of this token. The spelling of a
238/// token are the characters used to represent the token in the source file
239/// after trigraph expansion and escaped-newline folding. In particular, this
240/// wants to get the true, uncanonicalized, spelling of things like digraphs
241/// UCNs, etc.
242std::string Preprocessor::getSpelling(const Token &Tok) const {
243 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
244
245 // If this token contains nothing interesting, return it directly.
246 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
247 if (!Tok.needsCleaning())
248 return std::string(TokStart, TokStart+Tok.getLength());
249
250 std::string Result;
251 Result.reserve(Tok.getLength());
252
253 // Otherwise, hard case, relex the characters into the string.
254 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
255 Ptr != End; ) {
256 unsigned CharSize;
257 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
258 Ptr += CharSize;
259 }
260 assert(Result.size() != unsigned(Tok.getLength()) &&
261 "NeedsCleaning flag set on something that didn't need cleaning!");
262 return Result;
263}
264
265/// getSpelling - This method is used to get the spelling of a token into a
266/// preallocated buffer, instead of as an std::string. The caller is required
267/// to allocate enough space for the token, which is guaranteed to be at least
268/// Tok.getLength() bytes long. The actual length of the token is returned.
269///
270/// Note that this method may do two possible things: it may either fill in
271/// the buffer specified with characters, or it may *change the input pointer*
272/// to point to a constant buffer with the data already in it (avoiding a
273/// copy). The caller is not allowed to modify the returned buffer pointer
274/// if an internal buffer is returned.
275unsigned Preprocessor::getSpelling(const Token &Tok,
276 const char *&Buffer) const {
277 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
278
279 // If this token is an identifier, just return the string from the identifier
280 // table, which is very quick.
281 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
282 Buffer = II->getName();
283
284 // Return the length of the token. If the token needed cleaning, don't
285 // include the size of the newlines or trigraphs in it.
286 if (!Tok.needsCleaning())
287 return Tok.getLength();
288 else
289 return strlen(Buffer);
290 }
291
292 // Otherwise, compute the start of the token in the input lexer buffer.
293 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
294
295 // If this token contains nothing interesting, return it directly.
296 if (!Tok.needsCleaning()) {
297 Buffer = TokStart;
298 return Tok.getLength();
299 }
300 // Otherwise, hard case, relex the characters into the string.
301 char *OutBuf = const_cast<char*>(Buffer);
302 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
303 Ptr != End; ) {
304 unsigned CharSize;
305 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
306 Ptr += CharSize;
307 }
308 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
309 "NeedsCleaning flag set on something that didn't need cleaning!");
310
311 return OutBuf-Buffer;
312}
313
314
315/// CreateString - Plop the specified string into a scratch buffer and return a
316/// location for it. If specified, the source location provides a source
317/// location for the token.
318SourceLocation Preprocessor::
319CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
320 if (SLoc.isValid())
321 return ScratchBuf->getToken(Buf, Len, SLoc);
322 return ScratchBuf->getToken(Buf, Len);
323}
324
325
326/// AdvanceToTokenCharacter - Given a location that specifies the start of a
327/// token, return a new location that specifies a character within the token.
328SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
329 unsigned CharNo) {
330 // If they request the first char of the token, we're trivially done. If this
331 // is a macro expansion, it doesn't make sense to point to a character within
332 // the instantiation point (the name). We could point to the source
333 // character, but without also pointing to instantiation info, this is
334 // confusing.
335 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
336
337 // Figure out how many physical characters away the specified logical
338 // character is. This needs to take into consideration newlines and
339 // trigraphs.
340 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
341 unsigned PhysOffset = 0;
342
343 // The usual case is that tokens don't contain anything interesting. Skip
344 // over the uninteresting characters. If a token only consists of simple
345 // chars, this method is extremely fast.
346 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
347 ++TokPtr, --CharNo, ++PhysOffset;
348
349 // If we have a character that may be a trigraph or escaped newline, create a
350 // lexer to parse it correctly.
351 if (CharNo != 0) {
352 // Create a lexer starting at this token position.
353 Lexer TheLexer(TokStart, *this, TokPtr);
354 Token Tok;
355 // Skip over characters the remaining characters.
356 const char *TokStartPtr = TokPtr;
357 for (; CharNo; --CharNo)
358 TheLexer.getAndAdvanceChar(TokPtr, Tok);
359
360 PhysOffset += TokPtr-TokStartPtr;
361 }
362
363 return TokStart.getFileLocWithOffset(PhysOffset);
364}
365
366
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000367//===----------------------------------------------------------------------===//
368// Preprocessor Initialization Methods
369//===----------------------------------------------------------------------===//
370
371// Append a #define line to Buf for Macro. Macro should be of the form XXX,
372// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
373// "#define XXX Y z W". To get a #define with no value, use "XXX=".
374static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
375 const char *Command = "#define ") {
376 Buf.insert(Buf.end(), Command, Command+strlen(Command));
377 if (const char *Equal = strchr(Macro, '=')) {
378 // Turn the = into ' '.
379 Buf.insert(Buf.end(), Macro, Equal);
380 Buf.push_back(' ');
381 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
382 } else {
383 // Push "macroname 1".
384 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
385 Buf.push_back(' ');
386 Buf.push_back('1');
387 }
388 Buf.push_back('\n');
389}
390
391
392static void InitializePredefinedMacros(Preprocessor &PP,
393 std::vector<char> &Buf) {
394 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
395 // and __DATE__ etc.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000396 // These should all be defined in the preprocessor according to the
397 // current language configuration.
398 DefineBuiltinMacro(Buf, "__STDC__=1");
399 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
400 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
401 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
402 else if (0) // STDC94 ?
403 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
404
405 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000406 if (PP.getLangOptions().ObjC1) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000407 DefineBuiltinMacro(Buf, "__OBJC__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000408
409 if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) {
410 DefineBuiltinMacro(Buf, "__weak=");
411 DefineBuiltinMacro(Buf, "__strong=");
412 } else {
413 DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))");
414 DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))");
415 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
416 }
417
418 if (PP.getLangOptions().NeXTRuntime)
419 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
420
421 // darwin_constant_cfstrings controls this. This is also dependent
422 // on other things like the runtime I believe.
423 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
424 }
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000425 if (PP.getLangOptions().ObjC2)
426 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
Steve Naroffae84af82007-10-31 18:42:27 +0000427
Chris Lattner77cec472007-10-10 17:48:53 +0000428 // Add __builtin_va_list typedef.
429 {
430 const char *VAList = PP.getTargetInfo().getVAListDeclaration();
431 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
432 Buf.push_back('\n');
433 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000434
435 // Get the target #defines.
436 PP.getTargetInfo().getTargetDefines(Buf);
Chris Lattnerc74ae3b2008-06-26 17:26:01 +0000437
438 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
439 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000440
441 // Compiler set macros.
442 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
Steve Naroffb5a086e2007-11-10 18:06:36 +0000443 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1050");
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000444 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
445 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
446 DefineBuiltinMacro(Buf, "__GNUC__=4");
447 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
448 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
449 "build 5250)\"");
450
451 // Build configuration options.
452 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
453 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
454 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
455 DefineBuiltinMacro(Buf, "__PIC__=1");
456
457
458 if (PP.getLangOptions().CPlusPlus) {
459 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
460 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
461 DefineBuiltinMacro(Buf, "__GNUG__=4");
462 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
463 DefineBuiltinMacro(Buf, "__cplusplus=1");
464 DefineBuiltinMacro(Buf, "__private_extern__=extern");
465 }
Steve Naroff73a07032008-02-07 03:50:06 +0000466 if (PP.getLangOptions().Microsoft) {
467 DefineBuiltinMacro(Buf, "__stdcall=");
468 DefineBuiltinMacro(Buf, "__cdecl=");
469 DefineBuiltinMacro(Buf, "_cdecl=");
470 DefineBuiltinMacro(Buf, "__ptr64=");
Steve Naroffbe880ec2008-02-07 23:24:32 +0000471 DefineBuiltinMacro(Buf, "__w64=");
Steve Naroff73a07032008-02-07 03:50:06 +0000472 DefineBuiltinMacro(Buf, "__forceinline=");
Steve Narofff9bba132008-02-07 15:26:07 +0000473 DefineBuiltinMacro(Buf, "__int8=char");
474 DefineBuiltinMacro(Buf, "__int16=short");
475 DefineBuiltinMacro(Buf, "__int32=int");
Chris Lattnerd1a552b2008-02-10 21:12:45 +0000476 DefineBuiltinMacro(Buf, "__int64=long long");
Steve Naroffcfe78212008-02-11 22:29:58 +0000477 DefineBuiltinMacro(Buf, "__declspec(X)=");
Steve Naroff73a07032008-02-07 03:50:06 +0000478 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000479 // FIXME: Should emit a #line directive here.
480}
481
482
483/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman886bf132008-01-07 04:01:26 +0000484/// which implicitly adds the builtin defines etc.
Ted Kremenek17861c52007-12-19 22:51:13 +0000485void Preprocessor::EnterMainSourceFile() {
486
487 unsigned MainFileID = SourceMgr.getMainFileID();
488
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000489 // Enter the main file source buffer.
490 EnterSourceFile(MainFileID, 0);
491
Chris Lattnerb45f05c2007-11-15 19:07:47 +0000492 // Tell the header info that the main file was entered. If the file is later
493 // #imported, it won't be re-entered.
494 if (const FileEntry *FE =
495 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
496 HeaderInfo.IncrementIncludeCount(FE);
497
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000498 std::vector<char> PrologFile;
499 PrologFile.reserve(4080);
500
501 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
502 InitializePredefinedMacros(*this, PrologFile);
503
504 // Add on the predefines from the driver.
Chris Lattner47b6a162008-04-19 23:09:31 +0000505 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000506
507 // Memory buffer must end with a null byte!
508 PrologFile.push_back(0);
509
510 // Now that we have emitted the predefined macros, #includes, etc into
511 // PrologFile, preprocess it to populate the initial preprocessor state.
512 llvm::MemoryBuffer *SB =
513 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
514 "<predefines>");
515 assert(SB && "Cannot fail to create predefined source buffer");
516 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
517 assert(FileID && "Could not create FileID for predefines?");
518
519 // Start parsing the predefines.
520 EnterSourceFile(FileID, 0);
521}
Chris Lattner4b009652007-07-25 00:24:17 +0000522
Chris Lattner4b009652007-07-25 00:24:17 +0000523
524//===----------------------------------------------------------------------===//
525// Lexer Event Handling.
526//===----------------------------------------------------------------------===//
527
528/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
529/// identifier information for the token and install it into the token.
530IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
531 const char *BufPtr) {
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000532 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattner4b009652007-07-25 00:24:17 +0000533 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
534
535 // Look up this token, see if it is a macro, or if it is a language keyword.
536 IdentifierInfo *II;
537 if (BufPtr && !Identifier.needsCleaning()) {
538 // No cleaning needed, just use the characters from the lexed buffer.
539 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
540 } else {
541 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
542 llvm::SmallVector<char, 64> IdentifierBuffer;
543 IdentifierBuffer.resize(Identifier.getLength());
544 const char *TmpBuf = &IdentifierBuffer[0];
545 unsigned Size = getSpelling(Identifier, TmpBuf);
546 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
547 }
548 Identifier.setIdentifierInfo(II);
549 return II;
550}
551
552
553/// HandleIdentifier - This callback is invoked when the lexer reads an
554/// identifier. This callback looks up the identifier in the map and/or
555/// potentially macro expands it or turns it into a named token (like 'for').
556void Preprocessor::HandleIdentifier(Token &Identifier) {
557 assert(Identifier.getIdentifierInfo() &&
558 "Can't handle identifiers without identifier info!");
559
560 IdentifierInfo &II = *Identifier.getIdentifierInfo();
561
562 // If this identifier was poisoned, and if it was not produced from a macro
563 // expansion, emit an error.
564 if (II.isPoisoned() && CurLexer) {
565 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
566 Diag(Identifier, diag::err_pp_used_poisoned_id);
567 else
568 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
569 }
570
571 // If this is a macro to be expanded, do it.
Chris Lattner7a1b0882007-10-07 08:44:20 +0000572 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000573 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
574 if (MI->isEnabled()) {
575 if (!HandleMacroExpandedIdentifier(Identifier, MI))
576 return;
577 } else {
578 // C99 6.10.3.4p2 says that a disabled macro may never again be
579 // expanded, even if it's in a context where it could be expanded in the
580 // future.
581 Identifier.setFlag(Token::DisableExpand);
582 }
583 }
Chris Lattner4b009652007-07-25 00:24:17 +0000584 }
585
586 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
587 // then we act as if it is the actual operator and not the textual
588 // representation of it.
589 if (II.isCPlusPlusOperatorKeyword())
590 Identifier.setIdentifierInfo(0);
591
592 // Change the kind of this identifier to the appropriate token kind, e.g.
593 // turning "for" into a keyword.
594 Identifier.setKind(II.getTokenID());
595
596 // If this is an extension token, diagnose its use.
597 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
598 // For now, I'm just commenting it out (while I work on attributes).
599 if (II.isExtensionToken() && Features.C99)
600 Diag(Identifier, diag::ext_token_used);
601}