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