blob: e1857b7583cabd3ee2bef71c43fd9999bd289d04 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Sema class, which performs semantic analysis and
11// builds ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_SEMA_H
16#define LLVM_CLANG_AST_SEMA_H
17
18#include "clang/Parse/Action.h"
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/SmallVector.h"
21#include <vector>
22#include <string>
23
24namespace clang {
25 class ASTContext;
26 class Preprocessor;
27 class Decl;
28 class Expr;
29 class VarDecl;
30 class ParmVarDecl;
31 class TypedefDecl;
32 class FunctionDecl;
33 class QualType;
34 class LangOptions;
35 class DeclaratorChunk;
36 class Token;
37 class IntegerLiteral;
38 class ArrayType;
39 class LabelStmt;
40 class SwitchStmt;
41
42/// Sema - This implements semantic analysis and AST building for C.
43class Sema : public Action {
44 Preprocessor &PP;
45
46 ASTContext &Context;
47
48 /// CurFunctionDecl - If inside of a function body, this contains a pointer to
49 /// the function decl for the function being parsed.
50 FunctionDecl *CurFunctionDecl;
51
52 /// LastInGroupList - This vector is populated when there are multiple
53 /// declarators in a single decl group (e.g. "int A, B, C"). In this case,
54 /// all but the last decl will be entered into this. This is used by the
55 /// ASTStreamer.
56 std::vector<Decl*> &LastInGroupList;
57
58 /// LabelMap - This is a mapping from label identifiers to the LabelStmt for
59 /// it (which acts like the label decl in some ways). Forward referenced
60 /// labels have a LabelStmt created for them with a null location & SubStmt.
61 llvm::DenseMap<IdentifierInfo*, LabelStmt*> LabelMap;
62
63 llvm::SmallVector<SwitchStmt*, 8> SwitchStack;
64public:
65 Sema(Preprocessor &pp, ASTContext &ctxt, std::vector<Decl*> &prevInGroup);
66
67 const LangOptions &getLangOptions() const;
68
69 /// The primitive diagnostic helpers - always returns true, which simplifies
70 /// error handling (i.e. less code).
71 bool Diag(SourceLocation Loc, unsigned DiagID);
72 bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg);
73 bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg1,
74 const std::string &Msg2);
75
76 /// More expressive diagnostic helpers for expressions (say that 6 times:-)
77 bool Diag(SourceLocation Loc, unsigned DiagID, SourceRange R1);
78 bool Diag(SourceLocation Loc, unsigned DiagID,
79 SourceRange R1, SourceRange R2);
80 bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg,
81 SourceRange R1);
82 bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg,
83 SourceRange R1, SourceRange R2);
84 bool Diag(SourceLocation Loc, unsigned DiagID, const std::string &Msg1,
85 const std::string &Msg2, SourceRange R1);
86 bool Diag(SourceLocation Loc, unsigned DiagID,
87 const std::string &Msg1, const std::string &Msg2,
88 SourceRange R1, SourceRange R2);
89
90 //===--------------------------------------------------------------------===//
91 // Type Analysis / Processing: SemaType.cpp.
92 //
93 QualType GetTypeForDeclarator(Declarator &D, Scope *S);
94
95 virtual TypeResult ParseTypeName(Scope *S, Declarator &D);
96
97 virtual TypeResult ParseParamDeclaratorType(Scope *S, Declarator &D);
98private:
99 //===--------------------------------------------------------------------===//
100 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
101 //
102 virtual DeclTy *isTypeName(const IdentifierInfo &II, Scope *S) const;
103 virtual DeclTy *ParseDeclarator(Scope *S, Declarator &D, ExprTy *Init,
104 DeclTy *LastInGroup);
105 virtual DeclTy *FinalizeDeclaratorGroup(Scope *S, DeclTy *Group);
106
107 virtual DeclTy *ParseStartOfFunctionDef(Scope *S, Declarator &D);
108 virtual DeclTy *ParseFunctionDefBody(DeclTy *Decl, StmtTy *Body);
109 virtual void PopScope(SourceLocation Loc, Scope *S);
110
111 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
112 /// no declarator (e.g. "struct foo;") is parsed.
113 virtual DeclTy *ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS);
114
115 virtual DeclTy *ParseTag(Scope *S, unsigned TagType, TagKind TK,
116 SourceLocation KWLoc, IdentifierInfo *Name,
117 SourceLocation NameLoc, AttributeList *Attr);
118 virtual DeclTy *ParseField(Scope *S, DeclTy *TagDecl,SourceLocation DeclStart,
119 Declarator &D, ExprTy *BitfieldWidth);
120 virtual void ParseRecordBody(SourceLocation RecLoc, DeclTy *TagDecl,
121 DeclTy **Fields, unsigned NumFields);
122 virtual DeclTy *ParseEnumConstant(Scope *S, DeclTy *EnumDecl,
123 DeclTy *LastEnumConstant,
124 SourceLocation IdLoc, IdentifierInfo *Id,
125 SourceLocation EqualLoc, ExprTy *Val);
126 virtual void ParseEnumBody(SourceLocation EnumLoc, DeclTy *EnumDecl,
127 DeclTy **Elements, unsigned NumElements);
128private:
129 /// Subroutines of ParseDeclarator()...
130 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, Decl *LastDeclarator);
131 TypedefDecl *MergeTypeDefDecl(TypedefDecl *New, Decl *Old);
132 FunctionDecl *MergeFunctionDecl(FunctionDecl *New, Decl *Old);
133 VarDecl *MergeVarDecl(VarDecl *New, Decl *Old);
134 /// AddTopLevelDecl - called after the decl has been fully processed.
135 /// Allows for bookkeeping and post-processing of each declaration.
136 void AddTopLevelDecl(Decl *current, Decl *last);
137
138 /// More parsing and symbol table subroutines...
139 ParmVarDecl *ParseParamDeclarator(DeclaratorChunk &FI, unsigned ArgNo,
140 Scope *FnBodyScope);
141 Decl *LookupScopedDecl(IdentifierInfo *II, unsigned NSI, SourceLocation IdLoc,
142 Scope *S);
143 Decl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S);
144 Decl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
145 Scope *S);
146 // Decl attributes - this routine is the top level dispatcher.
147 void HandleDeclAttributes(Decl *New, AttributeList *declspec_prefix,
148 AttributeList *declarator_postfix);
149 void HandleDeclAttribute(Decl *New, AttributeList *rawAttr);
150
151 // HandleVectorTypeAttribute - this attribute is only applicable to
152 // integral and float scalars, although arrays, pointers, and function
153 // return values are allowed in conjunction with this construct. Aggregates
154 // with this attribute are invalid, even if they are of the same size as a
155 // corresponding scalar.
156 // The raw attribute should contain precisely 1 argument, the vector size
157 // for the variable, measured in bytes. If curType and rawAttr are well
158 // formed, this routine will return a new vector type.
159 QualType HandleVectorTypeAttribute(QualType curType, AttributeList *rawAttr);
160 QualType HandleOCUVectorTypeAttribute(QualType curType, AttributeList *rawAttr);
161
162 //===--------------------------------------------------------------------===//
163 // Statement Parsing Callbacks: SemaStmt.cpp.
164public:
165 virtual StmtResult ParseExprStmt(ExprTy *Expr);
166
167 virtual StmtResult ParseNullStmt(SourceLocation SemiLoc);
168 virtual StmtResult ParseCompoundStmt(SourceLocation L, SourceLocation R,
169 StmtTy **Elts, unsigned NumElts);
170 virtual StmtResult ParseDeclStmt(DeclTy *Decl);
171 virtual StmtResult ParseCaseStmt(SourceLocation CaseLoc, ExprTy *LHSVal,
172 SourceLocation DotDotDotLoc, ExprTy *RHSVal,
173 SourceLocation ColonLoc, StmtTy *SubStmt);
174 virtual StmtResult ParseDefaultStmt(SourceLocation DefaultLoc,
175 SourceLocation ColonLoc, StmtTy *SubStmt,
176 Scope *CurScope);
177 virtual StmtResult ParseLabelStmt(SourceLocation IdentLoc, IdentifierInfo *II,
178 SourceLocation ColonLoc, StmtTy *SubStmt);
179 virtual StmtResult ParseIfStmt(SourceLocation IfLoc, ExprTy *CondVal,
180 StmtTy *ThenVal, SourceLocation ElseLoc,
181 StmtTy *ElseVal);
182 virtual StmtResult StartSwitchStmt(ExprTy *Cond);
183 virtual StmtResult FinishSwitchStmt(SourceLocation SwitchLoc, StmtTy *Switch,
184 ExprTy *Body);
185 virtual StmtResult ParseWhileStmt(SourceLocation WhileLoc, ExprTy *Cond,
186 StmtTy *Body);
187 virtual StmtResult ParseDoStmt(SourceLocation DoLoc, StmtTy *Body,
188 SourceLocation WhileLoc, ExprTy *Cond);
189
190 virtual StmtResult ParseForStmt(SourceLocation ForLoc,
191 SourceLocation LParenLoc,
192 StmtTy *First, ExprTy *Second, ExprTy *Third,
193 SourceLocation RParenLoc, StmtTy *Body);
194 virtual StmtResult ParseGotoStmt(SourceLocation GotoLoc,
195 SourceLocation LabelLoc,
196 IdentifierInfo *LabelII);
197 virtual StmtResult ParseIndirectGotoStmt(SourceLocation GotoLoc,
198 SourceLocation StarLoc,
199 ExprTy *DestExp);
200 virtual StmtResult ParseContinueStmt(SourceLocation ContinueLoc,
201 Scope *CurScope);
202 virtual StmtResult ParseBreakStmt(SourceLocation GotoLoc, Scope *CurScope);
203
204 virtual StmtResult ParseReturnStmt(SourceLocation ReturnLoc,
205 ExprTy *RetValExp);
206
207 //===--------------------------------------------------------------------===//
208 // Expression Parsing Callbacks: SemaExpr.cpp.
209
210 // Primary Expressions.
211 virtual ExprResult ParseIdentifierExpr(Scope *S, SourceLocation Loc,
212 IdentifierInfo &II,
213 bool HasTrailingLParen);
214 virtual ExprResult ParsePreDefinedExpr(SourceLocation Loc,
215 tok::TokenKind Kind);
216 virtual ExprResult ParseNumericConstant(const Token &);
217 virtual ExprResult ParseCharacterConstant(const Token &);
218 virtual ExprResult ParseParenExpr(SourceLocation L, SourceLocation R,
219 ExprTy *Val);
220
221 /// ParseStringLiteral - The specified tokens were lexed as pasted string
222 /// fragments (e.g. "foo" "bar" L"baz").
223 virtual ExprResult ParseStringLiteral(const Token *Toks, unsigned NumToks);
224
225 // Binary/Unary Operators. 'Tok' is the token for the operator.
226 virtual ExprResult ParseUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
227 ExprTy *Input);
228 virtual ExprResult
229 ParseSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
230 SourceLocation LParenLoc, TypeTy *Ty,
231 SourceLocation RParenLoc);
232
233 virtual ExprResult ParsePostfixUnaryOp(SourceLocation OpLoc,
234 tok::TokenKind Kind, ExprTy *Input);
235
236 virtual ExprResult ParseArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
237 ExprTy *Idx, SourceLocation RLoc);
238 virtual ExprResult ParseMemberReferenceExpr(ExprTy *Base,SourceLocation OpLoc,
239 tok::TokenKind OpKind,
240 SourceLocation MemberLoc,
241 IdentifierInfo &Member);
242
243 /// ParseCallExpr - Handle a call to Fn with the specified array of arguments.
244 /// This provides the location of the left/right parens and a list of comma
245 /// locations.
246 virtual ExprResult ParseCallExpr(ExprTy *Fn, SourceLocation LParenLoc,
247 ExprTy **Args, unsigned NumArgs,
248 SourceLocation *CommaLocs,
249 SourceLocation RParenLoc);
250
251 virtual ExprResult ParseCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
252 SourceLocation RParenLoc, ExprTy *Op);
253
254 virtual ExprResult ParseCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
255 SourceLocation RParenLoc, ExprTy *Op);
256
257 virtual ExprResult ParseInitList(SourceLocation LParenLoc,
258 ExprTy **InitList, unsigned NumInit,
259 SourceLocation RParenLoc);
260
261 virtual ExprResult ParseBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
262 ExprTy *LHS,ExprTy *RHS);
263
264 /// ParseConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
265 /// in the case of a the GNU conditional expr extension.
266 virtual ExprResult ParseConditionalOp(SourceLocation QuestionLoc,
267 SourceLocation ColonLoc,
268 ExprTy *Cond, ExprTy *LHS, ExprTy *RHS);
269
270 /// ParseAddrLabel - Parse the GNU address of label extension: "&&foo".
271 virtual ExprResult ParseAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
272 IdentifierInfo *LabelII);
273
274 virtual ExprResult ParseStmtExpr(SourceLocation LPLoc, StmtTy *SubStmt,
275 SourceLocation RPLoc); // "({..})"
276
277 /// ParseCXXCasts - Parse {dynamic,static,reinterpret,const}_cast's.
278 virtual ExprResult ParseCXXCasts(SourceLocation OpLoc, tok::TokenKind Kind,
279 SourceLocation LAngleBracketLoc, TypeTy *Ty,
280 SourceLocation RAngleBracketLoc,
281 SourceLocation LParenLoc, ExprTy *E,
282 SourceLocation RParenLoc);
283
284 /// ParseCXXBoolLiteral - Parse {true,false} literals.
285 virtual ExprResult ParseCXXBoolLiteral(SourceLocation OpLoc,
286 tok::TokenKind Kind);
287private:
288 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
289 // functions and arrays to their respective pointers (C99 6.3.2.1).
290 void UsualUnaryConversions(Expr *&expr);
291
292 // DefaultFunctionArrayConversion - converts functions and arrays
293 // to their respective pointers (C99 6.3.2.1).
294 void DefaultFunctionArrayConversion(Expr *&expr);
295
296 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
297 // operands and then handles various conversions that are common to binary
298 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
299 // routine returns the first non-arithmetic type found. The client is
300 // responsible for emitting appropriate error diagnostics.
301 void UsualArithmeticConversions(Expr *&lExpr, Expr *&rExpr);
302
303 enum AssignmentCheckResult {
304 Compatible,
305 Incompatible,
306 PointerFromInt,
307 IntFromPointer,
308 IncompatiblePointer,
309 CompatiblePointerDiscardsQualifiers
310 };
311 // CheckAssignmentConstraints - Perform type checking for assignment,
312 // argument passing, variable initialization, and function return values.
313 // This routine is only used by the following two methods. C99 6.5.16.
314 AssignmentCheckResult CheckAssignmentConstraints(QualType lhs, QualType rhs);
315
316 // CheckSingleAssignmentConstraints - Currently used by ParseCallExpr,
317 // CheckAssignmentOperands, and ParseReturnStmt. Prior to type checking,
318 // this routine performs the default function/array converions.
319 AssignmentCheckResult CheckSingleAssignmentConstraints(QualType lhs,
320 Expr *&rExpr);
321 // CheckCompoundAssignmentConstraints - Type check without performing any
322 // conversions. For compound assignments, the "Check...Operands" methods
323 // perform the necessary conversions.
324 AssignmentCheckResult CheckCompoundAssignmentConstraints(QualType lhs,
325 QualType rhs);
326
327 // Helper function for CheckAssignmentConstraints (C99 6.5.16.1p1)
328 AssignmentCheckResult CheckPointerTypesForAssignment(QualType lhsType,
329 QualType rhsType);
330
331 /// the following "Check" methods will return a valid/converted QualType
332 /// or a null QualType (indicating an error diagnostic was issued).
333
334 /// type checking binary operators (subroutines of ParseBinOp).
335 inline void InvalidOperands(SourceLocation l, Expr *&lex, Expr *&rex);
336 inline QualType CheckVectorOperands(SourceLocation l, Expr *&lex, Expr *&rex);
337 inline QualType CheckMultiplyDivideOperands( // C99 6.5.5
338 Expr *&lex, Expr *&rex, SourceLocation OpLoc);
339 inline QualType CheckRemainderOperands( // C99 6.5.5
340 Expr *&lex, Expr *&rex, SourceLocation OpLoc);
341 inline QualType CheckAdditionOperands( // C99 6.5.6
342 Expr *&lex, Expr *&rex, SourceLocation OpLoc);
343 inline QualType CheckSubtractionOperands( // C99 6.5.6
344 Expr *&lex, Expr *&rex, SourceLocation OpLoc);
345 inline QualType CheckShiftOperands( // C99 6.5.7
346 Expr *&lex, Expr *&rex, SourceLocation OpLoc);
347 inline QualType CheckRelationalOperands( // C99 6.5.8
348 Expr *&lex, Expr *&rex, SourceLocation OpLoc);
349 inline QualType CheckEqualityOperands( // C99 6.5.9
350 Expr *&lex, Expr *&rex, SourceLocation OpLoc);
351 inline QualType CheckBitwiseOperands( // C99 6.5.[10...12]
352 Expr *&lex, Expr *&rex, SourceLocation OpLoc);
353 inline QualType CheckLogicalOperands( // C99 6.5.[13,14]
354 Expr *&lex, Expr *&rex, SourceLocation OpLoc);
355 // CheckAssignmentOperands is used for both simple and compound assignment.
356 // For simple assignment, pass both expressions and a null converted type.
357 // For compound assignment, pass both expressions and the converted type.
358 inline QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
359 Expr *lex, Expr *rex, SourceLocation OpLoc, QualType convertedType);
360 inline QualType CheckCommaOperands( // C99 6.5.17
361 Expr *&lex, Expr *&rex, SourceLocation OpLoc);
362 inline QualType CheckConditionalOperands( // C99 6.5.15
363 Expr *&cond, Expr *&lhs, Expr *&rhs, SourceLocation questionLoc);
364
365 /// type checking unary operators (subroutines of ParseUnaryOp).
366 /// C99 6.5.3.1, 6.5.3.2, 6.5.3.4
367 QualType CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc);
368 QualType CheckAddressOfOperand(Expr *op, SourceLocation OpLoc);
369 QualType CheckIndirectionOperand(Expr *op, SourceLocation OpLoc);
370 QualType CheckSizeOfAlignOfOperand(QualType type, SourceLocation loc,
371 bool isSizeof);
372
373 /// C99: 6.7.5p3: Used by ParseDeclarator/ParseField to make sure we have
374 /// a constant expression of type int with a value greater than zero. If the
375 /// array has an incomplete type or a valid constant size, return false,
376 /// otherwise emit a diagnostic and return true.
377 bool VerifyConstantArrayType(const ArrayType *ary, SourceLocation loc);
378};
379
380
381} // end namespace clang
382
383#endif