Sema.cpp revision 193326
1193326Sed//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file implements the actions class which performs semantic analysis and
11193326Sed// builds an AST out of a parse stream.
12193326Sed//
13193326Sed//===----------------------------------------------------------------------===//
14193326Sed
15193326Sed#include "Sema.h"
16193326Sed#include "clang/AST/ASTConsumer.h"
17193326Sed#include "clang/AST/ASTContext.h"
18193326Sed#include "clang/AST/DeclObjC.h"
19193326Sed#include "clang/AST/Expr.h"
20193326Sed#include "clang/Lex/Preprocessor.h"
21193326Sed#include "clang/Basic/TargetInfo.h"
22193326Sedusing namespace clang;
23193326Sed
24193326Sed/// ConvertQualTypeToStringFn - This function is used to pretty print the
25193326Sed/// specified QualType as a string in diagnostics.
26193326Sedstatic void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val,
27193326Sed                                 const char *Modifier, unsigned ModLen,
28193326Sed                                 const char *Argument, unsigned ArgLen,
29193326Sed                                 llvm::SmallVectorImpl<char> &Output,
30193326Sed                                 void *Cookie) {
31193326Sed  ASTContext &Context = *static_cast<ASTContext*>(Cookie);
32193326Sed
33193326Sed  std::string S;
34193326Sed  if (Kind == Diagnostic::ak_qualtype) {
35193326Sed    assert(ModLen == 0 && ArgLen == 0 &&
36193326Sed           "Invalid modifier for QualType argument");
37193326Sed
38193326Sed    QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
39193326Sed
40193326Sed    // FIXME: Playing with std::string is really slow.
41193326Sed    S = Ty.getAsString(Context.PrintingPolicy);
42193326Sed
43193326Sed    // If this is a sugared type (like a typedef, typeof, etc), then unwrap one
44193326Sed    // level of the sugar so that the type is more obvious to the user.
45193326Sed    QualType DesugaredTy = Ty->getDesugaredType(true);
46193326Sed    DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() |
47193326Sed                                 Ty.getCVRQualifiers());
48193326Sed
49193326Sed    if (Ty != DesugaredTy &&
50193326Sed        // If the desugared type is a vector type, we don't want to expand it,
51193326Sed        // it will turn into an attribute mess. People want their "vec4".
52193326Sed        !isa<VectorType>(DesugaredTy) &&
53193326Sed
54193326Sed        // Don't desugar magic Objective-C types.
55193326Sed        Ty.getUnqualifiedType() != Context.getObjCIdType() &&
56193326Sed        Ty.getUnqualifiedType() != Context.getObjCSelType() &&
57193326Sed        Ty.getUnqualifiedType() != Context.getObjCProtoType() &&
58193326Sed        Ty.getUnqualifiedType() != Context.getObjCClassType() &&
59193326Sed
60193326Sed        // Not va_list.
61193326Sed        Ty.getUnqualifiedType() != Context.getBuiltinVaListType()) {
62193326Sed      S = "'"+S+"' (aka '";
63193326Sed      S += DesugaredTy.getAsString();
64193326Sed      S += "')";
65193326Sed      Output.append(S.begin(), S.end());
66193326Sed      return;
67193326Sed    }
68193326Sed
69193326Sed  } else if (Kind == Diagnostic::ak_declarationname) {
70193326Sed
71193326Sed    DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
72193326Sed    S = N.getAsString();
73193326Sed
74193326Sed    if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
75193326Sed      S = '+' + S;
76193326Sed    else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0)
77193326Sed      S = '-' + S;
78193326Sed    else
79193326Sed      assert(ModLen == 0 && ArgLen == 0 &&
80193326Sed             "Invalid modifier for DeclarationName argument");
81193326Sed  } else {
82193326Sed    assert(Kind == Diagnostic::ak_nameddecl);
83193326Sed    if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
84193326Sed      S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString();
85193326Sed    else {
86193326Sed      assert(ModLen == 0 && ArgLen == 0 &&
87193326Sed           "Invalid modifier for NamedDecl* argument");
88193326Sed      S = reinterpret_cast<NamedDecl*>(Val)->getNameAsString();
89193326Sed    }
90193326Sed  }
91193326Sed
92193326Sed  Output.push_back('\'');
93193326Sed  Output.append(S.begin(), S.end());
94193326Sed  Output.push_back('\'');
95193326Sed}
96193326Sed
97193326Sed
98193326Sedstatic inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
99193326Sed  if (C.getLangOptions().CPlusPlus)
100193326Sed    return CXXRecordDecl::Create(C, TagDecl::TK_struct,
101193326Sed                                 C.getTranslationUnitDecl(),
102193326Sed                                 SourceLocation(), &C.Idents.get(Name));
103193326Sed
104193326Sed  return RecordDecl::Create(C, TagDecl::TK_struct,
105193326Sed                            C.getTranslationUnitDecl(),
106193326Sed                            SourceLocation(), &C.Idents.get(Name));
107193326Sed}
108193326Sed
109193326Sedvoid Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
110193326Sed  TUScope = S;
111193326Sed  PushDeclContext(S, Context.getTranslationUnitDecl());
112193326Sed
113193326Sed  if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
114193326Sed    // Install [u]int128_t for 64-bit targets.
115193326Sed    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
116193326Sed                                          SourceLocation(),
117193326Sed                                          &Context.Idents.get("__int128_t"),
118193326Sed                                          Context.Int128Ty), TUScope);
119193326Sed    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
120193326Sed                                          SourceLocation(),
121193326Sed                                          &Context.Idents.get("__uint128_t"),
122193326Sed                                          Context.UnsignedInt128Ty), TUScope);
123193326Sed  }
124193326Sed
125193326Sed
126193326Sed  if (!PP.getLangOptions().ObjC1) return;
127193326Sed
128193326Sed  if (Context.getObjCSelType().isNull()) {
129193326Sed    // Synthesize "typedef struct objc_selector *SEL;"
130193326Sed    RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
131193326Sed    PushOnScopeChains(SelTag, TUScope);
132193326Sed
133193326Sed    QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag));
134193326Sed    TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext,
135193326Sed                                                  SourceLocation(),
136193326Sed                                                  &Context.Idents.get("SEL"),
137193326Sed                                                  SelT);
138193326Sed    PushOnScopeChains(SelTypedef, TUScope);
139193326Sed    Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
140193326Sed  }
141193326Sed
142193326Sed  if (Context.getObjCClassType().isNull()) {
143193326Sed    RecordDecl *ClassTag = CreateStructDecl(Context, "objc_class");
144193326Sed    QualType ClassT = Context.getPointerType(Context.getTagDeclType(ClassTag));
145193326Sed    TypedefDecl *ClassTypedef =
146193326Sed      TypedefDecl::Create(Context, CurContext, SourceLocation(),
147193326Sed                          &Context.Idents.get("Class"), ClassT);
148193326Sed    PushOnScopeChains(ClassTag, TUScope);
149193326Sed    PushOnScopeChains(ClassTypedef, TUScope);
150193326Sed    Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
151193326Sed  }
152193326Sed
153193326Sed  // Synthesize "@class Protocol;
154193326Sed  if (Context.getObjCProtoType().isNull()) {
155193326Sed    ObjCInterfaceDecl *ProtocolDecl =
156193326Sed      ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
157193326Sed                                &Context.Idents.get("Protocol"),
158193326Sed                                SourceLocation(), true);
159193326Sed    Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
160193326Sed    PushOnScopeChains(ProtocolDecl, TUScope);
161193326Sed  }
162193326Sed
163193326Sed  // Synthesize "typedef struct objc_object { Class isa; } *id;"
164193326Sed  if (Context.getObjCIdType().isNull()) {
165193326Sed    RecordDecl *ObjectTag = CreateStructDecl(Context, "objc_object");
166193326Sed
167193326Sed    QualType ObjT = Context.getPointerType(Context.getTagDeclType(ObjectTag));
168193326Sed    PushOnScopeChains(ObjectTag, TUScope);
169193326Sed    TypedefDecl *IdTypedef = TypedefDecl::Create(Context, CurContext,
170193326Sed                                                 SourceLocation(),
171193326Sed                                                 &Context.Idents.get("id"),
172193326Sed                                                 ObjT);
173193326Sed    PushOnScopeChains(IdTypedef, TUScope);
174193326Sed    Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
175193326Sed  }
176193326Sed}
177193326Sed
178193326SedSema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
179193326Sed           bool CompleteTranslationUnit)
180193326Sed  : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
181193326Sed    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
182193326Sed    ExternalSource(0), CurContext(0), PreDeclaratorDC(0),
183193326Sed    CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()),
184193326Sed    GlobalNewDeleteDeclared(false),
185193326Sed    CompleteTranslationUnit(CompleteTranslationUnit),
186193326Sed    CurrentInstantiationScope(0) {
187193326Sed
188193326Sed  StdNamespace = 0;
189193326Sed  TUScope = 0;
190193326Sed  if (getLangOptions().CPlusPlus)
191193326Sed    FieldCollector.reset(new CXXFieldCollector());
192193326Sed
193193326Sed  // Tell diagnostics how to render things from the AST library.
194193326Sed  PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
195193326Sed}
196193326Sed
197193326Sed/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
198193326Sed/// If there is already an implicit cast, merge into the existing one.
199193326Sed/// If isLvalue, the result of the cast is an lvalue.
200193326Sedvoid Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) {
201193326Sed  QualType ExprTy = Context.getCanonicalType(Expr->getType());
202193326Sed  QualType TypeTy = Context.getCanonicalType(Ty);
203193326Sed
204193326Sed  if (ExprTy == TypeTy)
205193326Sed    return;
206193326Sed
207193326Sed  if (Expr->getType().getTypePtr()->isPointerType() &&
208193326Sed      Ty.getTypePtr()->isPointerType()) {
209193326Sed    QualType ExprBaseType =
210193326Sed      cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType();
211193326Sed    QualType BaseType =
212193326Sed      cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType();
213193326Sed    if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
214193326Sed      Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
215193326Sed        << Expr->getSourceRange();
216193326Sed    }
217193326Sed  }
218193326Sed
219193326Sed  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
220193326Sed    ImpCast->setType(Ty);
221193326Sed    ImpCast->setLvalueCast(isLvalue);
222193326Sed  } else
223193326Sed    Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue);
224193326Sed}
225193326Sed
226193326Sedvoid Sema::DeleteExpr(ExprTy *E) {
227193326Sed  if (E) static_cast<Expr*>(E)->Destroy(Context);
228193326Sed}
229193326Sedvoid Sema::DeleteStmt(StmtTy *S) {
230193326Sed  if (S) static_cast<Stmt*>(S)->Destroy(Context);
231193326Sed}
232193326Sed
233193326Sed/// ActOnEndOfTranslationUnit - This is called at the very end of the
234193326Sed/// translation unit when EOF is reached and all but the top-level scope is
235193326Sed/// popped.
236193326Sedvoid Sema::ActOnEndOfTranslationUnit() {
237193326Sed  if (!CompleteTranslationUnit)
238193326Sed    return;
239193326Sed
240193326Sed  // C99 6.9.2p2:
241193326Sed  //   A declaration of an identifier for an object that has file
242193326Sed  //   scope without an initializer, and without a storage-class
243193326Sed  //   specifier or with the storage-class specifier static,
244193326Sed  //   constitutes a tentative definition. If a translation unit
245193326Sed  //   contains one or more tentative definitions for an identifier,
246193326Sed  //   and the translation unit contains no external definition for
247193326Sed  //   that identifier, then the behavior is exactly as if the
248193326Sed  //   translation unit contains a file scope declaration of that
249193326Sed  //   identifier, with the composite type as of the end of the
250193326Sed  //   translation unit, with an initializer equal to 0.
251193326Sed  for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
252193326Sed         D = TentativeDefinitions.begin(),
253193326Sed         DEnd = TentativeDefinitions.end();
254193326Sed       D != DEnd; ++D) {
255193326Sed    VarDecl *VD = D->second;
256193326Sed
257193326Sed    if (VD->isInvalidDecl() || !VD->isTentativeDefinition(Context))
258193326Sed      continue;
259193326Sed
260193326Sed    if (const IncompleteArrayType *ArrayT
261193326Sed        = Context.getAsIncompleteArrayType(VD->getType())) {
262193326Sed      if (RequireCompleteType(VD->getLocation(),
263193326Sed                              ArrayT->getElementType(),
264193326Sed                              diag::err_tentative_def_incomplete_type_arr))
265193326Sed        VD->setInvalidDecl();
266193326Sed      else {
267193326Sed        // Set the length of the array to 1 (C99 6.9.2p5).
268193326Sed        Diag(VD->getLocation(),  diag::warn_tentative_incomplete_array);
269193326Sed        llvm::APInt One(Context.getTypeSize(Context.getSizeType()),
270193326Sed                        true);
271193326Sed        QualType T
272193326Sed          = Context.getConstantArrayType(ArrayT->getElementType(),
273193326Sed                                         One, ArrayType::Normal, 0);
274193326Sed        VD->setType(T);
275193326Sed      }
276193326Sed    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
277193326Sed                                   diag::err_tentative_def_incomplete_type))
278193326Sed      VD->setInvalidDecl();
279193326Sed
280193326Sed    // Notify the consumer that we've completed a tentative definition.
281193326Sed    if (!VD->isInvalidDecl())
282193326Sed      Consumer.CompleteTentativeDefinition(VD);
283193326Sed
284193326Sed  }
285193326Sed}
286193326Sed
287193326Sed
288193326Sed//===----------------------------------------------------------------------===//
289193326Sed// Helper functions.
290193326Sed//===----------------------------------------------------------------------===//
291193326Sed
292193326Sed/// getCurFunctionDecl - If inside of a function body, this returns a pointer
293193326Sed/// to the function decl for the function being parsed.  If we're currently
294193326Sed/// in a 'block', this returns the containing context.
295193326SedFunctionDecl *Sema::getCurFunctionDecl() {
296193326Sed  DeclContext *DC = CurContext;
297193326Sed  while (isa<BlockDecl>(DC))
298193326Sed    DC = DC->getParent();
299193326Sed  return dyn_cast<FunctionDecl>(DC);
300193326Sed}
301193326Sed
302193326SedObjCMethodDecl *Sema::getCurMethodDecl() {
303193326Sed  DeclContext *DC = CurContext;
304193326Sed  while (isa<BlockDecl>(DC))
305193326Sed    DC = DC->getParent();
306193326Sed  return dyn_cast<ObjCMethodDecl>(DC);
307193326Sed}
308193326Sed
309193326SedNamedDecl *Sema::getCurFunctionOrMethodDecl() {
310193326Sed  DeclContext *DC = CurContext;
311193326Sed  while (isa<BlockDecl>(DC))
312193326Sed    DC = DC->getParent();
313193326Sed  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
314193326Sed    return cast<NamedDecl>(DC);
315193326Sed  return 0;
316193326Sed}
317193326Sed
318193326SedSema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
319193326Sed  this->Emit();
320193326Sed
321193326Sed  // If this is not a note, and we're in a template instantiation
322193326Sed  // that is different from the last template instantiation where
323193326Sed  // we emitted an error, print a template instantiation
324193326Sed  // backtrace.
325193326Sed  if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
326193326Sed      !SemaRef.ActiveTemplateInstantiations.empty() &&
327193326Sed      SemaRef.ActiveTemplateInstantiations.back()
328193326Sed        != SemaRef.LastTemplateInstantiationErrorContext) {
329193326Sed    SemaRef.PrintInstantiationStack();
330193326Sed    SemaRef.LastTemplateInstantiationErrorContext
331193326Sed      = SemaRef.ActiveTemplateInstantiations.back();
332193326Sed  }
333193326Sed}
334