blob: b931cf896728e2f18086c845f6f0c59d86fd8714 [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"
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Daniel Dunbare91593e2008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Lex/Preprocessor.h"
Chris Lattner4d150c82009-04-30 06:18:40 +000021#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23
Chris Lattner22caddc2008-11-23 09:13:29 +000024/// ConvertQualTypeToStringFn - This function is used to pretty print the
25/// specified QualType as a string in diagnostics.
Chris Lattner011bb4e2008-11-23 20:28:15 +000026static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val,
Chris Lattnerd0344a42009-02-19 23:45:49 +000027 const char *Modifier, unsigned ModLen,
28 const char *Argument, unsigned ArgLen,
Chris Lattner92dd3862009-02-19 23:53:20 +000029 llvm::SmallVectorImpl<char> &Output,
30 void *Cookie) {
31 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
Chris Lattner3fdf4b02008-11-23 09:21:17 +000032
Chris Lattner011bb4e2008-11-23 20:28:15 +000033 std::string S;
34 if (Kind == Diagnostic::ak_qualtype) {
Chris Lattnerd0344a42009-02-19 23:45:49 +000035 assert(ModLen == 0 && ArgLen == 0 &&
36 "Invalid modifier for QualType argument");
37
Chris Lattner011bb4e2008-11-23 20:28:15 +000038 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
Chris Lattner077bf5e2008-11-24 03:33:13 +000039
Chris Lattner011bb4e2008-11-23 20:28:15 +000040 // FIXME: Playing with std::string is really slow.
41 S = Ty.getAsString();
Chris Lattnerd0344a42009-02-19 23:45:49 +000042
43 // If this is a sugared type (like a typedef, typeof, etc), then unwrap one
44 // level of the sugar so that the type is more obvious to the user.
Douglas Gregor969c6892009-04-01 15:47:24 +000045 QualType DesugaredTy = Ty->getDesugaredType(true);
Chris Lattnerd0344a42009-02-19 23:45:49 +000046 DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() |
47 Ty.getCVRQualifiers());
Chris Lattner077bf5e2008-11-24 03:33:13 +000048
Chris Lattnerd0344a42009-02-19 23:45:49 +000049 if (Ty != DesugaredTy &&
50 // If the desugared type is a vector type, we don't want to expand it,
51 // it will turn into an attribute mess. People want their "vec4".
52 !isa<VectorType>(DesugaredTy) &&
53
Chris Lattner92dd3862009-02-19 23:53:20 +000054 // Don't desugar magic Objective-C types.
55 Ty.getUnqualifiedType() != Context.getObjCIdType() &&
56 Ty.getUnqualifiedType() != Context.getObjCSelType() &&
57 Ty.getUnqualifiedType() != Context.getObjCProtoType() &&
58 Ty.getUnqualifiedType() != Context.getObjCClassType() &&
59
60 // Not va_list.
61 Ty.getUnqualifiedType() != Context.getBuiltinVaListType()) {
Chris Lattnerd0344a42009-02-19 23:45:49 +000062 S = "'"+S+"' (aka '";
63 S += DesugaredTy.getAsString();
64 S += "')";
65 Output.append(S.begin(), S.end());
66 return;
67 }
Chris Lattner077bf5e2008-11-24 03:33:13 +000068
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000069 } else if (Kind == Diagnostic::ak_declarationname) {
Chris Lattner011bb4e2008-11-23 20:28:15 +000070
71 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
72 S = N.getAsString();
Chris Lattner077bf5e2008-11-24 03:33:13 +000073
74 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
75 S = '+' + S;
76 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0)
77 S = '-' + S;
78 else
79 assert(ModLen == 0 && ArgLen == 0 &&
80 "Invalid modifier for DeclarationName argument");
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000081 } else {
82 assert(Kind == Diagnostic::ak_nameddecl);
Douglas Gregoreeb15d42009-02-04 22:46:25 +000083 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
84 S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString();
85 else {
86 assert(ModLen == 0 && ArgLen == 0 &&
Douglas Gregor47b9a1c2009-02-04 17:27:36 +000087 "Invalid modifier for NamedDecl* argument");
Douglas Gregoreeb15d42009-02-04 22:46:25 +000088 S = reinterpret_cast<NamedDecl*>(Val)->getNameAsString();
89 }
Chris Lattner011bb4e2008-11-23 20:28:15 +000090 }
Chris Lattnerd0344a42009-02-19 23:45:49 +000091
92 Output.push_back('\'');
Chris Lattner22caddc2008-11-23 09:13:29 +000093 Output.append(S.begin(), S.end());
Chris Lattnerd0344a42009-02-19 23:45:49 +000094 Output.push_back('\'');
Chris Lattner22caddc2008-11-23 09:13:29 +000095}
96
97
Chris Lattner0a14eee2008-11-18 07:04:44 +000098static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
Anders Carlssonc3036062008-08-23 22:20:38 +000099 if (C.getLangOptions().CPlusPlus)
100 return CXXRecordDecl::Create(C, TagDecl::TK_struct,
101 C.getTranslationUnitDecl(),
Ted Kremenekdf042e62008-09-05 01:34:33 +0000102 SourceLocation(), &C.Idents.get(Name));
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000103
104 return RecordDecl::Create(C, TagDecl::TK_struct,
105 C.getTranslationUnitDecl(),
106 SourceLocation(), &C.Idents.get(Name));
Anders Carlssonc3036062008-08-23 22:20:38 +0000107}
108
Steve Naroffb216c882007-10-09 22:01:59 +0000109void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
110 TUScope = S;
Douglas Gregor44b43212008-12-11 16:49:14 +0000111 PushDeclContext(S, Context.getTranslationUnitDecl());
Chris Lattner2df9ced2009-04-30 02:43:43 +0000112
Chris Lattner4d150c82009-04-30 06:18:40 +0000113 if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
114 // Install [u]int128_t for 64-bit targets.
115 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
116 SourceLocation(),
117 &Context.Idents.get("__int128_t"),
118 Context.Int128Ty), TUScope);
119 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
120 SourceLocation(),
121 &Context.Idents.get("__uint128_t"),
122 Context.UnsignedInt128Ty), TUScope);
123 }
Chris Lattner2df9ced2009-04-30 02:43:43 +0000124
125
Chris Lattner2ae34ed2008-02-06 00:46:58 +0000126 if (!PP.getLangOptions().ObjC1) return;
127
Douglas Gregor319ac892009-04-23 22:29:11 +0000128 if (Context.getObjCSelType().isNull()) {
129 // Synthesize "typedef struct objc_selector *SEL;"
130 RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
131 PushOnScopeChains(SelTag, TUScope);
Steve Naroff69d63752008-02-24 16:25:02 +0000132
Douglas Gregor319ac892009-04-23 22:29:11 +0000133 QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag));
134 TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext,
135 SourceLocation(),
136 &Context.Idents.get("SEL"),
137 SelT);
138 PushOnScopeChains(SelTypedef, TUScope);
139 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
140 }
Chris Lattner6ee1f9c2008-06-21 20:20:39 +0000141
Douglas Gregor319ac892009-04-23 22:29:11 +0000142 if (Context.getObjCClassType().isNull()) {
143 RecordDecl *ClassTag = CreateStructDecl(Context, "objc_class");
144 QualType ClassT = Context.getPointerType(Context.getTagDeclType(ClassTag));
145 TypedefDecl *ClassTypedef =
146 TypedefDecl::Create(Context, CurContext, SourceLocation(),
147 &Context.Idents.get("Class"), ClassT);
148 PushOnScopeChains(ClassTag, TUScope);
149 PushOnScopeChains(ClassTypedef, TUScope);
150 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
151 }
152
Chris Lattner6ee1f9c2008-06-21 20:20:39 +0000153 // Synthesize "@class Protocol;
Douglas Gregor319ac892009-04-23 22:29:11 +0000154 if (Context.getObjCProtoType().isNull()) {
155 ObjCInterfaceDecl *ProtocolDecl =
156 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
157 &Context.Idents.get("Protocol"),
158 SourceLocation(), true);
159 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
160 PushOnScopeChains(ProtocolDecl, TUScope);
161 }
Anders Carlssonc3036062008-08-23 22:20:38 +0000162
Douglas Gregor319ac892009-04-23 22:29:11 +0000163 // Synthesize "typedef struct objc_object { Class isa; } *id;"
164 if (Context.getObjCIdType().isNull()) {
165 RecordDecl *ObjectTag = CreateStructDecl(Context, "objc_object");
166
167 QualType ObjT = Context.getPointerType(Context.getTagDeclType(ObjectTag));
168 PushOnScopeChains(ObjectTag, TUScope);
169 TypedefDecl *IdTypedef = TypedefDecl::Create(Context, CurContext,
170 SourceLocation(),
171 &Context.Idents.get("id"),
172 ObjT);
173 PushOnScopeChains(IdTypedef, TUScope);
174 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
175 }
Steve Naroff3b950172007-10-10 21:53:07 +0000176}
177
Douglas Gregorf807fe02009-04-14 16:27:31 +0000178Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
179 bool CompleteTranslationUnit)
Chris Lattner53ebff32009-01-22 19:21:44 +0000180 : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +0000181 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
182 ExternalSource(0), CurContext(0), PreDeclaratorDC(0),
Sebastian Redlb5a57a62008-12-03 20:26:15 +0000183 CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()),
Douglas Gregorf807fe02009-04-14 16:27:31 +0000184 GlobalNewDeleteDeclared(false),
185 CompleteTranslationUnit(CompleteTranslationUnit) {
Chris Lattner59907c42007-08-10 20:18:51 +0000186
Sebastian Redlc42e1182008-11-11 11:37:55 +0000187 StdNamespace = 0;
Steve Naroff3b950172007-10-10 21:53:07 +0000188 TUScope = 0;
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000189 if (getLangOptions().CPlusPlus)
190 FieldCollector.reset(new CXXFieldCollector());
Chris Lattner22caddc2008-11-23 09:13:29 +0000191
192 // Tell diagnostics how to render things from the AST library.
Chris Lattner92dd3862009-02-19 23:53:20 +0000193 PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
Reid Spencer5f016e22007-07-11 17:01:13 +0000194}
195
Chris Lattner1e0a3902008-01-16 19:17:22 +0000196/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
197/// If there is already an implicit cast, merge into the existing one.
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000198/// If isLvalue, the result of the cast is an lvalue.
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000199void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) {
Mon P Wang3a2c7442008-09-04 08:38:01 +0000200 QualType ExprTy = Context.getCanonicalType(Expr->getType());
201 QualType TypeTy = Context.getCanonicalType(Ty);
202
203 if (ExprTy == TypeTy)
204 return;
205
206 if (Expr->getType().getTypePtr()->isPointerType() &&
207 Ty.getTypePtr()->isPointerType()) {
208 QualType ExprBaseType =
209 cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType();
210 QualType BaseType =
211 cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType();
212 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000213 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
214 << Expr->getSourceRange();
Mon P Wang3a2c7442008-09-04 08:38:01 +0000215 }
216 }
Chris Lattner1e0a3902008-01-16 19:17:22 +0000217
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000218 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
Mon P Wang3a2c7442008-09-04 08:38:01 +0000219 ImpCast->setType(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000220 ImpCast->setLvalueCast(isLvalue);
221 } else
Ted Kremenek8189cde2009-02-07 01:47:29 +0000222 Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue);
Chris Lattner1e0a3902008-01-16 19:17:22 +0000223}
224
Chris Lattner394a3fd2007-08-31 04:53:24 +0000225void Sema::DeleteExpr(ExprTy *E) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000226 if (E) static_cast<Expr*>(E)->Destroy(Context);
Chris Lattner394a3fd2007-08-31 04:53:24 +0000227}
228void Sema::DeleteStmt(StmtTy *S) {
Douglas Gregor05c13a32009-01-22 00:58:24 +0000229 if (S) static_cast<Stmt*>(S)->Destroy(Context);
Chris Lattner394a3fd2007-08-31 04:53:24 +0000230}
231
Chris Lattner9299f3f2008-08-23 03:19:52 +0000232/// ActOnEndOfTranslationUnit - This is called at the very end of the
233/// translation unit when EOF is reached and all but the top-level scope is
234/// popped.
235void Sema::ActOnEndOfTranslationUnit() {
Douglas Gregorf807fe02009-04-14 16:27:31 +0000236 if (!CompleteTranslationUnit)
237 return;
238
Douglas Gregor275a3692009-03-10 23:43:53 +0000239 // C99 6.9.2p2:
240 // A declaration of an identifier for an object that has file
241 // scope without an initializer, and without a storage-class
242 // specifier or with the storage-class specifier static,
243 // constitutes a tentative definition. If a translation unit
244 // contains one or more tentative definitions for an identifier,
245 // and the translation unit contains no external definition for
246 // that identifier, then the behavior is exactly as if the
247 // translation unit contains a file scope declaration of that
248 // identifier, with the composite type as of the end of the
249 // translation unit, with an initializer equal to 0.
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000250 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
251 D = TentativeDefinitions.begin(),
252 DEnd = TentativeDefinitions.end();
253 D != DEnd; ++D) {
254 VarDecl *VD = D->second;
Chris Lattner9299f3f2008-08-23 03:19:52 +0000255
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000256 if (VD->isInvalidDecl() || !VD->isTentativeDefinition(Context))
257 continue;
258
259 if (const IncompleteArrayType *ArrayT
260 = Context.getAsIncompleteArrayType(VD->getType())) {
261 if (RequireCompleteType(VD->getLocation(),
262 ArrayT->getElementType(),
263 diag::err_tentative_def_incomplete_type_arr))
264 VD->setInvalidDecl();
265 else {
266 // Set the length of the array to 1 (C99 6.9.2p5).
267 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
268 llvm::APInt One(Context.getTypeSize(Context.getSizeType()),
269 true);
270 QualType T
271 = Context.getConstantArrayType(ArrayT->getElementType(),
272 One, ArrayType::Normal, 0);
273 VD->setType(T);
Douglas Gregor275a3692009-03-10 23:43:53 +0000274 }
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000275 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
276 diag::err_tentative_def_incomplete_type))
277 VD->setInvalidDecl();
278
279 // Notify the consumer that we've completed a tentative definition.
280 if (!VD->isInvalidDecl())
281 Consumer.CompleteTentativeDefinition(VD);
282
Douglas Gregor275a3692009-03-10 23:43:53 +0000283 }
Chris Lattner9299f3f2008-08-23 03:19:52 +0000284}
285
286
Reid Spencer5f016e22007-07-11 17:01:13 +0000287//===----------------------------------------------------------------------===//
288// Helper functions.
289//===----------------------------------------------------------------------===//
290
Chris Lattner371f2582008-12-04 23:50:19 +0000291/// getCurFunctionDecl - If inside of a function body, this returns a pointer
292/// to the function decl for the function being parsed. If we're currently
293/// in a 'block', this returns the containing context.
294FunctionDecl *Sema::getCurFunctionDecl() {
295 DeclContext *DC = CurContext;
296 while (isa<BlockDecl>(DC))
297 DC = DC->getParent();
298 return dyn_cast<FunctionDecl>(DC);
299}
300
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000301ObjCMethodDecl *Sema::getCurMethodDecl() {
Steve Naroffd7612e12008-11-17 16:28:52 +0000302 DeclContext *DC = CurContext;
303 while (isa<BlockDecl>(DC))
304 DC = DC->getParent();
305 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +0000306}
Chris Lattner371f2582008-12-04 23:50:19 +0000307
308NamedDecl *Sema::getCurFunctionOrMethodDecl() {
309 DeclContext *DC = CurContext;
310 while (isa<BlockDecl>(DC))
311 DC = DC->getParent();
312 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000313 return cast<NamedDecl>(DC);
Chris Lattner371f2582008-12-04 23:50:19 +0000314 return 0;
315}
316
Douglas Gregor25a88bb2009-03-20 22:48:49 +0000317Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
318 this->Emit();
319
320 // If this is not a note, and we're in a template instantiation
321 // that is different from the last template instantiation where
322 // we emitted an error, print a template instantiation
323 // backtrace.
324 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
325 !SemaRef.ActiveTemplateInstantiations.empty() &&
326 SemaRef.ActiveTemplateInstantiations.back()
327 != SemaRef.LastTemplateInstantiationErrorContext) {
328 SemaRef.PrintInstantiationStack();
329 SemaRef.LastTemplateInstantiationErrorContext
330 = SemaRef.ActiveTemplateInstantiations.back();
331 }
332}