Sema.cpp revision f5b269a115352029a14d81c44647f042bbf6843c
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"
20#include "clang/Basic/Diagnostic.h"
21using namespace clang;
22
23/// ConvertQualTypeToStringFn - This function is used to pretty print the
24/// specified QualType as a string in diagnostics.
25static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t QT,
26                                      const char *Modifier, unsigned ML,
27                                      const char *Argument, unsigned ArgLen,
28                                      llvm::SmallVectorImpl<char> &Output) {
29  assert(ML == 0 && ArgLen == 0 && "Invalid modifier for QualType argument");
30  assert(Kind == Diagnostic::ak_qualtype);
31
32  QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(QT)));
33
34  // FIXME: Playing with std::string is really slow.
35  std::string S = Ty.getAsString();
36  Output.append(S.begin(), S.end());
37}
38
39
40static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
41  if (C.getLangOptions().CPlusPlus)
42    return CXXRecordDecl::Create(C, TagDecl::TK_struct,
43                                 C.getTranslationUnitDecl(),
44                                 SourceLocation(), &C.Idents.get(Name));
45
46  return RecordDecl::Create(C, TagDecl::TK_struct,
47                            C.getTranslationUnitDecl(),
48                            SourceLocation(), &C.Idents.get(Name));
49}
50
51void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
52  TUScope = S;
53  PushDeclContext(Context.getTranslationUnitDecl());
54  if (!PP.getLangOptions().ObjC1) return;
55
56  // Synthesize "typedef struct objc_selector *SEL;"
57  RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
58  PushOnScopeChains(SelTag, TUScope);
59
60  QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag));
61  TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext,
62                                                SourceLocation(),
63                                                &Context.Idents.get("SEL"),
64                                                SelT, 0);
65  PushOnScopeChains(SelTypedef, TUScope);
66  Context.setObjCSelType(SelTypedef);
67
68  // FIXME: Make sure these don't leak!
69  RecordDecl *ClassTag = CreateStructDecl(Context, "objc_class");
70  QualType ClassT = Context.getPointerType(Context.getTagDeclType(ClassTag));
71  TypedefDecl *ClassTypedef =
72    TypedefDecl::Create(Context, CurContext, SourceLocation(),
73                        &Context.Idents.get("Class"), ClassT, 0);
74  PushOnScopeChains(ClassTag, TUScope);
75  PushOnScopeChains(ClassTypedef, TUScope);
76  Context.setObjCClassType(ClassTypedef);
77  // Synthesize "@class Protocol;
78  ObjCInterfaceDecl *ProtocolDecl =
79    ObjCInterfaceDecl::Create(Context, SourceLocation(),
80                              &Context.Idents.get("Protocol"),
81                              SourceLocation(), true);
82  Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
83  PushOnScopeChains(ProtocolDecl, TUScope);
84
85  // Synthesize "typedef struct objc_object { Class isa; } *id;"
86  RecordDecl *ObjectTag = CreateStructDecl(Context, "objc_object");
87
88  QualType ObjT = Context.getPointerType(Context.getTagDeclType(ObjectTag));
89  PushOnScopeChains(ObjectTag, TUScope);
90  TypedefDecl *IdTypedef = TypedefDecl::Create(Context, CurContext,
91                                               SourceLocation(),
92                                               &Context.Idents.get("id"),
93                                               ObjT, 0);
94  PushOnScopeChains(IdTypedef, TUScope);
95  Context.setObjCIdType(IdTypedef);
96}
97
98Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer)
99  : PP(pp), Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
100    SourceMgr(PP.getSourceManager()), CurContext(0), PreDeclaratorDC(0),
101    CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()) {
102
103  // Get IdentifierInfo objects for known functions for which we
104  // do extra checking.
105  IdentifierTable &IT = PP.getIdentifierTable();
106
107  KnownFunctionIDs[id_printf]        = &IT.get("printf");
108  KnownFunctionIDs[id_fprintf]       = &IT.get("fprintf");
109  KnownFunctionIDs[id_sprintf]       = &IT.get("sprintf");
110  KnownFunctionIDs[id_sprintf_chk]   = &IT.get("__builtin___sprintf_chk");
111  KnownFunctionIDs[id_snprintf]      = &IT.get("snprintf");
112  KnownFunctionIDs[id_snprintf_chk]  = &IT.get("__builtin___snprintf_chk");
113  KnownFunctionIDs[id_asprintf]      = &IT.get("asprintf");
114  KnownFunctionIDs[id_NSLog]         = &IT.get("NSLog");
115  KnownFunctionIDs[id_vsnprintf]     = &IT.get("vsnprintf");
116  KnownFunctionIDs[id_vasprintf]     = &IT.get("vasprintf");
117  KnownFunctionIDs[id_vfprintf]      = &IT.get("vfprintf");
118  KnownFunctionIDs[id_vsprintf]      = &IT.get("vsprintf");
119  KnownFunctionIDs[id_vsprintf_chk]  = &IT.get("__builtin___vsprintf_chk");
120  KnownFunctionIDs[id_vsnprintf]     = &IT.get("vsnprintf");
121  KnownFunctionIDs[id_vsnprintf_chk] = &IT.get("__builtin___vsnprintf_chk");
122  KnownFunctionIDs[id_vprintf]       = &IT.get("vprintf");
123
124  StdNamespace = 0;
125  TUScope = 0;
126  if (getLangOptions().CPlusPlus)
127    FieldCollector.reset(new CXXFieldCollector());
128
129  // Tell diagnostics how to render things from the AST library.
130  PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn);
131}
132
133/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
134/// If there is already an implicit cast, merge into the existing one.
135  /// If isLvalue, the result of the cast is an lvalue.
136void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) {
137  QualType ExprTy = Context.getCanonicalType(Expr->getType());
138  QualType TypeTy = Context.getCanonicalType(Ty);
139
140  if (ExprTy == TypeTy)
141    return;
142
143  if (Expr->getType().getTypePtr()->isPointerType() &&
144      Ty.getTypePtr()->isPointerType()) {
145    QualType ExprBaseType =
146      cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType();
147    QualType BaseType =
148      cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType();
149    if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
150      Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
151        << Expr->getSourceRange();
152    }
153  }
154
155  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
156    ImpCast->setType(Ty);
157    ImpCast->setLvalueCast(isLvalue);
158  } else
159    Expr = new ImplicitCastExpr(Ty, Expr, isLvalue);
160}
161
162void Sema::DeleteExpr(ExprTy *E) {
163  delete static_cast<Expr*>(E);
164}
165void Sema::DeleteStmt(StmtTy *S) {
166  delete static_cast<Stmt*>(S);
167}
168
169/// ActOnEndOfTranslationUnit - This is called at the very end of the
170/// translation unit when EOF is reached and all but the top-level scope is
171/// popped.
172void Sema::ActOnEndOfTranslationUnit() {
173
174}
175
176
177//===----------------------------------------------------------------------===//
178// Helper functions.
179//===----------------------------------------------------------------------===//
180
181const LangOptions &Sema::getLangOptions() const {
182  return PP.getLangOptions();
183}
184
185ObjCMethodDecl *Sema::getCurMethodDecl() {
186  DeclContext *DC = CurContext;
187  while (isa<BlockDecl>(DC))
188    DC = DC->getParent();
189  return dyn_cast<ObjCMethodDecl>(DC);
190}
191