]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/Sema/Sema.cpp
Import Clang, at r72770.
[FreeBSD/FreeBSD.git] / lib / Sema / Sema.cpp
1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
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"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Basic/TargetInfo.h"
22 using namespace clang;
23
24 /// ConvertQualTypeToStringFn - This function is used to pretty print the 
25 /// specified QualType as a string in diagnostics.
26 static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val,
27                                  const char *Modifier, unsigned ModLen,
28                                  const char *Argument, unsigned ArgLen,
29                                  llvm::SmallVectorImpl<char> &Output,
30                                  void *Cookie) {
31   ASTContext &Context = *static_cast<ASTContext*>(Cookie);
32   
33   std::string S;
34   if (Kind == Diagnostic::ak_qualtype) {
35     assert(ModLen == 0 && ArgLen == 0 &&
36            "Invalid modifier for QualType argument");
37
38     QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
39
40     // FIXME: Playing with std::string is really slow.
41     S = Ty.getAsString(Context.PrintingPolicy);
42     
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.
45     QualType DesugaredTy = Ty->getDesugaredType(true);
46     DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() |
47                                  Ty.getCVRQualifiers());
48
49     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       
54         // 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()) {
62       S = "'"+S+"' (aka '";
63       S += DesugaredTy.getAsString(Context.PrintingPolicy);
64       S += "')";
65       Output.append(S.begin(), S.end());
66       return;
67     }
68     
69   } else if (Kind == Diagnostic::ak_declarationname) {
70    
71     DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
72     S = N.getAsString();
73     
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");
81   } else {
82     assert(Kind == Diagnostic::ak_nameddecl);
83     if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
84       S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString();
85     else { 
86       assert(ModLen == 0 && ArgLen == 0 &&
87            "Invalid modifier for NamedDecl* argument");
88       S = reinterpret_cast<NamedDecl*>(Val)->getNameAsString();
89     }
90   }
91   
92   Output.push_back('\'');
93   Output.append(S.begin(), S.end());
94   Output.push_back('\'');
95 }
96
97
98 static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
99   if (C.getLangOptions().CPlusPlus)
100     return CXXRecordDecl::Create(C, TagDecl::TK_struct, 
101                                  C.getTranslationUnitDecl(),
102                                  SourceLocation(), &C.Idents.get(Name));
103
104   return RecordDecl::Create(C, TagDecl::TK_struct, 
105                             C.getTranslationUnitDecl(),
106                             SourceLocation(), &C.Idents.get(Name));
107 }
108
109 void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
110   TUScope = S;
111   PushDeclContext(S, Context.getTranslationUnitDecl());
112   
113   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   }
124   
125   
126   if (!PP.getLangOptions().ObjC1) return;
127   
128   if (Context.getObjCSelType().isNull()) {
129     // Synthesize "typedef struct objc_selector *SEL;"
130     RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
131     PushOnScopeChains(SelTag, TUScope);
132   
133     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   }
141
142   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
153   // Synthesize "@class Protocol;
154   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   }
162
163   // 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   }
176 }
177
178 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
179            bool CompleteTranslationUnit)
180   : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
181     Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 
182     ExternalSource(0), CurContext(0), PreDeclaratorDC(0),
183     CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()),
184     GlobalNewDeleteDeclared(false), 
185     CompleteTranslationUnit(CompleteTranslationUnit),
186     CurrentInstantiationScope(0) {
187   
188   StdNamespace = 0;
189   TUScope = 0;
190   if (getLangOptions().CPlusPlus)
191     FieldCollector.reset(new CXXFieldCollector());
192       
193   // Tell diagnostics how to render things from the AST library.
194   PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
195 }
196
197 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 
198 /// If there is already an implicit cast, merge into the existing one.
199 /// If isLvalue, the result of the cast is an lvalue.
200 void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) {
201   QualType ExprTy = Context.getCanonicalType(Expr->getType());
202   QualType TypeTy = Context.getCanonicalType(Ty);
203   
204   if (ExprTy == TypeTy)
205     return;
206   
207   if (Expr->getType().getTypePtr()->isPointerType() &&
208       Ty.getTypePtr()->isPointerType()) {
209     QualType ExprBaseType = 
210       cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType();
211     QualType BaseType =
212       cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType();
213     if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
214       Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
215         << Expr->getSourceRange();
216     }
217   }
218   
219   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
220     ImpCast->setType(Ty);
221     ImpCast->setLvalueCast(isLvalue);
222   } else 
223     Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue);
224 }
225
226 void Sema::DeleteExpr(ExprTy *E) {
227   if (E) static_cast<Expr*>(E)->Destroy(Context);
228 }
229 void Sema::DeleteStmt(StmtTy *S) {
230   if (S) static_cast<Stmt*>(S)->Destroy(Context);
231 }
232
233 /// ActOnEndOfTranslationUnit - This is called at the very end of the
234 /// translation unit when EOF is reached and all but the top-level scope is
235 /// popped.
236 void Sema::ActOnEndOfTranslationUnit() {
237   if (!CompleteTranslationUnit)
238     return;
239
240   // C99 6.9.2p2:
241   //   A declaration of an identifier for an object that has file
242   //   scope without an initializer, and without a storage-class
243   //   specifier or with the storage-class specifier static,
244   //   constitutes a tentative definition. If a translation unit
245   //   contains one or more tentative definitions for an identifier,
246   //   and the translation unit contains no external definition for
247   //   that identifier, then the behavior is exactly as if the
248   //   translation unit contains a file scope declaration of that
249   //   identifier, with the composite type as of the end of the
250   //   translation unit, with an initializer equal to 0.
251   for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator 
252          D = TentativeDefinitions.begin(),
253          DEnd = TentativeDefinitions.end();
254        D != DEnd; ++D) {
255     VarDecl *VD = D->second;
256
257     if (VD->isInvalidDecl() || !VD->isTentativeDefinition(Context))
258       continue;
259
260     if (const IncompleteArrayType *ArrayT 
261         = Context.getAsIncompleteArrayType(VD->getType())) {
262       if (RequireCompleteType(VD->getLocation(), 
263                               ArrayT->getElementType(),
264                               diag::err_tentative_def_incomplete_type_arr))
265         VD->setInvalidDecl();
266       else {
267         // Set the length of the array to 1 (C99 6.9.2p5).
268         Diag(VD->getLocation(),  diag::warn_tentative_incomplete_array);
269         llvm::APInt One(Context.getTypeSize(Context.getSizeType()), 
270                         true);
271         QualType T 
272           = Context.getConstantArrayType(ArrayT->getElementType(),
273                                          One, ArrayType::Normal, 0);
274         VD->setType(T);
275       }
276     } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 
277                                    diag::err_tentative_def_incomplete_type))
278       VD->setInvalidDecl();
279
280     // Notify the consumer that we've completed a tentative definition.
281     if (!VD->isInvalidDecl())
282       Consumer.CompleteTentativeDefinition(VD);
283
284   }
285 }
286
287
288 //===----------------------------------------------------------------------===//
289 // Helper functions.
290 //===----------------------------------------------------------------------===//
291
292 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
293 /// to the function decl for the function being parsed.  If we're currently
294 /// in a 'block', this returns the containing context.
295 FunctionDecl *Sema::getCurFunctionDecl() {
296   DeclContext *DC = CurContext;
297   while (isa<BlockDecl>(DC))
298     DC = DC->getParent();
299   return dyn_cast<FunctionDecl>(DC);
300 }
301
302 ObjCMethodDecl *Sema::getCurMethodDecl() {
303   DeclContext *DC = CurContext;
304   while (isa<BlockDecl>(DC))
305     DC = DC->getParent();
306   return dyn_cast<ObjCMethodDecl>(DC);
307 }
308
309 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
310   DeclContext *DC = CurContext;
311   while (isa<BlockDecl>(DC))
312     DC = DC->getParent();
313   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
314     return cast<NamedDecl>(DC);
315   return 0;
316 }
317
318 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
319   this->Emit();
320   
321   // If this is not a note, and we're in a template instantiation
322   // that is different from the last template instantiation where
323   // we emitted an error, print a template instantiation
324   // backtrace.
325   if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
326       !SemaRef.ActiveTemplateInstantiations.empty() &&
327       SemaRef.ActiveTemplateInstantiations.back() 
328         != SemaRef.LastTemplateInstantiationErrorContext) {
329     SemaRef.PrintInstantiationStack();
330     SemaRef.LastTemplateInstantiationErrorContext 
331       = SemaRef.ActiveTemplateInstantiations.back();
332   }
333 }