Sema.cpp revision 2e22253e03e175144aeb9d13350a12fd83f858be
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"
22using namespace clang;
23
24/// ConvertQualTypeToStringFn - This function is used to pretty print the
25/// specified QualType as a string in diagnostics.
26static 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
98static 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
109void 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  // Built-in ObjC types may already be set by PCHReader (hence isNull checks).
129  if (Context.getObjCSelType().isNull()) {
130    // Synthesize "typedef struct objc_selector *SEL;"
131    RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
132    PushOnScopeChains(SelTag, TUScope);
133
134    QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag));
135    TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext,
136                                                  SourceLocation(),
137                                                  &Context.Idents.get("SEL"),
138                                                  SelT);
139    PushOnScopeChains(SelTypedef, TUScope);
140    Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
141  }
142
143  if (Context.getObjCClassType().isNull()) {
144    RecordDecl *ClassTag = CreateStructDecl(Context, "objc_class");
145    QualType ClassT = Context.getPointerType(Context.getTagDeclType(ClassTag));
146    TypedefDecl *ClassTypedef =
147      TypedefDecl::Create(Context, CurContext, SourceLocation(),
148                          &Context.Idents.get("Class"), ClassT);
149    PushOnScopeChains(ClassTag, TUScope);
150    PushOnScopeChains(ClassTypedef, TUScope);
151    Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
152  }
153
154  // Synthesize "@class Protocol;
155  if (Context.getObjCProtoType().isNull()) {
156    ObjCInterfaceDecl *ProtocolDecl =
157      ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
158                                &Context.Idents.get("Protocol"),
159                                SourceLocation(), true);
160    Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
161    PushOnScopeChains(ProtocolDecl, TUScope);
162  }
163
164  // Synthesize "typedef struct objc_object { Class isa; } *id;"
165  if (Context.getObjCIdType().isNull()) {
166    RecordDecl *ObjectTag = CreateStructDecl(Context, "objc_object");
167
168    QualType ObjT = Context.getPointerType(Context.getTagDeclType(ObjectTag));
169    PushOnScopeChains(ObjectTag, TUScope);
170    TypedefDecl *IdTypedef = TypedefDecl::Create(Context, CurContext,
171                                                 SourceLocation(),
172                                                 &Context.Idents.get("id"),
173                                                 ObjT);
174    PushOnScopeChains(IdTypedef, TUScope);
175    Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
176  }
177}
178
179Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
180           bool CompleteTranslationUnit)
181  : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
182    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
183    ExternalSource(0), CurContext(0), PreDeclaratorDC(0),
184    CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()),
185    GlobalNewDeleteDeclared(false), ExprEvalContext(PotentiallyEvaluated),
186    CompleteTranslationUnit(CompleteTranslationUnit),
187    NumSFINAEErrors(0), CurrentInstantiationScope(0) {
188
189  StdNamespace = 0;
190  TUScope = 0;
191  if (getLangOptions().CPlusPlus)
192    FieldCollector.reset(new CXXFieldCollector());
193
194  // Tell diagnostics how to render things from the AST library.
195  PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
196}
197
198/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
199/// If there is already an implicit cast, merge into the existing one.
200/// If isLvalue, the result of the cast is an lvalue.
201void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) {
202  QualType ExprTy = Context.getCanonicalType(Expr->getType());
203  QualType TypeTy = Context.getCanonicalType(Ty);
204
205  if (ExprTy == TypeTy)
206    return;
207
208  if (Expr->getType().getTypePtr()->isPointerType() &&
209      Ty.getTypePtr()->isPointerType()) {
210    QualType ExprBaseType =
211      cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType();
212    QualType BaseType =
213      cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType();
214    if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
215      Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
216        << Expr->getSourceRange();
217    }
218  }
219
220  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
221    ImpCast->setType(Ty);
222    ImpCast->setLvalueCast(isLvalue);
223  } else
224    Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue);
225}
226
227void Sema::DeleteExpr(ExprTy *E) {
228  if (E) static_cast<Expr*>(E)->Destroy(Context);
229}
230void Sema::DeleteStmt(StmtTy *S) {
231  if (S) static_cast<Stmt*>(S)->Destroy(Context);
232}
233
234/// ActOnEndOfTranslationUnit - This is called at the very end of the
235/// translation unit when EOF is reached and all but the top-level scope is
236/// popped.
237void Sema::ActOnEndOfTranslationUnit() {
238  // C++: Perform implicit template instantiations.
239  //
240  // FIXME: When we perform these implicit instantiations, we do not carefully
241  // keep track of the point of instantiation (C++ [temp.point]). This means
242  // that name lookup that occurs within the template instantiation will
243  // always happen at the end of the translation unit, so it will find
244  // some names that should not be found. Although this is common behavior
245  // for C++ compilers, it is technically wrong. In the future, we either need
246  // to be able to filter the results of name lookup or we need to perform
247  // template instantiations earlier.
248  PerformPendingImplicitInstantiations();
249
250  if (!CompleteTranslationUnit)
251    return;
252
253  // C99 6.9.2p2:
254  //   A declaration of an identifier for an object that has file
255  //   scope without an initializer, and without a storage-class
256  //   specifier or with the storage-class specifier static,
257  //   constitutes a tentative definition. If a translation unit
258  //   contains one or more tentative definitions for an identifier,
259  //   and the translation unit contains no external definition for
260  //   that identifier, then the behavior is exactly as if the
261  //   translation unit contains a file scope declaration of that
262  //   identifier, with the composite type as of the end of the
263  //   translation unit, with an initializer equal to 0.
264  for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
265         D = TentativeDefinitions.begin(),
266         DEnd = TentativeDefinitions.end();
267       D != DEnd; ++D) {
268    VarDecl *VD = D->second;
269
270    if (VD->isInvalidDecl() || !VD->isTentativeDefinition(Context))
271      continue;
272
273    if (const IncompleteArrayType *ArrayT
274        = Context.getAsIncompleteArrayType(VD->getType())) {
275      if (RequireCompleteType(VD->getLocation(),
276                              ArrayT->getElementType(),
277                              diag::err_tentative_def_incomplete_type_arr))
278        VD->setInvalidDecl();
279      else {
280        // Set the length of the array to 1 (C99 6.9.2p5).
281        Diag(VD->getLocation(),  diag::warn_tentative_incomplete_array);
282        llvm::APInt One(Context.getTypeSize(Context.getSizeType()),
283                        true);
284        QualType T
285          = Context.getConstantArrayType(ArrayT->getElementType(),
286                                         One, ArrayType::Normal, 0);
287        VD->setType(T);
288      }
289    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
290                                   diag::err_tentative_def_incomplete_type))
291      VD->setInvalidDecl();
292
293    // Notify the consumer that we've completed a tentative definition.
294    if (!VD->isInvalidDecl())
295      Consumer.CompleteTentativeDefinition(VD);
296
297  }
298}
299
300
301//===----------------------------------------------------------------------===//
302// Helper functions.
303//===----------------------------------------------------------------------===//
304
305/// getCurFunctionDecl - If inside of a function body, this returns a pointer
306/// to the function decl for the function being parsed.  If we're currently
307/// in a 'block', this returns the containing context.
308FunctionDecl *Sema::getCurFunctionDecl() {
309  DeclContext *DC = CurContext;
310  while (isa<BlockDecl>(DC))
311    DC = DC->getParent();
312  return dyn_cast<FunctionDecl>(DC);
313}
314
315ObjCMethodDecl *Sema::getCurMethodDecl() {
316  DeclContext *DC = CurContext;
317  while (isa<BlockDecl>(DC))
318    DC = DC->getParent();
319  return dyn_cast<ObjCMethodDecl>(DC);
320}
321
322NamedDecl *Sema::getCurFunctionOrMethodDecl() {
323  DeclContext *DC = CurContext;
324  while (isa<BlockDecl>(DC))
325    DC = DC->getParent();
326  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
327    return cast<NamedDecl>(DC);
328  return 0;
329}
330
331Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
332  if (!this->Emit())
333    return;
334
335  // If this is not a note, and we're in a template instantiation
336  // that is different from the last template instantiation where
337  // we emitted an error, print a template instantiation
338  // backtrace.
339  if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
340      !SemaRef.ActiveTemplateInstantiations.empty() &&
341      SemaRef.ActiveTemplateInstantiations.back()
342        != SemaRef.LastTemplateInstantiationErrorContext) {
343    SemaRef.PrintInstantiationStack();
344    SemaRef.LastTemplateInstantiationErrorContext
345      = SemaRef.ActiveTemplateInstantiations.back();
346  }
347}
348
349void Sema::ActOnComment(SourceRange Comment) {
350  Context.Comments.push_back(Comment);
351}
352