blob: dcb399d1fa300926fcd276f8733d8443d63a1f17 [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() {
87 // Free any active lexers.
88 delete CurLexer;
89
90 while (!IncludeMacroStack.empty()) {
91 delete IncludeMacroStack.back().TheLexer;
Chris Lattner5b54ed92008-03-09 02:26:03 +000092 delete IncludeMacroStack.back().TheTokenLexer;
Chris Lattner4b009652007-07-25 00:24:17 +000093 IncludeMacroStack.pop_back();
94 }
Chris Lattner7a1b0882007-10-07 08:44:20 +000095
96 // Free any macro definitions.
97 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
98 Macros.begin(), E = Macros.end(); I != E; ++I) {
99 // Free the macro definition.
100 delete I->second;
101 I->second = 0;
102 I->first->setHasMacroDefinition(false);
103 }
Chris Lattner4b009652007-07-25 00:24:17 +0000104
105 // Free any cached macro expanders.
Chris Lattner5b54ed92008-03-09 02:26:03 +0000106 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
107 delete TokenLexerCache[i];
Chris Lattner4b009652007-07-25 00:24:17 +0000108
109 // Release pragma information.
110 delete PragmaHandlers;
111
112 // Delete the scratch buffer info.
113 delete ScratchBuf;
Chris Lattner65829812008-03-14 06:07:05 +0000114
115 delete Callbacks;
Chris Lattner4b009652007-07-25 00:24:17 +0000116}
117
Nico Weberd2a6ac92008-08-10 19:59:06 +0000118bool Preprocessor::isSystemHeader(const FileEntry* F) const {
119 if (F) {
120 DirectoryLookup::DirType DirInfo = HeaderInfo.getFileDirFlavor(F);
121 if (DirInfo == DirectoryLookup::SystemHeaderDir ||
122 DirInfo == DirectoryLookup::ExternCSystemHeaderDir)
123 return true;
124 }
125 return false;
126}
127
128
Chris Lattner4b009652007-07-25 00:24:17 +0000129/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
130/// the specified Token's location, translating the token's start
131/// position in the current buffer into a SourcePosition object for rendering.
132void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000133 Diags.Report(getFullLoc(Loc), DiagID);
Chris Lattner4b009652007-07-25 00:24:17 +0000134}
135
136void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
137 const std::string &Msg) {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000138 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000139}
140
Chris Lattnerbef45c52008-05-05 06:45:50 +0000141void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
142 const std::string &Msg,
143 const SourceRange &R1, const SourceRange &R2) {
144 SourceRange R[] = {R1, R2};
145 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1, R, 2);
146}
147
148
149void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
150 const SourceRange &R) {
151 Diags.Report(getFullLoc(Loc), DiagID, 0, 0, &R, 1);
152}
153
154void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
155 const SourceRange &R1, const SourceRange &R2) {
156 SourceRange R[] = {R1, R2};
157 Diags.Report(getFullLoc(Loc), DiagID, 0, 0, R, 2);
158}
159
160
Chris Lattner4b009652007-07-25 00:24:17 +0000161void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000162 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
163 << getSpelling(Tok) << "'";
Chris Lattner4b009652007-07-25 00:24:17 +0000164
165 if (!DumpFlags) return;
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000166
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000167 llvm::cerr << "\t";
Chris Lattner4b009652007-07-25 00:24:17 +0000168 if (Tok.isAtStartOfLine())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000169 llvm::cerr << " [StartOfLine]";
Chris Lattner4b009652007-07-25 00:24:17 +0000170 if (Tok.hasLeadingSpace())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000171 llvm::cerr << " [LeadingSpace]";
Chris Lattner4b009652007-07-25 00:24:17 +0000172 if (Tok.isExpandDisabled())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000173 llvm::cerr << " [ExpandDisabled]";
Chris Lattner4b009652007-07-25 00:24:17 +0000174 if (Tok.needsCleaning()) {
175 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000176 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
177 << "']";
Chris Lattner4b009652007-07-25 00:24:17 +0000178 }
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000179
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000180 llvm::cerr << "\tLoc=<";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000181 DumpLocation(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000182 llvm::cerr << ">";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000183}
184
185void Preprocessor::DumpLocation(SourceLocation Loc) const {
186 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000187 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
188 << SourceMgr.getLineNumber(LogLoc) << ':'
Ted Kremenek79882742008-07-19 19:10:04 +0000189 << SourceMgr.getColumnNumber(LogLoc);
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000190
191 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
192 if (PhysLoc != LogLoc) {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000193 llvm::cerr << " <PhysLoc=";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000194 DumpLocation(PhysLoc);
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000195 llvm::cerr << ">";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000196 }
Chris Lattner4b009652007-07-25 00:24:17 +0000197}
198
199void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000200 llvm::cerr << "MACRO: ";
Chris Lattner4b009652007-07-25 00:24:17 +0000201 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
202 DumpToken(MI.getReplacementToken(i));
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000203 llvm::cerr << " ";
Chris Lattner4b009652007-07-25 00:24:17 +0000204 }
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000205 llvm::cerr << "\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000206}
207
208void Preprocessor::PrintStats() {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000209 llvm::cerr << "\n*** Preprocessor Stats:\n";
210 llvm::cerr << NumDirectives << " directives found:\n";
211 llvm::cerr << " " << NumDefined << " #define.\n";
212 llvm::cerr << " " << NumUndefined << " #undef.\n";
213 llvm::cerr << " #include/#include_next/#import:\n";
214 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
215 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
216 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
217 llvm::cerr << " " << NumElse << " #else/#elif.\n";
218 llvm::cerr << " " << NumEndif << " #endif.\n";
219 llvm::cerr << " " << NumPragma << " #pragma.\n";
220 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000221
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000222 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
223 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
224 << NumFastMacroExpanded << " on the fast path.\n";
225 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
226 << " token paste (##) operations performed, "
227 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000228}
229
230//===----------------------------------------------------------------------===//
231// Token Spelling
232//===----------------------------------------------------------------------===//
233
234
235/// getSpelling() - Return the 'spelling' of this token. The spelling of a
236/// token are the characters used to represent the token in the source file
237/// after trigraph expansion and escaped-newline folding. In particular, this
238/// wants to get the true, uncanonicalized, spelling of things like digraphs
239/// UCNs, etc.
240std::string Preprocessor::getSpelling(const Token &Tok) const {
241 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
242
243 // If this token contains nothing interesting, return it directly.
244 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
245 if (!Tok.needsCleaning())
246 return std::string(TokStart, TokStart+Tok.getLength());
247
248 std::string Result;
249 Result.reserve(Tok.getLength());
250
251 // Otherwise, hard case, relex the characters into the string.
252 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
253 Ptr != End; ) {
254 unsigned CharSize;
255 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
256 Ptr += CharSize;
257 }
258 assert(Result.size() != unsigned(Tok.getLength()) &&
259 "NeedsCleaning flag set on something that didn't need cleaning!");
260 return Result;
261}
262
263/// getSpelling - This method is used to get the spelling of a token into a
264/// preallocated buffer, instead of as an std::string. The caller is required
265/// to allocate enough space for the token, which is guaranteed to be at least
266/// Tok.getLength() bytes long. The actual length of the token is returned.
267///
268/// Note that this method may do two possible things: it may either fill in
269/// the buffer specified with characters, or it may *change the input pointer*
270/// to point to a constant buffer with the data already in it (avoiding a
271/// copy). The caller is not allowed to modify the returned buffer pointer
272/// if an internal buffer is returned.
273unsigned Preprocessor::getSpelling(const Token &Tok,
274 const char *&Buffer) const {
275 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
276
277 // If this token is an identifier, just return the string from the identifier
278 // table, which is very quick.
279 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
280 Buffer = II->getName();
281
282 // Return the length of the token. If the token needed cleaning, don't
283 // include the size of the newlines or trigraphs in it.
284 if (!Tok.needsCleaning())
285 return Tok.getLength();
286 else
287 return strlen(Buffer);
288 }
289
290 // Otherwise, compute the start of the token in the input lexer buffer.
291 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
292
293 // If this token contains nothing interesting, return it directly.
294 if (!Tok.needsCleaning()) {
295 Buffer = TokStart;
296 return Tok.getLength();
297 }
298 // Otherwise, hard case, relex the characters into the string.
299 char *OutBuf = const_cast<char*>(Buffer);
300 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
301 Ptr != End; ) {
302 unsigned CharSize;
303 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
304 Ptr += CharSize;
305 }
306 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
307 "NeedsCleaning flag set on something that didn't need cleaning!");
308
309 return OutBuf-Buffer;
310}
311
312
313/// CreateString - Plop the specified string into a scratch buffer and return a
314/// location for it. If specified, the source location provides a source
315/// location for the token.
316SourceLocation Preprocessor::
317CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
318 if (SLoc.isValid())
319 return ScratchBuf->getToken(Buf, Len, SLoc);
320 return ScratchBuf->getToken(Buf, Len);
321}
322
323
324/// AdvanceToTokenCharacter - Given a location that specifies the start of a
325/// token, return a new location that specifies a character within the token.
326SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
327 unsigned CharNo) {
328 // If they request the first char of the token, we're trivially done. If this
329 // is a macro expansion, it doesn't make sense to point to a character within
330 // the instantiation point (the name). We could point to the source
331 // character, but without also pointing to instantiation info, this is
332 // confusing.
333 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
334
335 // Figure out how many physical characters away the specified logical
336 // character is. This needs to take into consideration newlines and
337 // trigraphs.
338 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
339 unsigned PhysOffset = 0;
340
341 // The usual case is that tokens don't contain anything interesting. Skip
342 // over the uninteresting characters. If a token only consists of simple
343 // chars, this method is extremely fast.
344 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
345 ++TokPtr, --CharNo, ++PhysOffset;
346
347 // If we have a character that may be a trigraph or escaped newline, create a
348 // lexer to parse it correctly.
349 if (CharNo != 0) {
350 // Create a lexer starting at this token position.
351 Lexer TheLexer(TokStart, *this, TokPtr);
352 Token Tok;
353 // Skip over characters the remaining characters.
354 const char *TokStartPtr = TokPtr;
355 for (; CharNo; --CharNo)
356 TheLexer.getAndAdvanceChar(TokPtr, Tok);
357
358 PhysOffset += TokPtr-TokStartPtr;
359 }
360
361 return TokStart.getFileLocWithOffset(PhysOffset);
362}
363
364
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000365//===----------------------------------------------------------------------===//
366// Preprocessor Initialization Methods
367//===----------------------------------------------------------------------===//
368
369// Append a #define line to Buf for Macro. Macro should be of the form XXX,
370// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
371// "#define XXX Y z W". To get a #define with no value, use "XXX=".
372static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
373 const char *Command = "#define ") {
374 Buf.insert(Buf.end(), Command, Command+strlen(Command));
375 if (const char *Equal = strchr(Macro, '=')) {
376 // Turn the = into ' '.
377 Buf.insert(Buf.end(), Macro, Equal);
378 Buf.push_back(' ');
379 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
380 } else {
381 // Push "macroname 1".
382 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
383 Buf.push_back(' ');
384 Buf.push_back('1');
385 }
386 Buf.push_back('\n');
387}
388
389
390static void InitializePredefinedMacros(Preprocessor &PP,
391 std::vector<char> &Buf) {
392 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
393 // and __DATE__ etc.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000394 // These should all be defined in the preprocessor according to the
395 // current language configuration.
396 DefineBuiltinMacro(Buf, "__STDC__=1");
397 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
398 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
399 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
400 else if (0) // STDC94 ?
401 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
402
403 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
404 if (PP.getLangOptions().ObjC1)
405 DefineBuiltinMacro(Buf, "__OBJC__=1");
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000406 if (PP.getLangOptions().ObjC2)
407 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
Steve Naroffae84af82007-10-31 18:42:27 +0000408
Chris Lattner77cec472007-10-10 17:48:53 +0000409 // Add __builtin_va_list typedef.
410 {
411 const char *VAList = PP.getTargetInfo().getVAListDeclaration();
412 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
413 Buf.push_back('\n');
414 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000415
416 // Get the target #defines.
417 PP.getTargetInfo().getTargetDefines(Buf);
Chris Lattnerc74ae3b2008-06-26 17:26:01 +0000418
419 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
420 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000421
422 // Compiler set macros.
423 DefineBuiltinMacro(Buf, "__APPLE_CC__=5250");
Steve Naroffb5a086e2007-11-10 18:06:36 +0000424 DefineBuiltinMacro(Buf, "__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1050");
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000425 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=0");
426 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
427 DefineBuiltinMacro(Buf, "__GNUC__=4");
428 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
429 DefineBuiltinMacro(Buf, "__VERSION__=\"4.0.1 (Apple Computer, Inc. "
430 "build 5250)\"");
431
432 // Build configuration options.
433 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
434 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
435 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
436 DefineBuiltinMacro(Buf, "__PIC__=1");
437
438
439 if (PP.getLangOptions().CPlusPlus) {
440 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
441 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
442 DefineBuiltinMacro(Buf, "__GNUG__=4");
443 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
444 DefineBuiltinMacro(Buf, "__cplusplus=1");
445 DefineBuiltinMacro(Buf, "__private_extern__=extern");
446 }
Steve Naroff73a07032008-02-07 03:50:06 +0000447 if (PP.getLangOptions().Microsoft) {
448 DefineBuiltinMacro(Buf, "__stdcall=");
449 DefineBuiltinMacro(Buf, "__cdecl=");
450 DefineBuiltinMacro(Buf, "_cdecl=");
451 DefineBuiltinMacro(Buf, "__ptr64=");
Steve Naroffbe880ec2008-02-07 23:24:32 +0000452 DefineBuiltinMacro(Buf, "__w64=");
Steve Naroff73a07032008-02-07 03:50:06 +0000453 DefineBuiltinMacro(Buf, "__forceinline=");
Steve Narofff9bba132008-02-07 15:26:07 +0000454 DefineBuiltinMacro(Buf, "__int8=char");
455 DefineBuiltinMacro(Buf, "__int16=short");
456 DefineBuiltinMacro(Buf, "__int32=int");
Chris Lattnerd1a552b2008-02-10 21:12:45 +0000457 DefineBuiltinMacro(Buf, "__int64=long long");
Steve Naroffcfe78212008-02-11 22:29:58 +0000458 DefineBuiltinMacro(Buf, "__declspec(X)=");
Steve Naroff73a07032008-02-07 03:50:06 +0000459 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000460 // FIXME: Should emit a #line directive here.
461}
462
463
464/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman886bf132008-01-07 04:01:26 +0000465/// which implicitly adds the builtin defines etc.
Ted Kremenek17861c52007-12-19 22:51:13 +0000466void Preprocessor::EnterMainSourceFile() {
467
468 unsigned MainFileID = SourceMgr.getMainFileID();
469
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000470 // Enter the main file source buffer.
471 EnterSourceFile(MainFileID, 0);
472
Chris Lattnerb45f05c2007-11-15 19:07:47 +0000473 // Tell the header info that the main file was entered. If the file is later
474 // #imported, it won't be re-entered.
475 if (const FileEntry *FE =
476 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
477 HeaderInfo.IncrementIncludeCount(FE);
478
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000479 std::vector<char> PrologFile;
480 PrologFile.reserve(4080);
481
482 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
483 InitializePredefinedMacros(*this, PrologFile);
484
485 // Add on the predefines from the driver.
Chris Lattner47b6a162008-04-19 23:09:31 +0000486 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000487
488 // Memory buffer must end with a null byte!
489 PrologFile.push_back(0);
490
491 // Now that we have emitted the predefined macros, #includes, etc into
492 // PrologFile, preprocess it to populate the initial preprocessor state.
493 llvm::MemoryBuffer *SB =
494 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
495 "<predefines>");
496 assert(SB && "Cannot fail to create predefined source buffer");
497 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
498 assert(FileID && "Could not create FileID for predefines?");
499
500 // Start parsing the predefines.
501 EnterSourceFile(FileID, 0);
502}
Chris Lattner4b009652007-07-25 00:24:17 +0000503
Chris Lattner4b009652007-07-25 00:24:17 +0000504
505//===----------------------------------------------------------------------===//
506// Lexer Event Handling.
507//===----------------------------------------------------------------------===//
508
509/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
510/// identifier information for the token and install it into the token.
511IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
512 const char *BufPtr) {
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000513 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattner4b009652007-07-25 00:24:17 +0000514 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
515
516 // Look up this token, see if it is a macro, or if it is a language keyword.
517 IdentifierInfo *II;
518 if (BufPtr && !Identifier.needsCleaning()) {
519 // No cleaning needed, just use the characters from the lexed buffer.
520 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
521 } else {
522 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
523 llvm::SmallVector<char, 64> IdentifierBuffer;
524 IdentifierBuffer.resize(Identifier.getLength());
525 const char *TmpBuf = &IdentifierBuffer[0];
526 unsigned Size = getSpelling(Identifier, TmpBuf);
527 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
528 }
529 Identifier.setIdentifierInfo(II);
530 return II;
531}
532
533
534/// HandleIdentifier - This callback is invoked when the lexer reads an
535/// identifier. This callback looks up the identifier in the map and/or
536/// potentially macro expands it or turns it into a named token (like 'for').
537void Preprocessor::HandleIdentifier(Token &Identifier) {
538 assert(Identifier.getIdentifierInfo() &&
539 "Can't handle identifiers without identifier info!");
540
541 IdentifierInfo &II = *Identifier.getIdentifierInfo();
542
543 // If this identifier was poisoned, and if it was not produced from a macro
544 // expansion, emit an error.
545 if (II.isPoisoned() && CurLexer) {
546 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
547 Diag(Identifier, diag::err_pp_used_poisoned_id);
548 else
549 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
550 }
551
552 // If this is a macro to be expanded, do it.
Chris Lattner7a1b0882007-10-07 08:44:20 +0000553 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000554 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
555 if (MI->isEnabled()) {
556 if (!HandleMacroExpandedIdentifier(Identifier, MI))
557 return;
558 } else {
559 // C99 6.10.3.4p2 says that a disabled macro may never again be
560 // expanded, even if it's in a context where it could be expanded in the
561 // future.
562 Identifier.setFlag(Token::DisableExpand);
563 }
564 }
Chris Lattner4b009652007-07-25 00:24:17 +0000565 }
566
567 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
568 // then we act as if it is the actual operator and not the textual
569 // representation of it.
570 if (II.isCPlusPlusOperatorKeyword())
571 Identifier.setIdentifierInfo(0);
572
573 // Change the kind of this identifier to the appropriate token kind, e.g.
574 // turning "for" into a keyword.
575 Identifier.setKind(II.getTokenID());
576
577 // If this is an extension token, diagnose its use.
578 // FIXME: tried (unsuccesfully) to shut this up when compiling with gnu99
579 // For now, I'm just commenting it out (while I work on attributes).
580 if (II.isExtensionToken() && Features.C99)
581 Diag(Identifier, diag::ext_token_used);
582}