blob: dc4dd877b67390451f4fe88a7d72977ccf479514 [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"
Chris Lattnercbed2992008-10-05 20:40:30 +000036#include "llvm/ADT/APFloat.h"
Chris Lattner4b009652007-07-25 00:24:17 +000037#include "llvm/ADT/SmallVector.h"
38#include "llvm/Support/MemoryBuffer.h"
Ted Kremenekce4c64e2008-01-14 16:44:48 +000039#include "llvm/Support/Streams.h"
Chris Lattner4b009652007-07-25 00:24:17 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
Ted Kremenek5ab36b02008-04-17 21:23:07 +000044PreprocessorFactory::~PreprocessorFactory() {}
45
Chris Lattner4b009652007-07-25 00:24:17 +000046Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
47 TargetInfo &target, SourceManager &SM,
48 HeaderSearch &Headers)
49 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
50 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattner5b54ed92008-03-09 02:26:03 +000051 CurLexer(0), CurDirLookup(0), CurTokenLexer(0), Callbacks(0) {
Chris Lattner4b009652007-07-25 00:24:17 +000052 ScratchBuf = new ScratchBuffer(SourceMgr);
53
54 // Clear stats.
55 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
56 NumIf = NumElse = NumEndif = 0;
57 NumEnteredSourceFiles = 0;
58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
59 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
60 MaxIncludeStackDepth = 0;
61 NumSkipped = 0;
62
63 // Default to discarding comments.
64 KeepComments = false;
65 KeepMacroComments = false;
66
67 // Macro expansion is enabled.
68 DisableMacroExpansion = false;
69 InMacroArgs = false;
Chris Lattner5b54ed92008-03-09 02:26:03 +000070 NumCachedTokenLexers = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000071
Argiris Kirtzidisf55b1102008-08-10 13:15:22 +000072 CacheTokens = false;
73 CachedLexPos = 0;
74
Chris Lattner4b009652007-07-25 00:24:17 +000075 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
76 // This gets unpoisoned where it is allowed.
77 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
78
79 // Initialize the pragma handlers.
80 PragmaHandlers = new PragmaNamespace(0);
81 RegisterBuiltinPragmas();
82
83 // Initialize builtin macros like __LINE__ and friends.
84 RegisterBuiltinMacros();
85}
86
87Preprocessor::~Preprocessor() {
Argiris Kirtzidis1370cf12008-08-23 12:12:06 +000088 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
89
Chris Lattner4b009652007-07-25 00:24:17 +000090 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
Chris Lattner4b009652007-07-25 00:24:17 +0000118/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
119/// the specified Token's location, translating the token's start
120/// position in the current buffer into a SourcePosition object for rendering.
121void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
Ted Kremenekd7f64cd2007-12-12 22:39:36 +0000122 Diags.Report(getFullLoc(Loc), DiagID);
Chris Lattner4b009652007-07-25 00:24:17 +0000123}
124
125void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
126 const std::string &Msg) {
Chris Lattnerb034e282008-11-18 04:56:44 +0000127 const std::string *Strs[] = { &Msg };
128 Diags.Report(getFullLoc(Loc), DiagID, Strs, 1);
Chris Lattner4b009652007-07-25 00:24:17 +0000129}
130
Chris Lattnerbef45c52008-05-05 06:45:50 +0000131void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
132 const std::string &Msg,
133 const SourceRange &R1, const SourceRange &R2) {
Chris Lattnerb034e282008-11-18 04:56:44 +0000134 const std::string *Strs[] = { &Msg };
Chris Lattnerbef45c52008-05-05 06:45:50 +0000135 SourceRange R[] = {R1, R2};
Chris Lattnerb034e282008-11-18 04:56:44 +0000136 Diags.Report(getFullLoc(Loc), DiagID, Strs, 1, R, 2);
Chris Lattnerbef45c52008-05-05 06:45:50 +0000137}
138
139
140void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
141 const SourceRange &R) {
142 Diags.Report(getFullLoc(Loc), DiagID, 0, 0, &R, 1);
143}
144
145void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
146 const SourceRange &R1, const SourceRange &R2) {
147 SourceRange R[] = {R1, R2};
148 Diags.Report(getFullLoc(Loc), DiagID, 0, 0, R, 2);
149}
150
151
Chris Lattner4b009652007-07-25 00:24:17 +0000152void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000153 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
154 << getSpelling(Tok) << "'";
Chris Lattner4b009652007-07-25 00:24:17 +0000155
156 if (!DumpFlags) return;
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000157
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000158 llvm::cerr << "\t";
Chris Lattner4b009652007-07-25 00:24:17 +0000159 if (Tok.isAtStartOfLine())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000160 llvm::cerr << " [StartOfLine]";
Chris Lattner4b009652007-07-25 00:24:17 +0000161 if (Tok.hasLeadingSpace())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000162 llvm::cerr << " [LeadingSpace]";
Chris Lattner4b009652007-07-25 00:24:17 +0000163 if (Tok.isExpandDisabled())
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000164 llvm::cerr << " [ExpandDisabled]";
Chris Lattner4b009652007-07-25 00:24:17 +0000165 if (Tok.needsCleaning()) {
166 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000167 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
168 << "']";
Chris Lattner4b009652007-07-25 00:24:17 +0000169 }
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000170
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000171 llvm::cerr << "\tLoc=<";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000172 DumpLocation(Tok.getLocation());
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000173 llvm::cerr << ">";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000174}
175
176void Preprocessor::DumpLocation(SourceLocation Loc) const {
177 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000178 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
179 << SourceMgr.getLineNumber(LogLoc) << ':'
Ted Kremenek79882742008-07-19 19:10:04 +0000180 << SourceMgr.getColumnNumber(LogLoc);
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000181
182 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
183 if (PhysLoc != LogLoc) {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000184 llvm::cerr << " <PhysLoc=";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000185 DumpLocation(PhysLoc);
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000186 llvm::cerr << ">";
Chris Lattnerc0f7c512007-12-09 20:31:55 +0000187 }
Chris Lattner4b009652007-07-25 00:24:17 +0000188}
189
190void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000191 llvm::cerr << "MACRO: ";
Chris Lattner4b009652007-07-25 00:24:17 +0000192 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
193 DumpToken(MI.getReplacementToken(i));
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000194 llvm::cerr << " ";
Chris Lattner4b009652007-07-25 00:24:17 +0000195 }
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000196 llvm::cerr << "\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000197}
198
199void Preprocessor::PrintStats() {
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000200 llvm::cerr << "\n*** Preprocessor Stats:\n";
201 llvm::cerr << NumDirectives << " directives found:\n";
202 llvm::cerr << " " << NumDefined << " #define.\n";
203 llvm::cerr << " " << NumUndefined << " #undef.\n";
204 llvm::cerr << " #include/#include_next/#import:\n";
205 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
206 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
207 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
208 llvm::cerr << " " << NumElse << " #else/#elif.\n";
209 llvm::cerr << " " << NumEndif << " #endif.\n";
210 llvm::cerr << " " << NumPragma << " #pragma.\n";
211 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000212
Ted Kremenekce4c64e2008-01-14 16:44:48 +0000213 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
214 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
215 << NumFastMacroExpanded << " on the fast path.\n";
216 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
217 << " token paste (##) operations performed, "
218 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner4b009652007-07-25 00:24:17 +0000219}
220
221//===----------------------------------------------------------------------===//
222// Token Spelling
223//===----------------------------------------------------------------------===//
224
225
226/// getSpelling() - Return the 'spelling' of this token. The spelling of a
227/// token are the characters used to represent the token in the source file
228/// after trigraph expansion and escaped-newline folding. In particular, this
229/// wants to get the true, uncanonicalized, spelling of things like digraphs
230/// UCNs, etc.
231std::string Preprocessor::getSpelling(const Token &Tok) const {
232 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
233
234 // If this token contains nothing interesting, return it directly.
235 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
236 if (!Tok.needsCleaning())
237 return std::string(TokStart, TokStart+Tok.getLength());
238
239 std::string Result;
240 Result.reserve(Tok.getLength());
241
242 // Otherwise, hard case, relex the characters into the string.
243 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
244 Ptr != End; ) {
245 unsigned CharSize;
246 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
247 Ptr += CharSize;
248 }
249 assert(Result.size() != unsigned(Tok.getLength()) &&
250 "NeedsCleaning flag set on something that didn't need cleaning!");
251 return Result;
252}
253
254/// getSpelling - This method is used to get the spelling of a token into a
255/// preallocated buffer, instead of as an std::string. The caller is required
256/// to allocate enough space for the token, which is guaranteed to be at least
257/// Tok.getLength() bytes long. The actual length of the token is returned.
258///
259/// Note that this method may do two possible things: it may either fill in
260/// the buffer specified with characters, or it may *change the input pointer*
261/// to point to a constant buffer with the data already in it (avoiding a
262/// copy). The caller is not allowed to modify the returned buffer pointer
263/// if an internal buffer is returned.
264unsigned Preprocessor::getSpelling(const Token &Tok,
265 const char *&Buffer) const {
266 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
267
268 // If this token is an identifier, just return the string from the identifier
269 // table, which is very quick.
270 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
271 Buffer = II->getName();
272
273 // Return the length of the token. If the token needed cleaning, don't
274 // include the size of the newlines or trigraphs in it.
275 if (!Tok.needsCleaning())
276 return Tok.getLength();
277 else
278 return strlen(Buffer);
279 }
280
281 // Otherwise, compute the start of the token in the input lexer buffer.
282 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
283
284 // If this token contains nothing interesting, return it directly.
285 if (!Tok.needsCleaning()) {
286 Buffer = TokStart;
287 return Tok.getLength();
288 }
289 // Otherwise, hard case, relex the characters into the string.
290 char *OutBuf = const_cast<char*>(Buffer);
291 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
292 Ptr != End; ) {
293 unsigned CharSize;
294 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
295 Ptr += CharSize;
296 }
297 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
298 "NeedsCleaning flag set on something that didn't need cleaning!");
299
300 return OutBuf-Buffer;
301}
302
303
304/// CreateString - Plop the specified string into a scratch buffer and return a
305/// location for it. If specified, the source location provides a source
306/// location for the token.
307SourceLocation Preprocessor::
308CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
309 if (SLoc.isValid())
310 return ScratchBuf->getToken(Buf, Len, SLoc);
311 return ScratchBuf->getToken(Buf, Len);
312}
313
314
315/// AdvanceToTokenCharacter - Given a location that specifies the start of a
316/// token, return a new location that specifies a character within the token.
317SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
318 unsigned CharNo) {
319 // If they request the first char of the token, we're trivially done. If this
320 // is a macro expansion, it doesn't make sense to point to a character within
321 // the instantiation point (the name). We could point to the source
322 // character, but without also pointing to instantiation info, this is
323 // confusing.
324 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
325
326 // Figure out how many physical characters away the specified logical
327 // character is. This needs to take into consideration newlines and
328 // trigraphs.
329 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
330 unsigned PhysOffset = 0;
331
332 // The usual case is that tokens don't contain anything interesting. Skip
333 // over the uninteresting characters. If a token only consists of simple
334 // chars, this method is extremely fast.
335 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
336 ++TokPtr, --CharNo, ++PhysOffset;
337
338 // If we have a character that may be a trigraph or escaped newline, create a
339 // lexer to parse it correctly.
340 if (CharNo != 0) {
341 // Create a lexer starting at this token position.
342 Lexer TheLexer(TokStart, *this, TokPtr);
343 Token Tok;
344 // Skip over characters the remaining characters.
345 const char *TokStartPtr = TokPtr;
346 for (; CharNo; --CharNo)
347 TheLexer.getAndAdvanceChar(TokPtr, Tok);
348
349 PhysOffset += TokPtr-TokStartPtr;
350 }
351
352 return TokStart.getFileLocWithOffset(PhysOffset);
353}
354
355
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000356//===----------------------------------------------------------------------===//
357// Preprocessor Initialization Methods
358//===----------------------------------------------------------------------===//
359
360// Append a #define line to Buf for Macro. Macro should be of the form XXX,
361// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
362// "#define XXX Y z W". To get a #define with no value, use "XXX=".
363static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
364 const char *Command = "#define ") {
365 Buf.insert(Buf.end(), Command, Command+strlen(Command));
366 if (const char *Equal = strchr(Macro, '=')) {
367 // Turn the = into ' '.
368 Buf.insert(Buf.end(), Macro, Equal);
369 Buf.push_back(' ');
370 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
371 } else {
372 // Push "macroname 1".
373 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
374 Buf.push_back(' ');
375 Buf.push_back('1');
376 }
377 Buf.push_back('\n');
378}
379
Chris Lattnercbed2992008-10-05 20:40:30 +0000380/// PickFP - This is used to pick a value based on the FP semantics of the
381/// specified FP model.
382template <typename T>
383static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
384 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
385 if (Sem == &llvm::APFloat::IEEEsingle)
386 return IEEESingleVal;
387 if (Sem == &llvm::APFloat::IEEEdouble)
388 return IEEEDoubleVal;
389 if (Sem == &llvm::APFloat::x87DoubleExtended)
390 return X87DoubleExtendedVal;
391 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
392 return PPCDoubleDoubleVal;
393}
394
395static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
396 const llvm::fltSemantics *Sem) {
Chris Lattner5c8f64a2008-10-05 21:40:58 +0000397 const char *DenormMin, *Epsilon, *Max, *Min;
398 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
399 "3.64519953188247460253e-4951L",
400 "4.94065645841246544176568792868221e-324L");
401 int Digits = PickFP(Sem, 6, 15, 18, 31);
402 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
403 "1.08420217248550443401e-19L",
404 "4.94065645841246544176568792868221e-324L");
405 int HasInifinity = 1, HasQuietNaN = 1;
406 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
407 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
408 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
409 int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
410 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
411 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
412 "3.36210314311209350626e-4932L",
413 "2.00416836000897277799610805135016e-292L");
414 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
415 "1.18973149535723176502e+4932L",
416 "1.79769313486231580793728971405301e+308L");
Chris Lattnercbed2992008-10-05 20:40:30 +0000417
418 char MacroBuf[60];
419 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
420 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner5c8f64a2008-10-05 21:40:58 +0000421 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
422 DefineBuiltinMacro(Buf, MacroBuf);
423 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
424 DefineBuiltinMacro(Buf, MacroBuf);
425 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
426 DefineBuiltinMacro(Buf, MacroBuf);
427 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
428 DefineBuiltinMacro(Buf, MacroBuf);
429 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
430 DefineBuiltinMacro(Buf, MacroBuf);
431 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
432 DefineBuiltinMacro(Buf, MacroBuf);
433 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
434 DefineBuiltinMacro(Buf, MacroBuf);
435 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
436 DefineBuiltinMacro(Buf, MacroBuf);
437 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
438 DefineBuiltinMacro(Buf, MacroBuf);
439 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
440 DefineBuiltinMacro(Buf, MacroBuf);
441 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
442 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattnercbed2992008-10-05 20:40:30 +0000443}
444
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000445
446static void InitializePredefinedMacros(Preprocessor &PP,
447 std::vector<char> &Buf) {
Chris Lattnera023ec52008-10-05 19:32:22 +0000448 // Compiler version introspection macros.
449 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
450 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
451
452 // Currently claim to be compatible with GCC 4.2.1-5621.
453 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
454 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
455 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
456 DefineBuiltinMacro(Buf, "__GNUC__=4");
457 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
458 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 (Apple Computer, Inc. "
459 "build 5621) (dot 3)\"");
460
461
462 // Initialize language-specific preprocessor defines.
463
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000464 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
465 // and __DATE__ etc.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000466 // These should all be defined in the preprocessor according to the
467 // current language configuration.
468 DefineBuiltinMacro(Buf, "__STDC__=1");
469 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
470 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
471 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
472 else if (0) // STDC94 ?
473 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
474
475 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000476 if (PP.getLangOptions().ObjC1) {
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000477 DefineBuiltinMacro(Buf, "__OBJC__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000478
479 if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) {
480 DefineBuiltinMacro(Buf, "__weak=");
481 DefineBuiltinMacro(Buf, "__strong=");
482 } else {
483 DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))");
484 DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))");
485 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
486 }
487
488 if (PP.getLangOptions().NeXTRuntime)
489 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
Daniel Dunbar428e6762008-08-12 00:21:46 +0000490 }
Chris Lattner5edfe012008-10-05 19:44:25 +0000491
Chris Lattnerd5e60992008-10-06 07:43:09 +0000492 // darwin_constant_cfstrings controls this. This is also dependent
493 // on other things like the runtime I believe. This is set even for C code.
494 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
495
Steve Naroffb3cd9ac2008-05-15 21:12:10 +0000496 if (PP.getLangOptions().ObjC2)
497 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
Steve Naroffae84af82007-10-31 18:42:27 +0000498
Chris Lattner9b96b152008-09-30 00:48:48 +0000499 if (PP.getLangOptions().PascalStrings)
500 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
501
Chris Lattnera023ec52008-10-05 19:32:22 +0000502 if (PP.getLangOptions().Blocks) {
503 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
504 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
Chris Lattnerce296f82008-10-05 19:32:52 +0000505 }
Chris Lattnera023ec52008-10-05 19:32:22 +0000506
507 if (PP.getLangOptions().CPlusPlus) {
508 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
509 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
510 DefineBuiltinMacro(Buf, "__GNUG__=4");
511 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
512 DefineBuiltinMacro(Buf, "__cplusplus=1");
513 DefineBuiltinMacro(Buf, "__private_extern__=extern");
514 }
515
516 // Filter out some microsoft extensions when trying to parse in ms-compat
517 // mode.
518 if (PP.getLangOptions().Microsoft) {
519 DefineBuiltinMacro(Buf, "__stdcall=");
520 DefineBuiltinMacro(Buf, "__cdecl=");
521 DefineBuiltinMacro(Buf, "_cdecl=");
522 DefineBuiltinMacro(Buf, "__ptr64=");
523 DefineBuiltinMacro(Buf, "__w64=");
524 DefineBuiltinMacro(Buf, "__forceinline=");
525 DefineBuiltinMacro(Buf, "__int8=char");
526 DefineBuiltinMacro(Buf, "__int16=short");
527 DefineBuiltinMacro(Buf, "__int32=int");
528 DefineBuiltinMacro(Buf, "__int64=long long");
529 DefineBuiltinMacro(Buf, "__declspec(X)=");
530 }
531
532
533 // Initialize target-specific preprocessor defines.
Chris Lattner5edfe012008-10-05 19:44:25 +0000534 const TargetInfo &TI = PP.getTargetInfo();
535
536 // Define type sizing macros based on the target properties.
537 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
538 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
539 DefineBuiltinMacro(Buf, "__SCHAR_MAX__=127");
Chris Lattnercbed2992008-10-05 20:40:30 +0000540
541 assert(TI.getWCharWidth() == 32 && "Only support 32-bit wchar so far");
542 DefineBuiltinMacro(Buf, "__WCHAR_MAX__=2147483647");
543 DefineBuiltinMacro(Buf, "__WCHAR_TYPE__=int");
544 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
Chris Lattner5edfe012008-10-05 19:44:25 +0000545
546 assert(TI.getShortWidth() == 16 && "Only support 16-bit short so far");
Chris Lattner5edfe012008-10-05 19:44:25 +0000547 DefineBuiltinMacro(Buf, "__SHRT_MAX__=32767");
548
Chris Lattner1be8bb92008-10-05 20:06:37 +0000549 if (TI.getIntWidth() == 32)
550 DefineBuiltinMacro(Buf, "__INT_MAX__=2147483647");
551 else if (TI.getIntWidth() == 16)
552 DefineBuiltinMacro(Buf, "__INT_MAX__=32767");
553 else
554 assert(0 && "Unknown integer size");
Sanjiv Guptafa451432008-10-31 09:52:39 +0000555
556 if (TI.getLongLongWidth() == 64)
557 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=9223372036854775807LL");
558 else if (TI.getLongLongWidth() == 32)
559 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=2147483647L");
Chris Lattner5edfe012008-10-05 19:44:25 +0000560
Chris Lattner1be8bb92008-10-05 20:06:37 +0000561 if (TI.getLongWidth() == 32)
562 DefineBuiltinMacro(Buf, "__LONG_MAX__=2147483647L");
563 else if (TI.getLongWidth() == 64)
564 DefineBuiltinMacro(Buf, "__LONG_MAX__=9223372036854775807L");
565 else if (TI.getLongWidth() == 16)
566 DefineBuiltinMacro(Buf, "__LONG_MAX__=32767L");
567 else
568 assert(0 && "Unknown long size");
Sanjiv Guptafa451432008-10-31 09:52:39 +0000569 char MacroBuf[60];
570 sprintf(MacroBuf, "__INTMAX_MAX__=%lld",
571 (TI.getIntMaxType() == TargetInfo::UnsignedLongLong?
Sanjiv Guptaf9bfd002008-10-31 10:24:31 +0000572 (1LL << (TI.getLongLongWidth() - 1)) :
573 ((1LL << (TI.getLongLongWidth() - 2)) - 1)));
Sanjiv Guptafa451432008-10-31 09:52:39 +0000574 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner1be8bb92008-10-05 20:06:37 +0000575
Sanjiv Guptafa451432008-10-31 09:52:39 +0000576 if (TI.getIntMaxType() == TargetInfo::UnsignedLongLong)
577 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long long int");
578 else if (TI.getIntMaxType() == TargetInfo::SignedLongLong)
Chris Lattner1be8bb92008-10-05 20:06:37 +0000579 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long long int");
Sanjiv Guptafa451432008-10-31 09:52:39 +0000580 else if (TI.getIntMaxType() == TargetInfo::UnsignedLong)
581 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long int");
582 else if (TI.getIntMaxType() == TargetInfo::SignedLong)
583 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long int");
584 else if (TI.getIntMaxType() == TargetInfo::UnsignedInt)
585 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned int");
586 else
587 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=int");
Chris Lattner1be8bb92008-10-05 20:06:37 +0000588
Sanjiv Guptafa451432008-10-31 09:52:39 +0000589 if (TI.getUIntMaxType() == TargetInfo::UnsignedLongLong)
590 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long long int");
591 else if (TI.getUIntMaxType() == TargetInfo::SignedLongLong)
592 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long long int");
593 else if (TI.getUIntMaxType() == TargetInfo::UnsignedLong)
594 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long int");
595 else if (TI.getUIntMaxType() == TargetInfo::SignedLong)
596 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long int");
597 else if (TI.getUIntMaxType() == TargetInfo::UnsignedInt)
598 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned int");
599 else
600 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=int");
601
602 if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLongLong)
603 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long long int");
604 else if (TI.getPtrDiffType(0) == TargetInfo::SignedLongLong)
605 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long long int");
606 else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLong)
607 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long int");
608 else if (TI.getPtrDiffType(0) == TargetInfo::SignedLong)
609 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long int");
610 else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedInt)
611 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned int");
612 else
613 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=int");
614
615 if (TI.getSizeType() == TargetInfo::UnsignedLongLong)
616 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long long int");
617 else if (TI.getSizeType() == TargetInfo::SignedLongLong)
618 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long long int");
619 else if (TI.getSizeType() == TargetInfo::UnsignedLong)
620 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long int");
621 else if (TI.getSizeType() == TargetInfo::SignedLong)
622 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long int");
623 else if (TI.getSizeType() == TargetInfo::UnsignedInt)
624 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned int");
625 else if (TI.getSizeType() == TargetInfo::SignedInt)
626 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=int");
627 else
628 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned short");
629
Chris Lattnercbed2992008-10-05 20:40:30 +0000630 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
631 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
632 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
Chris Lattner1be8bb92008-10-05 20:06:37 +0000633
Chris Lattner9b96b152008-09-30 00:48:48 +0000634
Chris Lattner77cec472007-10-10 17:48:53 +0000635 // Add __builtin_va_list typedef.
636 {
Chris Lattner5edfe012008-10-05 19:44:25 +0000637 const char *VAList = TI.getVAListDeclaration();
Chris Lattner77cec472007-10-10 17:48:53 +0000638 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
639 Buf.push_back('\n');
640 }
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000641
Chris Lattner5edfe012008-10-05 19:44:25 +0000642 if (const char *Prefix = TI.getUserLabelPrefix()) {
Chris Lattner3da35682008-10-05 21:49:27 +0000643 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
644 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner3f6d8cf2008-10-05 19:22:37 +0000645 }
646
Chris Lattner5edfe012008-10-05 19:44:25 +0000647 // Build configuration options. FIXME: these should be controlled by
648 // command line options or something.
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000649 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
650 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
651 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
652 DefineBuiltinMacro(Buf, "__PIC__=1");
Chris Lattner5edfe012008-10-05 19:44:25 +0000653
Chris Lattner3da35682008-10-05 21:49:27 +0000654 // Macros to control C99 numerics and <float.h>
655 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
656 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
657 sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
658 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
659 DefineBuiltinMacro(Buf, MacroBuf);
660
Chris Lattner5edfe012008-10-05 19:44:25 +0000661 // Get other target #defines.
662 TI.getTargetDefines(Buf);
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000663
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000664 // FIXME: Should emit a #line directive here.
665}
666
667
668/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman886bf132008-01-07 04:01:26 +0000669/// which implicitly adds the builtin defines etc.
Ted Kremenek17861c52007-12-19 22:51:13 +0000670void Preprocessor::EnterMainSourceFile() {
671
672 unsigned MainFileID = SourceMgr.getMainFileID();
673
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000674 // Enter the main file source buffer.
675 EnterSourceFile(MainFileID, 0);
676
Chris Lattnerb45f05c2007-11-15 19:07:47 +0000677 // Tell the header info that the main file was entered. If the file is later
678 // #imported, it won't be re-entered.
679 if (const FileEntry *FE =
680 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
681 HeaderInfo.IncrementIncludeCount(FE);
682
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000683 std::vector<char> PrologFile;
684 PrologFile.reserve(4080);
685
686 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
687 InitializePredefinedMacros(*this, PrologFile);
688
689 // Add on the predefines from the driver.
Chris Lattner47b6a162008-04-19 23:09:31 +0000690 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
Chris Lattnerd1f21e12007-10-09 22:10:18 +0000691
692 // Memory buffer must end with a null byte!
693 PrologFile.push_back(0);
694
695 // Now that we have emitted the predefined macros, #includes, etc into
696 // PrologFile, preprocess it to populate the initial preprocessor state.
697 llvm::MemoryBuffer *SB =
698 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
699 "<predefines>");
700 assert(SB && "Cannot fail to create predefined source buffer");
701 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
702 assert(FileID && "Could not create FileID for predefines?");
703
704 // Start parsing the predefines.
705 EnterSourceFile(FileID, 0);
706}
Chris Lattner4b009652007-07-25 00:24:17 +0000707
Chris Lattner4b009652007-07-25 00:24:17 +0000708
709//===----------------------------------------------------------------------===//
710// Lexer Event Handling.
711//===----------------------------------------------------------------------===//
712
713/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
714/// identifier information for the token and install it into the token.
715IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
716 const char *BufPtr) {
Chris Lattnercb8e41c2007-10-09 18:02:16 +0000717 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattner4b009652007-07-25 00:24:17 +0000718 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
719
720 // Look up this token, see if it is a macro, or if it is a language keyword.
721 IdentifierInfo *II;
722 if (BufPtr && !Identifier.needsCleaning()) {
723 // No cleaning needed, just use the characters from the lexed buffer.
724 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
725 } else {
726 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
727 llvm::SmallVector<char, 64> IdentifierBuffer;
728 IdentifierBuffer.resize(Identifier.getLength());
729 const char *TmpBuf = &IdentifierBuffer[0];
730 unsigned Size = getSpelling(Identifier, TmpBuf);
731 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
732 }
733 Identifier.setIdentifierInfo(II);
734 return II;
735}
736
737
738/// HandleIdentifier - This callback is invoked when the lexer reads an
739/// identifier. This callback looks up the identifier in the map and/or
740/// potentially macro expands it or turns it into a named token (like 'for').
741void Preprocessor::HandleIdentifier(Token &Identifier) {
742 assert(Identifier.getIdentifierInfo() &&
743 "Can't handle identifiers without identifier info!");
744
745 IdentifierInfo &II = *Identifier.getIdentifierInfo();
746
747 // If this identifier was poisoned, and if it was not produced from a macro
748 // expansion, emit an error.
749 if (II.isPoisoned() && CurLexer) {
750 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
751 Diag(Identifier, diag::err_pp_used_poisoned_id);
752 else
753 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
754 }
755
756 // If this is a macro to be expanded, do it.
Chris Lattner7a1b0882007-10-07 08:44:20 +0000757 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000758 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
759 if (MI->isEnabled()) {
760 if (!HandleMacroExpandedIdentifier(Identifier, MI))
761 return;
762 } else {
763 // C99 6.10.3.4p2 says that a disabled macro may never again be
764 // expanded, even if it's in a context where it could be expanded in the
765 // future.
766 Identifier.setFlag(Token::DisableExpand);
767 }
768 }
Chris Lattner4b009652007-07-25 00:24:17 +0000769 }
770
771 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
772 // then we act as if it is the actual operator and not the textual
773 // representation of it.
774 if (II.isCPlusPlusOperatorKeyword())
775 Identifier.setIdentifierInfo(0);
776
777 // Change the kind of this identifier to the appropriate token kind, e.g.
778 // turning "for" into a keyword.
779 Identifier.setKind(II.getTokenID());
780
781 // If this is an extension token, diagnose its use.
Steve Naroff892bc0e2008-09-02 18:50:17 +0000782 // We avoid diagnosing tokens that originate from macro definitions.
783 if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion)
Chris Lattner4b009652007-07-25 00:24:17 +0000784 Diag(Identifier, diag::ext_token_used);
785}