blob: d3d3d3556c40150af32319feec3ffe5db48a7127 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner04421082008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027using namespace clang;
28
Chris Lattnere7a2e912008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattnere7a2e912008-07-25 21:10:04 +000033/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
34void Sema::DefaultFunctionArrayConversion(Expr *&E) {
35 QualType Ty = E->getType();
36 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
37
Chris Lattnere7a2e912008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +000040 else if (Ty->isArrayType()) {
41 // In C90 mode, arrays only promote to pointers if the array expression is
42 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
43 // type 'array of type' is converted to an expression that has type 'pointer
44 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
45 // that has type 'array of type' ...". The relevant change is "an lvalue"
46 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +000047 //
48 // C++ 4.2p1:
49 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
50 // T" can be converted to an rvalue of type "pointer to T".
51 //
52 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
53 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner67d33d82008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattnere7a2e912008-07-25 21:10:04 +000056}
57
58/// UsualUnaryConversions - Performs various conversions that are common to most
59/// operators (C99 6.3). The conversions of array and function types are
60/// sometimes surpressed. For example, the array->pointer conversion doesn't
61/// apply if the array is an argument to the sizeof or address (&) operators.
62/// In these instances, this routine should *not* be called.
63Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
64 QualType Ty = Expr->getType();
65 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
66
Chris Lattnere7a2e912008-07-25 21:10:04 +000067 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
68 ImpCastExprToType(Expr, Context.IntTy);
69 else
70 DefaultFunctionArrayConversion(Expr);
71
72 return Expr;
73}
74
Chris Lattner05faf172008-07-25 22:25:12 +000075/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
76/// do not have a prototype. Arguments that have type float are promoted to
77/// double. All other argument types are converted by UsualUnaryConversions().
78void Sema::DefaultArgumentPromotion(Expr *&Expr) {
79 QualType Ty = Expr->getType();
80 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
81
82 // If this is a 'float' (CVR qualified or typedef) promote to double.
83 if (const BuiltinType *BT = Ty->getAsBuiltinType())
84 if (BT->getKind() == BuiltinType::Float)
85 return ImpCastExprToType(Expr, Context.DoubleTy);
86
87 UsualUnaryConversions(Expr);
88}
89
Chris Lattnere7a2e912008-07-25 21:10:04 +000090/// UsualArithmeticConversions - Performs various conversions that are common to
91/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
92/// routine returns the first non-arithmetic type found. The client is
93/// responsible for emitting appropriate error diagnostics.
94/// FIXME: verify the conversion rules for "complex int" are consistent with
95/// GCC.
96QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
97 bool isCompAssign) {
98 if (!isCompAssign) {
99 UsualUnaryConversions(lhsExpr);
100 UsualUnaryConversions(rhsExpr);
101 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000102
Chris Lattnere7a2e912008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000109
110 // If both types are identical, no conversion is needed.
111 if (lhs == rhs)
112 return lhs;
113
114 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
115 // The caller can deal with this (e.g. pointer + int).
116 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
117 return lhs;
118
119 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
120 if (!isCompAssign) {
121 ImpCastExprToType(lhsExpr, destType);
122 ImpCastExprToType(rhsExpr, destType);
123 }
124 return destType;
125}
126
127QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
128 // Perform the usual unary conversions. We do this early so that
129 // integral promotions to "int" can allow us to exit early, in the
130 // lhs == rhs check. Also, for conversion purposes, we ignore any
131 // qualifiers. For example, "const float" and "float" are
132 // equivalent.
Douglas Gregorbf3af052008-11-13 20:12:29 +0000133 if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
134 else lhs = lhs.getUnqualifiedType();
135 if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
136 else rhs = rhs.getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000137
Chris Lattnere7a2e912008-07-25 21:10:04 +0000138 // If both types are identical, no conversion is needed.
139 if (lhs == rhs)
140 return lhs;
141
142 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
143 // The caller can deal with this (e.g. pointer + int).
144 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
145 return lhs;
146
147 // At this point, we have two different arithmetic types.
148
149 // Handle complex types first (C99 6.3.1.8p1).
150 if (lhs->isComplexType() || rhs->isComplexType()) {
151 // if we have an integer operand, the result is the complex type.
152 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
153 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000154 return lhs;
155 }
156 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
157 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000158 return rhs;
159 }
160 // This handles complex/complex, complex/float, or float/complex.
161 // When both operands are complex, the shorter operand is converted to the
162 // type of the longer, and that is the type of the result. This corresponds
163 // to what is done when combining two real floating-point operands.
164 // The fun begins when size promotion occur across type domains.
165 // From H&S 6.3.4: When one operand is complex and the other is a real
166 // floating-point type, the less precise type is converted, within it's
167 // real or complex domain, to the precision of the other type. For example,
168 // when combining a "long double" with a "double _Complex", the
169 // "double _Complex" is promoted to "long double _Complex".
170 int result = Context.getFloatingTypeOrder(lhs, rhs);
171
172 if (result > 0) { // The left side is bigger, convert rhs.
173 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000176 }
177 // At this point, lhs and rhs have the same rank/size. Now, make sure the
178 // domains match. This is a requirement for our implementation, C99
179 // does not require this promotion.
180 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
181 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattnere7a2e912008-07-25 21:10:04 +0000184 return lhs;
185 }
186 }
187 return lhs; // The domain/size match exactly.
188 }
189 // Now handle "real" floating types (i.e. float, double, long double).
190 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
191 // if we have an integer operand, the result is the real floating type.
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000192 if (rhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000193 // convert rhs to the lhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000194 return lhs;
195 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000196 if (rhs->isComplexIntegerType()) {
197 // convert rhs to the complex floating point type.
198 return Context.getComplexType(lhs);
199 }
200 if (lhs->isIntegerType()) {
Chris Lattnere7a2e912008-07-25 21:10:04 +0000201 // convert lhs to the rhs floating point type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000202 return rhs;
203 }
Anders Carlsson5b1f3f02008-12-10 23:30:05 +0000204 if (lhs->isComplexIntegerType()) {
205 // convert lhs to the complex floating point type.
206 return Context.getComplexType(rhs);
207 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000208 // We have two real floating types, float/complex combos were handled above.
209 // Convert the smaller operand to the bigger result.
210 int result = Context.getFloatingTypeOrder(lhs, rhs);
211
212 if (result > 0) { // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000213 return lhs;
214 }
215 if (result < 0) { // convert the lhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000216 return rhs;
217 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000218 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattnere7a2e912008-07-25 21:10:04 +0000219 }
220 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
221 // Handle GCC complex int extension.
222 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
223 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
224
225 if (lhsComplexInt && rhsComplexInt) {
226 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
227 rhsComplexInt->getElementType()) >= 0) {
228 // convert the rhs
Chris Lattnere7a2e912008-07-25 21:10:04 +0000229 return lhs;
230 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000231 return rhs;
232 } else if (lhsComplexInt && rhs->isIntegerType()) {
233 // convert the rhs to the lhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000234 return lhs;
235 } else if (rhsComplexInt && lhs->isIntegerType()) {
236 // convert the lhs to the rhs complex type.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000237 return rhs;
238 }
239 }
240 // Finally, we have two differing integer types.
241 // The rules for this case are in C99 6.3.1.8
242 int compare = Context.getIntegerTypeOrder(lhs, rhs);
243 bool lhsSigned = lhs->isSignedIntegerType(),
244 rhsSigned = rhs->isSignedIntegerType();
245 QualType destType;
246 if (lhsSigned == rhsSigned) {
247 // Same signedness; use the higher-ranked type
248 destType = compare >= 0 ? lhs : rhs;
249 } else if (compare != (lhsSigned ? 1 : -1)) {
250 // The unsigned type has greater than or equal rank to the
251 // signed type, so use the unsigned type
252 destType = lhsSigned ? rhs : lhs;
253 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
254 // The two types are different widths; if we are here, that
255 // means the signed type is larger than the unsigned type, so
256 // use the signed type.
257 destType = lhsSigned ? lhs : rhs;
258 } else {
259 // The signed type is higher-ranked than the unsigned type,
260 // but isn't actually any bigger (like unsigned int and long
261 // on most 32-bit systems). Use the unsigned type corresponding
262 // to the signed type.
263 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
264 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000265 return destType;
266}
267
268//===----------------------------------------------------------------------===//
269// Semantic Analysis for various Expression Types
270//===----------------------------------------------------------------------===//
271
272
Steve Narofff69936d2007-09-16 03:34:24 +0000273/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000274/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
275/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
276/// multiple tokens. However, the common case is that StringToks points to one
277/// string.
278///
279Action::ExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000280Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 assert(NumStringToks && "Must have at least one string!");
282
283 StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
284 if (Literal.hadError)
285 return ExprResult(true);
286
287 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
288 for (unsigned i = 0; i != NumStringToks; ++i)
289 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000290
291 // Verify that pascal strings aren't too large.
Anders Carlssonee98ac52007-10-15 02:50:23 +0000292 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000293 return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long)
294 << SourceRange(StringToks[0].getLocation(),
295 StringToks[NumStringToks-1].getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000296
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000297 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000298 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000299 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000300
301 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
302 if (getLangOptions().CPlusPlus)
303 StrTy.addConst();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000304
305 // Get an array type for the string, according to C99 6.4.5. This includes
306 // the nul terminator character as well as the string length for pascal
307 // strings.
308 StrTy = Context.getConstantArrayType(StrTy,
309 llvm::APInt(32, Literal.GetStringLength()+1),
310 ArrayType::Normal, 0);
311
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
313 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000314 Literal.AnyWide, StrTy,
Anders Carlssonee98ac52007-10-15 02:50:23 +0000315 StringToks[0].getLocation(),
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 StringToks[NumStringToks-1].getLocation());
317}
318
Chris Lattner639e2d32008-10-20 05:16:36 +0000319/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
320/// CurBlock to VD should cause it to be snapshotted (as we do for auto
321/// variables defined outside the block) or false if this is not needed (e.g.
322/// for values inside the block or for globals).
323///
324/// FIXME: This will create BlockDeclRefExprs for global variables,
325/// function references, etc which is suboptimal :) and breaks
326/// things like "integer constant expression" tests.
327static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
328 ValueDecl *VD) {
329 // If the value is defined inside the block, we couldn't snapshot it even if
330 // we wanted to.
331 if (CurBlock->TheDecl == VD->getDeclContext())
332 return false;
333
334 // If this is an enum constant or function, it is constant, don't snapshot.
335 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
336 return false;
337
338 // If this is a reference to an extern, static, or global variable, no need to
339 // snapshot it.
340 // FIXME: What about 'const' variables in C++?
341 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
342 return Var->hasLocalStorage();
343
344 return true;
345}
346
347
348
Steve Naroff08d92e42007-09-15 18:49:24 +0000349/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000350/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000351/// identifier is used in a function call context.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000352/// LookupCtx is only used for a C++ qualified-id (foo::bar) to indicate the
353/// class or namespace that the identifier must be a member of.
Steve Naroff08d92e42007-09-15 18:49:24 +0000354Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Reid Spencer5f016e22007-07-11 17:01:13 +0000355 IdentifierInfo &II,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +0000356 bool HasTrailingLParen,
357 const CXXScopeSpec *SS) {
Douglas Gregor10c42622008-11-18 15:03:34 +0000358 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
359}
360
Douglas Gregor1a49af92009-01-06 05:10:23 +0000361/// BuildDeclRefExpr - Build either a DeclRefExpr or a
362/// QualifiedDeclRefExpr based on whether or not SS is a
363/// nested-name-specifier.
364DeclRefExpr *Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
365 bool TypeDependent, bool ValueDependent,
366 const CXXScopeSpec *SS) {
367 if (SS && !SS->isEmpty())
368 return new QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent,
369 SS->getRange().getBegin());
370 else
371 return new DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
372}
373
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000374/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
375/// variable corresponding to the anonymous union or struct whose type
376/// is Record.
377static ScopedDecl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
378 assert(Record->isAnonymousStructOrUnion() &&
379 "Record must be an anonymous struct or union!");
380
381 // FIXME: Once ScopedDecls are directly linked together, this will
382 // be an O(1) operation rather than a slow walk through DeclContext's
383 // vector (which itself will be eliminated). DeclGroups might make
384 // this even better.
385 DeclContext *Ctx = Record->getDeclContext();
386 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
387 DEnd = Ctx->decls_end();
388 D != DEnd; ++D) {
389 if (*D == Record) {
390 // The object for the anonymous struct/union directly
391 // follows its type in the list of declarations.
392 ++D;
393 assert(D != DEnd && "Missing object for anonymous record");
394 assert(!cast<ScopedDecl>(*D)->getDeclName() && "Decl should be unnamed");
395 return *D;
396 }
397 }
398
399 assert(false && "Missing object for anonymous record");
400 return 0;
401}
402
403Sema::ExprResult
404Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
405 FieldDecl *Field,
406 Expr *BaseObjectExpr,
407 SourceLocation OpLoc) {
408 assert(Field->getDeclContext()->isRecord() &&
409 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
410 && "Field must be stored inside an anonymous struct or union");
411
412 // Construct the sequence of field member references
413 // we'll have to perform to get to the field in the anonymous
414 // union/struct. The list of members is built from the field
415 // outward, so traverse it backwards to go from an object in
416 // the current context to the field we found.
417 llvm::SmallVector<FieldDecl *, 4> AnonFields;
418 AnonFields.push_back(Field);
419 VarDecl *BaseObject = 0;
420 DeclContext *Ctx = Field->getDeclContext();
421 do {
422 RecordDecl *Record = cast<RecordDecl>(Ctx);
423 ScopedDecl *AnonObject = getObjectForAnonymousRecordDecl(Record);
424 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
425 AnonFields.push_back(AnonField);
426 else {
427 BaseObject = cast<VarDecl>(AnonObject);
428 break;
429 }
430 Ctx = Ctx->getParent();
431 } while (Ctx->isRecord() &&
432 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
433
434 // Build the expression that refers to the base object, from
435 // which we will build a sequence of member references to each
436 // of the anonymous union objects and, eventually, the field we
437 // found via name lookup.
438 bool BaseObjectIsPointer = false;
439 unsigned ExtraQuals = 0;
440 if (BaseObject) {
441 // BaseObject is an anonymous struct/union variable (and is,
442 // therefore, not part of another non-anonymous record).
443 delete BaseObjectExpr;
444
445 BaseObjectExpr = new DeclRefExpr(BaseObject, BaseObject->getType(),
446 SourceLocation());
447 ExtraQuals
448 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
449 } else if (BaseObjectExpr) {
450 // The caller provided the base object expression. Determine
451 // whether its a pointer and whether it adds any qualifiers to the
452 // anonymous struct/union fields we're looking into.
453 QualType ObjectType = BaseObjectExpr->getType();
454 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
455 BaseObjectIsPointer = true;
456 ObjectType = ObjectPtr->getPointeeType();
457 }
458 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
459 } else {
460 // We've found a member of an anonymous struct/union that is
461 // inside a non-anonymous struct/union, so in a well-formed
462 // program our base object expression is "this".
463 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
464 if (!MD->isStatic()) {
465 QualType AnonFieldType
466 = Context.getTagDeclType(
467 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
468 QualType ThisType = Context.getTagDeclType(MD->getParent());
469 if ((Context.getCanonicalType(AnonFieldType)
470 == Context.getCanonicalType(ThisType)) ||
471 IsDerivedFrom(ThisType, AnonFieldType)) {
472 // Our base object expression is "this".
473 BaseObjectExpr = new CXXThisExpr(SourceLocation(),
474 MD->getThisType(Context));
475 BaseObjectIsPointer = true;
476 }
477 } else {
478 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
479 << Field->getDeclName();
480 }
481 ExtraQuals = MD->getTypeQualifiers();
482 }
483
484 if (!BaseObjectExpr)
485 return Diag(Loc, diag::err_invalid_non_static_member_use)
486 << Field->getDeclName();
487 }
488
489 // Build the implicit member references to the field of the
490 // anonymous struct/union.
491 Expr *Result = BaseObjectExpr;
492 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
493 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
494 FI != FIEnd; ++FI) {
495 QualType MemberType = (*FI)->getType();
496 if (!(*FI)->isMutable()) {
497 unsigned combinedQualifiers
498 = MemberType.getCVRQualifiers() | ExtraQuals;
499 MemberType = MemberType.getQualifiedType(combinedQualifiers);
500 }
501 Result = new MemberExpr(Result, BaseObjectIsPointer, *FI,
502 OpLoc, MemberType);
503 BaseObjectIsPointer = false;
504 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
505 OpLoc = SourceLocation();
506 }
507
508 return Result;
509}
510
Douglas Gregor10c42622008-11-18 15:03:34 +0000511/// ActOnDeclarationNameExpr - The parser has read some kind of name
512/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
513/// performs lookup on that name and returns an expression that refers
514/// to that name. This routine isn't directly called from the parser,
515/// because the parser doesn't know about DeclarationName. Rather,
516/// this routine is called by ActOnIdentifierExpr,
517/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
518/// which form the DeclarationName from the corresponding syntactic
519/// forms.
520///
521/// HasTrailingLParen indicates whether this identifier is used in a
522/// function call context. LookupCtx is only used for a C++
523/// qualified-id (foo::bar) to indicate the class or namespace that
524/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000525///
526/// If ForceResolution is true, then we will attempt to resolve the
527/// name even if it looks like a dependent name. This option is off by
528/// default.
Douglas Gregor10c42622008-11-18 15:03:34 +0000529Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
530 DeclarationName Name,
531 bool HasTrailingLParen,
Douglas Gregor5c37de72008-12-06 00:22:45 +0000532 const CXXScopeSpec *SS,
533 bool ForceResolution) {
534 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
535 HasTrailingLParen && !SS && !ForceResolution) {
536 // We've seen something of the form
537 // identifier(
538 // and we are in a template, so it is likely that 's' is a
539 // dependent name. However, we won't know until we've parsed all
540 // of the call arguments. So, build a CXXDependentNameExpr node
541 // to represent this name. Then, if it turns out that none of the
542 // arguments are type-dependent, we'll force the resolution of the
543 // dependent name at that point.
544 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
545 Context.DependentTy, Loc);
546 }
547
Chris Lattner8a934232008-03-31 00:36:02 +0000548 // Could be enum-constant, value decl, instance variable, etc.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000549 Decl *D;
550 if (SS && !SS->isEmpty()) {
551 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
552 if (DC == 0)
553 return true;
Douglas Gregor10c42622008-11-18 15:03:34 +0000554 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000555 } else
Douglas Gregor10c42622008-11-18 15:03:34 +0000556 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregor5c37de72008-12-06 00:22:45 +0000557
Chris Lattner8a934232008-03-31 00:36:02 +0000558 // If this reference is in an Objective-C method, then ivar lookup happens as
559 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000560 IdentifierInfo *II = Name.getAsIdentifierInfo();
561 if (II && getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000562 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000563 // There are two cases to handle here. 1) scoped lookup could have failed,
564 // in which case we should look for an ivar. 2) scoped lookup could have
565 // found a decl, but that decl is outside the current method (i.e. a global
566 // variable). In these two cases, we do a lookup for an ivar with this
567 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000568 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000569 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000570 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000571 // FIXME: This should use a new expr for a direct reference, don't turn
572 // this into Self->ivar, just return a BareIVarExpr or something.
573 IdentifierInfo &II = Context.Idents.get("self");
574 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000575 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
576 static_cast<Expr*>(SelfExpr.Val), true, true);
577 Context.setFieldDecl(IFace, IV, MRef);
578 return MRef;
Chris Lattner8a934232008-03-31 00:36:02 +0000579 }
580 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000581 // Needed to implement property "super.method" notation.
Chris Lattner84692652008-11-20 05:35:30 +0000582 if (SD == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000583 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000584 getCurMethodDecl()->getClassInterface()));
Douglas Gregorcd9b46e2008-11-04 14:56:14 +0000585 return new ObjCSuperExpr(Loc, T);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000586 }
Chris Lattner8a934232008-03-31 00:36:02 +0000587 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000588 if (D == 0) {
589 // Otherwise, this could be an implicitly declared function reference (legal
590 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000591 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000592 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000593 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000594 else {
595 // If this name wasn't predeclared and if this is not a function call,
596 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000597 if (SS && !SS->isEmpty())
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000598 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattner08631c52008-11-23 21:45:46 +0000599 << Name << SS->getRange();
Douglas Gregor10c42622008-11-18 15:03:34 +0000600 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
601 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000602 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000603 else
Chris Lattner08631c52008-11-23 21:45:46 +0000604 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 }
606 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000607
608 // We may have found a field within an anonymous union or struct
609 // (C++ [class.union]).
610 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
611 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
612 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Chris Lattner8a934232008-03-31 00:36:02 +0000613
Douglas Gregor88a35142008-12-22 05:46:06 +0000614 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
615 if (!MD->isStatic()) {
616 // C++ [class.mfct.nonstatic]p2:
617 // [...] if name lookup (3.4.1) resolves the name in the
618 // id-expression to a nonstatic nontype member of class X or of
619 // a base class of X, the id-expression is transformed into a
620 // class member access expression (5.2.5) using (*this) (9.3.2)
621 // as the postfix-expression to the left of the '.' operator.
622 DeclContext *Ctx = 0;
623 QualType MemberType;
624 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
625 Ctx = FD->getDeclContext();
626 MemberType = FD->getType();
627
628 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
629 MemberType = RefType->getPointeeType();
630 else if (!FD->isMutable()) {
631 unsigned combinedQualifiers
632 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
633 MemberType = MemberType.getQualifiedType(combinedQualifiers);
634 }
635 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
636 if (!Method->isStatic()) {
637 Ctx = Method->getParent();
638 MemberType = Method->getType();
639 }
640 } else if (OverloadedFunctionDecl *Ovl
641 = dyn_cast<OverloadedFunctionDecl>(D)) {
642 for (OverloadedFunctionDecl::function_iterator
643 Func = Ovl->function_begin(),
644 FuncEnd = Ovl->function_end();
645 Func != FuncEnd; ++Func) {
646 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
647 if (!DMethod->isStatic()) {
648 Ctx = Ovl->getDeclContext();
649 MemberType = Context.OverloadTy;
650 break;
651 }
652 }
653 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000654
655 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000656 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
657 QualType ThisType = Context.getTagDeclType(MD->getParent());
658 if ((Context.getCanonicalType(CtxType)
659 == Context.getCanonicalType(ThisType)) ||
660 IsDerivedFrom(ThisType, CtxType)) {
661 // Build the implicit member access expression.
662 Expr *This = new CXXThisExpr(SourceLocation(),
663 MD->getThisType(Context));
664 return new MemberExpr(This, true, cast<NamedDecl>(D),
665 SourceLocation(), MemberType);
666 }
667 }
668 }
669 }
670
Douglas Gregor44b43212008-12-11 16:49:14 +0000671 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000672 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
673 if (MD->isStatic())
674 // "invalid use of member 'x' in static member function"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000675 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000676 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000677 }
678
Douglas Gregor88a35142008-12-22 05:46:06 +0000679 // Any other ways we could have found the field in a well-formed
680 // program would have been turned into implicit member expressions
681 // above.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000682 return Diag(Loc, diag::err_invalid_non_static_member_use)
683 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000684 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000685
Reid Spencer5f016e22007-07-11 17:01:13 +0000686 if (isa<TypedefDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000687 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000688 if (isa<ObjCInterfaceDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000689 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000690 if (isa<NamespaceDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000691 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Reid Spencer5f016e22007-07-11 17:01:13 +0000692
Steve Naroffdd972f22008-09-05 22:11:13 +0000693 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000694 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Douglas Gregor1a49af92009-01-06 05:10:23 +0000695 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, false, false, SS);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000696
Steve Naroffdd972f22008-09-05 22:11:13 +0000697 ValueDecl *VD = cast<ValueDecl>(D);
698
699 // check if referencing an identifier with __attribute__((deprecated)).
700 if (VD->getAttr<DeprecatedAttr>())
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000701 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000702
703 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
704 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
705 Scope *CheckS = S;
706 while (CheckS) {
707 if (CheckS->isWithinElse() &&
708 CheckS->getControlParent()->isDeclScope(Var)) {
709 if (Var->getType()->isBooleanType())
710 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
711 else
712 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
713 break;
714 }
715
716 // Move up one more control parent to check again.
717 CheckS = CheckS->getControlParent();
718 if (CheckS)
719 CheckS = CheckS->getParent();
720 }
721 }
722 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000723
724 // Only create DeclRefExpr's for valid Decl's.
725 if (VD->isInvalidDecl())
726 return true;
Chris Lattner639e2d32008-10-20 05:16:36 +0000727
728 // If the identifier reference is inside a block, and it refers to a value
729 // that is outside the block, create a BlockDeclRefExpr instead of a
730 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
731 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000732 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000733 // We do not do this for things like enum constants, global variables, etc,
734 // as they do not get snapshotted.
735 //
736 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000737 // The BlocksAttr indicates the variable is bound by-reference.
738 if (VD->getAttr<BlocksAttr>())
Douglas Gregor9d293df2008-10-28 00:22:11 +0000739 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
740 Loc, true);
Steve Naroff090276f2008-10-10 01:28:17 +0000741
742 // Variable will be bound by-copy, make it const within the closure.
743 VD->getType().addConst();
Douglas Gregor9d293df2008-10-28 00:22:11 +0000744 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
745 Loc, false);
Steve Naroff090276f2008-10-10 01:28:17 +0000746 }
747 // If this reference is not in a block or if the referenced variable is
748 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000749
Douglas Gregor898574e2008-12-05 23:32:09 +0000750 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000751 bool ValueDependent = false;
752 if (getLangOptions().CPlusPlus) {
753 // C++ [temp.dep.expr]p3:
754 // An id-expression is type-dependent if it contains:
755 // - an identifier that was declared with a dependent type,
756 if (VD->getType()->isDependentType())
757 TypeDependent = true;
758 // - FIXME: a template-id that is dependent,
759 // - a conversion-function-id that specifies a dependent type,
760 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
761 Name.getCXXNameType()->isDependentType())
762 TypeDependent = true;
763 // - a nested-name-specifier that contains a class-name that
764 // names a dependent type.
765 else if (SS && !SS->isEmpty()) {
766 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
767 DC; DC = DC->getParent()) {
768 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000769 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000770 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
771 if (Context.getTypeDeclType(Record)->isDependentType()) {
772 TypeDependent = true;
773 break;
774 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000775 }
776 }
777 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000778
Douglas Gregor83f96f62008-12-10 20:57:37 +0000779 // C++ [temp.dep.constexpr]p2:
780 //
781 // An identifier is value-dependent if it is:
782 // - a name declared with a dependent type,
783 if (TypeDependent)
784 ValueDependent = true;
785 // - the name of a non-type template parameter,
786 else if (isa<NonTypeTemplateParmDecl>(VD))
787 ValueDependent = true;
788 // - a constant with integral or enumeration type and is
789 // initialized with an expression that is value-dependent
790 // (FIXME!).
791 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000792
Douglas Gregor1a49af92009-01-06 05:10:23 +0000793 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
794 TypeDependent, ValueDependent, SS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000795}
796
Chris Lattnerd9f69102008-08-10 01:53:14 +0000797Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000798 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000799 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000800
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000802 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000803 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
804 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
805 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000807
Chris Lattnerfa28b302008-01-12 08:14:25 +0000808 // Pre-defined identifiers are of type char[x], where x is the length of the
809 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000810 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000811 if (FunctionDecl *FD = getCurFunctionDecl())
812 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000813 else if (ObjCMethodDecl *MD = getCurMethodDecl())
814 Length = MD->getSynthesizedMethodSize();
815 else {
816 Diag(Loc, diag::ext_predef_outside_function);
817 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
818 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
819 }
820
Chris Lattner1423ea42008-01-12 18:39:25 +0000821
Chris Lattner8f978d52008-01-12 19:32:28 +0000822 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000823 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000824 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000825 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000826}
827
Steve Narofff69936d2007-09-16 03:34:24 +0000828Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 llvm::SmallString<16> CharBuffer;
830 CharBuffer.resize(Tok.getLength());
831 const char *ThisTokBegin = &CharBuffer[0];
832 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
833
834 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
835 Tok.getLocation(), PP);
836 if (Literal.hadError())
837 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000838
839 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
840
Chris Lattnerc250aae2008-06-07 22:35:38 +0000841 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
842 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000843}
844
Steve Narofff69936d2007-09-16 03:34:24 +0000845Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000846 // fast path for a single digit (which is quite common). A single digit
847 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
848 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000849 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000850
Chris Lattner98be4942008-03-05 18:54:05 +0000851 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000852 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000853 Context.IntTy,
854 Tok.getLocation()));
855 }
856 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000857 // Add padding so that NumericLiteralParser can overread by one character.
858 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000859 const char *ThisTokBegin = &IntegerBuffer[0];
860
861 // Get the spelling of the token, which eliminates trigraphs, etc.
862 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000863
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
865 Tok.getLocation(), PP);
866 if (Literal.hadError)
867 return ExprResult(true);
868
Chris Lattner5d661452007-08-26 03:42:43 +0000869 Expr *Res;
870
871 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000872 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000873 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000874 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000875 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000876 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000877 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000878 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000879
880 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
881
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000882 // isExact will be set by GetFloatValue().
883 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000884 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000885 Ty, Tok.getLocation());
886
Chris Lattner5d661452007-08-26 03:42:43 +0000887 } else if (!Literal.isIntegerLiteral()) {
888 return ExprResult(true);
889 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000890 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000891
Neil Boothb9449512007-08-29 22:00:19 +0000892 // long long is a C99 feature.
893 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000894 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000895 Diag(Tok.getLocation(), diag::ext_longlong);
896
Reid Spencer5f016e22007-07-11 17:01:13 +0000897 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000898 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000899
900 if (Literal.GetIntegerValue(ResultVal)) {
901 // If this value didn't fit into uintmax_t, warn and force to ull.
902 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000903 Ty = Context.UnsignedLongLongTy;
904 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000905 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000906 } else {
907 // If this value fits into a ULL, try to figure out what else it fits into
908 // according to the rules of C99 6.4.4.1p5.
909
910 // Octal, Hexadecimal, and integers with a U suffix are allowed to
911 // be an unsigned int.
912 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
913
914 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000915 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000916 if (!Literal.isLong && !Literal.isLongLong) {
917 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000918 unsigned IntSize = Context.Target.getIntWidth();
919
Reid Spencer5f016e22007-07-11 17:01:13 +0000920 // Does it fit in a unsigned int?
921 if (ResultVal.isIntN(IntSize)) {
922 // Does it fit in a signed int?
923 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000924 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000925 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000926 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000927 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000928 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 }
930
931 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000932 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000933 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000934
935 // Does it fit in a unsigned long?
936 if (ResultVal.isIntN(LongSize)) {
937 // Does it fit in a signed long?
938 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000939 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000940 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000941 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000942 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000943 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 }
945
946 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000947 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000948 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000949
950 // Does it fit in a unsigned long long?
951 if (ResultVal.isIntN(LongLongSize)) {
952 // Does it fit in a signed long long?
953 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000954 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000955 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000956 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000957 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000958 }
959 }
960
961 // If we still couldn't decide a type, we probably have something that
962 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000963 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000964 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000965 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000966 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000967 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000968
969 if (ResultVal.getBitWidth() != Width)
970 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 }
972
Chris Lattnerf0467b32008-04-02 04:24:33 +0000973 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000974 }
Chris Lattner5d661452007-08-26 03:42:43 +0000975
976 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
977 if (Literal.isImaginary)
978 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
979
980 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000981}
982
Steve Narofff69936d2007-09-16 03:34:24 +0000983Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000984 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000985 Expr *E = (Expr *)Val;
986 assert((E != 0) && "ActOnParenExpr() missing expr");
987 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000988}
989
990/// The UsualUnaryConversions() function is *not* called by this routine.
991/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +0000992bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
993 SourceLocation OpLoc,
994 const SourceRange &ExprRange,
995 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000996 // C99 6.5.3.4p1:
997 if (isa<FunctionType>(exprType) && isSizeof)
998 // alignof(function) is allowed.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000999 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 else if (exprType->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001001 Diag(OpLoc, diag::ext_sizeof_void_type)
1002 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1003 else if (exprType->isIncompleteType())
1004 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
1005 diag::err_alignof_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00001006 << exprType << ExprRange;
Sebastian Redl05189992008-11-11 17:56:53 +00001007
1008 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001009}
1010
Sebastian Redl05189992008-11-11 17:56:53 +00001011/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1012/// the same for @c alignof and @c __alignof
1013/// Note that the ArgRange is invalid if isType is false.
1014Action::ExprResult
1015Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1016 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001017 // If error parsing type, ignore.
Sebastian Redl05189992008-11-11 17:56:53 +00001018 if (TyOrEx == 0) return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001019
Sebastian Redl05189992008-11-11 17:56:53 +00001020 QualType ArgTy;
1021 SourceRange Range;
1022 if (isType) {
1023 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1024 Range = ArgRange;
1025 } else {
1026 // Get the end location.
1027 Expr *ArgEx = (Expr *)TyOrEx;
1028 Range = ArgEx->getSourceRange();
1029 ArgTy = ArgEx->getType();
1030 }
1031
1032 // Verify that the operand is valid.
1033 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001034 return true;
Sebastian Redl05189992008-11-11 17:56:53 +00001035
1036 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1037 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
1038 OpLoc, Range.getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +00001039}
1040
Chris Lattner5d794252007-08-24 21:41:10 +00001041QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +00001042 DefaultFunctionArrayConversion(V);
1043
Chris Lattnercc26ed72007-08-26 05:39:26 +00001044 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001045 if (const ComplexType *CT = V->getType()->getAsComplexType())
1046 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001047
1048 // Otherwise they pass through real integer and floating point types here.
1049 if (V->getType()->isArithmeticType())
1050 return V->getType();
1051
1052 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +00001053 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001054 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001055}
1056
1057
Reid Spencer5f016e22007-07-11 17:01:13 +00001058
Douglas Gregor74253732008-11-19 15:42:04 +00001059Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 tok::TokenKind Kind,
1061 ExprTy *Input) {
Douglas Gregor74253732008-11-19 15:42:04 +00001062 Expr *Arg = (Expr *)Input;
1063
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 UnaryOperator::Opcode Opc;
1065 switch (Kind) {
1066 default: assert(0 && "Unknown unary op!");
1067 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1068 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1069 }
Douglas Gregor74253732008-11-19 15:42:04 +00001070
1071 if (getLangOptions().CPlusPlus &&
1072 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1073 // Which overloaded operator?
1074 OverloadedOperatorKind OverOp =
1075 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1076
1077 // C++ [over.inc]p1:
1078 //
1079 // [...] If the function is a member function with one
1080 // parameter (which shall be of type int) or a non-member
1081 // function with two parameters (the second of which shall be
1082 // of type int), it defines the postfix increment operator ++
1083 // for objects of that type. When the postfix increment is
1084 // called as a result of using the ++ operator, the int
1085 // argument will have value zero.
1086 Expr *Args[2] = {
1087 Arg,
1088 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1089 /*isSigned=*/true),
1090 Context.IntTy, SourceLocation())
1091 };
1092
1093 // Build the candidate set for overloading
1094 OverloadCandidateSet CandidateSet;
1095 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1096
1097 // Perform overload resolution.
1098 OverloadCandidateSet::iterator Best;
1099 switch (BestViableFunction(CandidateSet, Best)) {
1100 case OR_Success: {
1101 // We found a built-in operator or an overloaded operator.
1102 FunctionDecl *FnDecl = Best->Function;
1103
1104 if (FnDecl) {
1105 // We matched an overloaded operator. Build a call to that
1106 // operator.
1107
1108 // Convert the arguments.
1109 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1110 if (PerformObjectArgumentInitialization(Arg, Method))
1111 return true;
1112 } else {
1113 // Convert the arguments.
1114 if (PerformCopyInitialization(Arg,
1115 FnDecl->getParamDecl(0)->getType(),
1116 "passing"))
1117 return true;
1118 }
1119
1120 // Determine the result type
1121 QualType ResultTy
1122 = FnDecl->getType()->getAsFunctionType()->getResultType();
1123 ResultTy = ResultTy.getNonReferenceType();
1124
1125 // Build the actual expression node.
1126 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1127 SourceLocation());
1128 UsualUnaryConversions(FnExpr);
1129
1130 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
1131 } else {
1132 // We matched a built-in operator. Convert the arguments, then
1133 // break out so that we will build the appropriate built-in
1134 // operator node.
1135 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1136 "passing"))
1137 return true;
1138
1139 break;
1140 }
1141 }
1142
1143 case OR_No_Viable_Function:
1144 // No viable function; fall through to handling this as a
1145 // built-in operator, which will produce an error message for us.
1146 break;
1147
1148 case OR_Ambiguous:
1149 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1150 << UnaryOperator::getOpcodeStr(Opc)
1151 << Arg->getSourceRange();
1152 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1153 return true;
1154 }
1155
1156 // Either we found no viable overloaded operator or we matched a
1157 // built-in operator. In either case, fall through to trying to
1158 // build a built-in operation.
1159 }
1160
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001161 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1162 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001163 if (result.isNull())
1164 return true;
Douglas Gregor74253732008-11-19 15:42:04 +00001165 return new UnaryOperator(Arg, Opc, result, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001166}
1167
1168Action::ExprResult Sema::
Douglas Gregor337c6b92008-11-19 17:17:41 +00001169ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001170 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +00001171 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +00001172
Douglas Gregor337c6b92008-11-19 17:17:41 +00001173 if (getLangOptions().CPlusPlus &&
Eli Friedman03f332a2008-12-15 22:34:21 +00001174 (LHSExp->getType()->isRecordType() ||
1175 LHSExp->getType()->isEnumeralType() ||
1176 RHSExp->getType()->isRecordType() ||
1177 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001178 // Add the appropriate overloaded operators (C++ [over.match.oper])
1179 // to the candidate set.
1180 OverloadCandidateSet CandidateSet;
1181 Expr *Args[2] = { LHSExp, RHSExp };
1182 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
1183
1184 // Perform overload resolution.
1185 OverloadCandidateSet::iterator Best;
1186 switch (BestViableFunction(CandidateSet, Best)) {
1187 case OR_Success: {
1188 // We found a built-in operator or an overloaded operator.
1189 FunctionDecl *FnDecl = Best->Function;
1190
1191 if (FnDecl) {
1192 // We matched an overloaded operator. Build a call to that
1193 // operator.
1194
1195 // Convert the arguments.
1196 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1197 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1198 PerformCopyInitialization(RHSExp,
1199 FnDecl->getParamDecl(0)->getType(),
1200 "passing"))
1201 return true;
1202 } else {
1203 // Convert the arguments.
1204 if (PerformCopyInitialization(LHSExp,
1205 FnDecl->getParamDecl(0)->getType(),
1206 "passing") ||
1207 PerformCopyInitialization(RHSExp,
1208 FnDecl->getParamDecl(1)->getType(),
1209 "passing"))
1210 return true;
1211 }
1212
1213 // Determine the result type
1214 QualType ResultTy
1215 = FnDecl->getType()->getAsFunctionType()->getResultType();
1216 ResultTy = ResultTy.getNonReferenceType();
1217
1218 // Build the actual expression node.
1219 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1220 SourceLocation());
1221 UsualUnaryConversions(FnExpr);
1222
1223 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1224 } else {
1225 // We matched a built-in operator. Convert the arguments, then
1226 // break out so that we will build the appropriate built-in
1227 // operator node.
1228 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1229 "passing") ||
1230 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1231 "passing"))
1232 return true;
1233
1234 break;
1235 }
1236 }
1237
1238 case OR_No_Viable_Function:
1239 // No viable function; fall through to handling this as a
1240 // built-in operator, which will produce an error message for us.
1241 break;
1242
1243 case OR_Ambiguous:
1244 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1245 << "[]"
1246 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1247 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1248 return true;
1249 }
1250
1251 // Either we found no viable overloaded operator or we matched a
1252 // built-in operator. In either case, fall through to trying to
1253 // build a built-in operation.
1254 }
1255
Chris Lattner12d9ff62007-07-16 00:14:47 +00001256 // Perform default conversions.
1257 DefaultFunctionArrayConversion(LHSExp);
1258 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +00001259
Chris Lattner12d9ff62007-07-16 00:14:47 +00001260 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001261
Reid Spencer5f016e22007-07-11 17:01:13 +00001262 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001263 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 // in the subscript position. As a result, we need to derive the array base
1265 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001266 Expr *BaseExpr, *IndexExpr;
1267 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +00001268 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001269 BaseExpr = LHSExp;
1270 IndexExpr = RHSExp;
1271 // FIXME: need to deal with const...
1272 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001273 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001274 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001275 BaseExpr = RHSExp;
1276 IndexExpr = LHSExp;
1277 // FIXME: need to deal with const...
1278 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001279 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1280 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001281 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +00001282
1283 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +00001284 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1285 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001286 return Diag(LLoc, diag::err_ext_vector_component_access)
1287 << SourceRange(LLoc, RLoc);
Chris Lattner12d9ff62007-07-16 00:14:47 +00001288 // FIXME: need to deal with const...
1289 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001290 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001291 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1292 << RHSExp->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001293 }
1294 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +00001295 if (!IndexExpr->getType()->isIntegerType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001296 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1297 << IndexExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001298
Chris Lattner12d9ff62007-07-16 00:14:47 +00001299 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1300 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001301 // void (*)(int)) and pointers to incomplete types. Functions are not
1302 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001303 if (!ResultType->isObjectType())
1304 return Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001305 diag::err_typecheck_subscript_not_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00001306 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner12d9ff62007-07-16 00:14:47 +00001307
1308 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001309}
1310
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001311QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001312CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001313 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001314 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001315
1316 // This flag determines whether or not the component is to be treated as a
1317 // special name, or a regular GLSL-style component access.
1318 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001319
1320 // The vector accessor can't exceed the number of elements.
1321 const char *compStr = CompName.getName();
1322 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001323 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattnerd1625842008-11-24 06:25:27 +00001324 << baseType << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001325 return QualType();
1326 }
Nate Begeman8a997642008-05-09 06:41:27 +00001327
1328 // Check that we've found one of the special components, or that the component
1329 // names must come from the same set.
1330 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1331 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1332 SpecialComponent = true;
1333 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001334 do
1335 compStr++;
1336 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1337 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1338 do
1339 compStr++;
1340 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1341 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1342 do
1343 compStr++;
1344 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1345 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001346
Nate Begeman8a997642008-05-09 06:41:27 +00001347 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001348 // We didn't get to the end of the string. This means the component names
1349 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001350 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1351 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001352 return QualType();
1353 }
1354 // Each component accessor can't exceed the vector type.
1355 compStr = CompName.getName();
1356 while (*compStr) {
1357 if (vecType->isAccessorWithinNumElements(*compStr))
1358 compStr++;
1359 else
1360 break;
1361 }
Nate Begeman8a997642008-05-09 06:41:27 +00001362 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001363 // We didn't get to the end of the string. This means a component accessor
1364 // exceeds the number of elements in the vector.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001365 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattnerd1625842008-11-24 06:25:27 +00001366 << baseType << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001367 return QualType();
1368 }
Nate Begeman8a997642008-05-09 06:41:27 +00001369
1370 // If we have a special component name, verify that the current vector length
1371 // is an even number, since all special component names return exactly half
1372 // the elements.
1373 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001374 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001375 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001376 return QualType();
1377 }
1378
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001379 // The component accessor looks fine - now we need to compute the actual type.
1380 // The vector type is implied by the component accessor. For example,
1381 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001382 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1383 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner3c73c412008-11-19 08:23:25 +00001384 : CompName.getLength();
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001385 if (CompSize == 1)
1386 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001387
Nate Begeman213541a2008-04-18 23:10:10 +00001388 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001389 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001390 // diagostics look bad. We want extended vector types to appear built-in.
1391 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1392 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1393 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001394 }
1395 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001396}
1397
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001398/// constructSetterName - Return the setter name for the given
1399/// identifier, i.e. "set" + Name where the initial character of Name
1400/// has been capitalized.
1401// FIXME: Merge with same routine in Parser. But where should this
1402// live?
1403static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1404 const IdentifierInfo *Name) {
1405 llvm::SmallString<100> SelectorName;
1406 SelectorName = "set";
1407 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1408 SelectorName[3] = toupper(SelectorName[3]);
1409 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1410}
1411
Reid Spencer5f016e22007-07-11 17:01:13 +00001412Action::ExprResult Sema::
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001413ActOnMemberReferenceExpr(Scope *S, ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001414 tok::TokenKind OpKind, SourceLocation MemberLoc,
1415 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001416 Expr *BaseExpr = static_cast<Expr *>(Base);
1417 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001418
1419 // Perform default conversions.
1420 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001421
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001422 QualType BaseType = BaseExpr->getType();
1423 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001424
Chris Lattner68a057b2008-07-21 04:36:39 +00001425 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1426 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001427 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001428 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001429 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001430 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001431 return BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001432 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001433 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00001434 << BaseType << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001435 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001436
Chris Lattner68a057b2008-07-21 04:36:39 +00001437 // Handle field access to simple records. This also handles access to fields
1438 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001439 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001440 RecordDecl *RDecl = RTy->getDecl();
1441 if (RTy->isIncompleteType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001442 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001443 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001444 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001445 // FIXME: Qualified name lookup for C++ is a bit more complicated
1446 // than this.
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001447 Decl *MemberDecl = LookupDecl(DeclarationName(&Member), Decl::IDNS_Ordinary,
1448 S, RDecl, false, false);
1449 if (!MemberDecl)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001450 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner3c73c412008-11-19 08:23:25 +00001451 << &Member << BaseExpr->getSourceRange();
Douglas Gregor44b43212008-12-11 16:49:14 +00001452
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001453 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001454 // We may have found a field within an anonymous union or struct
1455 // (C++ [class.union]).
1456 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1457 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1458 BaseExpr, OpLoc);
1459
Douglas Gregor86f19402008-12-20 23:49:58 +00001460 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1461 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001462 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001463 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1464 MemberType = Ref->getPointeeType();
1465 else {
1466 unsigned combinedQualifiers =
1467 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001468 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001469 combinedQualifiers &= ~QualType::Const;
1470 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1471 }
Eli Friedman51019072008-02-06 22:48:16 +00001472
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001473 return new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
Douglas Gregor86f19402008-12-20 23:49:58 +00001474 MemberLoc, MemberType);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001475 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001476 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc,
1477 Var->getType().getNonReferenceType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001478 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001479 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc,
1480 MemberFn->getType());
1481 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001482 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001483 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc,
1484 Context.OverloadTy);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001485 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001486 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc,
1487 Enum->getType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001488 else if (isa<TypeDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001489 return Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1490 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Eli Friedman51019072008-02-06 22:48:16 +00001491
Douglas Gregor86f19402008-12-20 23:49:58 +00001492 // We found a declaration kind that we didn't expect. This is a
1493 // generic error message that tells the user that she can't refer
1494 // to this member with '.' or '->'.
1495 return Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1496 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001497 }
1498
Chris Lattnera38e6b12008-07-21 04:59:05 +00001499 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1500 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001501 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001502 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001503 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1504 BaseExpr,
1505 OpKind == tok::arrow);
1506 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1507 return MRef;
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001508 }
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001509 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001510 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001511 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001512 }
1513
Chris Lattnera38e6b12008-07-21 04:59:05 +00001514 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1515 // pointer to a (potentially qualified) interface type.
1516 const PointerType *PTy;
1517 const ObjCInterfaceType *IFTy;
1518 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1519 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1520 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001521
Daniel Dunbar2307d312008-09-03 01:05:41 +00001522 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001523 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1524 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1525
Daniel Dunbar2307d312008-09-03 01:05:41 +00001526 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001527 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1528 E = IFTy->qual_end(); I != E; ++I)
1529 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1530 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001531
1532 // If that failed, look for an "implicit" property by seeing if the nullary
1533 // selector is implemented.
1534
1535 // FIXME: The logic for looking up nullary and unary selectors should be
1536 // shared with the code in ActOnInstanceMessage.
1537
1538 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1539 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1540
1541 // If this reference is in an @implementation, check for 'private' methods.
1542 if (!Getter)
1543 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1544 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1545 if (ObjCImplementationDecl *ImpDecl =
1546 ObjCImplementations[ClassDecl->getIdentifier()])
1547 Getter = ImpDecl->getInstanceMethod(Sel);
1548
Steve Naroff7692ed62008-10-22 19:16:27 +00001549 // Look through local category implementations associated with the class.
1550 if (!Getter) {
1551 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1552 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1553 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1554 }
1555 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001556 if (Getter) {
1557 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001558 // will look for the matching setter, in case it is needed.
1559 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1560 &Member);
1561 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1562 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1563 if (!Setter) {
1564 // If this reference is in an @implementation, also check for 'private'
1565 // methods.
1566 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1567 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1568 if (ObjCImplementationDecl *ImpDecl =
1569 ObjCImplementations[ClassDecl->getIdentifier()])
1570 Setter = ImpDecl->getInstanceMethod(SetterSel);
1571 }
1572 // Look through local category implementations associated with the class.
1573 if (!Setter) {
1574 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1575 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1576 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1577 }
1578 }
1579
1580 // FIXME: we must check that the setter has property type.
1581 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00001582 MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001583 }
Anders Carlsson00165a22008-12-19 17:27:57 +00001584
1585 return Diag(MemberLoc, diag::err_property_not_found) <<
1586 &Member << BaseType;
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001587 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001588 // Handle properties on qualified "id" protocols.
1589 const ObjCQualifiedIdType *QIdTy;
1590 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1591 // Check protocols on qualified interfaces.
1592 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001593 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroff18bc1642008-10-20 22:53:06 +00001594 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1595 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001596 // Also must look for a getter name which uses property syntax.
1597 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1598 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1599 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1600 OpLoc, MemberLoc, NULL, 0);
1601 }
1602 }
Anders Carlsson00165a22008-12-19 17:27:57 +00001603
1604 return Diag(MemberLoc, diag::err_property_not_found) <<
1605 &Member << BaseType;
Steve Naroff18bc1642008-10-20 22:53:06 +00001606 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001607 // Handle 'field access' to vectors, such as 'V.xx'.
1608 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1609 // Component access limited to variables (reject vec4.rg.g).
1610 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1611 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001612 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1613 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001614 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1615 if (ret.isNull())
1616 return true;
1617 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1618 }
1619
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001620 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattnerd1625842008-11-24 06:25:27 +00001621 << BaseType << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001622}
1623
Douglas Gregor88a35142008-12-22 05:46:06 +00001624/// ConvertArgumentsForCall - Converts the arguments specified in
1625/// Args/NumArgs to the parameter types of the function FDecl with
1626/// function prototype Proto. Call is the call expression itself, and
1627/// Fn is the function expression. For a C++ member function, this
1628/// routine does not attempt to convert the object argument. Returns
1629/// true if the call is ill-formed.
1630bool
1631Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1632 FunctionDecl *FDecl,
1633 const FunctionTypeProto *Proto,
1634 Expr **Args, unsigned NumArgs,
1635 SourceLocation RParenLoc) {
1636 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1637 // assignment, to the types of the corresponding parameter, ...
1638 unsigned NumArgsInProto = Proto->getNumArgs();
1639 unsigned NumArgsToCheck = NumArgs;
1640
1641 // If too few arguments are available (and we don't have default
1642 // arguments for the remaining parameters), don't make the call.
1643 if (NumArgs < NumArgsInProto) {
1644 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1645 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1646 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1647 // Use default arguments for missing arguments
1648 NumArgsToCheck = NumArgsInProto;
1649 Call->setNumArgs(NumArgsInProto);
1650 }
1651
1652 // If too many are passed and not variadic, error on the extras and drop
1653 // them.
1654 if (NumArgs > NumArgsInProto) {
1655 if (!Proto->isVariadic()) {
1656 Diag(Args[NumArgsInProto]->getLocStart(),
1657 diag::err_typecheck_call_too_many_args)
1658 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1659 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1660 Args[NumArgs-1]->getLocEnd());
1661 // This deletes the extra arguments.
1662 Call->setNumArgs(NumArgsInProto);
1663 }
1664 NumArgsToCheck = NumArgsInProto;
1665 }
1666
1667 // Continue to check argument types (even if we have too few/many args).
1668 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1669 QualType ProtoArgType = Proto->getArgType(i);
1670
1671 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00001672 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001673 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00001674
1675 // Pass the argument.
1676 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1677 return true;
1678 } else
1679 // We already type-checked the argument, so we know it works.
Douglas Gregor88a35142008-12-22 05:46:06 +00001680 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1681 QualType ArgType = Arg->getType();
Douglas Gregor61366e92008-12-24 00:01:03 +00001682
Douglas Gregor88a35142008-12-22 05:46:06 +00001683 Call->setArg(i, Arg);
1684 }
1685
1686 // If this is a variadic call, handle args passed through "...".
1687 if (Proto->isVariadic()) {
1688 // Promote the arguments (C99 6.5.2.2p7).
1689 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1690 Expr *Arg = Args[i];
1691 DefaultArgumentPromotion(Arg);
1692 Call->setArg(i, Arg);
1693 }
1694 }
1695
1696 return false;
1697}
1698
Steve Narofff69936d2007-09-16 03:34:24 +00001699/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001700/// This provides the location of the left/right parens and a list of comma
1701/// locations.
Douglas Gregor88a35142008-12-22 05:46:06 +00001702Action::ExprResult
1703Sema::ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
1704 ExprTy **args, unsigned NumArgs,
1705 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001706 Expr *Fn = static_cast<Expr *>(fn);
1707 Expr **Args = reinterpret_cast<Expr**>(args);
1708 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001709 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001710 OverloadedFunctionDecl *Ovl = NULL;
1711
Douglas Gregor5c37de72008-12-06 00:22:45 +00001712 // Determine whether this is a dependent call inside a C++ template,
1713 // in which case we won't do any semantic analysis now.
1714 bool Dependent = false;
1715 if (Fn->isTypeDependent()) {
1716 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1717 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1718 Dependent = true;
1719 else {
1720 // Resolve the CXXDependentNameExpr to an actual identifier;
1721 // it wasn't really a dependent name after all.
1722 ExprResult Resolved
1723 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1724 /*HasTrailingLParen=*/true,
1725 /*SS=*/0,
1726 /*ForceResolution=*/true);
1727 if (Resolved.isInvalid)
1728 return true;
1729 else {
1730 delete Fn;
1731 Fn = (Expr *)Resolved.Val;
1732 }
1733 }
1734 } else
1735 Dependent = true;
1736 } else
1737 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1738
Douglas Gregor898574e2008-12-05 23:32:09 +00001739 // FIXME: Will need to cache the results of name lookup (including
1740 // ADL) in Fn.
Douglas Gregor5c37de72008-12-06 00:22:45 +00001741 if (Dependent)
Douglas Gregor898574e2008-12-05 23:32:09 +00001742 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1743
Douglas Gregor88a35142008-12-22 05:46:06 +00001744 // Determine whether this is a call to an object (C++ [over.call.object]).
1745 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1746 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1747 CommaLocs, RParenLoc);
1748
1749 // Determine whether this is a call to a member function.
1750 if (getLangOptions().CPlusPlus) {
1751 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1752 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1753 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1754 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1755 CommaLocs, RParenLoc);
1756 }
1757
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001758 // If we're directly calling a function or a set of overloaded
1759 // functions, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001760 DeclRefExpr *DRExpr = NULL;
1761 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1762 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1763 else
1764 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1765
1766 if (DRExpr) {
1767 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1768 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001769 }
1770
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001771 if (Ovl) {
Douglas Gregor0a396682008-11-26 06:01:48 +00001772 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1773 RParenLoc);
1774 if (!FDecl)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001775 return true;
1776
Douglas Gregor0a396682008-11-26 06:01:48 +00001777 // Update Fn to refer to the actual function selected.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001778 Expr *NewFn = 0;
1779 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1780 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1781 QDRExpr->getLocation(), false, false,
1782 QDRExpr->getSourceRange().getBegin());
1783 else
1784 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1785 Fn->getSourceRange().getBegin());
Douglas Gregor0a396682008-11-26 06:01:48 +00001786 Fn->Destroy(Context);
1787 Fn = NewFn;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001788 }
Chris Lattner04421082008-04-08 04:40:51 +00001789
1790 // Promote the function operand.
1791 UsualUnaryConversions(Fn);
1792
Chris Lattner925e60d2007-12-28 05:29:59 +00001793 // Make the call expr early, before semantic checks. This guarantees cleanup
1794 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001795 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001796 Context.BoolTy, RParenLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00001797
Steve Naroffdd972f22008-09-05 22:11:13 +00001798 const FunctionType *FuncT;
1799 if (!Fn->getType()->isBlockPointerType()) {
1800 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1801 // have type pointer to function".
1802 const PointerType *PT = Fn->getType()->getAsPointerType();
1803 if (PT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001804 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerd1625842008-11-24 06:25:27 +00001805 << Fn->getType() << Fn->getSourceRange();
Steve Naroffdd972f22008-09-05 22:11:13 +00001806 FuncT = PT->getPointeeType()->getAsFunctionType();
1807 } else { // This is a block call.
1808 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1809 getAsFunctionType();
1810 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001811 if (FuncT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001812 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerd1625842008-11-24 06:25:27 +00001813 << Fn->getType() << Fn->getSourceRange();
Chris Lattner925e60d2007-12-28 05:29:59 +00001814
1815 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001816 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001817
Chris Lattner925e60d2007-12-28 05:29:59 +00001818 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001819 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1820 RParenLoc))
1821 return true;
Chris Lattner925e60d2007-12-28 05:29:59 +00001822 } else {
1823 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1824
Steve Naroffb291ab62007-08-28 23:30:39 +00001825 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001826 for (unsigned i = 0; i != NumArgs; i++) {
1827 Expr *Arg = Args[i];
1828 DefaultArgumentPromotion(Arg);
1829 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001830 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001831 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001832
Douglas Gregor88a35142008-12-22 05:46:06 +00001833 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1834 if (!Method->isStatic())
1835 return Diag(LParenLoc, diag::err_member_call_without_object)
1836 << Fn->getSourceRange();
1837
Chris Lattner59907c42007-08-10 20:18:51 +00001838 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001839 if (FDecl)
1840 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001841
Chris Lattner925e60d2007-12-28 05:29:59 +00001842 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001843}
1844
1845Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001846ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001847 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001848 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001849 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001850 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001851 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001852 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001853
Eli Friedman6223c222008-05-20 05:22:08 +00001854 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001855 if (literalType->isVariableArrayType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001856 return Diag(LParenLoc, diag::err_variable_object_no_init)
1857 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001858 } else if (literalType->isIncompleteType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001859 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001860 << literalType
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001861 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001862 }
1863
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001864 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001865 DeclarationName()))
Steve Naroff58d18212008-01-09 20:58:06 +00001866 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001867
Chris Lattner371f2582008-12-04 23:50:19 +00001868 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00001869 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001870 if (CheckForConstantInitializer(literalExpr, literalType))
1871 return true;
1872 }
Chris Lattner220ad7c2008-10-26 23:35:51 +00001873 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1874 isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001875}
1876
1877Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001878ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattner220ad7c2008-10-26 23:35:51 +00001879 InitListDesignations &Designators,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001880 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001881 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001882
Steve Naroff08d92e42007-09-15 18:49:24 +00001883 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001884 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001885
Chris Lattner418f6c72008-10-26 23:43:26 +00001886 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1887 Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001888 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1889 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001890}
1891
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001892/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001893bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001894 UsualUnaryConversions(castExpr);
1895
1896 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1897 // type needs to be scalar.
1898 if (castType->isVoidType()) {
1899 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00001900 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1901 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001902 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1903 // GCC struct/union extension: allow cast to self.
1904 if (Context.getCanonicalType(castType) !=
1905 Context.getCanonicalType(castExpr->getType()) ||
1906 (!castType->isStructureType() && !castType->isUnionType())) {
1907 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001908 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001909 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001910 }
1911
1912 // accept this, but emit an ext-warn.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001913 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001914 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001915 } else if (!castExpr->getType()->isScalarType() &&
1916 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001917 return Diag(castExpr->getLocStart(),
1918 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00001919 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001920 } else if (castExpr->getType()->isVectorType()) {
1921 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1922 return true;
1923 } else if (castType->isVectorType()) {
1924 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1925 return true;
1926 }
1927 return false;
1928}
1929
Chris Lattnerfe23e212007-12-20 00:44:32 +00001930bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001931 assert(VectorTy->isVectorType() && "Not a vector type!");
1932
1933 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001934 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001935 return Diag(R.getBegin(),
1936 Ty->isVectorType() ?
1937 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001938 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00001939 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001940 } else
1941 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001942 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001943 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001944
1945 return false;
1946}
1947
Steve Naroff4aa88f82007-07-19 01:06:55 +00001948Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001949ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001950 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001951 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001952
1953 Expr *castExpr = static_cast<Expr*>(Op);
1954 QualType castType = QualType::getFromOpaquePtr(Ty);
1955
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001956 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1957 return true;
Steve Naroffb2f9e512008-11-03 23:29:32 +00001958 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001959}
1960
Chris Lattnera21ddb32007-11-26 01:40:58 +00001961/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1962/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001963inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001964 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001965 UsualUnaryConversions(cond);
1966 UsualUnaryConversions(lex);
1967 UsualUnaryConversions(rex);
1968 QualType condT = cond->getType();
1969 QualType lexT = lex->getType();
1970 QualType rexT = rex->getType();
1971
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 // first, check the condition.
Douglas Gregor898574e2008-12-05 23:32:09 +00001973 if (!cond->isTypeDependent()) {
1974 if (!condT->isScalarType()) { // C99 6.5.15p2
1975 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1976 return QualType();
1977 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001978 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001979
1980 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00001981 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1982 return Context.DependentTy;
1983
Chris Lattner70d67a92008-01-06 22:42:25 +00001984 // If both operands have arithmetic type, do the usual arithmetic conversions
1985 // to find a common type: C99 6.5.15p3,5.
1986 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001987 UsualArithmeticConversions(lex, rex);
1988 return lex->getType();
1989 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001990
1991 // If both operands are the same structure or union type, the result is that
1992 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001993 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001994 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001995 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00001996 // "If both the operands have structure or union type, the result has
1997 // that type." This implies that CV qualifiers are dropped.
1998 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001999 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002000
2001 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002002 // The following || allows only one side to be void (a GCC-ism).
2003 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00002004 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002005 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2006 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00002007 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002008 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2009 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00002010 ImpCastExprToType(lex, Context.VoidTy);
2011 ImpCastExprToType(rex, Context.VoidTy);
2012 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002013 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002014 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2015 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002016 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2017 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002018 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002019 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002020 return lexT;
2021 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002022 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2023 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002024 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002025 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002026 return rexT;
2027 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00002028 // Handle the case where both operands are pointers before we handle null
2029 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002030 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2031 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2032 // get the "pointed to" types
2033 QualType lhptee = LHSPT->getPointeeType();
2034 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002035
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002036 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2037 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002038 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002039 // Figure out necessary qualifiers (C99 6.5.15p6)
2040 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002041 QualType destType = Context.getPointerType(destPointee);
2042 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2043 ImpCastExprToType(rex, destType); // promote to void*
2044 return destType;
2045 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002046 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002047 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002048 QualType destType = Context.getPointerType(destPointee);
2049 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2050 ImpCastExprToType(rex, destType); // promote to void*
2051 return destType;
2052 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002053
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002054 QualType compositeType = lexT;
2055
2056 // If either type is an Objective-C object type then check
2057 // compatibility according to Objective-C.
2058 if (Context.isObjCObjectPointerType(lexT) ||
2059 Context.isObjCObjectPointerType(rexT)) {
2060 // If both operands are interfaces and either operand can be
2061 // assigned to the other, use that type as the composite
2062 // type. This allows
2063 // xxx ? (A*) a : (B*) b
2064 // where B is a subclass of A.
2065 //
2066 // Additionally, as for assignment, if either type is 'id'
2067 // allow silent coercion. Finally, if the types are
2068 // incompatible then make sure to use 'id' as the composite
2069 // type so the result is acceptable for sending messages to.
2070
2071 // FIXME: This code should not be localized to here. Also this
2072 // should use a compatible check instead of abusing the
2073 // canAssignObjCInterfaces code.
2074 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2075 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2076 if (LHSIface && RHSIface &&
2077 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2078 compositeType = lexT;
2079 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002080 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002081 compositeType = rexT;
2082 } else if (Context.isObjCIdType(lhptee) ||
2083 Context.isObjCIdType(rhptee)) {
2084 // FIXME: This code looks wrong, because isObjCIdType checks
2085 // the struct but getObjCIdType returns the pointer to
2086 // struct. This is horrible and should be fixed.
2087 compositeType = Context.getObjCIdType();
2088 } else {
2089 QualType incompatTy = Context.getObjCIdType();
2090 ImpCastExprToType(lex, incompatTy);
2091 ImpCastExprToType(rex, incompatTy);
2092 return incompatTy;
2093 }
2094 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2095 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002096 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002097 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002098 // In this situation, we assume void* type. No especially good
2099 // reason, but this is what gcc does, and we do have to pick
2100 // to get a consistent AST.
2101 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002102 ImpCastExprToType(lex, incompatTy);
2103 ImpCastExprToType(rex, incompatTy);
2104 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002105 }
2106 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002107 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2108 // differently qualified versions of compatible types, the result type is
2109 // a pointer to an appropriately qualified version of the *composite*
2110 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002111 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002112 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00002113 ImpCastExprToType(lex, compositeType);
2114 ImpCastExprToType(rex, compositeType);
2115 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002116 }
2117 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002118 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2119 // evaluates to "struct objc_object *" (and is handled above when comparing
2120 // id with statically typed objects).
2121 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2122 // GCC allows qualified id and any Objective-C type to devolve to
2123 // id. Currently localizing to here until clear this should be
2124 // part of ObjCQualifiedIdTypesAreCompatible.
2125 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2126 (lexT->isObjCQualifiedIdType() &&
2127 Context.isObjCObjectPointerType(rexT)) ||
2128 (rexT->isObjCQualifiedIdType() &&
2129 Context.isObjCObjectPointerType(lexT))) {
2130 // FIXME: This is not the correct composite type. This only
2131 // happens to work because id can more or less be used anywhere,
2132 // however this may change the type of method sends.
2133 // FIXME: gcc adds some type-checking of the arguments and emits
2134 // (confusing) incompatible comparison warnings in some
2135 // cases. Investigate.
2136 QualType compositeType = Context.getObjCIdType();
2137 ImpCastExprToType(lex, compositeType);
2138 ImpCastExprToType(rex, compositeType);
2139 return compositeType;
2140 }
2141 }
2142
Steve Naroff61f40a22008-09-10 19:17:48 +00002143 // Selection between block pointer types is ok as long as they are the same.
2144 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2145 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2146 return lexT;
2147
Chris Lattner70d67a92008-01-06 22:42:25 +00002148 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002149 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00002150 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 return QualType();
2152}
2153
Steve Narofff69936d2007-09-16 03:34:24 +00002154/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002155/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00002156Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002157 SourceLocation ColonLoc,
2158 ExprTy *Cond, ExprTy *LHS,
2159 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00002160 Expr *CondExpr = (Expr *) Cond;
2161 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00002162
2163 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2164 // was the condition.
2165 bool isLHSNull = LHSExpr == 0;
2166 if (isLHSNull)
2167 LHSExpr = CondExpr;
2168
Chris Lattner26824902007-07-16 21:39:03 +00002169 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2170 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002171 if (result.isNull())
2172 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00002173 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2174 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002175}
2176
Reid Spencer5f016e22007-07-11 17:01:13 +00002177
2178// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2179// being closely modeled after the C99 spec:-). The odd characteristic of this
2180// routine is it effectively iqnores the qualifiers on the top level pointee.
2181// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2182// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002183Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002184Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2185 QualType lhptee, rhptee;
2186
2187 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002188 lhptee = lhsType->getAsPointerType()->getPointeeType();
2189 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002190
2191 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002192 lhptee = Context.getCanonicalType(lhptee);
2193 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002194
Chris Lattner5cf216b2008-01-04 18:04:52 +00002195 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002196
2197 // C99 6.5.16.1p1: This following citation is common to constraints
2198 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2199 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00002200 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002201 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002202 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002203
2204 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2205 // incomplete type and the other is a pointer to a qualified or unqualified
2206 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002207 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002208 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002209 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002210
2211 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002212 assert(rhptee->isFunctionType());
2213 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002214 }
2215
2216 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002217 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002218 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002219
2220 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002221 assert(lhptee->isFunctionType());
2222 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002223 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002224
2225 // Check for ObjC interfaces
2226 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2227 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2228 if (LHSIface && RHSIface &&
2229 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2230 return ConvTy;
2231
2232 // ID acts sort of like void* for ObjC interfaces
2233 if (LHSIface && Context.isObjCIdType(rhptee))
2234 return ConvTy;
2235 if (RHSIface && Context.isObjCIdType(lhptee))
2236 return ConvTy;
2237
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2239 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002240 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2241 rhptee.getUnqualifiedType()))
2242 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002243 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002244}
2245
Steve Naroff1c7d0672008-09-04 15:10:53 +00002246/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2247/// block pointer types are compatible or whether a block and normal pointer
2248/// are compatible. It is more restrict than comparing two function pointer
2249// types.
2250Sema::AssignConvertType
2251Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2252 QualType rhsType) {
2253 QualType lhptee, rhptee;
2254
2255 // get the "pointed to" type (ignoring qualifiers at the top level)
2256 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2257 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2258
2259 // make sure we operate on the canonical type
2260 lhptee = Context.getCanonicalType(lhptee);
2261 rhptee = Context.getCanonicalType(rhptee);
2262
2263 AssignConvertType ConvTy = Compatible;
2264
2265 // For blocks we enforce that qualifiers are identical.
2266 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2267 ConvTy = CompatiblePointerDiscardsQualifiers;
2268
2269 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2270 return IncompatibleBlockPointer;
2271 return ConvTy;
2272}
2273
Reid Spencer5f016e22007-07-11 17:01:13 +00002274/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2275/// has code to accommodate several GCC extensions when type checking
2276/// pointers. Here are some objectionable examples that GCC considers warnings:
2277///
2278/// int a, *pint;
2279/// short *pshort;
2280/// struct foo *pfoo;
2281///
2282/// pint = pshort; // warning: assignment from incompatible pointer type
2283/// a = pint; // warning: assignment makes integer from pointer without a cast
2284/// pint = a; // warning: assignment makes pointer from integer without a cast
2285/// pint = pfoo; // warning: assignment from incompatible pointer type
2286///
2287/// As a result, the code for dealing with pointers is more complex than the
2288/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002289///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002290Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002291Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002292 // Get canonical types. We're not formatting these types, just comparing
2293 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002294 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2295 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002296
2297 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002298 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002299
Douglas Gregor9d293df2008-10-28 00:22:11 +00002300 // If the left-hand side is a reference type, then we are in a
2301 // (rare!) case where we've allowed the use of references in C,
2302 // e.g., as a parameter type in a built-in function. In this case,
2303 // just make sure that the type referenced is compatible with the
2304 // right-hand side type. The caller is responsible for adjusting
2305 // lhsType so that the resulting expression does not have reference
2306 // type.
2307 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2308 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002309 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002310 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002311 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002312
Chris Lattnereca7be62008-04-07 05:30:13 +00002313 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2314 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002315 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002316 // Relax integer conversions like we do for pointers below.
2317 if (rhsType->isIntegerType())
2318 return IntToPointer;
2319 if (lhsType->isIntegerType())
2320 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002321 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002322 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002323
Nate Begemanbe2341d2008-07-14 18:02:46 +00002324 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002325 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002326 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2327 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002328 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002329
Nate Begemanbe2341d2008-07-14 18:02:46 +00002330 // If we are allowing lax vector conversions, and LHS and RHS are both
2331 // vectors, the total size only needs to be the same. This is a bitcast;
2332 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002333 if (getLangOptions().LaxVectorConversions &&
2334 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002335 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2336 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002337 }
2338 return Incompatible;
2339 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002340
Chris Lattnere8b3e962008-01-04 23:32:24 +00002341 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002342 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002343
Chris Lattner78eca282008-04-07 06:49:41 +00002344 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002345 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002346 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002347
Chris Lattner78eca282008-04-07 06:49:41 +00002348 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002349 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002350
Steve Naroffb4406862008-09-29 18:10:17 +00002351 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002352 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002353 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002354
2355 // Treat block pointers as objects.
2356 if (getLangOptions().ObjC1 &&
2357 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2358 return Compatible;
2359 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002360 return Incompatible;
2361 }
2362
2363 if (isa<BlockPointerType>(lhsType)) {
2364 if (rhsType->isIntegerType())
2365 return IntToPointer;
2366
Steve Naroffb4406862008-09-29 18:10:17 +00002367 // Treat block pointers as objects.
2368 if (getLangOptions().ObjC1 &&
2369 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2370 return Compatible;
2371
Steve Naroff1c7d0672008-09-04 15:10:53 +00002372 if (rhsType->isBlockPointerType())
2373 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2374
2375 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2376 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002377 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002378 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002379 return Incompatible;
2380 }
2381
Chris Lattner78eca282008-04-07 06:49:41 +00002382 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002383 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002384 if (lhsType == Context.BoolTy)
2385 return Compatible;
2386
2387 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002388 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002389
Chris Lattner78eca282008-04-07 06:49:41 +00002390 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002391 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002392
2393 if (isa<BlockPointerType>(lhsType) &&
2394 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002395 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002396 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002397 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002398
Chris Lattnerfc144e22008-01-04 23:18:45 +00002399 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002400 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002401 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002402 }
2403 return Incompatible;
2404}
2405
Chris Lattner5cf216b2008-01-04 18:04:52 +00002406Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002407Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002408 if (getLangOptions().CPlusPlus) {
2409 if (!lhsType->isRecordType()) {
2410 // C++ 5.17p3: If the left operand is not of class type, the
2411 // expression is implicitly converted (C++ 4) to the
2412 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002413 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2414 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002415 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002416 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002417 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002418 }
2419
2420 // FIXME: Currently, we fall through and treat C++ classes like C
2421 // structures.
2422 }
2423
Steve Naroff529a4ad2007-11-27 17:58:44 +00002424 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2425 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002426 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2427 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002428 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002429 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002430 return Compatible;
2431 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002432
2433 // We don't allow conversion of non-null-pointer constants to integers.
2434 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2435 return IntToBlockPointer;
2436
Chris Lattner943140e2007-10-16 02:55:40 +00002437 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002438 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002439 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002440 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002441 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002442 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002443 if (!lhsType->isReferenceType())
2444 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002445
Chris Lattner5cf216b2008-01-04 18:04:52 +00002446 Sema::AssignConvertType result =
2447 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002448
2449 // C99 6.5.16.1p2: The value of the right operand is converted to the
2450 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002451 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2452 // so that we can use references in built-in functions even in C.
2453 // The getNonReferenceType() call makes sure that the resulting expression
2454 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002455 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002456 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002457 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002458}
2459
Chris Lattner5cf216b2008-01-04 18:04:52 +00002460Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002461Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2462 return CheckAssignmentConstraints(lhsType, rhsType);
2463}
2464
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002465QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002466 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002467 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002468 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002469 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002470}
2471
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002472inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002473 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002474 // For conversion purposes, we ignore any qualifiers.
2475 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002476 QualType lhsType =
2477 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2478 QualType rhsType =
2479 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002480
Nate Begemanbe2341d2008-07-14 18:02:46 +00002481 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002482 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002483 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002484
Nate Begemanbe2341d2008-07-14 18:02:46 +00002485 // Handle the case of a vector & extvector type of the same size and element
2486 // type. It would be nice if we only had one vector type someday.
2487 if (getLangOptions().LaxVectorConversions)
2488 if (const VectorType *LV = lhsType->getAsVectorType())
2489 if (const VectorType *RV = rhsType->getAsVectorType())
2490 if (LV->getElementType() == RV->getElementType() &&
2491 LV->getNumElements() == RV->getNumElements())
2492 return lhsType->isExtVectorType() ? lhsType : rhsType;
2493
2494 // If the lhs is an extended vector and the rhs is a scalar of the same type
2495 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002496 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002497 QualType eltType = V->getElementType();
2498
2499 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2500 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2501 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002502 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002503 return lhsType;
2504 }
2505 }
2506
Nate Begemanbe2341d2008-07-14 18:02:46 +00002507 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002508 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002509 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002510 QualType eltType = V->getElementType();
2511
2512 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2513 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2514 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002515 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002516 return rhsType;
2517 }
2518 }
2519
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002521 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002522 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002523 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 return QualType();
2525}
2526
2527inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002528 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002529{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00002530 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002531 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002532
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002533 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002534
Steve Naroffa4332e22007-07-17 00:58:39 +00002535 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002536 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002537 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002538}
2539
2540inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002541 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002542{
Daniel Dunbar523aa602009-01-05 22:55:36 +00002543 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2544 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2545 return CheckVectorOperands(Loc, lex, rex);
2546 return InvalidOperands(Loc, lex, rex);
2547 }
Steve Naroff90045e82007-07-13 23:32:42 +00002548
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002549 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002550
Steve Naroffa4332e22007-07-17 00:58:39 +00002551 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002552 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002553 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002554}
2555
2556inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002557 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002558{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002559 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002560 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002561
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002562 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002563
Reid Spencer5f016e22007-07-11 17:01:13 +00002564 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002565 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002566 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002567
Eli Friedmand72d16e2008-05-18 18:08:51 +00002568 // Put any potential pointer into PExp
2569 Expr* PExp = lex, *IExp = rex;
2570 if (IExp->getType()->isPointerType())
2571 std::swap(PExp, IExp);
2572
2573 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2574 if (IExp->getType()->isIntegerType()) {
2575 // Check for arithmetic on pointers to incomplete types
2576 if (!PTy->getPointeeType()->isObjectType()) {
2577 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002578 Diag(Loc, diag::ext_gnu_void_ptr)
2579 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002580 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002581 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00002582 << lex->getType() << lex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002583 return QualType();
2584 }
2585 }
2586 return PExp->getType();
2587 }
2588 }
2589
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002590 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002591}
2592
Chris Lattnereca7be62008-04-07 05:30:13 +00002593// C99 6.5.6
2594QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002595 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002596 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002597 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002598
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002599 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002600
Chris Lattner6e4ab612007-12-09 21:53:25 +00002601 // Enforce type constraints: C99 6.5.6p3.
2602
2603 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002604 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002605 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002606
2607 // Either ptr - int or ptr - ptr.
2608 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002609 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002610
Chris Lattner6e4ab612007-12-09 21:53:25 +00002611 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002612 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002613 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002614 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002615 Diag(Loc, diag::ext_gnu_void_ptr)
2616 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002617 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002618 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002619 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002620 return QualType();
2621 }
2622 }
2623
2624 // The result type of a pointer-int computation is the pointer type.
2625 if (rex->getType()->isIntegerType())
2626 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002627
Chris Lattner6e4ab612007-12-09 21:53:25 +00002628 // Handle pointer-pointer subtractions.
2629 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002630 QualType rpointee = RHSPTy->getPointeeType();
2631
Chris Lattner6e4ab612007-12-09 21:53:25 +00002632 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002633 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002634 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002635 if (rpointee->isVoidType()) {
2636 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002637 Diag(Loc, diag::ext_gnu_void_ptr)
2638 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002639 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002640 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002641 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002642 return QualType();
2643 }
2644 }
2645
2646 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002647 if (!Context.typesAreCompatible(
2648 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2649 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002650 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002651 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002652 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002653 return QualType();
2654 }
2655
2656 return Context.getPointerDiffType();
2657 }
2658 }
2659
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002660 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002661}
2662
Chris Lattnereca7be62008-04-07 05:30:13 +00002663// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002664QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002665 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002666 // C99 6.5.7p2: Each of the operands shall have integer type.
2667 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002668 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002669
Chris Lattnerca5eede2007-12-12 05:47:28 +00002670 // Shifts don't perform usual arithmetic conversions, they just do integer
2671 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002672 if (!isCompAssign)
2673 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002674 UsualUnaryConversions(rex);
2675
2676 // "The type of the result is that of the promoted left operand."
2677 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002678}
2679
Eli Friedman3d815e72008-08-22 00:56:42 +00002680static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2681 ASTContext& Context) {
2682 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2683 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2684 // ID acts sort of like void* for ObjC interfaces
2685 if (LHSIface && Context.isObjCIdType(RHS))
2686 return true;
2687 if (RHSIface && Context.isObjCIdType(LHS))
2688 return true;
2689 if (!LHSIface || !RHSIface)
2690 return false;
2691 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2692 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2693}
2694
Chris Lattnereca7be62008-04-07 05:30:13 +00002695// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002696QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002697 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002698 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002699 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002700
Chris Lattnera5937dd2007-08-26 01:18:55 +00002701 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002702 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2703 UsualArithmeticConversions(lex, rex);
2704 else {
2705 UsualUnaryConversions(lex);
2706 UsualUnaryConversions(rex);
2707 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002708 QualType lType = lex->getType();
2709 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002710
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002711 // For non-floating point types, check for self-comparisons of the form
2712 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2713 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002714 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002715 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2716 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002717 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002718 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002719 }
2720
Douglas Gregor447b69e2008-11-19 03:25:36 +00002721 // The result of comparisons is 'bool' in C++, 'int' in C.
2722 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2723
Chris Lattnera5937dd2007-08-26 01:18:55 +00002724 if (isRelational) {
2725 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002726 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002727 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002728 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002729 if (lType->isFloatingType()) {
2730 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002731 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002732 }
2733
Chris Lattnera5937dd2007-08-26 01:18:55 +00002734 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002735 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002736 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002737
Chris Lattnerd28f8152007-08-26 01:10:14 +00002738 bool LHSIsNull = lex->isNullPointerConstant(Context);
2739 bool RHSIsNull = rex->isNullPointerConstant(Context);
2740
Chris Lattnera5937dd2007-08-26 01:18:55 +00002741 // All of the following pointer related warnings are GCC extensions, except
2742 // when handling null pointer constants. One day, we can consider making them
2743 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002744 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002745 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002746 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002747 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002748 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002749
Steve Naroff66296cb2007-11-13 14:57:38 +00002750 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002751 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2752 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002753 RCanPointeeTy.getUnqualifiedType()) &&
2754 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002755 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002756 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002758 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002759 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002760 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002761 // Handle block pointer types.
2762 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2763 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2764 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2765
2766 if (!LHSIsNull && !RHSIsNull &&
2767 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002768 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002769 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002770 }
2771 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002772 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002773 }
Steve Naroff59f53942008-09-28 01:11:11 +00002774 // Allow block pointers to be compared with null pointer constants.
2775 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2776 (lType->isPointerType() && rType->isBlockPointerType())) {
2777 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002778 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002779 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002780 }
2781 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002782 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002783 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002784
Steve Naroff20373222008-06-03 14:04:54 +00002785 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002786 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002787 const PointerType *LPT = lType->getAsPointerType();
2788 const PointerType *RPT = rType->getAsPointerType();
2789 bool LPtrToVoid = LPT ?
2790 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2791 bool RPtrToVoid = RPT ?
2792 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2793
2794 if (!LPtrToVoid && !RPtrToVoid &&
2795 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002796 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002797 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00002798 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002799 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00002800 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002801 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002802 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002803 }
Steve Naroff20373222008-06-03 14:04:54 +00002804 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2805 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002806 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002807 } else {
2808 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002809 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002810 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002811 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002812 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002813 }
Steve Naroff20373222008-06-03 14:04:54 +00002814 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002815 }
Steve Naroff20373222008-06-03 14:04:54 +00002816 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2817 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002818 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002819 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002820 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002821 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002822 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002823 }
Steve Naroff20373222008-06-03 14:04:54 +00002824 if (lType->isIntegerType() &&
2825 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002826 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002827 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002828 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002829 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002830 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002831 }
Steve Naroff39218df2008-09-04 16:56:14 +00002832 // Handle block pointers.
2833 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2834 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002835 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002836 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002837 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002838 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002839 }
2840 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2841 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002842 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002843 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002844 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002845 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002846 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002847 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002848}
2849
Nate Begemanbe2341d2008-07-14 18:02:46 +00002850/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2851/// operates on extended vector types. Instead of producing an IntTy result,
2852/// like a scalar comparison, a vector comparison produces a vector of integer
2853/// types.
2854QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002855 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00002856 bool isRelational) {
2857 // Check to make sure we're operating on vectors of the same type and width,
2858 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002859 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002860 if (vType.isNull())
2861 return vType;
2862
2863 QualType lType = lex->getType();
2864 QualType rType = rex->getType();
2865
2866 // For non-floating point types, check for self-comparisons of the form
2867 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2868 // often indicate logic errors in the program.
2869 if (!lType->isFloatingType()) {
2870 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2871 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2872 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002873 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002874 }
2875
2876 // Check for comparisons of floating point operands using != and ==.
2877 if (!isRelational && lType->isFloatingType()) {
2878 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002879 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002880 }
2881
2882 // Return the type for the comparison, which is the same as vector type for
2883 // integer vectors, or an integer type of identical size and number of
2884 // elements for floating point vectors.
2885 if (lType->isIntegerType())
2886 return lType;
2887
2888 const VectorType *VTy = lType->getAsVectorType();
2889
2890 // FIXME: need to deal with non-32b int / non-64b long long
2891 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2892 if (TypeSize == 32) {
2893 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2894 }
2895 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2896 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2897}
2898
Reid Spencer5f016e22007-07-11 17:01:13 +00002899inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002900 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002901{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002902 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002903 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002904
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002905 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002906
Steve Naroffa4332e22007-07-17 00:58:39 +00002907 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002908 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002909 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002910}
2911
2912inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002913 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002914{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002915 UsualUnaryConversions(lex);
2916 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002917
Eli Friedman5773a6c2008-05-13 20:16:47 +00002918 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002920 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002921}
2922
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00002923/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
2924/// is a read-only property; return true if so. A readonly property expression
2925/// depends on various declarations and thus must be treated specially.
2926///
2927static bool IsReadonlyProperty(Expr *E, Sema &S)
2928{
2929 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
2930 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
2931 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
2932 QualType BaseType = PropExpr->getBase()->getType();
2933 if (const PointerType *PTy = BaseType->getAsPointerType())
2934 if (const ObjCInterfaceType *IFTy =
2935 PTy->getPointeeType()->getAsObjCInterfaceType())
2936 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
2937 if (S.isPropertyReadonly(PDecl, IFace))
2938 return true;
2939 }
2940 }
2941 return false;
2942}
2943
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002944/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2945/// emit an error and return true. If so, return false.
2946static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00002947 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2948 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
2949 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002950 if (IsLV == Expr::MLV_Valid)
2951 return false;
2952
2953 unsigned Diag = 0;
2954 bool NeedType = false;
2955 switch (IsLV) { // C99 6.5.16p2
2956 default: assert(0 && "Unknown result from isModifiableLvalue!");
2957 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002958 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002959 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2960 NeedType = true;
2961 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002962 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002963 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2964 NeedType = true;
2965 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00002966 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002967 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2968 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002969 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002970 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2971 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002972 case Expr::MLV_IncompleteType:
2973 case Expr::MLV_IncompleteVoidType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002974 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2975 NeedType = true;
2976 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002977 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002978 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2979 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002980 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002981 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2982 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00002983 case Expr::MLV_ReadonlyProperty:
2984 Diag = diag::error_readonly_property_assignment;
2985 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00002986 case Expr::MLV_NoSetterProperty:
2987 Diag = diag::error_nosetter_property_assignment;
2988 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002989 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002990
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002991 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00002992 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002993 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002994 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002995 return true;
2996}
2997
2998
2999
3000// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003001QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3002 SourceLocation Loc,
3003 QualType CompoundType) {
3004 // Verify that LHS is a modifiable lvalue, and emit error if not.
3005 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003006 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003007
3008 QualType LHSType = LHS->getType();
3009 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00003010
Chris Lattner5cf216b2008-01-04 18:04:52 +00003011 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003012 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00003013 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003014 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner2c156472008-08-21 18:04:13 +00003015
3016 // If the RHS is a unary plus or minus, check to see if they = and + are
3017 // right next to each other. If so, the user may have typo'd "x =+ 4"
3018 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003019 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003020 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3021 RHSCheck = ICE->getSubExpr();
3022 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3023 if ((UO->getOpcode() == UnaryOperator::Plus ||
3024 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003025 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003026 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003027 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003028 Diag(Loc, diag::warn_not_compound_assign)
3029 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3030 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00003031 }
3032 } else {
3033 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003034 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003035 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003036
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003037 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3038 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003039 return QualType();
3040
Reid Spencer5f016e22007-07-11 17:01:13 +00003041 // C99 6.5.16p3: The type of an assignment expression is the type of the
3042 // left operand unless the left operand has qualified type, in which case
3043 // it is the unqualified version of the type of the left operand.
3044 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3045 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003046 // C++ 5.17p1: the type of the assignment expression is that of its left
3047 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003048 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003049}
3050
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003051// C99 6.5.17
3052QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3053 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00003054
3055 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003056 DefaultFunctionArrayConversion(RHS);
3057 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003058}
3059
Steve Naroff49b45262007-07-13 16:58:59 +00003060/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3061/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003062QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3063 bool isInc) {
Chris Lattner3528d352008-11-21 07:05:48 +00003064 QualType ResType = Op->getType();
3065 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003066
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003067 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3068 // Decrement of bool is not allowed.
3069 if (!isInc) {
3070 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3071 return QualType();
3072 }
3073 // Increment of bool sets it to true, but is deprecated.
3074 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3075 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003076 // OK!
3077 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3078 // C99 6.5.2.4p2, 6.5.6p2
3079 if (PT->getPointeeType()->isObjectType()) {
3080 // Pointer to object is ok!
3081 } else if (PT->getPointeeType()->isVoidType()) {
3082 // Pointer to void is extension.
3083 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3084 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003085 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00003086 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003087 return QualType();
3088 }
Chris Lattner3528d352008-11-21 07:05:48 +00003089 } else if (ResType->isComplexType()) {
3090 // C99 does not support ++/-- on complex types, we allow as an extension.
3091 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003092 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003093 } else {
3094 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003095 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003096 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003097 }
Steve Naroffdd10e022007-08-23 21:37:33 +00003098 // At this point, we know we have a real, complex or pointer type.
3099 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003100 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003101 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003102 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003103}
3104
Anders Carlsson369dee42008-02-01 07:15:58 +00003105/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003106/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003107/// where the declaration is needed for type checking. We only need to
3108/// handle cases when the expression references a function designator
3109/// or is an lvalue. Here are some examples:
3110/// - &(x) => x
3111/// - &*****f => f for f a function designator.
3112/// - &s.xx => s
3113/// - &s.zz[1].yy -> s, if zz is an array
3114/// - *(x + 1) -> x, if x is an array
3115/// - &"123"[2] -> 0
3116/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003117static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003118 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003119 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003120 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003121 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003122 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003123 // Fields cannot be declared with a 'register' storage class.
3124 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003125 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003126 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003127 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003128 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003129 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00003130
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003131 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003132 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003133 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003134 return 0;
3135 else
3136 return VD;
3137 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003138 case Stmt::UnaryOperatorClass: {
3139 UnaryOperator *UO = cast<UnaryOperator>(E);
3140
3141 switch(UO->getOpcode()) {
3142 case UnaryOperator::Deref: {
3143 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003144 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3145 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3146 if (!VD || VD->getType()->isPointerType())
3147 return 0;
3148 return VD;
3149 }
3150 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003151 }
3152 case UnaryOperator::Real:
3153 case UnaryOperator::Imag:
3154 case UnaryOperator::Extension:
3155 return getPrimaryDecl(UO->getSubExpr());
3156 default:
3157 return 0;
3158 }
3159 }
3160 case Stmt::BinaryOperatorClass: {
3161 BinaryOperator *BO = cast<BinaryOperator>(E);
3162
3163 // Handle cases involving pointer arithmetic. The result of an
3164 // Assign or AddAssign is not an lvalue so they can be ignored.
3165
3166 // (x + n) or (n + x) => x
3167 if (BO->getOpcode() == BinaryOperator::Add) {
3168 if (BO->getLHS()->getType()->isPointerType()) {
3169 return getPrimaryDecl(BO->getLHS());
3170 } else if (BO->getRHS()->getType()->isPointerType()) {
3171 return getPrimaryDecl(BO->getRHS());
3172 }
3173 }
3174
3175 return 0;
3176 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003177 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003178 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003179 case Stmt::ImplicitCastExprClass:
3180 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003181 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003182 default:
3183 return 0;
3184 }
3185}
3186
3187/// CheckAddressOfOperand - The operand of & must be either a function
3188/// designator or an lvalue designating an object. If it is an lvalue, the
3189/// object cannot be declared with storage class register or be a bit field.
3190/// Note: The usual conversions are *not* applied to the operand of the &
3191/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00003192/// In C++, the operand might be an overloaded function name, in which case
3193/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003194QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003195 if (op->isTypeDependent())
3196 return Context.DependentTy;
3197
Steve Naroff08f19672008-01-13 17:10:08 +00003198 if (getLangOptions().C99) {
3199 // Implement C99-only parts of addressof rules.
3200 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3201 if (uOp->getOpcode() == UnaryOperator::Deref)
3202 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3203 // (assuming the deref expression is valid).
3204 return uOp->getSubExpr()->getType();
3205 }
3206 // Technically, there should be a check for array subscript
3207 // expressions here, but the result of one is always an lvalue anyway.
3208 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003209 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003210 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003211
Reid Spencer5f016e22007-07-11 17:01:13 +00003212 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003213 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3214 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003215 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3216 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003217 return QualType();
3218 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003219 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003220 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3221 if (Field->isBitField()) {
3222 Diag(OpLoc, diag::err_typecheck_address_of)
3223 << "bit-field" << op->getSourceRange();
3224 return QualType();
3225 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003226 }
3227 // Check for Apple extension for accessing vector components.
3228 } else if (isa<ArraySubscriptExpr>(op) &&
3229 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003230 Diag(OpLoc, diag::err_typecheck_address_of)
3231 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003232 return QualType();
3233 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00003234 // We have an lvalue with a decl. Make sure the decl is not declared
3235 // with the register storage-class specifier.
3236 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3237 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003238 Diag(OpLoc, diag::err_typecheck_address_of)
3239 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003240 return QualType();
3241 }
Douglas Gregor29882052008-12-10 21:26:49 +00003242 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003243 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003244 } else if (isa<FieldDecl>(dcl)) {
3245 // Okay: we can take the address of a field.
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003246 } else if (isa<FunctionDecl>(dcl)) {
3247 // Okay: we can take the address of a function.
Douglas Gregor29882052008-12-10 21:26:49 +00003248 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003249 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003250 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003251 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00003252
Reid Spencer5f016e22007-07-11 17:01:13 +00003253 // If the operand has type "type", the result has type "pointer to type".
3254 return Context.getPointerType(op->getType());
3255}
3256
Chris Lattner22caddc2008-11-23 09:13:29 +00003257QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3258 UsualUnaryConversions(Op);
3259 QualType Ty = Op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003260
Chris Lattner22caddc2008-11-23 09:13:29 +00003261 // Note that per both C89 and C99, this is always legal, even if ptype is an
3262 // incomplete type or void. It would be possible to warn about dereferencing
3263 // a void pointer, but it's completely well-defined, and such a warning is
3264 // unlikely to catch any mistakes.
3265 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003266 return PT->getPointeeType();
Chris Lattner22caddc2008-11-23 09:13:29 +00003267
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003268 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003269 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003270 return QualType();
3271}
3272
3273static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3274 tok::TokenKind Kind) {
3275 BinaryOperator::Opcode Opc;
3276 switch (Kind) {
3277 default: assert(0 && "Unknown binop!");
3278 case tok::star: Opc = BinaryOperator::Mul; break;
3279 case tok::slash: Opc = BinaryOperator::Div; break;
3280 case tok::percent: Opc = BinaryOperator::Rem; break;
3281 case tok::plus: Opc = BinaryOperator::Add; break;
3282 case tok::minus: Opc = BinaryOperator::Sub; break;
3283 case tok::lessless: Opc = BinaryOperator::Shl; break;
3284 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3285 case tok::lessequal: Opc = BinaryOperator::LE; break;
3286 case tok::less: Opc = BinaryOperator::LT; break;
3287 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3288 case tok::greater: Opc = BinaryOperator::GT; break;
3289 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3290 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3291 case tok::amp: Opc = BinaryOperator::And; break;
3292 case tok::caret: Opc = BinaryOperator::Xor; break;
3293 case tok::pipe: Opc = BinaryOperator::Or; break;
3294 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3295 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3296 case tok::equal: Opc = BinaryOperator::Assign; break;
3297 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3298 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3299 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3300 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3301 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3302 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3303 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3304 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3305 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3306 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3307 case tok::comma: Opc = BinaryOperator::Comma; break;
3308 }
3309 return Opc;
3310}
3311
3312static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3313 tok::TokenKind Kind) {
3314 UnaryOperator::Opcode Opc;
3315 switch (Kind) {
3316 default: assert(0 && "Unknown unary op!");
3317 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3318 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3319 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3320 case tok::star: Opc = UnaryOperator::Deref; break;
3321 case tok::plus: Opc = UnaryOperator::Plus; break;
3322 case tok::minus: Opc = UnaryOperator::Minus; break;
3323 case tok::tilde: Opc = UnaryOperator::Not; break;
3324 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003325 case tok::kw___real: Opc = UnaryOperator::Real; break;
3326 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3327 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3328 }
3329 return Opc;
3330}
3331
Douglas Gregoreaebc752008-11-06 23:29:22 +00003332/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3333/// operator @p Opc at location @c TokLoc. This routine only supports
3334/// built-in operations; ActOnBinOp handles overloaded operators.
3335Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3336 unsigned Op,
3337 Expr *lhs, Expr *rhs) {
3338 QualType ResultTy; // Result type of the binary operator.
3339 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3340 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3341
3342 switch (Opc) {
3343 default:
3344 assert(0 && "Unknown binary expr!");
3345 case BinaryOperator::Assign:
3346 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3347 break;
3348 case BinaryOperator::Mul:
3349 case BinaryOperator::Div:
3350 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3351 break;
3352 case BinaryOperator::Rem:
3353 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3354 break;
3355 case BinaryOperator::Add:
3356 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3357 break;
3358 case BinaryOperator::Sub:
3359 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3360 break;
3361 case BinaryOperator::Shl:
3362 case BinaryOperator::Shr:
3363 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3364 break;
3365 case BinaryOperator::LE:
3366 case BinaryOperator::LT:
3367 case BinaryOperator::GE:
3368 case BinaryOperator::GT:
3369 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3370 break;
3371 case BinaryOperator::EQ:
3372 case BinaryOperator::NE:
3373 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3374 break;
3375 case BinaryOperator::And:
3376 case BinaryOperator::Xor:
3377 case BinaryOperator::Or:
3378 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3379 break;
3380 case BinaryOperator::LAnd:
3381 case BinaryOperator::LOr:
3382 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3383 break;
3384 case BinaryOperator::MulAssign:
3385 case BinaryOperator::DivAssign:
3386 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3387 if (!CompTy.isNull())
3388 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3389 break;
3390 case BinaryOperator::RemAssign:
3391 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3392 if (!CompTy.isNull())
3393 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3394 break;
3395 case BinaryOperator::AddAssign:
3396 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3397 if (!CompTy.isNull())
3398 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3399 break;
3400 case BinaryOperator::SubAssign:
3401 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3402 if (!CompTy.isNull())
3403 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3404 break;
3405 case BinaryOperator::ShlAssign:
3406 case BinaryOperator::ShrAssign:
3407 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3408 if (!CompTy.isNull())
3409 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3410 break;
3411 case BinaryOperator::AndAssign:
3412 case BinaryOperator::XorAssign:
3413 case BinaryOperator::OrAssign:
3414 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3415 if (!CompTy.isNull())
3416 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3417 break;
3418 case BinaryOperator::Comma:
3419 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3420 break;
3421 }
3422 if (ResultTy.isNull())
3423 return true;
3424 if (CompTy.isNull())
3425 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3426 else
3427 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3428}
3429
Reid Spencer5f016e22007-07-11 17:01:13 +00003430// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003431Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3432 tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00003433 ExprTy *LHS, ExprTy *RHS) {
3434 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3435 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3436
Steve Narofff69936d2007-09-16 03:34:24 +00003437 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3438 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003439
Douglas Gregor898574e2008-12-05 23:32:09 +00003440 // If either expression is type-dependent, just build the AST.
3441 // FIXME: We'll need to perform some caching of the result of name
3442 // lookup for operator+.
3443 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3444 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3445 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3446 Context.DependentTy, TokLoc);
3447 else
3448 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3449 }
3450
Douglas Gregoreaebc752008-11-06 23:29:22 +00003451 if (getLangOptions().CPlusPlus &&
3452 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3453 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003454 // If this is one of the assignment operators, we only perform
3455 // overload resolution if the left-hand side is a class or
3456 // enumeration type (C++ [expr.ass]p3).
3457 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3458 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3459 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3460 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003461
3462 // Determine which overloaded operator we're dealing with.
3463 static const OverloadedOperatorKind OverOps[] = {
3464 OO_Star, OO_Slash, OO_Percent,
3465 OO_Plus, OO_Minus,
3466 OO_LessLess, OO_GreaterGreater,
3467 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3468 OO_EqualEqual, OO_ExclaimEqual,
3469 OO_Amp,
3470 OO_Caret,
3471 OO_Pipe,
3472 OO_AmpAmp,
3473 OO_PipePipe,
3474 OO_Equal, OO_StarEqual,
3475 OO_SlashEqual, OO_PercentEqual,
3476 OO_PlusEqual, OO_MinusEqual,
3477 OO_LessLessEqual, OO_GreaterGreaterEqual,
3478 OO_AmpEqual, OO_CaretEqual,
3479 OO_PipeEqual,
3480 OO_Comma
3481 };
3482 OverloadedOperatorKind OverOp = OverOps[Opc];
3483
Douglas Gregor96176b32008-11-18 23:14:02 +00003484 // Add the appropriate overloaded operators (C++ [over.match.oper])
3485 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003486 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003487 Expr *Args[2] = { lhs, rhs };
Douglas Gregor96176b32008-11-18 23:14:02 +00003488 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregoreaebc752008-11-06 23:29:22 +00003489
3490 // Perform overload resolution.
3491 OverloadCandidateSet::iterator Best;
3492 switch (BestViableFunction(CandidateSet, Best)) {
3493 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003494 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003495 FunctionDecl *FnDecl = Best->Function;
3496
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003497 if (FnDecl) {
3498 // We matched an overloaded operator. Build a call to that
3499 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003500
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003501 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003502 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3503 if (PerformObjectArgumentInitialization(lhs, Method) ||
3504 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3505 "passing"))
3506 return true;
3507 } else {
3508 // Convert the arguments.
3509 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3510 "passing") ||
3511 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3512 "passing"))
3513 return true;
3514 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003515
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003516 // Determine the result type
3517 QualType ResultTy
3518 = FnDecl->getType()->getAsFunctionType()->getResultType();
3519 ResultTy = ResultTy.getNonReferenceType();
3520
3521 // Build the actual expression node.
Douglas Gregorb4609802008-11-14 16:09:21 +00003522 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3523 SourceLocation());
3524 UsualUnaryConversions(FnExpr);
3525
Douglas Gregorb4609802008-11-14 16:09:21 +00003526 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003527 } else {
3528 // We matched a built-in operator. Convert the arguments, then
3529 // break out so that we will build the appropriate built-in
3530 // operator node.
3531 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3532 "passing") ||
3533 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3534 "passing"))
3535 return true;
3536
3537 break;
3538 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003539 }
3540
3541 case OR_No_Viable_Function:
3542 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003543 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003544 break;
3545
3546 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003547 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3548 << BinaryOperator::getOpcodeStr(Opc)
3549 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003550 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3551 return true;
3552 }
3553
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003554 // Either we found no viable overloaded operator or we matched a
3555 // built-in operator. In either case, fall through to trying to
3556 // build a built-in operation.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003557 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003558
Douglas Gregoreaebc752008-11-06 23:29:22 +00003559 // Build a built-in binary operation.
3560 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003561}
3562
3563// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor74253732008-11-19 15:42:04 +00003564Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3565 tok::TokenKind Op, ExprTy *input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003566 Expr *Input = (Expr*)input;
3567 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003568
3569 if (getLangOptions().CPlusPlus &&
3570 (Input->getType()->isRecordType()
3571 || Input->getType()->isEnumeralType())) {
3572 // Determine which overloaded operator we're dealing with.
3573 static const OverloadedOperatorKind OverOps[] = {
3574 OO_None, OO_None,
3575 OO_PlusPlus, OO_MinusMinus,
3576 OO_Amp, OO_Star,
3577 OO_Plus, OO_Minus,
3578 OO_Tilde, OO_Exclaim,
3579 OO_None, OO_None,
3580 OO_None,
3581 OO_None
3582 };
3583 OverloadedOperatorKind OverOp = OverOps[Opc];
3584
3585 // Add the appropriate overloaded operators (C++ [over.match.oper])
3586 // to the candidate set.
3587 OverloadCandidateSet CandidateSet;
3588 if (OverOp != OO_None)
3589 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3590
3591 // Perform overload resolution.
3592 OverloadCandidateSet::iterator Best;
3593 switch (BestViableFunction(CandidateSet, Best)) {
3594 case OR_Success: {
3595 // We found a built-in operator or an overloaded operator.
3596 FunctionDecl *FnDecl = Best->Function;
3597
3598 if (FnDecl) {
3599 // We matched an overloaded operator. Build a call to that
3600 // operator.
3601
3602 // Convert the arguments.
3603 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3604 if (PerformObjectArgumentInitialization(Input, Method))
3605 return true;
3606 } else {
3607 // Convert the arguments.
3608 if (PerformCopyInitialization(Input,
3609 FnDecl->getParamDecl(0)->getType(),
3610 "passing"))
3611 return true;
3612 }
3613
3614 // Determine the result type
3615 QualType ResultTy
3616 = FnDecl->getType()->getAsFunctionType()->getResultType();
3617 ResultTy = ResultTy.getNonReferenceType();
3618
3619 // Build the actual expression node.
3620 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3621 SourceLocation());
3622 UsualUnaryConversions(FnExpr);
3623
3624 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3625 } else {
3626 // We matched a built-in operator. Convert the arguments, then
3627 // break out so that we will build the appropriate built-in
3628 // operator node.
3629 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3630 "passing"))
3631 return true;
3632
3633 break;
3634 }
3635 }
3636
3637 case OR_No_Viable_Function:
3638 // No viable function; fall through to handling this as a
3639 // built-in operator, which will produce an error message for us.
3640 break;
3641
3642 case OR_Ambiguous:
3643 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3644 << UnaryOperator::getOpcodeStr(Opc)
3645 << Input->getSourceRange();
3646 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3647 return true;
3648 }
3649
3650 // Either we found no viable overloaded operator or we matched a
3651 // built-in operator. In either case, fall through to trying to
3652 // build a built-in operation.
3653 }
3654
Reid Spencer5f016e22007-07-11 17:01:13 +00003655 QualType resultType;
3656 switch (Opc) {
3657 default:
3658 assert(0 && "Unimplemented unary expr!");
3659 case UnaryOperator::PreInc:
3660 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003661 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3662 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003663 break;
3664 case UnaryOperator::AddrOf:
3665 resultType = CheckAddressOfOperand(Input, OpLoc);
3666 break;
3667 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003668 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003669 resultType = CheckIndirectionOperand(Input, OpLoc);
3670 break;
3671 case UnaryOperator::Plus:
3672 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003673 UsualUnaryConversions(Input);
3674 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003675 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3676 break;
3677 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3678 resultType->isEnumeralType())
3679 break;
3680 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3681 Opc == UnaryOperator::Plus &&
3682 resultType->isPointerType())
3683 break;
3684
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003685 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003686 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003687 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003688 UsualUnaryConversions(Input);
3689 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003690 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3691 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3692 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003693 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003694 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003695 else if (!resultType->isIntegerType())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003696 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003697 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003698 break;
3699 case UnaryOperator::LNot: // logical negation
3700 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003701 DefaultFunctionArrayConversion(Input);
3702 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003703 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003704 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003705 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003706 // LNot always has type int. C99 6.5.3.3p5.
3707 resultType = Context.IntTy;
3708 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003709 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003710 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003711 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003712 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003713 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003714 resultType = Input->getType();
3715 break;
3716 }
3717 if (resultType.isNull())
3718 return true;
3719 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3720}
3721
Steve Naroff1b273c42007-09-16 14:56:35 +00003722/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3723Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003724 SourceLocation LabLoc,
3725 IdentifierInfo *LabelII) {
3726 // Look up the record for this label identifier.
3727 LabelStmt *&LabelDecl = LabelMap[LabelII];
3728
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003729 // If we haven't seen this label yet, create a forward reference. It
3730 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003731 if (LabelDecl == 0)
3732 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3733
3734 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00003735 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3736 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00003737}
3738
Steve Naroff1b273c42007-09-16 14:56:35 +00003739Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003740 SourceLocation RPLoc) { // "({..})"
3741 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3742 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3743 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3744
3745 // FIXME: there are a variety of strange constraints to enforce here, for
3746 // example, it is not possible to goto into a stmt expression apparently.
3747 // More semantic analysis is needed.
3748
3749 // FIXME: the last statement in the compount stmt has its value used. We
3750 // should not warn about it being unused.
3751
3752 // If there are sub stmts in the compound stmt, take the type of the last one
3753 // as the type of the stmtexpr.
3754 QualType Ty = Context.VoidTy;
3755
Chris Lattner611b2ec2008-07-26 19:51:01 +00003756 if (!Compound->body_empty()) {
3757 Stmt *LastStmt = Compound->body_back();
3758 // If LastStmt is a label, skip down through into the body.
3759 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3760 LastStmt = Label->getSubStmt();
3761
3762 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003763 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00003764 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003765
3766 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3767}
Steve Naroffd34e9152007-08-01 22:05:33 +00003768
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003769Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3770 SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003771 SourceLocation TypeLoc,
3772 TypeTy *argty,
3773 OffsetOfComponent *CompPtr,
3774 unsigned NumComponents,
3775 SourceLocation RPLoc) {
3776 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3777 assert(!ArgTy.isNull() && "Missing type argument!");
3778
3779 // We must have at least one component that refers to the type, and the first
3780 // one is known to be a field designator. Verify that the ArgTy represents
3781 // a struct/union/class.
3782 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00003783 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003784
3785 // Otherwise, create a compound literal expression as the base, and
3786 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00003787 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003788
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003789 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3790 // GCC extension, diagnose them.
3791 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003792 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3793 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003794
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003795 for (unsigned i = 0; i != NumComponents; ++i) {
3796 const OffsetOfComponent &OC = CompPtr[i];
3797 if (OC.isBrackets) {
3798 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003799 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003800 if (!AT) {
3801 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003802 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003803 }
3804
Chris Lattner704fe352007-08-30 17:59:59 +00003805 // FIXME: C++: Verify that operator[] isn't overloaded.
3806
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003807 // C99 6.5.2.1p1
3808 Expr *Idx = static_cast<Expr*>(OC.U.E);
3809 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003810 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3811 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003812
3813 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3814 continue;
3815 }
3816
3817 const RecordType *RC = Res->getType()->getAsRecordType();
3818 if (!RC) {
3819 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003820 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003821 }
3822
3823 // Get the decl corresponding to this.
3824 RecordDecl *RD = RC->getDecl();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003825 FieldDecl *MemberDecl
3826 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3827 Decl::IDNS_Ordinary,
3828 S, RD, false, false));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003829 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00003830 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3831 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00003832
3833 // FIXME: C++: Verify that MemberDecl isn't a static field.
3834 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00003835 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3836 // matter here.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003837 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3838 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003839 }
3840
3841 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3842 BuiltinLoc);
3843}
3844
3845
Steve Naroff1b273c42007-09-16 14:56:35 +00003846Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00003847 TypeTy *arg1, TypeTy *arg2,
3848 SourceLocation RPLoc) {
3849 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3850 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3851
3852 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3853
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003854 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00003855}
3856
Steve Naroff1b273c42007-09-16 14:56:35 +00003857Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00003858 ExprTy *expr1, ExprTy *expr2,
3859 SourceLocation RPLoc) {
3860 Expr *CondExpr = static_cast<Expr*>(cond);
3861 Expr *LHSExpr = static_cast<Expr*>(expr1);
3862 Expr *RHSExpr = static_cast<Expr*>(expr2);
3863
3864 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3865
3866 // The conditional expression is required to be a constant expression.
3867 llvm::APSInt condEval(32);
3868 SourceLocation ExpLoc;
3869 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003870 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3871 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00003872
3873 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3874 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3875 RHSExpr->getType();
3876 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3877}
3878
Steve Naroff4eb206b2008-09-03 18:15:37 +00003879//===----------------------------------------------------------------------===//
3880// Clang Extensions.
3881//===----------------------------------------------------------------------===//
3882
3883/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00003884void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003885 // Analyze block parameters.
3886 BlockSemaInfo *BSI = new BlockSemaInfo();
3887
3888 // Add BSI to CurBlock.
3889 BSI->PrevBlockInfo = CurBlock;
3890 CurBlock = BSI;
3891
3892 BSI->ReturnType = 0;
3893 BSI->TheScope = BlockScope;
3894
Steve Naroff090276f2008-10-10 01:28:17 +00003895 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00003896 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00003897}
3898
3899void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003900 // Analyze arguments to block.
3901 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3902 "Not a function declarator!");
3903 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3904
Steve Naroff090276f2008-10-10 01:28:17 +00003905 CurBlock->hasPrototype = FTI.hasPrototype;
3906 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003907
3908 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3909 // no arguments, not a function that takes a single void argument.
3910 if (FTI.hasPrototype &&
3911 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3912 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3913 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3914 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00003915 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003916 } else if (FTI.hasPrototype) {
3917 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00003918 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3919 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003920 }
Steve Naroff090276f2008-10-10 01:28:17 +00003921 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3922
3923 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3924 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3925 // If this has an identifier, add it to the scope stack.
3926 if ((*AI)->getIdentifier())
3927 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003928}
3929
3930/// ActOnBlockError - If there is an error parsing a block, this callback
3931/// is invoked to pop the information about the block from the action impl.
3932void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3933 // Ensure that CurBlock is deleted.
3934 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3935
3936 // Pop off CurBlock, handle nested blocks.
3937 CurBlock = CurBlock->PrevBlockInfo;
3938
3939 // FIXME: Delete the ParmVarDecl objects as well???
3940
3941}
3942
3943/// ActOnBlockStmtExpr - This is called when the body of a block statement
3944/// literal was successfully completed. ^(int x){...}
3945Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3946 Scope *CurScope) {
3947 // Ensure that CurBlock is deleted.
3948 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3949 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3950
Steve Naroff090276f2008-10-10 01:28:17 +00003951 PopDeclContext();
3952
Steve Naroff4eb206b2008-09-03 18:15:37 +00003953 // Pop off CurBlock, handle nested blocks.
3954 CurBlock = CurBlock->PrevBlockInfo;
3955
3956 QualType RetTy = Context.VoidTy;
3957 if (BSI->ReturnType)
3958 RetTy = QualType(BSI->ReturnType, 0);
3959
3960 llvm::SmallVector<QualType, 8> ArgTypes;
3961 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3962 ArgTypes.push_back(BSI->Params[i]->getType());
3963
3964 QualType BlockTy;
3965 if (!BSI->hasPrototype)
3966 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3967 else
3968 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003969 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003970
3971 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003972
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003973 BSI->TheDecl->setBody(Body.take());
3974 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003975}
3976
Nate Begeman67295d02008-01-30 20:50:20 +00003977/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003978/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003979/// The number of arguments has already been validated to match the number of
3980/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003981static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3982 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003983 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003984 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003985 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3986 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003987
3988 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003989 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003990 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003991 return true;
3992}
3993
3994Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3995 SourceLocation *CommaLocs,
3996 SourceLocation BuiltinLoc,
3997 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003998 // __builtin_overload requires at least 2 arguments
3999 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004000 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4001 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004002
Nate Begemane2ce1d92008-01-17 17:46:27 +00004003 // The first argument is required to be a constant expression. It tells us
4004 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004005 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004006 Expr *NParamsExpr = Args[0];
4007 llvm::APSInt constEval(32);
4008 SourceLocation ExpLoc;
4009 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004010 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4011 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004012
4013 // Verify that the number of parameters is > 0
4014 unsigned NumParams = constEval.getZExtValue();
4015 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004016 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4017 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004018 // Verify that we have at least 1 + NumParams arguments to the builtin.
4019 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004020 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4021 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004022
4023 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00004024 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004025 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004026 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4027 // UsualUnaryConversions will convert the function DeclRefExpr into a
4028 // pointer to function.
4029 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00004030 const FunctionTypeProto *FnType = 0;
4031 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4032 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004033
4034 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4035 // parameters, and the number of parameters must match the value passed to
4036 // the builtin.
4037 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004038 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4039 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004040
4041 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00004042 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00004043 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004044 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004045 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004046 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4047 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00004048 // Remember our match, and continue processing the remaining arguments
4049 // to catch any errors.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004050 OE = new OverloadExpr(Args, NumArgs, i,
4051 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00004052 BuiltinLoc, RParenLoc);
4053 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004054 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00004055 // Return the newly created OverloadExpr node, if we succeded in matching
4056 // exactly one of the candidate functions.
4057 if (OE)
4058 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004059
4060 // If we didn't find a matching function Expr in the __builtin_overload list
4061 // the return an error.
4062 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00004063 for (unsigned i = 0; i != NumParams; ++i) {
4064 if (i != 0) typeNames += ", ";
4065 typeNames += Args[i+1]->getType().getAsString();
4066 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004067
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004068 return Diag(BuiltinLoc, diag::err_overload_no_match)
4069 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004070}
4071
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004072Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4073 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00004074 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004075 Expr *E = static_cast<Expr*>(expr);
4076 QualType T = QualType::getFromOpaquePtr(type);
4077
4078 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004079
4080 // Get the va_list type
4081 QualType VaListType = Context.getBuiltinVaListType();
4082 // Deal with implicit array decay; for example, on x86-64,
4083 // va_list is an array, but it's supposed to decay to
4084 // a pointer for va_arg.
4085 if (VaListType->isArrayType())
4086 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004087 // Make sure the input expression also decays appropriately.
4088 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004089
4090 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004091 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004092 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00004093 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004094
4095 // FIXME: Warn if a non-POD type is passed in.
4096
Douglas Gregor9d293df2008-10-28 00:22:11 +00004097 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004098}
4099
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004100Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4101 // The type of __null will be int or long, depending on the size of
4102 // pointers on the target.
4103 QualType Ty;
4104 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4105 Ty = Context.IntTy;
4106 else
4107 Ty = Context.LongTy;
4108
4109 return new GNUNullExpr(Ty, TokenLoc);
4110}
4111
Chris Lattner5cf216b2008-01-04 18:04:52 +00004112bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4113 SourceLocation Loc,
4114 QualType DstType, QualType SrcType,
4115 Expr *SrcExpr, const char *Flavor) {
4116 // Decode the result (notice that AST's are still created for extensions).
4117 bool isInvalid = false;
4118 unsigned DiagKind;
4119 switch (ConvTy) {
4120 default: assert(0 && "Unknown conversion type");
4121 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004122 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004123 DiagKind = diag::ext_typecheck_convert_pointer_int;
4124 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004125 case IntToPointer:
4126 DiagKind = diag::ext_typecheck_convert_int_pointer;
4127 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004128 case IncompatiblePointer:
4129 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4130 break;
4131 case FunctionVoidPointer:
4132 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4133 break;
4134 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004135 // If the qualifiers lost were because we were applying the
4136 // (deprecated) C++ conversion from a string literal to a char*
4137 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4138 // Ideally, this check would be performed in
4139 // CheckPointerTypesForAssignment. However, that would require a
4140 // bit of refactoring (so that the second argument is an
4141 // expression, rather than a type), which should be done as part
4142 // of a larger effort to fix CheckPointerTypesForAssignment for
4143 // C++ semantics.
4144 if (getLangOptions().CPlusPlus &&
4145 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4146 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004147 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4148 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004149 case IntToBlockPointer:
4150 DiagKind = diag::err_int_to_block_pointer;
4151 break;
4152 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004153 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004154 break;
Steve Naroff39579072008-10-14 22:18:38 +00004155 case IncompatibleObjCQualifiedId:
4156 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4157 // it can give a more specific diagnostic.
4158 DiagKind = diag::warn_incompatible_qualified_id;
4159 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004160 case Incompatible:
4161 DiagKind = diag::err_typecheck_convert_incompatible;
4162 isInvalid = true;
4163 break;
4164 }
4165
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004166 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4167 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004168 return isInvalid;
4169}
Anders Carlssone21555e2008-11-30 19:50:32 +00004170
4171bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4172{
4173 Expr::EvalResult EvalResult;
4174
4175 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4176 EvalResult.HasSideEffects) {
4177 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4178
4179 if (EvalResult.Diag) {
4180 // We only show the note if it's not the usual "invalid subexpression"
4181 // or if it's actually in a subexpression.
4182 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4183 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4184 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4185 }
4186
4187 return true;
4188 }
4189
4190 if (EvalResult.Diag) {
4191 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4192 E->getSourceRange();
4193
4194 // Print the reason it's not a constant.
4195 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4196 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4197 }
4198
4199 if (Result)
4200 *Result = EvalResult.Val.getInt();
4201 return false;
4202}