blob: 903b987080dc1aa7783b1d6e20227077477a9b3f [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Sema.cpp - AST Builder and Semantic Analysis 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 actions class which performs semantic analysis and
11// builds an AST out of a parse stream.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000016#include "TargetAttributesSema.h"
Ryan Flynne25ff832009-07-30 03:15:39 +000017#include "llvm/ADT/DenseMap.h"
Sebastian Redle9d12b62010-01-31 22:27:38 +000018#include "llvm/ADT/SmallSet.h"
John McCall680523a2009-11-07 03:30:10 +000019#include "llvm/ADT/APFloat.h"
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +000020#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000023#include "clang/AST/Expr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Lex/Preprocessor.h"
Anders Carlsson91a0cc92009-08-26 22:33:56 +000025#include "clang/Basic/PartialDiagnostic.h"
Chris Lattner4d150c82009-04-30 06:18:40 +000026#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
John McCall49a832b2009-10-18 09:09:24 +000029/// Determines whether we should have an a.k.a. clause when
Chris Lattner0a026af2009-10-20 05:36:05 +000030/// pretty-printing a type. There are three main criteria:
John McCall49a832b2009-10-18 09:09:24 +000031///
32/// 1) Some types provide very minimal sugar that doesn't impede the
33/// user's understanding --- for example, elaborated type
34/// specifiers. If this is all the sugar we see, we don't want an
35/// a.k.a. clause.
36/// 2) Some types are technically sugared but are much more familiar
37/// when seen in their sugared form --- for example, va_list,
38/// vector types, and the magic Objective C types. We don't
39/// want to desugar these, even if we do produce an a.k.a. clause.
Chris Lattner0a026af2009-10-20 05:36:05 +000040/// 3) Some types may have already been desugared previously in this diagnostic.
41/// if this is the case, doing another "aka" would just be clutter.
42///
John McCall49a832b2009-10-18 09:09:24 +000043static bool ShouldAKA(ASTContext &Context, QualType QT,
Chris Lattner0a026af2009-10-20 05:36:05 +000044 const Diagnostic::ArgumentValue *PrevArgs,
45 unsigned NumPrevArgs,
46 QualType &DesugaredQT) {
47 QualType InputTy = QT;
48
John McCall49a832b2009-10-18 09:09:24 +000049 bool AKA = false;
50 QualifierCollector Qc;
51
52 while (true) {
53 const Type *Ty = Qc.strip(QT);
54
55 // Don't aka just because we saw an elaborated type...
56 if (isa<ElaboratedType>(Ty)) {
57 QT = cast<ElaboratedType>(Ty)->desugar();
58 continue;
59 }
60
61 // ...or a qualified name type...
62 if (isa<QualifiedNameType>(Ty)) {
63 QT = cast<QualifiedNameType>(Ty)->desugar();
64 continue;
65 }
66
67 // ...or a substituted template type parameter.
68 if (isa<SubstTemplateTypeParmType>(Ty)) {
69 QT = cast<SubstTemplateTypeParmType>(Ty)->desugar();
70 continue;
71 }
72
73 // Don't desugar template specializations.
74 if (isa<TemplateSpecializationType>(Ty))
75 break;
76
77 // Don't desugar magic Objective-C types.
78 if (QualType(Ty,0) == Context.getObjCIdType() ||
79 QualType(Ty,0) == Context.getObjCClassType() ||
80 QualType(Ty,0) == Context.getObjCSelType() ||
81 QualType(Ty,0) == Context.getObjCProtoType())
82 break;
83
84 // Don't desugar va_list.
85 if (QualType(Ty,0) == Context.getBuiltinVaListType())
86 break;
87
88 // Otherwise, do a single-step desugar.
89 QualType Underlying;
90 bool IsSugar = false;
91 switch (Ty->getTypeClass()) {
92#define ABSTRACT_TYPE(Class, Base)
93#define TYPE(Class, Base) \
94 case Type::Class: { \
95 const Class##Type *CTy = cast<Class##Type>(Ty); \
96 if (CTy->isSugared()) { \
97 IsSugar = true; \
98 Underlying = CTy->desugar(); \
99 } \
100 break; \
101 }
102#include "clang/AST/TypeNodes.def"
103 }
104
105 // If it wasn't sugared, we're done.
106 if (!IsSugar)
107 break;
108
109 // If the desugared type is a vector type, we don't want to expand
110 // it, it will turn into an attribute mess. People want their "vec4".
111 if (isa<VectorType>(Underlying))
112 break;
113
John McCall64f7e252010-01-13 22:07:44 +0000114 // Don't desugar through the primary typedef of an anonymous type.
115 if (isa<TagType>(Underlying) && isa<TypedefType>(QT))
116 if (cast<TagType>(Underlying)->getDecl()->getTypedefForAnonDecl() ==
117 cast<TypedefType>(QT)->getDecl())
118 break;
119
John McCall49a832b2009-10-18 09:09:24 +0000120 // Otherwise, we're tearing through something opaque; note that
121 // we'll eventually need an a.k.a. clause and keep going.
122 AKA = true;
123 QT = Underlying;
124 continue;
125 }
126
Chris Lattner0a026af2009-10-20 05:36:05 +0000127 // If we never tore through opaque sugar, don't print aka.
128 if (!AKA) return false;
John McCall49a832b2009-10-18 09:09:24 +0000129
Chris Lattner0a026af2009-10-20 05:36:05 +0000130 // If we did, check to see if we already desugared this type in this
131 // diagnostic. If so, don't do it again.
132 for (unsigned i = 0; i != NumPrevArgs; ++i) {
133 // TODO: Handle ak_declcontext case.
134 if (PrevArgs[i].first == Diagnostic::ak_qualtype) {
135 void *Ptr = (void*)PrevArgs[i].second;
136 QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
137 if (PrevTy == InputTy)
138 return false;
139 }
140 }
141
142 DesugaredQT = Qc.apply(QT);
143 return true;
John McCall49a832b2009-10-18 09:09:24 +0000144}
145
Douglas Gregor3f093272009-10-13 21:16:44 +0000146/// \brief Convert the given type to a string suitable for printing as part of
147/// a diagnostic.
148///
149/// \param Context the context in which the type was allocated
150/// \param Ty the type to print
Chris Lattner0a026af2009-10-20 05:36:05 +0000151static std::string
152ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
153 const Diagnostic::ArgumentValue *PrevArgs,
154 unsigned NumPrevArgs) {
Douglas Gregor3f093272009-10-13 21:16:44 +0000155 // FIXME: Playing with std::string is really slow.
156 std::string S = Ty.getAsString(Context.PrintingPolicy);
157
John McCall49a832b2009-10-18 09:09:24 +0000158 // Consider producing an a.k.a. clause if removing all the direct
159 // sugar gives us something "significantly different".
160
161 QualType DesugaredTy;
Chris Lattner0a026af2009-10-20 05:36:05 +0000162 if (ShouldAKA(Context, Ty, PrevArgs, NumPrevArgs, DesugaredTy)) {
Douglas Gregor3f093272009-10-13 21:16:44 +0000163 S = "'"+S+"' (aka '";
164 S += DesugaredTy.getAsString(Context.PrintingPolicy);
165 S += "')";
166 return S;
167 }
168
169 S = "'" + S + "'";
170 return S;
171}
172
Mike Stump1eb44332009-09-09 15:08:12 +0000173/// ConvertQualTypeToStringFn - This function is used to pretty print the
Chris Lattner22caddc2008-11-23 09:13:29 +0000174/// specified QualType as a string in diagnostics.
Chris Lattner011bb4e2008-11-23 20:28:15 +0000175static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val,
Chris Lattnerd0344a42009-02-19 23:45:49 +0000176 const char *Modifier, unsigned ModLen,
177 const char *Argument, unsigned ArgLen,
Chris Lattnerb54d8af2009-10-20 05:25:22 +0000178 const Diagnostic::ArgumentValue *PrevArgs,
179 unsigned NumPrevArgs,
Chris Lattner92dd3862009-02-19 23:53:20 +0000180 llvm::SmallVectorImpl<char> &Output,
181 void *Cookie) {
182 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattner011bb4e2008-11-23 20:28:15 +0000184 std::string S;
Douglas Gregor3f093272009-10-13 21:16:44 +0000185 bool NeedQuotes = true;
Chris Lattner9cf9f862009-10-20 05:12:36 +0000186
187 switch (Kind) {
188 default: assert(0 && "unknown ArgumentKind");
189 case Diagnostic::ak_qualtype: {
Chris Lattnerd0344a42009-02-19 23:45:49 +0000190 assert(ModLen == 0 && ArgLen == 0 &&
191 "Invalid modifier for QualType argument");
192
Chris Lattner011bb4e2008-11-23 20:28:15 +0000193 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
Chris Lattner0a026af2009-10-20 05:36:05 +0000194 S = ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, NumPrevArgs);
Douglas Gregor3f093272009-10-13 21:16:44 +0000195 NeedQuotes = false;
Chris Lattner9cf9f862009-10-20 05:12:36 +0000196 break;
197 }
198 case Diagnostic::ak_declarationname: {
Chris Lattner011bb4e2008-11-23 20:28:15 +0000199 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
200 S = N.getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Chris Lattner077bf5e2008-11-24 03:33:13 +0000202 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
203 S = '+' + S;
204 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0)
205 S = '-' + S;
206 else
207 assert(ModLen == 0 && ArgLen == 0 &&
208 "Invalid modifier for DeclarationName argument");
Chris Lattner9cf9f862009-10-20 05:12:36 +0000209 break;
210 }
211 case Diagnostic::ak_nameddecl: {
John McCall136a6982009-09-11 06:45:03 +0000212 bool Qualified;
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000213 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
John McCall136a6982009-09-11 06:45:03 +0000214 Qualified = true;
Mike Stump1eb44332009-09-09 15:08:12 +0000215 else {
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000216 assert(ModLen == 0 && ArgLen == 0 &&
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000217 "Invalid modifier for NamedDecl* argument");
John McCall136a6982009-09-11 06:45:03 +0000218 Qualified = false;
Douglas Gregoreeb15d42009-02-04 22:46:25 +0000219 }
Chris Lattner9cf9f862009-10-20 05:12:36 +0000220 reinterpret_cast<NamedDecl*>(Val)->
221 getNameForDiagnostic(S, Context.PrintingPolicy, Qualified);
222 break;
223 }
224 case Diagnostic::ak_nestednamespec: {
Douglas Gregordacd4342009-08-26 00:04:55 +0000225 llvm::raw_string_ostream OS(S);
Chris Lattner9cf9f862009-10-20 05:12:36 +0000226 reinterpret_cast<NestedNameSpecifier*>(Val)->print(OS,
227 Context.PrintingPolicy);
Douglas Gregora786fdb2009-10-13 23:27:22 +0000228 NeedQuotes = false;
Chris Lattner9cf9f862009-10-20 05:12:36 +0000229 break;
230 }
231 case Diagnostic::ak_declcontext: {
Douglas Gregor3f093272009-10-13 21:16:44 +0000232 DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
Chris Lattner9cf9f862009-10-20 05:12:36 +0000233 assert(DC && "Should never have a null declaration context");
234
235 if (DC->isTranslationUnit()) {
Douglas Gregor3f093272009-10-13 21:16:44 +0000236 // FIXME: Get these strings from some localized place
237 if (Context.getLangOptions().CPlusPlus)
238 S = "the global namespace";
239 else
240 S = "the global scope";
241 } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
Chris Lattner0a026af2009-10-20 05:36:05 +0000242 S = ConvertTypeToDiagnosticString(Context, Context.getTypeDeclType(Type),
243 PrevArgs, NumPrevArgs);
Douglas Gregor3f093272009-10-13 21:16:44 +0000244 } else {
245 // FIXME: Get these strings from some localized place
246 NamedDecl *ND = cast<NamedDecl>(DC);
247 if (isa<NamespaceDecl>(ND))
248 S += "namespace ";
249 else if (isa<ObjCMethodDecl>(ND))
250 S += "method ";
251 else if (isa<FunctionDecl>(ND))
252 S += "function ";
253
254 S += "'";
255 ND->getNameForDiagnostic(S, Context.PrintingPolicy, true);
256 S += "'";
Douglas Gregor3f093272009-10-13 21:16:44 +0000257 }
Chris Lattner9cf9f862009-10-20 05:12:36 +0000258 NeedQuotes = false;
259 break;
260 }
Chris Lattner011bb4e2008-11-23 20:28:15 +0000261 }
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Douglas Gregor3f093272009-10-13 21:16:44 +0000263 if (NeedQuotes)
264 Output.push_back('\'');
265
Chris Lattner22caddc2008-11-23 09:13:29 +0000266 Output.append(S.begin(), S.end());
Douglas Gregor3f093272009-10-13 21:16:44 +0000267
268 if (NeedQuotes)
269 Output.push_back('\'');
Chris Lattner22caddc2008-11-23 09:13:29 +0000270}
271
272
Chris Lattner0a14eee2008-11-18 07:04:44 +0000273static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
Anders Carlssonc3036062008-08-23 22:20:38 +0000274 if (C.getLangOptions().CPlusPlus)
Mike Stump1eb44332009-09-09 15:08:12 +0000275 return CXXRecordDecl::Create(C, TagDecl::TK_struct,
Anders Carlssonc3036062008-08-23 22:20:38 +0000276 C.getTranslationUnitDecl(),
Ted Kremenekdf042e62008-09-05 01:34:33 +0000277 SourceLocation(), &C.Idents.get(Name));
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000278
Mike Stump1eb44332009-09-09 15:08:12 +0000279 return RecordDecl::Create(C, TagDecl::TK_struct,
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000280 C.getTranslationUnitDecl(),
281 SourceLocation(), &C.Idents.get(Name));
Anders Carlssonc3036062008-08-23 22:20:38 +0000282}
283
Steve Naroffb216c882007-10-09 22:01:59 +0000284void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
285 TUScope = S;
Douglas Gregor44b43212008-12-11 16:49:14 +0000286 PushDeclContext(S, Context.getTranslationUnitDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000287
Chris Lattner4d150c82009-04-30 06:18:40 +0000288 if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
John McCalla93c9342009-12-07 02:54:59 +0000289 TypeSourceInfo *TInfo;
John McCallba6a9bd2009-10-24 08:00:42 +0000290
Chris Lattner4d150c82009-04-30 06:18:40 +0000291 // Install [u]int128_t for 64-bit targets.
John McCalla93c9342009-12-07 02:54:59 +0000292 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +0000293 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
294 SourceLocation(),
295 &Context.Idents.get("__int128_t"),
John McCalla93c9342009-12-07 02:54:59 +0000296 TInfo), TUScope);
John McCallba6a9bd2009-10-24 08:00:42 +0000297
John McCalla93c9342009-12-07 02:54:59 +0000298 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
Chris Lattner4d150c82009-04-30 06:18:40 +0000299 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
300 SourceLocation(),
301 &Context.Idents.get("__uint128_t"),
John McCalla93c9342009-12-07 02:54:59 +0000302 TInfo), TUScope);
Chris Lattner4d150c82009-04-30 06:18:40 +0000303 }
Mike Stump1eb44332009-09-09 15:08:12 +0000304
305
Chris Lattner2ae34ed2008-02-06 00:46:58 +0000306 if (!PP.getLangOptions().ObjC1) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Steve Naroffcb83c532009-06-16 00:20:10 +0000308 // Built-in ObjC types may already be set by PCHReader (hence isNull checks).
Douglas Gregor319ac892009-04-23 22:29:11 +0000309 if (Context.getObjCSelType().isNull()) {
Fariborz Jahanian13dcd002009-11-21 19:53:08 +0000310 // Create the built-in typedef for 'SEL'.
Fariborz Jahanian04765ac2009-11-23 18:04:25 +0000311 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
John McCalla93c9342009-12-07 02:54:59 +0000312 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
John McCallba6a9bd2009-10-24 08:00:42 +0000313 TypedefDecl *SelTypedef
314 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
315 &Context.Idents.get("SEL"), SelInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +0000316 PushOnScopeChains(SelTypedef, TUScope);
317 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +0000318 Context.ObjCSelRedefinitionType = Context.getObjCSelType();
Douglas Gregor319ac892009-04-23 22:29:11 +0000319 }
Chris Lattner6ee1f9c2008-06-21 20:20:39 +0000320
Chris Lattner6ee1f9c2008-06-21 20:20:39 +0000321 // Synthesize "@class Protocol;
Douglas Gregor319ac892009-04-23 22:29:11 +0000322 if (Context.getObjCProtoType().isNull()) {
323 ObjCInterfaceDecl *ProtocolDecl =
324 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +0000325 &Context.Idents.get("Protocol"),
Douglas Gregor319ac892009-04-23 22:29:11 +0000326 SourceLocation(), true);
327 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
Fariborz Jahanian10324db2009-11-18 23:15:37 +0000328 PushOnScopeChains(ProtocolDecl, TUScope, false);
Douglas Gregor319ac892009-04-23 22:29:11 +0000329 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000330 // Create the built-in typedef for 'id'.
Douglas Gregor319ac892009-04-23 22:29:11 +0000331 if (Context.getObjCIdType().isNull()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000332 QualType IdT = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy);
John McCalla93c9342009-12-07 02:54:59 +0000333 TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(IdT);
John McCallba6a9bd2009-10-24 08:00:42 +0000334 TypedefDecl *IdTypedef
335 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
336 &Context.Idents.get("id"), IdInfo);
Douglas Gregor319ac892009-04-23 22:29:11 +0000337 PushOnScopeChains(IdTypedef, TUScope);
338 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000339 Context.ObjCIdRedefinitionType = Context.getObjCIdType();
Douglas Gregor319ac892009-04-23 22:29:11 +0000340 }
Steve Naroffde2e22d2009-07-15 18:40:39 +0000341 // Create the built-in typedef for 'Class'.
Steve Naroff14108da2009-07-10 23:34:53 +0000342 if (Context.getObjCClassType().isNull()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000343 QualType ClassType
344 = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy);
John McCalla93c9342009-12-07 02:54:59 +0000345 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(ClassType);
John McCallba6a9bd2009-10-24 08:00:42 +0000346 TypedefDecl *ClassTypedef
347 = TypedefDecl::Create(Context, CurContext, SourceLocation(),
348 &Context.Idents.get("Class"), ClassInfo);
Steve Naroff14108da2009-07-10 23:34:53 +0000349 PushOnScopeChains(ClassTypedef, TUScope);
350 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
David Chisnall0f436562009-08-17 16:35:33 +0000351 Context.ObjCClassRedefinitionType = Context.getObjCClassType();
Steve Naroff14108da2009-07-10 23:34:53 +0000352 }
Steve Naroff3b950172007-10-10 21:53:07 +0000353}
354
Douglas Gregorf807fe02009-04-14 16:27:31 +0000355Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000356 bool CompleteTranslationUnit,
357 CodeCompleteConsumer *CodeCompleter)
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000358 : TheTargetAttributesSema(0),
359 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
Mike Stump1eb44332009-09-09 15:08:12 +0000360 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
Daniel Dunbar3a2838d2009-11-13 08:58:20 +0000361 ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
John McCalldb0ee1d2009-12-19 10:53:49 +0000362 CurBlock(0), PackContext(0), ParsingDeclDepth(0),
Douglas Gregor81b747b2009-09-17 21:32:03 +0000363 IdResolver(pp.getLangOptions()), StdNamespace(0), StdBadAlloc(0),
Douglas Gregor2afce722009-11-26 00:44:06 +0000364 GlobalNewDeleteDeclared(false),
Douglas Gregor48dd19b2009-05-14 21:44:34 +0000365 CompleteTranslationUnit(CompleteTranslationUnit),
Douglas Gregorf35f8282009-11-11 21:54:23 +0000366 NumSFINAEErrors(0), NonInstantiationEntries(0),
Ted Kremenekd0ed4482010-02-02 02:07:01 +0000367 CurrentInstantiationScope(0), TyposCorrected(0)
Douglas Gregorf35f8282009-11-11 21:54:23 +0000368{
Steve Naroff3b950172007-10-10 21:53:07 +0000369 TUScope = 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000370 if (getLangOptions().CPlusPlus)
371 FieldCollector.reset(new CXXFieldCollector());
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Chris Lattner22caddc2008-11-23 09:13:29 +0000373 // Tell diagnostics how to render things from the AST library.
Chris Lattner92dd3862009-02-19 23:53:20 +0000374 PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
Douglas Gregor2afce722009-11-26 00:44:06 +0000375
376 ExprEvalContexts.push_back(
377 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
Reid Spencer5f016e22007-07-11 17:01:13 +0000378}
379
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000380Sema::~Sema() {
381 if (PackContext) FreePackedContext();
382 delete TheTargetAttributesSema;
383}
384
Mike Stump1eb44332009-09-09 15:08:12 +0000385/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Chris Lattner1e0a3902008-01-16 19:17:22 +0000386/// If there is already an implicit cast, merge into the existing one.
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000387/// If isLvalue, the result of the cast is an lvalue.
Mike Stump1eb44332009-09-09 15:08:12 +0000388void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
Anders Carlssonc0a2fd82009-09-15 05:13:45 +0000389 CastExpr::CastKind Kind, bool isLvalue) {
Mon P Wang3a2c7442008-09-04 08:38:01 +0000390 QualType ExprTy = Context.getCanonicalType(Expr->getType());
391 QualType TypeTy = Context.getCanonicalType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Mon P Wang3a2c7442008-09-04 08:38:01 +0000393 if (ExprTy == TypeTy)
394 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000395
John McCall680523a2009-11-07 03:30:10 +0000396 if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
397 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
398 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000399 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000400 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
401 << Expr->getSourceRange();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000402 }
403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
John McCall51313c32010-01-04 23:31:57 +0000405 CheckImplicitConversion(Expr, Ty);
John McCall680523a2009-11-07 03:30:10 +0000406
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000407 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
Anders Carlsson4c5fad32009-09-15 05:28:24 +0000408 if (ImpCast->getCastKind() == Kind) {
409 ImpCast->setType(Ty);
410 ImpCast->setLvalueCast(isLvalue);
411 return;
412 }
413 }
414
415 Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, isLvalue);
Chris Lattner1e0a3902008-01-16 19:17:22 +0000416}
417
Chris Lattner394a3fd2007-08-31 04:53:24 +0000418void Sema::DeleteExpr(ExprTy *E) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000419 if (E) static_cast<Expr*>(E)->Destroy(Context);
Chris Lattner394a3fd2007-08-31 04:53:24 +0000420}
421void Sema::DeleteStmt(StmtTy *S) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000422 if (S) static_cast<Stmt*>(S)->Destroy(Context);
Chris Lattner394a3fd2007-08-31 04:53:24 +0000423}
424
Chris Lattner9299f3f2008-08-23 03:19:52 +0000425/// ActOnEndOfTranslationUnit - This is called at the very end of the
426/// translation unit when EOF is reached and all but the top-level scope is
427/// popped.
428void Sema::ActOnEndOfTranslationUnit() {
Anders Carlssond6a637f2009-12-07 08:24:59 +0000429
430 while (1) {
431 // C++: Perform implicit template instantiations.
432 //
433 // FIXME: When we perform these implicit instantiations, we do not carefully
434 // keep track of the point of instantiation (C++ [temp.point]). This means
435 // that name lookup that occurs within the template instantiation will
436 // always happen at the end of the translation unit, so it will find
437 // some names that should not be found. Although this is common behavior
438 // for C++ compilers, it is technically wrong. In the future, we either need
439 // to be able to filter the results of name lookup or we need to perform
440 // template instantiations earlier.
441 PerformPendingImplicitInstantiations();
442
443 /// If ProcessPendingClassesWithUnmarkedVirtualMembers ends up marking
444 /// any virtual member functions it might lead to more pending template
445 /// instantiations, which is why we need to loop here.
446 if (!ProcessPendingClassesWithUnmarkedVirtualMembers())
447 break;
448 }
449
Chris Lattner63d65f82009-09-08 18:19:27 +0000450 // Check for #pragma weak identifiers that were never declared
451 // FIXME: This will cause diagnostics to be emitted in a non-determinstic
452 // order! Iterating over a densemap like this is bad.
Ryan Flynne25ff832009-07-30 03:15:39 +0000453 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
Chris Lattner63d65f82009-09-08 18:19:27 +0000454 I = WeakUndeclaredIdentifiers.begin(),
455 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
456 if (I->second.getUsed()) continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Chris Lattner63d65f82009-09-08 18:19:27 +0000458 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
459 << I->first;
Ryan Flynne25ff832009-07-30 03:15:39 +0000460 }
461
Douglas Gregorf807fe02009-04-14 16:27:31 +0000462 if (!CompleteTranslationUnit)
463 return;
464
Douglas Gregor275a3692009-03-10 23:43:53 +0000465 // C99 6.9.2p2:
466 // A declaration of an identifier for an object that has file
467 // scope without an initializer, and without a storage-class
468 // specifier or with the storage-class specifier static,
469 // constitutes a tentative definition. If a translation unit
470 // contains one or more tentative definitions for an identifier,
471 // and the translation unit contains no external definition for
472 // that identifier, then the behavior is exactly as if the
473 // translation unit contains a file scope declaration of that
474 // identifier, with the composite type as of the end of the
475 // translation unit, with an initializer equal to 0.
Sebastian Redle9d12b62010-01-31 22:27:38 +0000476 llvm::SmallSet<VarDecl *, 32> Seen;
477 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
478 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Sebastian Redle9d12b62010-01-31 22:27:38 +0000480 // If the tentative definition was completed, getActingDefinition() returns
481 // null. If we've already seen this variable before, insert()'s second
482 // return value is false.
483 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000484 continue;
485
Mike Stump1eb44332009-09-09 15:08:12 +0000486 if (const IncompleteArrayType *ArrayT
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000487 = Context.getAsIncompleteArrayType(VD->getType())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000488 if (RequireCompleteType(VD->getLocation(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000489 ArrayT->getElementType(),
Chris Lattner63d65f82009-09-08 18:19:27 +0000490 diag::err_tentative_def_incomplete_type_arr)) {
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000491 VD->setInvalidDecl();
Chris Lattner63d65f82009-09-08 18:19:27 +0000492 continue;
Douglas Gregor275a3692009-03-10 23:43:53 +0000493 }
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Chris Lattner63d65f82009-09-08 18:19:27 +0000495 // Set the length of the array to 1 (C99 6.9.2p5).
496 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
497 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
John McCall46a617a2009-10-16 00:14:28 +0000498 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
499 One, ArrayType::Normal, 0);
Chris Lattner63d65f82009-09-08 18:19:27 +0000500 VD->setType(T);
Mike Stump1eb44332009-09-09 15:08:12 +0000501 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000502 diag::err_tentative_def_incomplete_type))
503 VD->setInvalidDecl();
504
505 // Notify the consumer that we've completed a tentative definition.
506 if (!VD->isInvalidDecl())
507 Consumer.CompleteTentativeDefinition(VD);
508
Douglas Gregor275a3692009-03-10 23:43:53 +0000509 }
Chris Lattner9299f3f2008-08-23 03:19:52 +0000510}
511
512
Reid Spencer5f016e22007-07-11 17:01:13 +0000513//===----------------------------------------------------------------------===//
514// Helper functions.
515//===----------------------------------------------------------------------===//
516
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000517DeclContext *Sema::getFunctionLevelDeclContext() {
John McCalldb0ee1d2009-12-19 10:53:49 +0000518 DeclContext *DC = CurContext;
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000520 while (isa<BlockDecl>(DC))
521 DC = DC->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000523 return DC;
524}
525
Chris Lattner371f2582008-12-04 23:50:19 +0000526/// getCurFunctionDecl - If inside of a function body, this returns a pointer
527/// to the function decl for the function being parsed. If we're currently
528/// in a 'block', this returns the containing context.
529FunctionDecl *Sema::getCurFunctionDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000530 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000531 return dyn_cast<FunctionDecl>(DC);
532}
533
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000534ObjCMethodDecl *Sema::getCurMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000535 DeclContext *DC = getFunctionLevelDeclContext();
Steve Naroffd7612e12008-11-17 16:28:52 +0000536 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000537}
Chris Lattner371f2582008-12-04 23:50:19 +0000538
539NamedDecl *Sema::getCurFunctionOrMethodDecl() {
Anders Carlsson8517d9b2009-08-08 17:45:02 +0000540 DeclContext *DC = getFunctionLevelDeclContext();
Chris Lattner371f2582008-12-04 23:50:19 +0000541 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000542 return cast<NamedDecl>(DC);
Chris Lattner371f2582008-12-04 23:50:19 +0000543 return 0;
544}
545
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000546Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000547 if (!this->Emit())
548 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000550 // If this is not a note, and we're in a template instantiation
551 // that is different from the last template instantiation where
552 // we emitted an error, print a template instantiation
553 // backtrace.
554 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
555 !SemaRef.ActiveTemplateInstantiations.empty() &&
Mike Stump1eb44332009-09-09 15:08:12 +0000556 SemaRef.ActiveTemplateInstantiations.back()
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000557 != SemaRef.LastTemplateInstantiationErrorContext) {
558 SemaRef.PrintInstantiationStack();
Mike Stump1eb44332009-09-09 15:08:12 +0000559 SemaRef.LastTemplateInstantiationErrorContext
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000560 = SemaRef.ActiveTemplateInstantiations.back();
561 }
562}
Douglas Gregor2e222532009-07-02 17:08:52 +0000563
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000564Sema::SemaDiagnosticBuilder
565Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
566 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
567 PD.Emit(Builder);
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000569 return Builder;
570}
571
Douglas Gregor2e222532009-07-02 17:08:52 +0000572void Sema::ActOnComment(SourceRange Comment) {
573 Context.Comments.push_back(Comment);
574}
Anders Carlsson91a0cc92009-08-26 22:33:56 +0000575