Sema.cpp revision 2f728b2144bb3e5cfc3b954a95b17f8da81d1448
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/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/Lex/Preprocessor.h"
20using namespace clang;
21
22/// ConvertQualTypeToStringFn - This function is used to pretty print the
23/// specified QualType as a string in diagnostics.
24static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val,
25                                 const char *Modifier, unsigned ModLen,
26                                 const char *Argument, unsigned ArgLen,
27                                 llvm::SmallVectorImpl<char> &Output,
28                                 void *Cookie) {
29  ASTContext &Context = *static_cast<ASTContext*>(Cookie);
30
31  std::string S;
32  if (Kind == Diagnostic::ak_qualtype) {
33    assert(ModLen == 0 && ArgLen == 0 &&
34           "Invalid modifier for QualType argument");
35
36    QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
37
38    // FIXME: Playing with std::string is really slow.
39    S = Ty.getAsString();
40
41    // If this is a sugared type (like a typedef, typeof, etc), then unwrap one
42    // level of the sugar so that the type is more obvious to the user.
43    QualType DesugaredTy = Ty->getDesugaredType();
44    DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() |
45                                 Ty.getCVRQualifiers());
46
47    if (Ty != DesugaredTy &&
48        // If the desugared type is a vector type, we don't want to expand it,
49        // it will turn into an attribute mess. People want their "vec4".
50        !isa<VectorType>(DesugaredTy) &&
51
52        // Don't desugar magic Objective-C types.
53        Ty.getUnqualifiedType() != Context.getObjCIdType() &&
54        Ty.getUnqualifiedType() != Context.getObjCSelType() &&
55        Ty.getUnqualifiedType() != Context.getObjCProtoType() &&
56        Ty.getUnqualifiedType() != Context.getObjCClassType() &&
57
58        // Not va_list.
59        Ty.getUnqualifiedType() != Context.getBuiltinVaListType()) {
60      S = "'"+S+"' (aka '";
61      S += DesugaredTy.getAsString();
62      S += "')";
63      Output.append(S.begin(), S.end());
64      return;
65    }
66
67  } else if (Kind == Diagnostic::ak_declarationname) {
68
69    DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
70    S = N.getAsString();
71
72    if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
73      S = '+' + S;
74    else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0)
75      S = '-' + S;
76    else
77      assert(ModLen == 0 && ArgLen == 0 &&
78             "Invalid modifier for DeclarationName argument");
79  } else {
80    assert(Kind == Diagnostic::ak_nameddecl);
81    if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
82      S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString();
83    else {
84      assert(ModLen == 0 && ArgLen == 0 &&
85           "Invalid modifier for NamedDecl* argument");
86      S = reinterpret_cast<NamedDecl*>(Val)->getNameAsString();
87    }
88  }
89
90  Output.push_back('\'');
91  Output.append(S.begin(), S.end());
92  Output.push_back('\'');
93}
94
95
96static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
97  if (C.getLangOptions().CPlusPlus)
98    return CXXRecordDecl::Create(C, TagDecl::TK_struct,
99                                 C.getTranslationUnitDecl(),
100                                 SourceLocation(), &C.Idents.get(Name));
101
102  return RecordDecl::Create(C, TagDecl::TK_struct,
103                            C.getTranslationUnitDecl(),
104                            SourceLocation(), &C.Idents.get(Name));
105}
106
107void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
108  TUScope = S;
109  PushDeclContext(S, Context.getTranslationUnitDecl());
110  if (!PP.getLangOptions().ObjC1) return;
111
112  // Synthesize "typedef struct objc_selector *SEL;"
113  RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
114  PushOnScopeChains(SelTag, TUScope);
115
116  QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag));
117  TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext,
118                                                SourceLocation(),
119                                                &Context.Idents.get("SEL"),
120                                                SelT);
121  PushOnScopeChains(SelTypedef, TUScope);
122  Context.setObjCSelType(SelTypedef);
123
124  // FIXME: Make sure these don't leak!
125  RecordDecl *ClassTag = CreateStructDecl(Context, "objc_class");
126  QualType ClassT = Context.getPointerType(Context.getTagDeclType(ClassTag));
127  TypedefDecl *ClassTypedef =
128    TypedefDecl::Create(Context, CurContext, SourceLocation(),
129                        &Context.Idents.get("Class"), ClassT);
130  PushOnScopeChains(ClassTag, TUScope);
131  PushOnScopeChains(ClassTypedef, TUScope);
132  Context.setObjCClassType(ClassTypedef);
133  // Synthesize "@class Protocol;
134  ObjCInterfaceDecl *ProtocolDecl =
135    ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
136                              &Context.Idents.get("Protocol"),
137                              SourceLocation(), true);
138  Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
139  PushOnScopeChains(ProtocolDecl, TUScope);
140
141  // Synthesize "typedef struct objc_object { Class isa; } *id;"
142  RecordDecl *ObjectTag = CreateStructDecl(Context, "objc_object");
143
144  QualType ObjT = Context.getPointerType(Context.getTagDeclType(ObjectTag));
145  PushOnScopeChains(ObjectTag, TUScope);
146  TypedefDecl *IdTypedef = TypedefDecl::Create(Context, CurContext,
147                                               SourceLocation(),
148                                               &Context.Idents.get("id"),
149                                               ObjT);
150  PushOnScopeChains(IdTypedef, TUScope);
151  Context.setObjCIdType(IdTypedef);
152}
153
154Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer)
155  : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
156    Diags(PP.getDiagnostics()),
157    SourceMgr(PP.getSourceManager()), CurContext(0), PreDeclaratorDC(0),
158    CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()),
159    GlobalNewDeleteDeclared(false) {
160
161  // Get IdentifierInfo objects for known functions for which we
162  // do extra checking.
163  IdentifierTable &IT = PP.getIdentifierTable();
164
165  KnownFunctionIDs[id_NSLog]         = &IT.get("NSLog");
166  KnownFunctionIDs[id_NSLogv]         = &IT.get("NSLogv");
167  KnownFunctionIDs[id_asprintf]      = &IT.get("asprintf");
168  KnownFunctionIDs[id_vasprintf]     = &IT.get("vasprintf");
169
170  StdNamespace = 0;
171  TUScope = 0;
172  ActiveScope = 0;
173
174  if (getLangOptions().CPlusPlus)
175    FieldCollector.reset(new CXXFieldCollector());
176
177  // Tell diagnostics how to render things from the AST library.
178  PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
179}
180
181/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
182/// If there is already an implicit cast, merge into the existing one.
183/// If isLvalue, the result of the cast is an lvalue.
184void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) {
185  QualType ExprTy = Context.getCanonicalType(Expr->getType());
186  QualType TypeTy = Context.getCanonicalType(Ty);
187
188  if (ExprTy == TypeTy)
189    return;
190
191  if (Expr->getType().getTypePtr()->isPointerType() &&
192      Ty.getTypePtr()->isPointerType()) {
193    QualType ExprBaseType =
194      cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType();
195    QualType BaseType =
196      cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType();
197    if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
198      Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
199        << Expr->getSourceRange();
200    }
201  }
202
203  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
204    ImpCast->setType(Ty);
205    ImpCast->setLvalueCast(isLvalue);
206  } else
207    Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue);
208}
209
210void Sema::DeleteExpr(ExprTy *E) {
211  if (E) static_cast<Expr*>(E)->Destroy(Context);
212}
213void Sema::DeleteStmt(StmtTy *S) {
214  if (S) static_cast<Stmt*>(S)->Destroy(Context);
215}
216
217/// ActOnEndOfTranslationUnit - This is called at the very end of the
218/// translation unit when EOF is reached and all but the top-level scope is
219/// popped.
220void Sema::ActOnEndOfTranslationUnit() {
221  // C99 6.9.2p2:
222  //   A declaration of an identifier for an object that has file
223  //   scope without an initializer, and without a storage-class
224  //   specifier or with the storage-class specifier static,
225  //   constitutes a tentative definition. If a translation unit
226  //   contains one or more tentative definitions for an identifier,
227  //   and the translation unit contains no external definition for
228  //   that identifier, then the behavior is exactly as if the
229  //   translation unit contains a file scope declaration of that
230  //   identifier, with the composite type as of the end of the
231  //   translation unit, with an initializer equal to 0.
232  if (!getLangOptions().CPlusPlus) {
233    // Note: we traverse the scope's list of declarations rather than
234    // the DeclContext's list, because we only want to see the most
235    // recent declaration of each identifier.
236    for (Scope::decl_iterator I = TUScope->decl_begin(),
237                           IEnd = TUScope->decl_end();
238         I != IEnd; ++I) {
239      Decl *D = static_cast<Decl *>(*I);
240      if (D->isInvalidDecl())
241        continue;
242
243      if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
244        if (VD->isTentativeDefinition(Context)) {
245          if (const IncompleteArrayType *ArrayT
246                = Context.getAsIncompleteArrayType(VD->getType())) {
247            if (RequireCompleteType(VD->getLocation(),
248                                    ArrayT->getElementType(),
249                                 diag::err_tentative_def_incomplete_type_arr))
250              VD->setInvalidDecl();
251            else {
252              // Set the length of the array to 1 (C99 6.9.2p5).
253              llvm::APSInt One(Context.getTypeSize(Context.getSizeType()),
254                               true);
255              QualType T
256                = Context.getConstantArrayType(ArrayT->getElementType(),
257                                               One, ArrayType::Normal, 0);
258              VD->setType(T);
259            }
260          } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
261                                    diag::err_tentative_def_incomplete_type))
262            VD->setInvalidDecl();
263        }
264      }
265    }
266  }
267}
268
269
270//===----------------------------------------------------------------------===//
271// Helper functions.
272//===----------------------------------------------------------------------===//
273
274/// getCurFunctionDecl - If inside of a function body, this returns a pointer
275/// to the function decl for the function being parsed.  If we're currently
276/// in a 'block', this returns the containing context.
277FunctionDecl *Sema::getCurFunctionDecl() {
278  DeclContext *DC = CurContext;
279  while (isa<BlockDecl>(DC))
280    DC = DC->getParent();
281  return dyn_cast<FunctionDecl>(DC);
282}
283
284ObjCMethodDecl *Sema::getCurMethodDecl() {
285  DeclContext *DC = CurContext;
286  while (isa<BlockDecl>(DC))
287    DC = DC->getParent();
288  return dyn_cast<ObjCMethodDecl>(DC);
289}
290
291NamedDecl *Sema::getCurFunctionOrMethodDecl() {
292  DeclContext *DC = CurContext;
293  while (isa<BlockDecl>(DC))
294    DC = DC->getParent();
295  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
296    return cast<NamedDecl>(DC);
297  return 0;
298}
299
300