blob: 2d4d3a7324d58bd27d00eb38b2c2d3d5f968a302 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +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"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Lex/Pragma.h"
32#include "clang/Lex/ScratchBuffer.h"
33#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
Chris Lattner2db78dd2008-10-05 20:40:30 +000036#include "llvm/ADT/APFloat.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000037#include "llvm/ADT/SmallVector.h"
Chris Lattner97ba77c2007-07-16 06:48:38 +000038#include "llvm/Support/MemoryBuffer.h"
Ted Kremenekbdd30c22008-01-14 16:44:48 +000039#include "llvm/Support/Streams.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
Ted Kremenekec6c5742008-04-17 21:23:07 +000044PreprocessorFactory::~PreprocessorFactory() {}
45
Reid Spencer5f016e22007-07-11 17:01:13 +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),
Ted Kremenek4b71e3e2008-11-19 00:44:06 +000051 CurPPLexer(0), CurDirLookup(0), Callbacks(0) {
Reid Spencer5f016e22007-07-11 17:01:13 +000052 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattner9594acf2007-07-15 00:25:26 +000053
Reid Spencer5f016e22007-07-11 17:01:13 +000054 // 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 Lattner6cfe7592008-03-09 02:26:03 +000070 NumCachedTokenLexers = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000071
Argyrios Kyrtzidis03db1b32008-08-10 13:15:22 +000072 CacheTokens = false;
73 CachedLexPos = 0;
74
Reid Spencer5f016e22007-07-11 17:01:13 +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() {
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +000088 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
89
Reid Spencer5f016e22007-07-11 17:01:13 +000090 while (!IncludeMacroStack.empty()) {
91 delete IncludeMacroStack.back().TheLexer;
Chris Lattner6cfe7592008-03-09 02:26:03 +000092 delete IncludeMacroStack.back().TheTokenLexer;
Reid Spencer5f016e22007-07-11 17:01:13 +000093 IncludeMacroStack.pop_back();
94 }
Chris Lattnercc1a8752007-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 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000104
Chris Lattner9594acf2007-07-15 00:25:26 +0000105 // Free any cached macro expanders.
Chris Lattner6cfe7592008-03-09 02:26:03 +0000106 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
107 delete TokenLexerCache[i];
Chris Lattner9594acf2007-07-15 00:25:26 +0000108
Reid Spencer5f016e22007-07-11 17:01:13 +0000109 // Release pragma information.
110 delete PragmaHandlers;
111
112 // Delete the scratch buffer info.
113 delete ScratchBuf;
Chris Lattnereb50ed82008-03-14 06:07:05 +0000114
115 delete Callbacks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000116}
117
Reid Spencer5f016e22007-07-11 17:01:13 +0000118/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
Chris Lattnerd2177732007-07-20 16:59:19 +0000119/// the specified Token's location, translating the token's start
Reid Spencer5f016e22007-07-11 17:01:13 +0000120/// position in the current buffer into a SourcePosition object for rendering.
Chris Lattner3692b092008-11-18 07:59:24 +0000121DiagnosticInfo Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
122 return Diags.Report(getFullLoc(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000123}
124
Chris Lattner3692b092008-11-18 07:59:24 +0000125DiagnosticInfo Preprocessor::Diag(const Token &Tok, unsigned DiagID) {
126 return Diags.Report(getFullLoc(Tok.getLocation()), DiagID);
127}
128
Chris Lattnerd2177732007-07-20 16:59:19 +0000129void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000130 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
131 << getSpelling(Tok) << "'";
Reid Spencer5f016e22007-07-11 17:01:13 +0000132
133 if (!DumpFlags) return;
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000134
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000135 llvm::cerr << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 if (Tok.isAtStartOfLine())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000137 llvm::cerr << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000138 if (Tok.hasLeadingSpace())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000139 llvm::cerr << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 if (Tok.isExpandDisabled())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000141 llvm::cerr << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000142 if (Tok.needsCleaning()) {
143 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000144 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
145 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 }
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000147
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000148 llvm::cerr << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000149 DumpLocation(Tok.getLocation());
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000150 llvm::cerr << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000151}
152
153void Preprocessor::DumpLocation(SourceLocation Loc) const {
154 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000155 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
156 << SourceMgr.getLineNumber(LogLoc) << ':'
Ted Kremenek109949a2008-07-19 19:10:04 +0000157 << SourceMgr.getColumnNumber(LogLoc);
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000158
159 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
160 if (PhysLoc != LogLoc) {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000161 llvm::cerr << " <PhysLoc=";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000162 DumpLocation(PhysLoc);
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000163 llvm::cerr << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000164 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000165}
166
167void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000168 llvm::cerr << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
170 DumpToken(MI.getReplacementToken(i));
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000171 llvm::cerr << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000172 }
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000173 llvm::cerr << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000174}
175
176void Preprocessor::PrintStats() {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000177 llvm::cerr << "\n*** Preprocessor Stats:\n";
178 llvm::cerr << NumDirectives << " directives found:\n";
179 llvm::cerr << " " << NumDefined << " #define.\n";
180 llvm::cerr << " " << NumUndefined << " #undef.\n";
181 llvm::cerr << " #include/#include_next/#import:\n";
182 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
183 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
184 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
185 llvm::cerr << " " << NumElse << " #else/#elif.\n";
186 llvm::cerr << " " << NumEndif << " #endif.\n";
187 llvm::cerr << " " << NumPragma << " #pragma.\n";
188 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000189
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000190 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
191 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
192 << NumFastMacroExpanded << " on the fast path.\n";
193 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
194 << " token paste (##) operations performed, "
195 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000196}
197
198//===----------------------------------------------------------------------===//
199// Token Spelling
200//===----------------------------------------------------------------------===//
201
202
203/// getSpelling() - Return the 'spelling' of this token. The spelling of a
204/// token are the characters used to represent the token in the source file
205/// after trigraph expansion and escaped-newline folding. In particular, this
206/// wants to get the true, uncanonicalized, spelling of things like digraphs
207/// UCNs, etc.
Chris Lattnerd2177732007-07-20 16:59:19 +0000208std::string Preprocessor::getSpelling(const Token &Tok) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
210
211 // If this token contains nothing interesting, return it directly.
212 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
213 if (!Tok.needsCleaning())
214 return std::string(TokStart, TokStart+Tok.getLength());
215
216 std::string Result;
217 Result.reserve(Tok.getLength());
218
219 // Otherwise, hard case, relex the characters into the string.
220 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
221 Ptr != End; ) {
222 unsigned CharSize;
223 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
224 Ptr += CharSize;
225 }
226 assert(Result.size() != unsigned(Tok.getLength()) &&
227 "NeedsCleaning flag set on something that didn't need cleaning!");
228 return Result;
229}
230
231/// getSpelling - This method is used to get the spelling of a token into a
232/// preallocated buffer, instead of as an std::string. The caller is required
233/// to allocate enough space for the token, which is guaranteed to be at least
234/// Tok.getLength() bytes long. The actual length of the token is returned.
235///
236/// Note that this method may do two possible things: it may either fill in
237/// the buffer specified with characters, or it may *change the input pointer*
238/// to point to a constant buffer with the data already in it (avoiding a
239/// copy). The caller is not allowed to modify the returned buffer pointer
240/// if an internal buffer is returned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000241unsigned Preprocessor::getSpelling(const Token &Tok,
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 const char *&Buffer) const {
243 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
244
245 // If this token is an identifier, just return the string from the identifier
246 // table, which is very quick.
247 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
248 Buffer = II->getName();
Chris Lattner0f670322007-07-22 22:50:09 +0000249
250 // Return the length of the token. If the token needed cleaning, don't
251 // include the size of the newlines or trigraphs in it.
252 if (!Tok.needsCleaning())
253 return Tok.getLength();
254 else
255 return strlen(Buffer);
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 }
257
258 // Otherwise, compute the start of the token in the input lexer buffer.
259 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
260
261 // If this token contains nothing interesting, return it directly.
262 if (!Tok.needsCleaning()) {
263 Buffer = TokStart;
264 return Tok.getLength();
265 }
266 // Otherwise, hard case, relex the characters into the string.
267 char *OutBuf = const_cast<char*>(Buffer);
268 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
269 Ptr != End; ) {
270 unsigned CharSize;
271 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
272 Ptr += CharSize;
273 }
274 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
275 "NeedsCleaning flag set on something that didn't need cleaning!");
276
277 return OutBuf-Buffer;
278}
279
280
281/// CreateString - Plop the specified string into a scratch buffer and return a
282/// location for it. If specified, the source location provides a source
283/// location for the token.
284SourceLocation Preprocessor::
285CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
286 if (SLoc.isValid())
287 return ScratchBuf->getToken(Buf, Len, SLoc);
288 return ScratchBuf->getToken(Buf, Len);
289}
290
291
Chris Lattner97ba77c2007-07-16 06:48:38 +0000292/// AdvanceToTokenCharacter - Given a location that specifies the start of a
293/// token, return a new location that specifies a character within the token.
294SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
295 unsigned CharNo) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000296 // If they request the first char of the token, we're trivially done. If this
297 // is a macro expansion, it doesn't make sense to point to a character within
298 // the instantiation point (the name). We could point to the source
299 // character, but without also pointing to instantiation info, this is
300 // confusing.
301 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000302
303 // Figure out how many physical characters away the specified logical
304 // character is. This needs to take into consideration newlines and
305 // trigraphs.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000306 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
307 unsigned PhysOffset = 0;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000308
309 // The usual case is that tokens don't contain anything interesting. Skip
310 // over the uninteresting characters. If a token only consists of simple
311 // chars, this method is extremely fast.
312 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattner9dc1f532007-07-20 16:37:10 +0000313 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000314
315 // If we have a character that may be a trigraph or escaped newline, create a
316 // lexer to parse it correctly.
Chris Lattner97ba77c2007-07-16 06:48:38 +0000317 if (CharNo != 0) {
318 // Create a lexer starting at this token position.
Chris Lattner25bdb512007-07-20 16:52:03 +0000319 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattnerd2177732007-07-20 16:59:19 +0000320 Token Tok;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000321 // Skip over characters the remaining characters.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000322 const char *TokStartPtr = TokPtr;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000323 for (; CharNo; --CharNo)
324 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattner9dc1f532007-07-20 16:37:10 +0000325
326 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000327 }
Chris Lattner9dc1f532007-07-20 16:37:10 +0000328
329 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner97ba77c2007-07-16 06:48:38 +0000330}
331
332
Chris Lattner53b0dab2007-10-09 22:10:18 +0000333//===----------------------------------------------------------------------===//
334// Preprocessor Initialization Methods
335//===----------------------------------------------------------------------===//
336
337// Append a #define line to Buf for Macro. Macro should be of the form XXX,
338// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
339// "#define XXX Y z W". To get a #define with no value, use "XXX=".
340static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
341 const char *Command = "#define ") {
342 Buf.insert(Buf.end(), Command, Command+strlen(Command));
343 if (const char *Equal = strchr(Macro, '=')) {
344 // Turn the = into ' '.
345 Buf.insert(Buf.end(), Macro, Equal);
346 Buf.push_back(' ');
347 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
348 } else {
349 // Push "macroname 1".
350 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
351 Buf.push_back(' ');
352 Buf.push_back('1');
353 }
354 Buf.push_back('\n');
355}
356
Chris Lattner2db78dd2008-10-05 20:40:30 +0000357/// PickFP - This is used to pick a value based on the FP semantics of the
358/// specified FP model.
359template <typename T>
360static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
361 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
362 if (Sem == &llvm::APFloat::IEEEsingle)
363 return IEEESingleVal;
364 if (Sem == &llvm::APFloat::IEEEdouble)
365 return IEEEDoubleVal;
366 if (Sem == &llvm::APFloat::x87DoubleExtended)
367 return X87DoubleExtendedVal;
368 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
369 return PPCDoubleDoubleVal;
370}
371
372static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
373 const llvm::fltSemantics *Sem) {
Chris Lattnere9863ca2008-10-05 21:40:58 +0000374 const char *DenormMin, *Epsilon, *Max, *Min;
375 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
376 "3.64519953188247460253e-4951L",
377 "4.94065645841246544176568792868221e-324L");
378 int Digits = PickFP(Sem, 6, 15, 18, 31);
379 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
380 "1.08420217248550443401e-19L",
381 "4.94065645841246544176568792868221e-324L");
382 int HasInifinity = 1, HasQuietNaN = 1;
383 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
384 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
385 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
386 int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
387 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
388 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
389 "3.36210314311209350626e-4932L",
390 "2.00416836000897277799610805135016e-292L");
391 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
392 "1.18973149535723176502e+4932L",
393 "1.79769313486231580793728971405301e+308L");
Chris Lattner2db78dd2008-10-05 20:40:30 +0000394
395 char MacroBuf[60];
396 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
397 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattnere9863ca2008-10-05 21:40:58 +0000398 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
399 DefineBuiltinMacro(Buf, MacroBuf);
400 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
401 DefineBuiltinMacro(Buf, MacroBuf);
402 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
403 DefineBuiltinMacro(Buf, MacroBuf);
404 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
405 DefineBuiltinMacro(Buf, MacroBuf);
406 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
407 DefineBuiltinMacro(Buf, MacroBuf);
408 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
409 DefineBuiltinMacro(Buf, MacroBuf);
410 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
411 DefineBuiltinMacro(Buf, MacroBuf);
412 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
413 DefineBuiltinMacro(Buf, MacroBuf);
414 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
415 DefineBuiltinMacro(Buf, MacroBuf);
416 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
417 DefineBuiltinMacro(Buf, MacroBuf);
418 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
419 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner2db78dd2008-10-05 20:40:30 +0000420}
421
Chris Lattner53b0dab2007-10-09 22:10:18 +0000422
423static void InitializePredefinedMacros(Preprocessor &PP,
424 std::vector<char> &Buf) {
Chris Lattner62213d92008-10-05 19:32:22 +0000425 // Compiler version introspection macros.
426 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
427 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
428
429 // Currently claim to be compatible with GCC 4.2.1-5621.
430 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
431 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
432 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
433 DefineBuiltinMacro(Buf, "__GNUC__=4");
434 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
435 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 (Apple Computer, Inc. "
436 "build 5621) (dot 3)\"");
437
438
439 // Initialize language-specific preprocessor defines.
440
Chris Lattner53b0dab2007-10-09 22:10:18 +0000441 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
442 // and __DATE__ etc.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000443 // These should all be defined in the preprocessor according to the
444 // current language configuration.
445 DefineBuiltinMacro(Buf, "__STDC__=1");
446 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
447 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
448 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
449 else if (0) // STDC94 ?
450 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
451
452 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
Daniel Dunbarfba5cb12008-08-12 00:21:46 +0000453 if (PP.getLangOptions().ObjC1) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000454 DefineBuiltinMacro(Buf, "__OBJC__=1");
Daniel Dunbarfba5cb12008-08-12 00:21:46 +0000455
456 if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) {
457 DefineBuiltinMacro(Buf, "__weak=");
458 DefineBuiltinMacro(Buf, "__strong=");
459 } else {
460 DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))");
461 DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))");
462 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
463 }
464
465 if (PP.getLangOptions().NeXTRuntime)
466 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
Daniel Dunbarfba5cb12008-08-12 00:21:46 +0000467 }
Chris Lattner9b533162008-10-05 19:44:25 +0000468
Chris Lattnereb52b442008-10-06 07:43:09 +0000469 // darwin_constant_cfstrings controls this. This is also dependent
470 // on other things like the runtime I believe. This is set even for C code.
471 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
472
Steve Naroff73b17cd2008-05-15 21:12:10 +0000473 if (PP.getLangOptions().ObjC2)
474 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
Steve Naroff8ee529b2007-10-31 18:42:27 +0000475
Chris Lattner048dd942008-09-30 00:48:48 +0000476 if (PP.getLangOptions().PascalStrings)
477 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
478
Chris Lattner62213d92008-10-05 19:32:22 +0000479 if (PP.getLangOptions().Blocks) {
480 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
481 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
Chris Lattner2b43ad92008-10-05 19:32:52 +0000482 }
Chris Lattner62213d92008-10-05 19:32:22 +0000483
484 if (PP.getLangOptions().CPlusPlus) {
485 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
486 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
487 DefineBuiltinMacro(Buf, "__GNUG__=4");
488 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
489 DefineBuiltinMacro(Buf, "__cplusplus=1");
490 DefineBuiltinMacro(Buf, "__private_extern__=extern");
491 }
492
493 // Filter out some microsoft extensions when trying to parse in ms-compat
494 // mode.
495 if (PP.getLangOptions().Microsoft) {
496 DefineBuiltinMacro(Buf, "__stdcall=");
497 DefineBuiltinMacro(Buf, "__cdecl=");
498 DefineBuiltinMacro(Buf, "_cdecl=");
499 DefineBuiltinMacro(Buf, "__ptr64=");
500 DefineBuiltinMacro(Buf, "__w64=");
501 DefineBuiltinMacro(Buf, "__forceinline=");
502 DefineBuiltinMacro(Buf, "__int8=char");
503 DefineBuiltinMacro(Buf, "__int16=short");
504 DefineBuiltinMacro(Buf, "__int32=int");
505 DefineBuiltinMacro(Buf, "__int64=long long");
506 DefineBuiltinMacro(Buf, "__declspec(X)=");
507 }
508
509
510 // Initialize target-specific preprocessor defines.
Chris Lattner9b533162008-10-05 19:44:25 +0000511 const TargetInfo &TI = PP.getTargetInfo();
512
513 // Define type sizing macros based on the target properties.
514 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
515 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
516 DefineBuiltinMacro(Buf, "__SCHAR_MAX__=127");
Chris Lattner2db78dd2008-10-05 20:40:30 +0000517
518 assert(TI.getWCharWidth() == 32 && "Only support 32-bit wchar so far");
519 DefineBuiltinMacro(Buf, "__WCHAR_MAX__=2147483647");
520 DefineBuiltinMacro(Buf, "__WCHAR_TYPE__=int");
521 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
Chris Lattner9b533162008-10-05 19:44:25 +0000522
523 assert(TI.getShortWidth() == 16 && "Only support 16-bit short so far");
Chris Lattner9b533162008-10-05 19:44:25 +0000524 DefineBuiltinMacro(Buf, "__SHRT_MAX__=32767");
525
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000526 if (TI.getIntWidth() == 32)
527 DefineBuiltinMacro(Buf, "__INT_MAX__=2147483647");
528 else if (TI.getIntWidth() == 16)
529 DefineBuiltinMacro(Buf, "__INT_MAX__=32767");
530 else
531 assert(0 && "Unknown integer size");
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000532
533 if (TI.getLongLongWidth() == 64)
534 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=9223372036854775807LL");
535 else if (TI.getLongLongWidth() == 32)
536 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=2147483647L");
Chris Lattner9b533162008-10-05 19:44:25 +0000537
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000538 if (TI.getLongWidth() == 32)
539 DefineBuiltinMacro(Buf, "__LONG_MAX__=2147483647L");
540 else if (TI.getLongWidth() == 64)
541 DefineBuiltinMacro(Buf, "__LONG_MAX__=9223372036854775807L");
542 else if (TI.getLongWidth() == 16)
543 DefineBuiltinMacro(Buf, "__LONG_MAX__=32767L");
544 else
545 assert(0 && "Unknown long size");
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000546 char MacroBuf[60];
547 sprintf(MacroBuf, "__INTMAX_MAX__=%lld",
548 (TI.getIntMaxType() == TargetInfo::UnsignedLongLong?
Sanjiv Gupta73608a82008-10-31 10:24:31 +0000549 (1LL << (TI.getLongLongWidth() - 1)) :
550 ((1LL << (TI.getLongLongWidth() - 2)) - 1)));
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000551 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000552
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000553 if (TI.getIntMaxType() == TargetInfo::UnsignedLongLong)
554 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long long int");
555 else if (TI.getIntMaxType() == TargetInfo::SignedLongLong)
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000556 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long long int");
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000557 else if (TI.getIntMaxType() == TargetInfo::UnsignedLong)
558 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long int");
559 else if (TI.getIntMaxType() == TargetInfo::SignedLong)
560 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long int");
561 else if (TI.getIntMaxType() == TargetInfo::UnsignedInt)
562 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned int");
563 else
564 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=int");
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000565
Sanjiv Gupta31fc07d2008-10-31 09:52:39 +0000566 if (TI.getUIntMaxType() == TargetInfo::UnsignedLongLong)
567 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long long int");
568 else if (TI.getUIntMaxType() == TargetInfo::SignedLongLong)
569 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long long int");
570 else if (TI.getUIntMaxType() == TargetInfo::UnsignedLong)
571 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long int");
572 else if (TI.getUIntMaxType() == TargetInfo::SignedLong)
573 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long int");
574 else if (TI.getUIntMaxType() == TargetInfo::UnsignedInt)
575 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned int");
576 else
577 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=int");
578
579 if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLongLong)
580 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long long int");
581 else if (TI.getPtrDiffType(0) == TargetInfo::SignedLongLong)
582 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long long int");
583 else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLong)
584 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long int");
585 else if (TI.getPtrDiffType(0) == TargetInfo::SignedLong)
586 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long int");
587 else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedInt)
588 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned int");
589 else
590 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=int");
591
592 if (TI.getSizeType() == TargetInfo::UnsignedLongLong)
593 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long long int");
594 else if (TI.getSizeType() == TargetInfo::SignedLongLong)
595 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long long int");
596 else if (TI.getSizeType() == TargetInfo::UnsignedLong)
597 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long int");
598 else if (TI.getSizeType() == TargetInfo::SignedLong)
599 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long int");
600 else if (TI.getSizeType() == TargetInfo::UnsignedInt)
601 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned int");
602 else if (TI.getSizeType() == TargetInfo::SignedInt)
603 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=int");
604 else
605 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned short");
606
Chris Lattner2db78dd2008-10-05 20:40:30 +0000607 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
608 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
609 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000610
Chris Lattner048dd942008-09-30 00:48:48 +0000611
Chris Lattnerd19144b2007-10-10 17:48:53 +0000612 // Add __builtin_va_list typedef.
613 {
Chris Lattner9b533162008-10-05 19:44:25 +0000614 const char *VAList = TI.getVAListDeclaration();
Chris Lattnerd19144b2007-10-10 17:48:53 +0000615 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
616 Buf.push_back('\n');
617 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000618
Chris Lattner9b533162008-10-05 19:44:25 +0000619 if (const char *Prefix = TI.getUserLabelPrefix()) {
Chris Lattner12f09262008-10-05 21:49:27 +0000620 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
621 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner3fdf4672008-10-05 19:22:37 +0000622 }
623
Chris Lattner9b533162008-10-05 19:44:25 +0000624 // Build configuration options. FIXME: these should be controlled by
625 // command line options or something.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000626 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
627 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
628 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
629 DefineBuiltinMacro(Buf, "__PIC__=1");
Chris Lattner9b533162008-10-05 19:44:25 +0000630
Chris Lattner12f09262008-10-05 21:49:27 +0000631 // Macros to control C99 numerics and <float.h>
632 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
633 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
634 sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
635 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
636 DefineBuiltinMacro(Buf, MacroBuf);
637
Chris Lattner9b533162008-10-05 19:44:25 +0000638 // Get other target #defines.
639 TI.getTargetDefines(Buf);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000640
Chris Lattner53b0dab2007-10-09 22:10:18 +0000641 // FIXME: Should emit a #line directive here.
642}
643
644
645/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000646/// which implicitly adds the builtin defines etc.
Ted Kremenek95041a22007-12-19 22:51:13 +0000647void Preprocessor::EnterMainSourceFile() {
648
649 unsigned MainFileID = SourceMgr.getMainFileID();
650
Chris Lattner53b0dab2007-10-09 22:10:18 +0000651 // Enter the main file source buffer.
652 EnterSourceFile(MainFileID, 0);
653
Chris Lattnerb2832982007-11-15 19:07:47 +0000654 // Tell the header info that the main file was entered. If the file is later
655 // #imported, it won't be re-entered.
656 if (const FileEntry *FE =
657 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
658 HeaderInfo.IncrementIncludeCount(FE);
659
Chris Lattner53b0dab2007-10-09 22:10:18 +0000660 std::vector<char> PrologFile;
661 PrologFile.reserve(4080);
662
663 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
664 InitializePredefinedMacros(*this, PrologFile);
665
666 // Add on the predefines from the driver.
Chris Lattneraa391972008-04-19 23:09:31 +0000667 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000668
669 // Memory buffer must end with a null byte!
670 PrologFile.push_back(0);
671
672 // Now that we have emitted the predefined macros, #includes, etc into
673 // PrologFile, preprocess it to populate the initial preprocessor state.
674 llvm::MemoryBuffer *SB =
675 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
676 "<predefines>");
677 assert(SB && "Cannot fail to create predefined source buffer");
678 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
679 assert(FileID && "Could not create FileID for predefines?");
680
681 // Start parsing the predefines.
682 EnterSourceFile(FileID, 0);
683}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000684
Reid Spencer5f016e22007-07-11 17:01:13 +0000685
686//===----------------------------------------------------------------------===//
687// Lexer Event Handling.
688//===----------------------------------------------------------------------===//
689
690/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
691/// identifier information for the token and install it into the token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000692IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +0000693 const char *BufPtr) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000694 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
696
697 // Look up this token, see if it is a macro, or if it is a language keyword.
698 IdentifierInfo *II;
699 if (BufPtr && !Identifier.needsCleaning()) {
700 // No cleaning needed, just use the characters from the lexed buffer.
701 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
702 } else {
703 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerc35717a2007-07-13 17:10:38 +0000704 llvm::SmallVector<char, 64> IdentifierBuffer;
705 IdentifierBuffer.resize(Identifier.getLength());
706 const char *TmpBuf = &IdentifierBuffer[0];
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 unsigned Size = getSpelling(Identifier, TmpBuf);
708 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
709 }
710 Identifier.setIdentifierInfo(II);
711 return II;
712}
713
714
715/// HandleIdentifier - This callback is invoked when the lexer reads an
716/// identifier. This callback looks up the identifier in the map and/or
717/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerd2177732007-07-20 16:59:19 +0000718void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000719 assert(Identifier.getIdentifierInfo() &&
720 "Can't handle identifiers without identifier info!");
721
722 IdentifierInfo &II = *Identifier.getIdentifierInfo();
723
724 // If this identifier was poisoned, and if it was not produced from a macro
725 // expansion, emit an error.
726 if (II.isPoisoned() && CurLexer) {
727 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
728 Diag(Identifier, diag::err_pp_used_poisoned_id);
729 else
730 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
731 }
732
733 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000734 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000735 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
736 if (MI->isEnabled()) {
737 if (!HandleMacroExpandedIdentifier(Identifier, MI))
738 return;
739 } else {
740 // C99 6.10.3.4p2 says that a disabled macro may never again be
741 // expanded, even if it's in a context where it could be expanded in the
742 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000743 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000744 }
745 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 }
747
748 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
749 // then we act as if it is the actual operator and not the textual
750 // representation of it.
751 if (II.isCPlusPlusOperatorKeyword())
752 Identifier.setIdentifierInfo(0);
753
754 // Change the kind of this identifier to the appropriate token kind, e.g.
755 // turning "for" into a keyword.
756 Identifier.setKind(II.getTokenID());
757
758 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000759 // We avoid diagnosing tokens that originate from macro definitions.
760 if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000761 Diag(Identifier, diag::ext_token_used);
762}