blob: 6db6ea19afd64adee76ce0db0241c21dadb752b3 [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());
Douglas Gregor83233a42009-01-07 21:26:07 +0000447 BaseObjectExpr->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000448 ExtraQuals
449 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
450 } else if (BaseObjectExpr) {
451 // The caller provided the base object expression. Determine
452 // whether its a pointer and whether it adds any qualifiers to the
453 // anonymous struct/union fields we're looking into.
454 QualType ObjectType = BaseObjectExpr->getType();
455 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
456 BaseObjectIsPointer = true;
457 ObjectType = ObjectPtr->getPointeeType();
458 }
459 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
460 } else {
461 // We've found a member of an anonymous struct/union that is
462 // inside a non-anonymous struct/union, so in a well-formed
463 // program our base object expression is "this".
464 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
465 if (!MD->isStatic()) {
466 QualType AnonFieldType
467 = Context.getTagDeclType(
468 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
469 QualType ThisType = Context.getTagDeclType(MD->getParent());
470 if ((Context.getCanonicalType(AnonFieldType)
471 == Context.getCanonicalType(ThisType)) ||
472 IsDerivedFrom(ThisType, AnonFieldType)) {
473 // Our base object expression is "this".
474 BaseObjectExpr = new CXXThisExpr(SourceLocation(),
475 MD->getThisType(Context));
476 BaseObjectIsPointer = true;
Douglas Gregor83233a42009-01-07 21:26:07 +0000477 BaseObjectExpr->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000478 }
479 } else {
480 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
481 << Field->getDeclName();
482 }
483 ExtraQuals = MD->getTypeQualifiers();
484 }
485
486 if (!BaseObjectExpr)
487 return Diag(Loc, diag::err_invalid_non_static_member_use)
488 << Field->getDeclName();
489 }
490
491 // Build the implicit member references to the field of the
492 // anonymous struct/union.
493 Expr *Result = BaseObjectExpr;
494 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
495 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
496 FI != FIEnd; ++FI) {
497 QualType MemberType = (*FI)->getType();
498 if (!(*FI)->isMutable()) {
499 unsigned combinedQualifiers
500 = MemberType.getCVRQualifiers() | ExtraQuals;
501 MemberType = MemberType.getQualifiedType(combinedQualifiers);
502 }
503 Result = new MemberExpr(Result, BaseObjectIsPointer, *FI,
504 OpLoc, MemberType);
Douglas Gregor83233a42009-01-07 21:26:07 +0000505 Result->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000506 BaseObjectIsPointer = false;
507 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
508 OpLoc = SourceLocation();
509 }
510
511 return Result;
512}
513
Douglas Gregor10c42622008-11-18 15:03:34 +0000514/// ActOnDeclarationNameExpr - The parser has read some kind of name
515/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
516/// performs lookup on that name and returns an expression that refers
517/// to that name. This routine isn't directly called from the parser,
518/// because the parser doesn't know about DeclarationName. Rather,
519/// this routine is called by ActOnIdentifierExpr,
520/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
521/// which form the DeclarationName from the corresponding syntactic
522/// forms.
523///
524/// HasTrailingLParen indicates whether this identifier is used in a
525/// function call context. LookupCtx is only used for a C++
526/// qualified-id (foo::bar) to indicate the class or namespace that
527/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000528///
529/// If ForceResolution is true, then we will attempt to resolve the
530/// name even if it looks like a dependent name. This option is off by
531/// default.
Douglas Gregor10c42622008-11-18 15:03:34 +0000532Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
533 DeclarationName Name,
534 bool HasTrailingLParen,
Douglas Gregor5c37de72008-12-06 00:22:45 +0000535 const CXXScopeSpec *SS,
536 bool ForceResolution) {
537 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
538 HasTrailingLParen && !SS && !ForceResolution) {
539 // We've seen something of the form
540 // identifier(
541 // and we are in a template, so it is likely that 's' is a
542 // dependent name. However, we won't know until we've parsed all
543 // of the call arguments. So, build a CXXDependentNameExpr node
544 // to represent this name. Then, if it turns out that none of the
545 // arguments are type-dependent, we'll force the resolution of the
546 // dependent name at that point.
547 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
548 Context.DependentTy, Loc);
549 }
550
Chris Lattner8a934232008-03-31 00:36:02 +0000551 // Could be enum-constant, value decl, instance variable, etc.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000552 Decl *D;
553 if (SS && !SS->isEmpty()) {
554 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
555 if (DC == 0)
556 return true;
Douglas Gregor10c42622008-11-18 15:03:34 +0000557 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000558 } else
Douglas Gregor10c42622008-11-18 15:03:34 +0000559 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregor5c37de72008-12-06 00:22:45 +0000560
Chris Lattner8a934232008-03-31 00:36:02 +0000561 // If this reference is in an Objective-C method, then ivar lookup happens as
562 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000563 IdentifierInfo *II = Name.getAsIdentifierInfo();
564 if (II && getCurMethodDecl()) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000565 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattner8a934232008-03-31 00:36:02 +0000566 // There are two cases to handle here. 1) scoped lookup could have failed,
567 // in which case we should look for an ivar. 2) scoped lookup could have
568 // found a decl, but that decl is outside the current method (i.e. a global
569 // variable). In these two cases, we do a lookup for an ivar with this
570 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe8043c32008-04-01 23:04:06 +0000571 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000572 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregor10c42622008-11-18 15:03:34 +0000573 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner8a934232008-03-31 00:36:02 +0000574 // FIXME: This should use a new expr for a direct reference, don't turn
575 // this into Self->ivar, just return a BareIVarExpr or something.
576 IdentifierInfo &II = Context.Idents.get("self");
577 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000578 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
579 static_cast<Expr*>(SelfExpr.Val), true, true);
580 Context.setFieldDecl(IFace, IV, MRef);
581 return MRef;
Chris Lattner8a934232008-03-31 00:36:02 +0000582 }
583 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000584 // Needed to implement property "super.method" notation.
Chris Lattner84692652008-11-20 05:35:30 +0000585 if (SD == 0 && II->isStr("super")) {
Steve Naroffe3e9add2008-06-02 23:03:37 +0000586 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000587 getCurMethodDecl()->getClassInterface()));
Douglas Gregorcd9b46e2008-11-04 14:56:14 +0000588 return new ObjCSuperExpr(Loc, T);
Steve Naroffe3e9add2008-06-02 23:03:37 +0000589 }
Chris Lattner8a934232008-03-31 00:36:02 +0000590 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000591 if (D == 0) {
592 // Otherwise, this could be an implicitly declared function reference (legal
593 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000594 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000595 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000596 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 else {
598 // If this name wasn't predeclared and if this is not a function call,
599 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000600 if (SS && !SS->isEmpty())
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000601 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattner08631c52008-11-23 21:45:46 +0000602 << Name << SS->getRange();
Douglas Gregor10c42622008-11-18 15:03:34 +0000603 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
604 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000605 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000606 else
Chris Lattner08631c52008-11-23 21:45:46 +0000607 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Reid Spencer5f016e22007-07-11 17:01:13 +0000608 }
609 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000610
611 // We may have found a field within an anonymous union or struct
612 // (C++ [class.union]).
613 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
614 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
615 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Chris Lattner8a934232008-03-31 00:36:02 +0000616
Douglas Gregor88a35142008-12-22 05:46:06 +0000617 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
618 if (!MD->isStatic()) {
619 // C++ [class.mfct.nonstatic]p2:
620 // [...] if name lookup (3.4.1) resolves the name in the
621 // id-expression to a nonstatic nontype member of class X or of
622 // a base class of X, the id-expression is transformed into a
623 // class member access expression (5.2.5) using (*this) (9.3.2)
624 // as the postfix-expression to the left of the '.' operator.
625 DeclContext *Ctx = 0;
626 QualType MemberType;
627 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
628 Ctx = FD->getDeclContext();
629 MemberType = FD->getType();
630
631 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
632 MemberType = RefType->getPointeeType();
633 else if (!FD->isMutable()) {
634 unsigned combinedQualifiers
635 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
636 MemberType = MemberType.getQualifiedType(combinedQualifiers);
637 }
638 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
639 if (!Method->isStatic()) {
640 Ctx = Method->getParent();
641 MemberType = Method->getType();
642 }
643 } else if (OverloadedFunctionDecl *Ovl
644 = dyn_cast<OverloadedFunctionDecl>(D)) {
645 for (OverloadedFunctionDecl::function_iterator
646 Func = Ovl->function_begin(),
647 FuncEnd = Ovl->function_end();
648 Func != FuncEnd; ++Func) {
649 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
650 if (!DMethod->isStatic()) {
651 Ctx = Ovl->getDeclContext();
652 MemberType = Context.OverloadTy;
653 break;
654 }
655 }
656 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000657
658 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000659 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
660 QualType ThisType = Context.getTagDeclType(MD->getParent());
661 if ((Context.getCanonicalType(CtxType)
662 == Context.getCanonicalType(ThisType)) ||
663 IsDerivedFrom(ThisType, CtxType)) {
664 // Build the implicit member access expression.
665 Expr *This = new CXXThisExpr(SourceLocation(),
666 MD->getThisType(Context));
Douglas Gregor83233a42009-01-07 21:26:07 +0000667 This->setImplicit();
Douglas Gregor88a35142008-12-22 05:46:06 +0000668 return new MemberExpr(This, true, cast<NamedDecl>(D),
669 SourceLocation(), MemberType);
670 }
671 }
672 }
673 }
674
Douglas Gregor44b43212008-12-11 16:49:14 +0000675 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000676 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
677 if (MD->isStatic())
678 // "invalid use of member 'x' in static member function"
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000679 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000680 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000681 }
682
Douglas Gregor88a35142008-12-22 05:46:06 +0000683 // Any other ways we could have found the field in a well-formed
684 // program would have been turned into implicit member expressions
685 // above.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000686 return Diag(Loc, diag::err_invalid_non_static_member_use)
687 << FD->getDeclName();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000688 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000689
Reid Spencer5f016e22007-07-11 17:01:13 +0000690 if (isa<TypedefDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000691 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000692 if (isa<ObjCInterfaceDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000693 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +0000694 if (isa<NamespaceDecl>(D))
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000695 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Reid Spencer5f016e22007-07-11 17:01:13 +0000696
Steve Naroffdd972f22008-09-05 22:11:13 +0000697 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000698 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Douglas Gregor1a49af92009-01-06 05:10:23 +0000699 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc, false, false, SS);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000700
Steve Naroffdd972f22008-09-05 22:11:13 +0000701 ValueDecl *VD = cast<ValueDecl>(D);
702
703 // check if referencing an identifier with __attribute__((deprecated)).
704 if (VD->getAttr<DeprecatedAttr>())
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000705 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregorcaaf29a2008-12-10 23:01:14 +0000706
707 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
708 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
709 Scope *CheckS = S;
710 while (CheckS) {
711 if (CheckS->isWithinElse() &&
712 CheckS->getControlParent()->isDeclScope(Var)) {
713 if (Var->getType()->isBooleanType())
714 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
715 else
716 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
717 break;
718 }
719
720 // Move up one more control parent to check again.
721 CheckS = CheckS->getControlParent();
722 if (CheckS)
723 CheckS = CheckS->getParent();
724 }
725 }
726 }
Steve Naroffdd972f22008-09-05 22:11:13 +0000727
728 // Only create DeclRefExpr's for valid Decl's.
729 if (VD->isInvalidDecl())
730 return true;
Chris Lattner639e2d32008-10-20 05:16:36 +0000731
732 // If the identifier reference is inside a block, and it refers to a value
733 // that is outside the block, create a BlockDeclRefExpr instead of a
734 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
735 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +0000736 //
Chris Lattner639e2d32008-10-20 05:16:36 +0000737 // We do not do this for things like enum constants, global variables, etc,
738 // as they do not get snapshotted.
739 //
740 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff090276f2008-10-10 01:28:17 +0000741 // The BlocksAttr indicates the variable is bound by-reference.
742 if (VD->getAttr<BlocksAttr>())
Douglas Gregor9d293df2008-10-28 00:22:11 +0000743 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
744 Loc, true);
Steve Naroff090276f2008-10-10 01:28:17 +0000745
746 // Variable will be bound by-copy, make it const within the closure.
747 VD->getType().addConst();
Douglas Gregor9d293df2008-10-28 00:22:11 +0000748 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
749 Loc, false);
Steve Naroff090276f2008-10-10 01:28:17 +0000750 }
751 // If this reference is not in a block or if the referenced variable is
752 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +0000753
Douglas Gregor898574e2008-12-05 23:32:09 +0000754 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +0000755 bool ValueDependent = false;
756 if (getLangOptions().CPlusPlus) {
757 // C++ [temp.dep.expr]p3:
758 // An id-expression is type-dependent if it contains:
759 // - an identifier that was declared with a dependent type,
760 if (VD->getType()->isDependentType())
761 TypeDependent = true;
762 // - FIXME: a template-id that is dependent,
763 // - a conversion-function-id that specifies a dependent type,
764 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
765 Name.getCXXNameType()->isDependentType())
766 TypeDependent = true;
767 // - a nested-name-specifier that contains a class-name that
768 // names a dependent type.
769 else if (SS && !SS->isEmpty()) {
770 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
771 DC; DC = DC->getParent()) {
772 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000773 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +0000774 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
775 if (Context.getTypeDeclType(Record)->isDependentType()) {
776 TypeDependent = true;
777 break;
778 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000779 }
780 }
781 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000782
Douglas Gregor83f96f62008-12-10 20:57:37 +0000783 // C++ [temp.dep.constexpr]p2:
784 //
785 // An identifier is value-dependent if it is:
786 // - a name declared with a dependent type,
787 if (TypeDependent)
788 ValueDependent = true;
789 // - the name of a non-type template parameter,
790 else if (isa<NonTypeTemplateParmDecl>(VD))
791 ValueDependent = true;
792 // - a constant with integral or enumeration type and is
793 // initialized with an expression that is value-dependent
794 // (FIXME!).
795 }
Douglas Gregor898574e2008-12-05 23:32:09 +0000796
Douglas Gregor1a49af92009-01-06 05:10:23 +0000797 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
798 TypeDependent, ValueDependent, SS);
Reid Spencer5f016e22007-07-11 17:01:13 +0000799}
800
Chris Lattnerd9f69102008-08-10 01:53:14 +0000801Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Anders Carlsson22742662007-07-21 05:21:51 +0000802 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +0000803 PredefinedExpr::IdentType IT;
Anders Carlsson22742662007-07-21 05:21:51 +0000804
Reid Spencer5f016e22007-07-11 17:01:13 +0000805 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +0000806 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +0000807 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
808 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
809 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 }
Chris Lattner1423ea42008-01-12 18:39:25 +0000811
Chris Lattnerfa28b302008-01-12 08:14:25 +0000812 // Pre-defined identifiers are of type char[x], where x is the length of the
813 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +0000814 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +0000815 if (FunctionDecl *FD = getCurFunctionDecl())
816 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +0000817 else if (ObjCMethodDecl *MD = getCurMethodDecl())
818 Length = MD->getSynthesizedMethodSize();
819 else {
820 Diag(Loc, diag::ext_predef_outside_function);
821 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
822 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
823 }
824
Chris Lattner1423ea42008-01-12 18:39:25 +0000825
Chris Lattner8f978d52008-01-12 19:32:28 +0000826 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +0000827 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +0000828 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattnerd9f69102008-08-10 01:53:14 +0000829 return new PredefinedExpr(Loc, ResTy, IT);
Reid Spencer5f016e22007-07-11 17:01:13 +0000830}
831
Steve Narofff69936d2007-09-16 03:34:24 +0000832Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000833 llvm::SmallString<16> CharBuffer;
834 CharBuffer.resize(Tok.getLength());
835 const char *ThisTokBegin = &CharBuffer[0];
836 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
837
838 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
839 Tok.getLocation(), PP);
840 if (Literal.hadError())
841 return ExprResult(true);
Chris Lattnerfc62bfd2008-03-01 08:32:21 +0000842
843 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
844
Chris Lattnerc250aae2008-06-07 22:35:38 +0000845 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
846 Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000847}
848
Steve Narofff69936d2007-09-16 03:34:24 +0000849Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000850 // fast path for a single digit (which is quite common). A single digit
851 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
852 if (Tok.getLength() == 1) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000853 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000854
Chris Lattner98be4942008-03-05 18:54:05 +0000855 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattnerf0467b32008-04-02 04:24:33 +0000856 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Reid Spencer5f016e22007-07-11 17:01:13 +0000857 Context.IntTy,
858 Tok.getLocation()));
859 }
860 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +0000861 // Add padding so that NumericLiteralParser can overread by one character.
862 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000863 const char *ThisTokBegin = &IntegerBuffer[0];
864
865 // Get the spelling of the token, which eliminates trigraphs, etc.
866 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner28997ec2008-09-30 20:51:14 +0000867
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
869 Tok.getLocation(), PP);
870 if (Literal.hadError)
871 return ExprResult(true);
872
Chris Lattner5d661452007-08-26 03:42:43 +0000873 Expr *Res;
874
875 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +0000876 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000877 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +0000878 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000879 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +0000880 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000881 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +0000882 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000883
884 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
885
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000886 // isExact will be set by GetFloatValue().
887 bool isExact = false;
Chris Lattnerb7cfe882008-06-30 18:32:54 +0000888 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenek720c4ec2007-11-29 00:56:49 +0000889 Ty, Tok.getLocation());
890
Chris Lattner5d661452007-08-26 03:42:43 +0000891 } else if (!Literal.isIntegerLiteral()) {
892 return ExprResult(true);
893 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000894 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +0000895
Neil Boothb9449512007-08-29 22:00:19 +0000896 // long long is a C99 feature.
897 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +0000898 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000899 Diag(Tok.getLocation(), diag::ext_longlong);
900
Reid Spencer5f016e22007-07-11 17:01:13 +0000901 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +0000902 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000903
904 if (Literal.GetIntegerValue(ResultVal)) {
905 // If this value didn't fit into uintmax_t, warn and force to ull.
906 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000907 Ty = Context.UnsignedLongLongTy;
908 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +0000909 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000910 } else {
911 // If this value fits into a ULL, try to figure out what else it fits into
912 // according to the rules of C99 6.4.4.1p5.
913
914 // Octal, Hexadecimal, and integers with a U suffix are allowed to
915 // be an unsigned int.
916 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
917
918 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000919 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +0000920 if (!Literal.isLong && !Literal.isLongLong) {
921 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000922 unsigned IntSize = Context.Target.getIntWidth();
923
Reid Spencer5f016e22007-07-11 17:01:13 +0000924 // Does it fit in a unsigned int?
925 if (ResultVal.isIntN(IntSize)) {
926 // Does it fit in a signed int?
927 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000928 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000929 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000930 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000931 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000932 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000933 }
934
935 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +0000936 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000937 unsigned LongSize = Context.Target.getLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000938
939 // Does it fit in a unsigned long?
940 if (ResultVal.isIntN(LongSize)) {
941 // Does it fit in a signed long?
942 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000943 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000944 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000945 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000946 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000947 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000948 }
949
950 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000951 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000952 unsigned LongLongSize = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000953
954 // Does it fit in a unsigned long long?
955 if (ResultVal.isIntN(LongLongSize)) {
956 // Does it fit in a signed long long?
957 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000958 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +0000959 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +0000960 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000961 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +0000962 }
963 }
964
965 // If we still couldn't decide a type, we probably have something that
966 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +0000967 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000968 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +0000969 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000970 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +0000971 }
Chris Lattner8cbcb0e2008-05-09 05:59:00 +0000972
973 if (ResultVal.getBitWidth() != Width)
974 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +0000975 }
976
Chris Lattnerf0467b32008-04-02 04:24:33 +0000977 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 }
Chris Lattner5d661452007-08-26 03:42:43 +0000979
980 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
981 if (Literal.isImaginary)
982 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
983
984 return Res;
Reid Spencer5f016e22007-07-11 17:01:13 +0000985}
986
Steve Narofff69936d2007-09-16 03:34:24 +0000987Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Reid Spencer5f016e22007-07-11 17:01:13 +0000988 ExprTy *Val) {
Chris Lattnerf0467b32008-04-02 04:24:33 +0000989 Expr *E = (Expr *)Val;
990 assert((E != 0) && "ActOnParenExpr() missing expr");
991 return new ParenExpr(L, R, E);
Reid Spencer5f016e22007-07-11 17:01:13 +0000992}
993
994/// The UsualUnaryConversions() function is *not* called by this routine.
995/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl05189992008-11-11 17:56:53 +0000996bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
997 SourceLocation OpLoc,
998 const SourceRange &ExprRange,
999 bool isSizeof) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001000 // C99 6.5.3.4p1:
1001 if (isa<FunctionType>(exprType) && isSizeof)
1002 // alignof(function) is allowed.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001003 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Reid Spencer5f016e22007-07-11 17:01:13 +00001004 else if (exprType->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001005 Diag(OpLoc, diag::ext_sizeof_void_type)
1006 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1007 else if (exprType->isIncompleteType())
1008 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
1009 diag::err_alignof_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00001010 << exprType << ExprRange;
Sebastian Redl05189992008-11-11 17:56:53 +00001011
1012 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001013}
1014
Sebastian Redl05189992008-11-11 17:56:53 +00001015/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1016/// the same for @c alignof and @c __alignof
1017/// Note that the ArgRange is invalid if isType is false.
1018Action::ExprResult
1019Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1020 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001021 // If error parsing type, ignore.
Sebastian Redl05189992008-11-11 17:56:53 +00001022 if (TyOrEx == 0) return true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001023
Sebastian Redl05189992008-11-11 17:56:53 +00001024 QualType ArgTy;
1025 SourceRange Range;
1026 if (isType) {
1027 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1028 Range = ArgRange;
1029 } else {
1030 // Get the end location.
1031 Expr *ArgEx = (Expr *)TyOrEx;
1032 Range = ArgEx->getSourceRange();
1033 ArgTy = ArgEx->getType();
1034 }
1035
1036 // Verify that the operand is valid.
1037 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Reid Spencer5f016e22007-07-11 17:01:13 +00001038 return true;
Sebastian Redl05189992008-11-11 17:56:53 +00001039
1040 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1041 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
1042 OpLoc, Range.getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +00001043}
1044
Chris Lattner5d794252007-08-24 21:41:10 +00001045QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattnerdbb36972007-08-24 21:16:53 +00001046 DefaultFunctionArrayConversion(V);
1047
Chris Lattnercc26ed72007-08-26 05:39:26 +00001048 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001049 if (const ComplexType *CT = V->getType()->getAsComplexType())
1050 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001051
1052 // Otherwise they pass through real integer and floating point types here.
1053 if (V->getType()->isArithmeticType())
1054 return V->getType();
1055
1056 // Reject anything else.
Chris Lattnerd1625842008-11-24 06:25:27 +00001057 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001058 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001059}
1060
1061
Reid Spencer5f016e22007-07-11 17:01:13 +00001062
Douglas Gregor74253732008-11-19 15:42:04 +00001063Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001064 tok::TokenKind Kind,
1065 ExprTy *Input) {
Douglas Gregor74253732008-11-19 15:42:04 +00001066 Expr *Arg = (Expr *)Input;
1067
Reid Spencer5f016e22007-07-11 17:01:13 +00001068 UnaryOperator::Opcode Opc;
1069 switch (Kind) {
1070 default: assert(0 && "Unknown unary op!");
1071 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1072 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1073 }
Douglas Gregor74253732008-11-19 15:42:04 +00001074
1075 if (getLangOptions().CPlusPlus &&
1076 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1077 // Which overloaded operator?
1078 OverloadedOperatorKind OverOp =
1079 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1080
1081 // C++ [over.inc]p1:
1082 //
1083 // [...] If the function is a member function with one
1084 // parameter (which shall be of type int) or a non-member
1085 // function with two parameters (the second of which shall be
1086 // of type int), it defines the postfix increment operator ++
1087 // for objects of that type. When the postfix increment is
1088 // called as a result of using the ++ operator, the int
1089 // argument will have value zero.
1090 Expr *Args[2] = {
1091 Arg,
1092 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1093 /*isSigned=*/true),
1094 Context.IntTy, SourceLocation())
1095 };
1096
1097 // Build the candidate set for overloading
1098 OverloadCandidateSet CandidateSet;
1099 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
1100
1101 // Perform overload resolution.
1102 OverloadCandidateSet::iterator Best;
1103 switch (BestViableFunction(CandidateSet, Best)) {
1104 case OR_Success: {
1105 // We found a built-in operator or an overloaded operator.
1106 FunctionDecl *FnDecl = Best->Function;
1107
1108 if (FnDecl) {
1109 // We matched an overloaded operator. Build a call to that
1110 // operator.
1111
1112 // Convert the arguments.
1113 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1114 if (PerformObjectArgumentInitialization(Arg, Method))
1115 return true;
1116 } else {
1117 // Convert the arguments.
1118 if (PerformCopyInitialization(Arg,
1119 FnDecl->getParamDecl(0)->getType(),
1120 "passing"))
1121 return true;
1122 }
1123
1124 // Determine the result type
1125 QualType ResultTy
1126 = FnDecl->getType()->getAsFunctionType()->getResultType();
1127 ResultTy = ResultTy.getNonReferenceType();
1128
1129 // Build the actual expression node.
1130 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1131 SourceLocation());
1132 UsualUnaryConversions(FnExpr);
1133
1134 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
1135 } else {
1136 // We matched a built-in operator. Convert the arguments, then
1137 // break out so that we will build the appropriate built-in
1138 // operator node.
1139 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1140 "passing"))
1141 return true;
1142
1143 break;
1144 }
1145 }
1146
1147 case OR_No_Viable_Function:
1148 // No viable function; fall through to handling this as a
1149 // built-in operator, which will produce an error message for us.
1150 break;
1151
1152 case OR_Ambiguous:
1153 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1154 << UnaryOperator::getOpcodeStr(Opc)
1155 << Arg->getSourceRange();
1156 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1157 return true;
1158 }
1159
1160 // Either we found no viable overloaded operator or we matched a
1161 // built-in operator. In either case, fall through to trying to
1162 // build a built-in operation.
1163 }
1164
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00001165 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1166 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001167 if (result.isNull())
1168 return true;
Douglas Gregor74253732008-11-19 15:42:04 +00001169 return new UnaryOperator(Arg, Opc, result, OpLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001170}
1171
1172Action::ExprResult Sema::
Douglas Gregor337c6b92008-11-19 17:17:41 +00001173ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001174 ExprTy *Idx, SourceLocation RLoc) {
Chris Lattner727a80d2007-07-15 23:59:53 +00001175 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
Chris Lattner12d9ff62007-07-16 00:14:47 +00001176
Douglas Gregor337c6b92008-11-19 17:17:41 +00001177 if (getLangOptions().CPlusPlus &&
Eli Friedman03f332a2008-12-15 22:34:21 +00001178 (LHSExp->getType()->isRecordType() ||
1179 LHSExp->getType()->isEnumeralType() ||
1180 RHSExp->getType()->isRecordType() ||
1181 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001182 // Add the appropriate overloaded operators (C++ [over.match.oper])
1183 // to the candidate set.
1184 OverloadCandidateSet CandidateSet;
1185 Expr *Args[2] = { LHSExp, RHSExp };
1186 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
1187
1188 // Perform overload resolution.
1189 OverloadCandidateSet::iterator Best;
1190 switch (BestViableFunction(CandidateSet, Best)) {
1191 case OR_Success: {
1192 // We found a built-in operator or an overloaded operator.
1193 FunctionDecl *FnDecl = Best->Function;
1194
1195 if (FnDecl) {
1196 // We matched an overloaded operator. Build a call to that
1197 // operator.
1198
1199 // Convert the arguments.
1200 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1201 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1202 PerformCopyInitialization(RHSExp,
1203 FnDecl->getParamDecl(0)->getType(),
1204 "passing"))
1205 return true;
1206 } else {
1207 // Convert the arguments.
1208 if (PerformCopyInitialization(LHSExp,
1209 FnDecl->getParamDecl(0)->getType(),
1210 "passing") ||
1211 PerformCopyInitialization(RHSExp,
1212 FnDecl->getParamDecl(1)->getType(),
1213 "passing"))
1214 return true;
1215 }
1216
1217 // Determine the result type
1218 QualType ResultTy
1219 = FnDecl->getType()->getAsFunctionType()->getResultType();
1220 ResultTy = ResultTy.getNonReferenceType();
1221
1222 // Build the actual expression node.
1223 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1224 SourceLocation());
1225 UsualUnaryConversions(FnExpr);
1226
1227 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1228 } else {
1229 // We matched a built-in operator. Convert the arguments, then
1230 // break out so that we will build the appropriate built-in
1231 // operator node.
1232 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1233 "passing") ||
1234 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1235 "passing"))
1236 return true;
1237
1238 break;
1239 }
1240 }
1241
1242 case OR_No_Viable_Function:
1243 // No viable function; fall through to handling this as a
1244 // built-in operator, which will produce an error message for us.
1245 break;
1246
1247 case OR_Ambiguous:
1248 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1249 << "[]"
1250 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1251 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1252 return true;
1253 }
1254
1255 // Either we found no viable overloaded operator or we matched a
1256 // built-in operator. In either case, fall through to trying to
1257 // build a built-in operation.
1258 }
1259
Chris Lattner12d9ff62007-07-16 00:14:47 +00001260 // Perform default conversions.
1261 DefaultFunctionArrayConversion(LHSExp);
1262 DefaultFunctionArrayConversion(RHSExp);
Chris Lattner727a80d2007-07-15 23:59:53 +00001263
Chris Lattner12d9ff62007-07-16 00:14:47 +00001264 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001265
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001267 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 // in the subscript position. As a result, we need to derive the array base
1269 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001270 Expr *BaseExpr, *IndexExpr;
1271 QualType ResultType;
Chris Lattnerbefee482007-07-31 16:53:04 +00001272 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001273 BaseExpr = LHSExp;
1274 IndexExpr = RHSExp;
1275 // FIXME: need to deal with const...
1276 ResultType = PTy->getPointeeType();
Chris Lattnerbefee482007-07-31 16:53:04 +00001277 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001278 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001279 BaseExpr = RHSExp;
1280 IndexExpr = LHSExp;
1281 // FIXME: need to deal with const...
1282 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001283 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1284 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001285 IndexExpr = RHSExp;
Steve Naroff608e0ee2007-08-03 22:40:33 +00001286
1287 // Component access limited to variables (reject vec4.rg[1]).
Nate Begeman8a997642008-05-09 06:41:27 +00001288 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1289 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001290 return Diag(LLoc, diag::err_ext_vector_component_access)
1291 << SourceRange(LLoc, RLoc);
Chris Lattner12d9ff62007-07-16 00:14:47 +00001292 // FIXME: need to deal with const...
1293 ResultType = VTy->getElementType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001295 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1296 << RHSExp->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 }
1298 // C99 6.5.2.1p1
Chris Lattner12d9ff62007-07-16 00:14:47 +00001299 if (!IndexExpr->getType()->isIntegerType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001300 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1301 << IndexExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001302
Chris Lattner12d9ff62007-07-16 00:14:47 +00001303 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1304 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattnerd805bec2008-04-02 06:59:01 +00001305 // void (*)(int)) and pointers to incomplete types. Functions are not
1306 // objects in C99.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001307 if (!ResultType->isObjectType())
1308 return Diag(BaseExpr->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001309 diag::err_typecheck_subscript_not_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00001310 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner12d9ff62007-07-16 00:14:47 +00001311
1312 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001313}
1314
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001315QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001316CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001317 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001318 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001319
1320 // This flag determines whether or not the component is to be treated as a
1321 // special name, or a regular GLSL-style component access.
1322 bool SpecialComponent = false;
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001323
1324 // The vector accessor can't exceed the number of elements.
1325 const char *compStr = CompName.getName();
1326 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001327 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattnerd1625842008-11-24 06:25:27 +00001328 << baseType << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001329 return QualType();
1330 }
Nate Begeman8a997642008-05-09 06:41:27 +00001331
1332 // Check that we've found one of the special components, or that the component
1333 // names must come from the same set.
1334 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1335 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1336 SpecialComponent = true;
1337 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001338 do
1339 compStr++;
1340 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1341 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1342 do
1343 compStr++;
1344 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1345 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1346 do
1347 compStr++;
1348 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1349 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001350
Nate Begeman8a997642008-05-09 06:41:27 +00001351 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001352 // We didn't get to the end of the string. This means the component names
1353 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001354 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1355 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001356 return QualType();
1357 }
1358 // Each component accessor can't exceed the vector type.
1359 compStr = CompName.getName();
1360 while (*compStr) {
1361 if (vecType->isAccessorWithinNumElements(*compStr))
1362 compStr++;
1363 else
1364 break;
1365 }
Nate Begeman8a997642008-05-09 06:41:27 +00001366 if (!SpecialComponent && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001367 // We didn't get to the end of the string. This means a component accessor
1368 // exceeds the number of elements in the vector.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001369 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattnerd1625842008-11-24 06:25:27 +00001370 << baseType << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001371 return QualType();
1372 }
Nate Begeman8a997642008-05-09 06:41:27 +00001373
1374 // If we have a special component name, verify that the current vector length
1375 // is an even number, since all special component names return exactly half
1376 // the elements.
1377 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001378 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001379 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001380 return QualType();
1381 }
1382
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001383 // The component accessor looks fine - now we need to compute the actual type.
1384 // The vector type is implied by the component accessor. For example,
1385 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001386 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1387 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner3c73c412008-11-19 08:23:25 +00001388 : CompName.getLength();
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001389 if (CompSize == 1)
1390 return vecType->getElementType();
Steve Naroffbea0b342007-07-29 16:33:31 +00001391
Nate Begeman213541a2008-04-18 23:10:10 +00001392 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroffbea0b342007-07-29 16:33:31 +00001393 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001394 // diagostics look bad. We want extended vector types to appear built-in.
1395 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1396 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1397 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001398 }
1399 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001400}
1401
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001402/// constructSetterName - Return the setter name for the given
1403/// identifier, i.e. "set" + Name where the initial character of Name
1404/// has been capitalized.
1405// FIXME: Merge with same routine in Parser. But where should this
1406// live?
1407static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1408 const IdentifierInfo *Name) {
1409 llvm::SmallString<100> SelectorName;
1410 SelectorName = "set";
1411 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1412 SelectorName[3] = toupper(SelectorName[3]);
1413 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1414}
1415
Reid Spencer5f016e22007-07-11 17:01:13 +00001416Action::ExprResult Sema::
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001417ActOnMemberReferenceExpr(Scope *S, ExprTy *Base, SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00001418 tok::TokenKind OpKind, SourceLocation MemberLoc,
1419 IdentifierInfo &Member) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001420 Expr *BaseExpr = static_cast<Expr *>(Base);
1421 assert(BaseExpr && "no record expression");
Steve Naroff3cc4af82007-12-16 21:42:28 +00001422
1423 // Perform default conversions.
1424 DefaultFunctionArrayConversion(BaseExpr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001425
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001426 QualType BaseType = BaseExpr->getType();
1427 assert(!BaseType.isNull() && "no type for member expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00001428
Chris Lattner68a057b2008-07-21 04:36:39 +00001429 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1430 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00001431 if (OpKind == tok::arrow) {
Chris Lattnerbefee482007-07-31 16:53:04 +00001432 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001433 BaseType = PT->getPointeeType();
Douglas Gregor8ba10742008-11-20 16:27:02 +00001434 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001435 return BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001436 else
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001437 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattnerd1625842008-11-24 06:25:27 +00001438 << BaseType << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001440
Chris Lattner68a057b2008-07-21 04:36:39 +00001441 // Handle field access to simple records. This also handles access to fields
1442 // of the ObjC 'id' struct.
Chris Lattnerc8629632007-07-31 19:29:30 +00001443 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001444 RecordDecl *RDecl = RTy->getDecl();
1445 if (RTy->isIncompleteType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001446 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001447 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001448 // The record definition is complete, now make sure the member is valid.
Douglas Gregor44b43212008-12-11 16:49:14 +00001449 // FIXME: Qualified name lookup for C++ is a bit more complicated
1450 // than this.
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001451 Decl *MemberDecl = LookupDecl(DeclarationName(&Member), Decl::IDNS_Ordinary,
1452 S, RDecl, false, false);
1453 if (!MemberDecl)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001454 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner3c73c412008-11-19 08:23:25 +00001455 << &Member << BaseExpr->getSourceRange();
Douglas Gregor44b43212008-12-11 16:49:14 +00001456
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001457 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001458 // We may have found a field within an anonymous union or struct
1459 // (C++ [class.union]).
1460 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1461 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1462 BaseExpr, OpLoc);
1463
Douglas Gregor86f19402008-12-20 23:49:58 +00001464 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1465 // FIXME: Handle address space modifiers
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001466 QualType MemberType = FD->getType();
Douglas Gregor86f19402008-12-20 23:49:58 +00001467 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1468 MemberType = Ref->getPointeeType();
1469 else {
1470 unsigned combinedQualifiers =
1471 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001472 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00001473 combinedQualifiers &= ~QualType::Const;
1474 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1475 }
Eli Friedman51019072008-02-06 22:48:16 +00001476
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001477 return new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
Douglas Gregor86f19402008-12-20 23:49:58 +00001478 MemberLoc, MemberType);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001479 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001480 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc,
1481 Var->getType().getNonReferenceType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001482 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001483 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc,
1484 MemberFn->getType());
1485 else if (OverloadedFunctionDecl *Ovl
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001486 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001487 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc,
1488 Context.OverloadTy);
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001489 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001490 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc,
1491 Enum->getType());
Douglas Gregor3fc749d2008-12-23 00:26:44 +00001492 else if (isa<TypeDecl>(MemberDecl))
Douglas Gregor86f19402008-12-20 23:49:58 +00001493 return Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1494 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Eli Friedman51019072008-02-06 22:48:16 +00001495
Douglas Gregor86f19402008-12-20 23:49:58 +00001496 // We found a declaration kind that we didn't expect. This is a
1497 // generic error message that tells the user that she can't refer
1498 // to this member with '.' or '->'.
1499 return Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1500 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001501 }
1502
Chris Lattnera38e6b12008-07-21 04:59:05 +00001503 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1504 // (*Obj).ivar.
Chris Lattner68a057b2008-07-21 04:36:39 +00001505 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001506 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +00001507 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1508 BaseExpr,
1509 OpKind == tok::arrow);
1510 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1511 return MRef;
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00001512 }
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001513 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001514 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001515 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001516 }
1517
Chris Lattnera38e6b12008-07-21 04:59:05 +00001518 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1519 // pointer to a (potentially qualified) interface type.
1520 const PointerType *PTy;
1521 const ObjCInterfaceType *IFTy;
1522 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1523 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1524 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +00001525
Daniel Dunbar2307d312008-09-03 01:05:41 +00001526 // Search for a declared property first.
Chris Lattnera38e6b12008-07-21 04:59:05 +00001527 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1528 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1529
Daniel Dunbar2307d312008-09-03 01:05:41 +00001530 // Check protocols on qualified interfaces.
Chris Lattner9baefc22008-07-21 05:20:01 +00001531 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1532 E = IFTy->qual_end(); I != E; ++I)
1533 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1534 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001535
1536 // If that failed, look for an "implicit" property by seeing if the nullary
1537 // selector is implemented.
1538
1539 // FIXME: The logic for looking up nullary and unary selectors should be
1540 // shared with the code in ActOnInstanceMessage.
1541
1542 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1543 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1544
1545 // If this reference is in an @implementation, check for 'private' methods.
1546 if (!Getter)
1547 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1548 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1549 if (ObjCImplementationDecl *ImpDecl =
1550 ObjCImplementations[ClassDecl->getIdentifier()])
1551 Getter = ImpDecl->getInstanceMethod(Sel);
1552
Steve Naroff7692ed62008-10-22 19:16:27 +00001553 // Look through local category implementations associated with the class.
1554 if (!Getter) {
1555 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1556 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1557 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1558 }
1559 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00001560 if (Getter) {
1561 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00001562 // will look for the matching setter, in case it is needed.
1563 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1564 &Member);
1565 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1566 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1567 if (!Setter) {
1568 // If this reference is in an @implementation, also check for 'private'
1569 // methods.
1570 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1571 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1572 if (ObjCImplementationDecl *ImpDecl =
1573 ObjCImplementations[ClassDecl->getIdentifier()])
1574 Setter = ImpDecl->getInstanceMethod(SetterSel);
1575 }
1576 // Look through local category implementations associated with the class.
1577 if (!Setter) {
1578 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1579 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1580 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1581 }
1582 }
1583
1584 // FIXME: we must check that the setter has property type.
1585 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00001586 MemberLoc, BaseExpr);
Daniel Dunbar2307d312008-09-03 01:05:41 +00001587 }
Anders Carlsson00165a22008-12-19 17:27:57 +00001588
1589 return Diag(MemberLoc, diag::err_property_not_found) <<
1590 &Member << BaseType;
Fariborz Jahanian232220c2007-11-12 22:29:28 +00001591 }
Steve Naroff18bc1642008-10-20 22:53:06 +00001592 // Handle properties on qualified "id" protocols.
1593 const ObjCQualifiedIdType *QIdTy;
1594 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1595 // Check protocols on qualified interfaces.
1596 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001597 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroff18bc1642008-10-20 22:53:06 +00001598 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1599 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian391d8952008-12-10 00:21:50 +00001600 // Also must look for a getter name which uses property syntax.
1601 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1602 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1603 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1604 OpLoc, MemberLoc, NULL, 0);
1605 }
1606 }
Anders Carlsson00165a22008-12-19 17:27:57 +00001607
1608 return Diag(MemberLoc, diag::err_property_not_found) <<
1609 &Member << BaseType;
Steve Naroff18bc1642008-10-20 22:53:06 +00001610 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001611 // Handle 'field access' to vectors, such as 'V.xx'.
1612 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1613 // Component access limited to variables (reject vec4.rg.g).
1614 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1615 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001616 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1617 << BaseExpr->getSourceRange();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00001618 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1619 if (ret.isNull())
1620 return true;
1621 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1622 }
1623
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001624 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattnerd1625842008-11-24 06:25:27 +00001625 << BaseType << BaseExpr->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00001626}
1627
Douglas Gregor88a35142008-12-22 05:46:06 +00001628/// ConvertArgumentsForCall - Converts the arguments specified in
1629/// Args/NumArgs to the parameter types of the function FDecl with
1630/// function prototype Proto. Call is the call expression itself, and
1631/// Fn is the function expression. For a C++ member function, this
1632/// routine does not attempt to convert the object argument. Returns
1633/// true if the call is ill-formed.
1634bool
1635Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1636 FunctionDecl *FDecl,
1637 const FunctionTypeProto *Proto,
1638 Expr **Args, unsigned NumArgs,
1639 SourceLocation RParenLoc) {
1640 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1641 // assignment, to the types of the corresponding parameter, ...
1642 unsigned NumArgsInProto = Proto->getNumArgs();
1643 unsigned NumArgsToCheck = NumArgs;
1644
1645 // If too few arguments are available (and we don't have default
1646 // arguments for the remaining parameters), don't make the call.
1647 if (NumArgs < NumArgsInProto) {
1648 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1649 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1650 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1651 // Use default arguments for missing arguments
1652 NumArgsToCheck = NumArgsInProto;
1653 Call->setNumArgs(NumArgsInProto);
1654 }
1655
1656 // If too many are passed and not variadic, error on the extras and drop
1657 // them.
1658 if (NumArgs > NumArgsInProto) {
1659 if (!Proto->isVariadic()) {
1660 Diag(Args[NumArgsInProto]->getLocStart(),
1661 diag::err_typecheck_call_too_many_args)
1662 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1663 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1664 Args[NumArgs-1]->getLocEnd());
1665 // This deletes the extra arguments.
1666 Call->setNumArgs(NumArgsInProto);
1667 }
1668 NumArgsToCheck = NumArgsInProto;
1669 }
1670
1671 // Continue to check argument types (even if we have too few/many args).
1672 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1673 QualType ProtoArgType = Proto->getArgType(i);
1674
1675 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00001676 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001677 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00001678
1679 // Pass the argument.
1680 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1681 return true;
1682 } else
1683 // We already type-checked the argument, so we know it works.
Douglas Gregor88a35142008-12-22 05:46:06 +00001684 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1685 QualType ArgType = Arg->getType();
Douglas Gregor61366e92008-12-24 00:01:03 +00001686
Douglas Gregor88a35142008-12-22 05:46:06 +00001687 Call->setArg(i, Arg);
1688 }
1689
1690 // If this is a variadic call, handle args passed through "...".
1691 if (Proto->isVariadic()) {
1692 // Promote the arguments (C99 6.5.2.2p7).
1693 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1694 Expr *Arg = Args[i];
1695 DefaultArgumentPromotion(Arg);
1696 Call->setArg(i, Arg);
1697 }
1698 }
1699
1700 return false;
1701}
1702
Steve Narofff69936d2007-09-16 03:34:24 +00001703/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00001704/// This provides the location of the left/right parens and a list of comma
1705/// locations.
Douglas Gregor88a35142008-12-22 05:46:06 +00001706Action::ExprResult
1707Sema::ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
1708 ExprTy **args, unsigned NumArgs,
1709 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner74c469f2007-07-21 03:03:59 +00001710 Expr *Fn = static_cast<Expr *>(fn);
1711 Expr **Args = reinterpret_cast<Expr**>(args);
1712 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00001713 FunctionDecl *FDecl = NULL;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001714 OverloadedFunctionDecl *Ovl = NULL;
1715
Douglas Gregor5c37de72008-12-06 00:22:45 +00001716 // Determine whether this is a dependent call inside a C++ template,
1717 // in which case we won't do any semantic analysis now.
1718 bool Dependent = false;
1719 if (Fn->isTypeDependent()) {
1720 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1721 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1722 Dependent = true;
1723 else {
1724 // Resolve the CXXDependentNameExpr to an actual identifier;
1725 // it wasn't really a dependent name after all.
1726 ExprResult Resolved
1727 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1728 /*HasTrailingLParen=*/true,
1729 /*SS=*/0,
1730 /*ForceResolution=*/true);
1731 if (Resolved.isInvalid)
1732 return true;
1733 else {
1734 delete Fn;
1735 Fn = (Expr *)Resolved.Val;
1736 }
1737 }
1738 } else
1739 Dependent = true;
1740 } else
1741 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1742
Douglas Gregor898574e2008-12-05 23:32:09 +00001743 // FIXME: Will need to cache the results of name lookup (including
1744 // ADL) in Fn.
Douglas Gregor5c37de72008-12-06 00:22:45 +00001745 if (Dependent)
Douglas Gregor898574e2008-12-05 23:32:09 +00001746 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1747
Douglas Gregor88a35142008-12-22 05:46:06 +00001748 // Determine whether this is a call to an object (C++ [over.call.object]).
1749 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1750 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1751 CommaLocs, RParenLoc);
1752
1753 // Determine whether this is a call to a member function.
1754 if (getLangOptions().CPlusPlus) {
1755 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1756 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1757 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1758 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1759 CommaLocs, RParenLoc);
1760 }
1761
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001762 // If we're directly calling a function or a set of overloaded
1763 // functions, get the appropriate declaration.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001764 DeclRefExpr *DRExpr = NULL;
1765 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1766 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1767 else
1768 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1769
1770 if (DRExpr) {
1771 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1772 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001773 }
1774
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001775 if (Ovl) {
Douglas Gregor0a396682008-11-26 06:01:48 +00001776 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1777 RParenLoc);
1778 if (!FDecl)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001779 return true;
1780
Douglas Gregor0a396682008-11-26 06:01:48 +00001781 // Update Fn to refer to the actual function selected.
Douglas Gregor1a49af92009-01-06 05:10:23 +00001782 Expr *NewFn = 0;
1783 if (QualifiedDeclRefExpr *QDRExpr = dyn_cast<QualifiedDeclRefExpr>(DRExpr))
1784 NewFn = new QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1785 QDRExpr->getLocation(), false, false,
1786 QDRExpr->getSourceRange().getBegin());
1787 else
1788 NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1789 Fn->getSourceRange().getBegin());
Douglas Gregor0a396682008-11-26 06:01:48 +00001790 Fn->Destroy(Context);
1791 Fn = NewFn;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001792 }
Chris Lattner04421082008-04-08 04:40:51 +00001793
1794 // Promote the function operand.
1795 UsualUnaryConversions(Fn);
1796
Chris Lattner925e60d2007-12-28 05:29:59 +00001797 // Make the call expr early, before semantic checks. This guarantees cleanup
1798 // of arguments and function on error.
Chris Lattner8123a952008-04-10 02:22:51 +00001799 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner925e60d2007-12-28 05:29:59 +00001800 Context.BoolTy, RParenLoc));
Douglas Gregor898574e2008-12-05 23:32:09 +00001801
Steve Naroffdd972f22008-09-05 22:11:13 +00001802 const FunctionType *FuncT;
1803 if (!Fn->getType()->isBlockPointerType()) {
1804 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1805 // have type pointer to function".
1806 const PointerType *PT = Fn->getType()->getAsPointerType();
1807 if (PT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001808 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerd1625842008-11-24 06:25:27 +00001809 << Fn->getType() << Fn->getSourceRange();
Steve Naroffdd972f22008-09-05 22:11:13 +00001810 FuncT = PT->getPointeeType()->getAsFunctionType();
1811 } else { // This is a block call.
1812 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1813 getAsFunctionType();
1814 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001815 if (FuncT == 0)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001816 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattnerd1625842008-11-24 06:25:27 +00001817 << Fn->getType() << Fn->getSourceRange();
Chris Lattner925e60d2007-12-28 05:29:59 +00001818
1819 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00001820 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Reid Spencer5f016e22007-07-11 17:01:13 +00001821
Chris Lattner925e60d2007-12-28 05:29:59 +00001822 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00001823 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1824 RParenLoc))
1825 return true;
Chris Lattner925e60d2007-12-28 05:29:59 +00001826 } else {
1827 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1828
Steve Naroffb291ab62007-08-28 23:30:39 +00001829 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00001830 for (unsigned i = 0; i != NumArgs; i++) {
1831 Expr *Arg = Args[i];
1832 DefaultArgumentPromotion(Arg);
1833 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00001834 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001835 }
Chris Lattner925e60d2007-12-28 05:29:59 +00001836
Douglas Gregor88a35142008-12-22 05:46:06 +00001837 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1838 if (!Method->isStatic())
1839 return Diag(LParenLoc, diag::err_member_call_without_object)
1840 << Fn->getSourceRange();
1841
Chris Lattner59907c42007-08-10 20:18:51 +00001842 // Do special checking on direct calls to functions.
Eli Friedmand38617c2008-05-14 19:38:39 +00001843 if (FDecl)
1844 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner59907c42007-08-10 20:18:51 +00001845
Chris Lattner925e60d2007-12-28 05:29:59 +00001846 return TheCall.take();
Reid Spencer5f016e22007-07-11 17:01:13 +00001847}
1848
1849Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001850ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Steve Naroffaff1edd2007-07-19 21:32:11 +00001851 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00001852 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff4aa88f82007-07-19 01:06:55 +00001853 QualType literalType = QualType::getFromOpaquePtr(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00001854 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00001855 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Steve Naroffaff1edd2007-07-19 21:32:11 +00001856 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlssond35c8322007-12-05 07:24:19 +00001857
Eli Friedman6223c222008-05-20 05:22:08 +00001858 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001859 if (literalType->isVariableArrayType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001860 return Diag(LParenLoc, diag::err_variable_object_no_init)
1861 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001862 } else if (literalType->isIncompleteType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001863 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001864 << literalType
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001865 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman6223c222008-05-20 05:22:08 +00001866 }
1867
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001868 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001869 DeclarationName()))
Steve Naroff58d18212008-01-09 20:58:06 +00001870 return true;
Steve Naroffe9b12192008-01-14 18:19:28 +00001871
Chris Lattner371f2582008-12-04 23:50:19 +00001872 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00001873 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00001874 if (CheckForConstantInitializer(literalExpr, literalType))
1875 return true;
1876 }
Chris Lattner220ad7c2008-10-26 23:35:51 +00001877 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1878 isFileScope);
Steve Naroff4aa88f82007-07-19 01:06:55 +00001879}
1880
1881Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001882ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattner220ad7c2008-10-26 23:35:51 +00001883 InitListDesignations &Designators,
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001884 SourceLocation RBraceLoc) {
Steve Narofff0090632007-09-02 02:04:30 +00001885 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001886
Steve Naroff08d92e42007-09-15 18:49:24 +00001887 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroffd35005e2007-09-03 01:24:23 +00001888 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00001889
Chris Lattner418f6c72008-10-26 23:43:26 +00001890 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1891 Designators.hasAnyDesignators());
Chris Lattnerf0467b32008-04-02 04:24:33 +00001892 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1893 return E;
Steve Naroff4aa88f82007-07-19 01:06:55 +00001894}
1895
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001896/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar58d5ebb2008-08-20 03:55:42 +00001897bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001898 UsualUnaryConversions(castExpr);
1899
1900 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1901 // type needs to be scalar.
1902 if (castType->isVoidType()) {
1903 // Cast to void allows any expr type.
Douglas Gregor898574e2008-12-05 23:32:09 +00001904 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1905 // We can't check any more until template instantiation time.
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001906 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1907 // GCC struct/union extension: allow cast to self.
1908 if (Context.getCanonicalType(castType) !=
1909 Context.getCanonicalType(castExpr->getType()) ||
1910 (!castType->isStructureType() && !castType->isUnionType())) {
1911 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001912 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001913 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001914 }
1915
1916 // accept this, but emit an ext-warn.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001917 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001918 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001919 } else if (!castExpr->getType()->isScalarType() &&
1920 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001921 return Diag(castExpr->getLocStart(),
1922 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00001923 << castExpr->getType() << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001924 } else if (castExpr->getType()->isVectorType()) {
1925 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1926 return true;
1927 } else if (castType->isVectorType()) {
1928 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1929 return true;
1930 }
1931 return false;
1932}
1933
Chris Lattnerfe23e212007-12-20 00:44:32 +00001934bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00001935 assert(VectorTy->isVectorType() && "Not a vector type!");
1936
1937 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00001938 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00001939 return Diag(R.getBegin(),
1940 Ty->isVectorType() ?
1941 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001942 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00001943 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001944 } else
1945 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001946 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00001947 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00001948
1949 return false;
1950}
1951
Steve Naroff4aa88f82007-07-19 01:06:55 +00001952Action::ExprResult Sema::
Steve Narofff69936d2007-09-16 03:34:24 +00001953ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Reid Spencer5f016e22007-07-11 17:01:13 +00001954 SourceLocation RParenLoc, ExprTy *Op) {
Steve Narofff69936d2007-09-16 03:34:24 +00001955 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00001956
1957 Expr *castExpr = static_cast<Expr*>(Op);
1958 QualType castType = QualType::getFromOpaquePtr(Ty);
1959
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00001960 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1961 return true;
Steve Naroffb2f9e512008-11-03 23:29:32 +00001962 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00001963}
1964
Chris Lattnera21ddb32007-11-26 01:40:58 +00001965/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1966/// In that case, lex = cond.
Reid Spencer5f016e22007-07-11 17:01:13 +00001967inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
Steve Naroff49b45262007-07-13 16:58:59 +00001968 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00001969 UsualUnaryConversions(cond);
1970 UsualUnaryConversions(lex);
1971 UsualUnaryConversions(rex);
1972 QualType condT = cond->getType();
1973 QualType lexT = lex->getType();
1974 QualType rexT = rex->getType();
1975
Reid Spencer5f016e22007-07-11 17:01:13 +00001976 // first, check the condition.
Douglas Gregor898574e2008-12-05 23:32:09 +00001977 if (!cond->isTypeDependent()) {
1978 if (!condT->isScalarType()) { // C99 6.5.15p2
1979 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1980 return QualType();
1981 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001983
1984 // Now check the two expressions.
Douglas Gregor898574e2008-12-05 23:32:09 +00001985 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1986 return Context.DependentTy;
1987
Chris Lattner70d67a92008-01-06 22:42:25 +00001988 // If both operands have arithmetic type, do the usual arithmetic conversions
1989 // to find a common type: C99 6.5.15p3,5.
1990 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Steve Naroffa4332e22007-07-17 00:58:39 +00001991 UsualArithmeticConversions(lex, rex);
1992 return lex->getType();
1993 }
Chris Lattner70d67a92008-01-06 22:42:25 +00001994
1995 // If both operands are the same structure or union type, the result is that
1996 // type.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00001997 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner70d67a92008-01-06 22:42:25 +00001998 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattnera21ddb32007-11-26 01:40:58 +00001999 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner70d67a92008-01-06 22:42:25 +00002000 // "If both the operands have structure or union type, the result has
2001 // that type." This implies that CV qualifiers are dropped.
2002 return lexT.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 }
Chris Lattner70d67a92008-01-06 22:42:25 +00002004
2005 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00002006 // The following || allows only one side to be void (a GCC-ism).
2007 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedman0e724012008-06-04 19:47:51 +00002008 if (!lexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002009 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2010 << rex->getSourceRange();
Steve Naroffe701c0a2008-05-12 21:44:38 +00002011 if (!rexT->isVoidType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002012 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2013 << lex->getSourceRange();
Eli Friedman0e724012008-06-04 19:47:51 +00002014 ImpCastExprToType(lex, Context.VoidTy);
2015 ImpCastExprToType(rex, Context.VoidTy);
2016 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00002017 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00002018 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2019 // the type of the other operand."
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002020 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2021 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002022 rex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002023 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002024 return lexT;
2025 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002026 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2027 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssond2652772008-12-01 06:28:23 +00002028 lex->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002029 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroffb6d54e52008-01-08 01:11:38 +00002030 return rexT;
2031 }
Chris Lattnerbd57d362008-01-06 22:50:31 +00002032 // Handle the case where both operands are pointers before we handle null
2033 // pointer constants in case both operands are null pointer constants.
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002034 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2035 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2036 // get the "pointed to" types
2037 QualType lhptee = LHSPT->getPointeeType();
2038 QualType rhptee = RHSPT->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002039
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002040 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2041 if (lhptee->isVoidType() &&
Chris Lattnerd805bec2008-04-02 06:59:01 +00002042 rhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002043 // Figure out necessary qualifiers (C99 6.5.15p6)
2044 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002045 QualType destType = Context.getPointerType(destPointee);
2046 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2047 ImpCastExprToType(rex, destType); // promote to void*
2048 return destType;
2049 }
Chris Lattnerd805bec2008-04-02 06:59:01 +00002050 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattnerf46699c2008-02-20 20:55:12 +00002051 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmana541d532008-02-10 22:59:36 +00002052 QualType destType = Context.getPointerType(destPointee);
2053 ImpCastExprToType(lex, destType); // add qualifiers if necessary
2054 ImpCastExprToType(rex, destType); // promote to void*
2055 return destType;
2056 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002057
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002058 QualType compositeType = lexT;
2059
2060 // If either type is an Objective-C object type then check
2061 // compatibility according to Objective-C.
2062 if (Context.isObjCObjectPointerType(lexT) ||
2063 Context.isObjCObjectPointerType(rexT)) {
2064 // If both operands are interfaces and either operand can be
2065 // assigned to the other, use that type as the composite
2066 // type. This allows
2067 // xxx ? (A*) a : (B*) b
2068 // where B is a subclass of A.
2069 //
2070 // Additionally, as for assignment, if either type is 'id'
2071 // allow silent coercion. Finally, if the types are
2072 // incompatible then make sure to use 'id' as the composite
2073 // type so the result is acceptable for sending messages to.
2074
2075 // FIXME: This code should not be localized to here. Also this
2076 // should use a compatible check instead of abusing the
2077 // canAssignObjCInterfaces code.
2078 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2079 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2080 if (LHSIface && RHSIface &&
2081 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2082 compositeType = lexT;
2083 } else if (LHSIface && RHSIface &&
Douglas Gregor7ffd0de2008-11-26 06:43:45 +00002084 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002085 compositeType = rexT;
2086 } else if (Context.isObjCIdType(lhptee) ||
2087 Context.isObjCIdType(rhptee)) {
2088 // FIXME: This code looks wrong, because isObjCIdType checks
2089 // the struct but getObjCIdType returns the pointer to
2090 // struct. This is horrible and should be fixed.
2091 compositeType = Context.getObjCIdType();
2092 } else {
2093 QualType incompatTy = Context.getObjCIdType();
2094 ImpCastExprToType(lex, incompatTy);
2095 ImpCastExprToType(rex, incompatTy);
2096 return incompatTy;
2097 }
2098 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2099 rhptee.getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002100 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002101 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002102 // In this situation, we assume void* type. No especially good
2103 // reason, but this is what gcc does, and we do have to pick
2104 // to get a consistent AST.
2105 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbara56f7462008-08-26 00:41:39 +00002106 ImpCastExprToType(lex, incompatTy);
2107 ImpCastExprToType(rex, incompatTy);
2108 return incompatTy;
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002109 }
2110 // The pointer types are compatible.
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002111 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2112 // differently qualified versions of compatible types, the result type is
2113 // a pointer to an appropriately qualified version of the *composite*
2114 // type.
Eli Friedman5835ea22008-05-16 20:37:07 +00002115 // FIXME: Need to calculate the composite type.
Eli Friedmana541d532008-02-10 22:59:36 +00002116 // FIXME: Need to add qualifiers
Eli Friedman5835ea22008-05-16 20:37:07 +00002117 ImpCastExprToType(lex, compositeType);
2118 ImpCastExprToType(rex, compositeType);
2119 return compositeType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002120 }
2121 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00002122 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2123 // evaluates to "struct objc_object *" (and is handled above when comparing
2124 // id with statically typed objects).
2125 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2126 // GCC allows qualified id and any Objective-C type to devolve to
2127 // id. Currently localizing to here until clear this should be
2128 // part of ObjCQualifiedIdTypesAreCompatible.
2129 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2130 (lexT->isObjCQualifiedIdType() &&
2131 Context.isObjCObjectPointerType(rexT)) ||
2132 (rexT->isObjCQualifiedIdType() &&
2133 Context.isObjCObjectPointerType(lexT))) {
2134 // FIXME: This is not the correct composite type. This only
2135 // happens to work because id can more or less be used anywhere,
2136 // however this may change the type of method sends.
2137 // FIXME: gcc adds some type-checking of the arguments and emits
2138 // (confusing) incompatible comparison warnings in some
2139 // cases. Investigate.
2140 QualType compositeType = Context.getObjCIdType();
2141 ImpCastExprToType(lex, compositeType);
2142 ImpCastExprToType(rex, compositeType);
2143 return compositeType;
2144 }
2145 }
2146
Steve Naroff61f40a22008-09-10 19:17:48 +00002147 // Selection between block pointer types is ok as long as they are the same.
2148 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2149 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2150 return lexT;
2151
Chris Lattner70d67a92008-01-06 22:42:25 +00002152 // Otherwise, the operands are not compatible.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002153 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattnerd1625842008-11-24 06:25:27 +00002154 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002155 return QualType();
2156}
2157
Steve Narofff69936d2007-09-16 03:34:24 +00002158/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00002159/// in the case of a the GNU conditional expr extension.
Steve Narofff69936d2007-09-16 03:34:24 +00002160Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 SourceLocation ColonLoc,
2162 ExprTy *Cond, ExprTy *LHS,
2163 ExprTy *RHS) {
Chris Lattner26824902007-07-16 21:39:03 +00002164 Expr *CondExpr = (Expr *) Cond;
2165 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattnera21ddb32007-11-26 01:40:58 +00002166
2167 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2168 // was the condition.
2169 bool isLHSNull = LHSExpr == 0;
2170 if (isLHSNull)
2171 LHSExpr = CondExpr;
2172
Chris Lattner26824902007-07-16 21:39:03 +00002173 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2174 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00002175 if (result.isNull())
2176 return true;
Chris Lattnera21ddb32007-11-26 01:40:58 +00002177 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2178 RHSExpr, result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002179}
2180
Reid Spencer5f016e22007-07-11 17:01:13 +00002181
2182// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2183// being closely modeled after the C99 spec:-). The odd characteristic of this
2184// routine is it effectively iqnores the qualifiers on the top level pointee.
2185// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2186// FIXME: add a couple examples in this comment.
Chris Lattner5cf216b2008-01-04 18:04:52 +00002187Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002188Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2189 QualType lhptee, rhptee;
2190
2191 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner2dcb6bb2007-07-31 21:27:01 +00002192 lhptee = lhsType->getAsPointerType()->getPointeeType();
2193 rhptee = rhsType->getAsPointerType()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002194
2195 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00002196 lhptee = Context.getCanonicalType(lhptee);
2197 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00002198
Chris Lattner5cf216b2008-01-04 18:04:52 +00002199 AssignConvertType ConvTy = Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002200
2201 // C99 6.5.16.1p1: This following citation is common to constraints
2202 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2203 // qualifiers of the type *pointed to* by the right;
Chris Lattnerf46699c2008-02-20 20:55:12 +00002204 // FIXME: Handle ASQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00002205 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00002206 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00002207
2208 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2209 // incomplete type and the other is a pointer to a qualified or unqualified
2210 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002211 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002212 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002213 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002214
2215 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002216 assert(rhptee->isFunctionType());
2217 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002218 }
2219
2220 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00002221 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00002222 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002223
2224 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00002225 assert(lhptee->isFunctionType());
2226 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002227 }
Eli Friedman3d815e72008-08-22 00:56:42 +00002228
2229 // Check for ObjC interfaces
2230 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2231 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2232 if (LHSIface && RHSIface &&
2233 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2234 return ConvTy;
2235
2236 // ID acts sort of like void* for ObjC interfaces
2237 if (LHSIface && Context.isObjCIdType(rhptee))
2238 return ConvTy;
2239 if (RHSIface && Context.isObjCIdType(lhptee))
2240 return ConvTy;
2241
Reid Spencer5f016e22007-07-11 17:01:13 +00002242 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2243 // unqualified versions of compatible types, ...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00002244 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2245 rhptee.getUnqualifiedType()))
2246 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner5cf216b2008-01-04 18:04:52 +00002247 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002248}
2249
Steve Naroff1c7d0672008-09-04 15:10:53 +00002250/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2251/// block pointer types are compatible or whether a block and normal pointer
2252/// are compatible. It is more restrict than comparing two function pointer
2253// types.
2254Sema::AssignConvertType
2255Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2256 QualType rhsType) {
2257 QualType lhptee, rhptee;
2258
2259 // get the "pointed to" type (ignoring qualifiers at the top level)
2260 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2261 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2262
2263 // make sure we operate on the canonical type
2264 lhptee = Context.getCanonicalType(lhptee);
2265 rhptee = Context.getCanonicalType(rhptee);
2266
2267 AssignConvertType ConvTy = Compatible;
2268
2269 // For blocks we enforce that qualifiers are identical.
2270 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2271 ConvTy = CompatiblePointerDiscardsQualifiers;
2272
2273 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2274 return IncompatibleBlockPointer;
2275 return ConvTy;
2276}
2277
Reid Spencer5f016e22007-07-11 17:01:13 +00002278/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2279/// has code to accommodate several GCC extensions when type checking
2280/// pointers. Here are some objectionable examples that GCC considers warnings:
2281///
2282/// int a, *pint;
2283/// short *pshort;
2284/// struct foo *pfoo;
2285///
2286/// pint = pshort; // warning: assignment from incompatible pointer type
2287/// a = pint; // warning: assignment makes integer from pointer without a cast
2288/// pint = a; // warning: assignment makes pointer from integer without a cast
2289/// pint = pfoo; // warning: assignment from incompatible pointer type
2290///
2291/// As a result, the code for dealing with pointers is more complex than the
2292/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00002293///
Chris Lattner5cf216b2008-01-04 18:04:52 +00002294Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00002295Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00002296 // Get canonical types. We're not formatting these types, just comparing
2297 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002298 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2299 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002300
2301 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00002302 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00002303
Douglas Gregor9d293df2008-10-28 00:22:11 +00002304 // If the left-hand side is a reference type, then we are in a
2305 // (rare!) case where we've allowed the use of references in C,
2306 // e.g., as a parameter type in a built-in function. In this case,
2307 // just make sure that the type referenced is compatible with the
2308 // right-hand side type. The caller is responsible for adjusting
2309 // lhsType so that the resulting expression does not have reference
2310 // type.
2311 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2312 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00002313 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002314 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002315 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002316
Chris Lattnereca7be62008-04-07 05:30:13 +00002317 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2318 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002319 return Compatible;
Steve Naroff20373222008-06-03 14:04:54 +00002320 // Relax integer conversions like we do for pointers below.
2321 if (rhsType->isIntegerType())
2322 return IntToPointer;
2323 if (lhsType->isIntegerType())
2324 return PointerToInt;
Steve Naroff39579072008-10-14 22:18:38 +00002325 return IncompatibleObjCQualifiedId;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00002326 }
Chris Lattnere8b3e962008-01-04 23:32:24 +00002327
Nate Begemanbe2341d2008-07-14 18:02:46 +00002328 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman213541a2008-04-18 23:10:10 +00002329 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanbe2341d2008-07-14 18:02:46 +00002330 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2331 if (LV->getElementType() == rhsType)
Chris Lattnere8b3e962008-01-04 23:32:24 +00002332 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002333
Nate Begemanbe2341d2008-07-14 18:02:46 +00002334 // If we are allowing lax vector conversions, and LHS and RHS are both
2335 // vectors, the total size only needs to be the same. This is a bitcast;
2336 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00002337 if (getLangOptions().LaxVectorConversions &&
2338 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002339 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2340 return Compatible;
Chris Lattnere8b3e962008-01-04 23:32:24 +00002341 }
2342 return Incompatible;
2343 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002344
Chris Lattnere8b3e962008-01-04 23:32:24 +00002345 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002346 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002347
Chris Lattner78eca282008-04-07 06:49:41 +00002348 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002349 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002350 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002351
Chris Lattner78eca282008-04-07 06:49:41 +00002352 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002354
Steve Naroffb4406862008-09-29 18:10:17 +00002355 if (rhsType->getAsBlockPointerType()) {
Steve Naroffdd972f22008-09-05 22:11:13 +00002356 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002357 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00002358
2359 // Treat block pointers as objects.
2360 if (getLangOptions().ObjC1 &&
2361 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2362 return Compatible;
2363 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002364 return Incompatible;
2365 }
2366
2367 if (isa<BlockPointerType>(lhsType)) {
2368 if (rhsType->isIntegerType())
2369 return IntToPointer;
2370
Steve Naroffb4406862008-09-29 18:10:17 +00002371 // Treat block pointers as objects.
2372 if (getLangOptions().ObjC1 &&
2373 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2374 return Compatible;
2375
Steve Naroff1c7d0672008-09-04 15:10:53 +00002376 if (rhsType->isBlockPointerType())
2377 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2378
2379 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2380 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002381 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002382 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00002383 return Incompatible;
2384 }
2385
Chris Lattner78eca282008-04-07 06:49:41 +00002386 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002387 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002388 if (lhsType == Context.BoolTy)
2389 return Compatible;
2390
2391 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00002392 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00002393
Chris Lattner78eca282008-04-07 06:49:41 +00002394 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002395 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff1c7d0672008-09-04 15:10:53 +00002396
2397 if (isa<BlockPointerType>(lhsType) &&
2398 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00002399 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002400 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00002401 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00002402
Chris Lattnerfc144e22008-01-04 23:18:45 +00002403 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00002404 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00002405 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00002406 }
2407 return Incompatible;
2408}
2409
Chris Lattner5cf216b2008-01-04 18:04:52 +00002410Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002411Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002412 if (getLangOptions().CPlusPlus) {
2413 if (!lhsType->isRecordType()) {
2414 // C++ 5.17p3: If the left operand is not of class type, the
2415 // expression is implicitly converted (C++ 4) to the
2416 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00002417 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2418 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002419 return Incompatible;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002420 else
Douglas Gregor98cd5992008-10-21 23:43:52 +00002421 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002422 }
2423
2424 // FIXME: Currently, we fall through and treat C++ classes like C
2425 // structures.
2426 }
2427
Steve Naroff529a4ad2007-11-27 17:58:44 +00002428 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2429 // a null pointer constant.
Steve Naroff39218df2008-09-04 16:56:14 +00002430 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2431 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00002432 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002433 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00002434 return Compatible;
2435 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002436
2437 // We don't allow conversion of non-null-pointer constants to integers.
2438 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2439 return IntToBlockPointer;
2440
Chris Lattner943140e2007-10-16 02:55:40 +00002441 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00002442 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00002443 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00002444 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00002445 //
Douglas Gregor9d293df2008-10-28 00:22:11 +00002446 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00002447 if (!lhsType->isReferenceType())
2448 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00002449
Chris Lattner5cf216b2008-01-04 18:04:52 +00002450 Sema::AssignConvertType result =
2451 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Narofff1120de2007-08-24 22:33:52 +00002452
2453 // C99 6.5.16.1p2: The value of the right operand is converted to the
2454 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00002455 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2456 // so that we can use references in built-in functions even in C.
2457 // The getNonReferenceType() call makes sure that the resulting expression
2458 // does not have reference type.
Steve Narofff1120de2007-08-24 22:33:52 +00002459 if (rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00002460 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00002461 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00002462}
2463
Chris Lattner5cf216b2008-01-04 18:04:52 +00002464Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00002465Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2466 return CheckAssignmentConstraints(lhsType, rhsType);
2467}
2468
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002469QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002470 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00002471 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002472 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00002473 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002474}
2475
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002476inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00002477 Expr *&rex) {
Nate Begeman1330b0e2008-04-04 01:30:25 +00002478 // For conversion purposes, we ignore any qualifiers.
2479 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00002480 QualType lhsType =
2481 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2482 QualType rhsType =
2483 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002484
Nate Begemanbe2341d2008-07-14 18:02:46 +00002485 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00002486 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00002488
Nate Begemanbe2341d2008-07-14 18:02:46 +00002489 // Handle the case of a vector & extvector type of the same size and element
2490 // type. It would be nice if we only had one vector type someday.
2491 if (getLangOptions().LaxVectorConversions)
2492 if (const VectorType *LV = lhsType->getAsVectorType())
2493 if (const VectorType *RV = rhsType->getAsVectorType())
2494 if (LV->getElementType() == RV->getElementType() &&
2495 LV->getNumElements() == RV->getNumElements())
2496 return lhsType->isExtVectorType() ? lhsType : rhsType;
2497
2498 // If the lhs is an extended vector and the rhs is a scalar of the same type
2499 // or a literal, promote the rhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002500 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002501 QualType eltType = V->getElementType();
2502
2503 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2504 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2505 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002506 ImpCastExprToType(rex, lhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002507 return lhsType;
2508 }
2509 }
2510
Nate Begemanbe2341d2008-07-14 18:02:46 +00002511 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begeman4119d1a2007-12-30 02:59:45 +00002512 // promote the lhs to the vector type.
Nate Begeman213541a2008-04-18 23:10:10 +00002513 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002514 QualType eltType = V->getElementType();
2515
2516 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2517 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2518 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00002519 ImpCastExprToType(lex, rhsType);
Nate Begeman4119d1a2007-12-30 02:59:45 +00002520 return rhsType;
2521 }
2522 }
2523
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 // You cannot convert between vector values of different size.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002525 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00002526 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002527 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002528 return QualType();
2529}
2530
2531inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002532 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002533{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00002534 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002535 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002536
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002537 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002538
Steve Naroffa4332e22007-07-17 00:58:39 +00002539 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002540 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002541 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002542}
2543
2544inline QualType Sema::CheckRemainderOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002545 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002546{
Daniel Dunbar523aa602009-01-05 22:55:36 +00002547 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2548 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2549 return CheckVectorOperands(Loc, lex, rex);
2550 return InvalidOperands(Loc, lex, rex);
2551 }
Steve Naroff90045e82007-07-13 23:32:42 +00002552
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002553 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002554
Steve Naroffa4332e22007-07-17 00:58:39 +00002555 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002556 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002557 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002558}
2559
2560inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002561 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002562{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002563 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002564 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff49b45262007-07-13 16:58:59 +00002565
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002566 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand72d16e2008-05-18 18:08:51 +00002567
Reid Spencer5f016e22007-07-11 17:01:13 +00002568 // handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002569 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002570 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00002571
Eli Friedmand72d16e2008-05-18 18:08:51 +00002572 // Put any potential pointer into PExp
2573 Expr* PExp = lex, *IExp = rex;
2574 if (IExp->getType()->isPointerType())
2575 std::swap(PExp, IExp);
2576
2577 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2578 if (IExp->getType()->isIntegerType()) {
2579 // Check for arithmetic on pointers to incomplete types
2580 if (!PTy->getPointeeType()->isObjectType()) {
2581 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002582 Diag(Loc, diag::ext_gnu_void_ptr)
2583 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002584 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002585 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00002586 << lex->getType() << lex->getSourceRange();
Eli Friedmand72d16e2008-05-18 18:08:51 +00002587 return QualType();
2588 }
2589 }
2590 return PExp->getType();
2591 }
2592 }
2593
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002594 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002595}
2596
Chris Lattnereca7be62008-04-07 05:30:13 +00002597// C99 6.5.6
2598QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002599 SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00002600 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002601 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002602
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002603 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002604
Chris Lattner6e4ab612007-12-09 21:53:25 +00002605 // Enforce type constraints: C99 6.5.6p3.
2606
2607 // Handle the common case first (both operands are arithmetic).
Steve Naroffa4332e22007-07-17 00:58:39 +00002608 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002609 return compType;
Chris Lattner6e4ab612007-12-09 21:53:25 +00002610
2611 // Either ptr - int or ptr - ptr.
2612 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff2565eef2008-01-29 18:58:14 +00002613 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman8e54ad02008-02-08 01:19:44 +00002614
Chris Lattner6e4ab612007-12-09 21:53:25 +00002615 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff2565eef2008-01-29 18:58:14 +00002616 if (!lpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002617 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002618 if (lpointee->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002619 Diag(Loc, diag::ext_gnu_void_ptr)
2620 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002621 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002622 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002623 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002624 return QualType();
2625 }
2626 }
2627
2628 // The result type of a pointer-int computation is the pointer type.
2629 if (rex->getType()->isIntegerType())
2630 return lex->getType();
Steve Naroff3e5e5562007-07-16 22:23:01 +00002631
Chris Lattner6e4ab612007-12-09 21:53:25 +00002632 // Handle pointer-pointer subtractions.
2633 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00002634 QualType rpointee = RHSPTy->getPointeeType();
2635
Chris Lattner6e4ab612007-12-09 21:53:25 +00002636 // RHS must be an object type, unless void (GNU).
Steve Naroff2565eef2008-01-29 18:58:14 +00002637 if (!rpointee->isObjectType()) {
Chris Lattner6e4ab612007-12-09 21:53:25 +00002638 // Handle the GNU void* extension.
Steve Naroff2565eef2008-01-29 18:58:14 +00002639 if (rpointee->isVoidType()) {
2640 if (!lpointee->isVoidType())
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002641 Diag(Loc, diag::ext_gnu_void_ptr)
2642 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002643 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002644 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattnerd1625842008-11-24 06:25:27 +00002645 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002646 return QualType();
2647 }
2648 }
2649
2650 // Pointee types must be compatible.
Eli Friedmanf1c7b482008-09-02 05:09:35 +00002651 if (!Context.typesAreCompatible(
2652 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2653 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002654 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattnerd1625842008-11-24 06:25:27 +00002655 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002656 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00002657 return QualType();
2658 }
2659
2660 return Context.getPointerDiffType();
2661 }
2662 }
2663
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002664 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002665}
2666
Chris Lattnereca7be62008-04-07 05:30:13 +00002667// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002668QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002669 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00002670 // C99 6.5.7p2: Each of the operands shall have integer type.
2671 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002672 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002673
Chris Lattnerca5eede2007-12-12 05:47:28 +00002674 // Shifts don't perform usual arithmetic conversions, they just do integer
2675 // promotions on each operand. C99 6.5.7p3
Chris Lattner1dcf2c82007-12-13 07:28:16 +00002676 if (!isCompAssign)
2677 UsualUnaryConversions(lex);
Chris Lattnerca5eede2007-12-12 05:47:28 +00002678 UsualUnaryConversions(rex);
2679
2680 // "The type of the result is that of the promoted left operand."
2681 return lex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002682}
2683
Eli Friedman3d815e72008-08-22 00:56:42 +00002684static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2685 ASTContext& Context) {
2686 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2687 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2688 // ID acts sort of like void* for ObjC interfaces
2689 if (LHSIface && Context.isObjCIdType(RHS))
2690 return true;
2691 if (RHSIface && Context.isObjCIdType(LHS))
2692 return true;
2693 if (!LHSIface || !RHSIface)
2694 return false;
2695 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2696 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2697}
2698
Chris Lattnereca7be62008-04-07 05:30:13 +00002699// C99 6.5.8
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002700QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00002701 bool isRelational) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00002702 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002703 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002704
Chris Lattnera5937dd2007-08-26 01:18:55 +00002705 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00002706 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2707 UsualArithmeticConversions(lex, rex);
2708 else {
2709 UsualUnaryConversions(lex);
2710 UsualUnaryConversions(rex);
2711 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002712 QualType lType = lex->getType();
2713 QualType rType = rex->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002714
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002715 // For non-floating point types, check for self-comparisons of the form
2716 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2717 // often indicate logic errors in the program.
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002718 if (!lType->isFloatingType()) {
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002719 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2720 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002721 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002722 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00002723 }
2724
Douglas Gregor447b69e2008-11-19 03:25:36 +00002725 // The result of comparisons is 'bool' in C++, 'int' in C.
2726 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2727
Chris Lattnera5937dd2007-08-26 01:18:55 +00002728 if (isRelational) {
2729 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002730 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002731 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002732 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00002733 if (lType->isFloatingType()) {
2734 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002735 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00002736 }
2737
Chris Lattnera5937dd2007-08-26 01:18:55 +00002738 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00002739 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00002740 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002741
Chris Lattnerd28f8152007-08-26 01:10:14 +00002742 bool LHSIsNull = lex->isNullPointerConstant(Context);
2743 bool RHSIsNull = rex->isNullPointerConstant(Context);
2744
Chris Lattnera5937dd2007-08-26 01:18:55 +00002745 // All of the following pointer related warnings are GCC extensions, except
2746 // when handling null pointer constants. One day, we can consider making them
2747 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00002748 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002749 QualType LCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002750 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00002751 QualType RCanPointeeTy =
Chris Lattnerb77792e2008-07-26 22:17:49 +00002752 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman8e54ad02008-02-08 01:19:44 +00002753
Steve Naroff66296cb2007-11-13 14:57:38 +00002754 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00002755 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2756 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman3d815e72008-08-22 00:56:42 +00002757 RCanPointeeTy.getUnqualifiedType()) &&
2758 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002759 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002760 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00002761 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00002762 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002763 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002764 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002765 // Handle block pointer types.
2766 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2767 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2768 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2769
2770 if (!LHSIsNull && !RHSIsNull &&
2771 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002772 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002773 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00002774 }
2775 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002776 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00002777 }
Steve Naroff59f53942008-09-28 01:11:11 +00002778 // Allow block pointers to be compared with null pointer constants.
2779 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2780 (lType->isPointerType() && rType->isBlockPointerType())) {
2781 if (!LHSIsNull && !RHSIsNull) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002782 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00002783 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00002784 }
2785 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002786 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00002787 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00002788
Steve Naroff20373222008-06-03 14:04:54 +00002789 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00002790 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroffa8069f12008-11-17 19:49:16 +00002791 const PointerType *LPT = lType->getAsPointerType();
2792 const PointerType *RPT = rType->getAsPointerType();
2793 bool LPtrToVoid = LPT ?
2794 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2795 bool RPtrToVoid = RPT ?
2796 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2797
2798 if (!LPtrToVoid && !RPtrToVoid &&
2799 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002800 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00002801 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00002802 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002803 return ResultTy;
Steve Naroffa5ad8632008-10-27 10:33:19 +00002804 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002805 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002806 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00002807 }
Steve Naroff20373222008-06-03 14:04:54 +00002808 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2809 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002810 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002811 } else {
2812 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002813 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002814 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00002815 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00002816 return ResultTy;
Steve Naroff39579072008-10-14 22:18:38 +00002817 }
Steve Naroff20373222008-06-03 14:04:54 +00002818 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00002819 }
Steve Naroff20373222008-06-03 14:04:54 +00002820 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2821 rType->isIntegerType()) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002822 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002823 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002824 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002825 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002826 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00002827 }
Steve Naroff20373222008-06-03 14:04:54 +00002828 if (lType->isIntegerType() &&
2829 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattnerd28f8152007-08-26 01:10:14 +00002830 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002831 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002832 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner1e0a3902008-01-16 19:17:22 +00002833 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002834 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00002835 }
Steve Naroff39218df2008-09-04 16:56:14 +00002836 // Handle block pointers.
2837 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2838 if (!RHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002839 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002840 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002841 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002842 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002843 }
2844 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2845 if (!LHSIsNull)
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00002846 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00002847 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff39218df2008-09-04 16:56:14 +00002848 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00002849 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00002850 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002851 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002852}
2853
Nate Begemanbe2341d2008-07-14 18:02:46 +00002854/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2855/// operates on extended vector types. Instead of producing an IntTy result,
2856/// like a scalar comparison, a vector comparison produces a vector of integer
2857/// types.
2858QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002859 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00002860 bool isRelational) {
2861 // Check to make sure we're operating on vectors of the same type and width,
2862 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002863 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002864 if (vType.isNull())
2865 return vType;
2866
2867 QualType lType = lex->getType();
2868 QualType rType = rex->getType();
2869
2870 // For non-floating point types, check for self-comparisons of the form
2871 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2872 // often indicate logic errors in the program.
2873 if (!lType->isFloatingType()) {
2874 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2875 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2876 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002877 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002878 }
2879
2880 // Check for comparisons of floating point operands using != and ==.
2881 if (!isRelational && lType->isFloatingType()) {
2882 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002883 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00002884 }
2885
2886 // Return the type for the comparison, which is the same as vector type for
2887 // integer vectors, or an integer type of identical size and number of
2888 // elements for floating point vectors.
2889 if (lType->isIntegerType())
2890 return lType;
2891
2892 const VectorType *VTy = lType->getAsVectorType();
2893
2894 // FIXME: need to deal with non-32b int / non-64b long long
2895 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2896 if (TypeSize == 32) {
2897 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2898 }
2899 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2900 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2901}
2902
Reid Spencer5f016e22007-07-11 17:01:13 +00002903inline QualType Sema::CheckBitwiseOperands(
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002904 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00002905{
Steve Naroff3e5e5562007-07-16 22:23:01 +00002906 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002907 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00002908
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002909 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Reid Spencer5f016e22007-07-11 17:01:13 +00002910
Steve Naroffa4332e22007-07-17 00:58:39 +00002911 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00002912 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002913 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002914}
2915
2916inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002917 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00002918{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00002919 UsualUnaryConversions(lex);
2920 UsualUnaryConversions(rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002921
Eli Friedman5773a6c2008-05-13 20:16:47 +00002922 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00002923 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002924 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00002925}
2926
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002927/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2928/// emit an error and return true. If so, return false.
2929static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2930 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2931 if (IsLV == Expr::MLV_Valid)
2932 return false;
2933
2934 unsigned Diag = 0;
2935 bool NeedType = false;
2936 switch (IsLV) { // C99 6.5.16p2
2937 default: assert(0 && "Unknown result from isModifiableLvalue!");
2938 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002939 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002940 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2941 NeedType = true;
2942 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002943 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002944 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2945 NeedType = true;
2946 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00002947 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002948 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2949 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002950 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002951 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2952 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002953 case Expr::MLV_IncompleteType:
2954 case Expr::MLV_IncompleteVoidType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002955 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2956 NeedType = true;
2957 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00002958 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002959 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2960 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00002961 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002962 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2963 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00002964 case Expr::MLV_ReadonlyProperty:
2965 Diag = diag::error_readonly_property_assignment;
2966 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00002967 case Expr::MLV_NoSetterProperty:
2968 Diag = diag::error_nosetter_property_assignment;
2969 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002970 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00002971
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002972 if (NeedType)
Chris Lattnerd1625842008-11-24 06:25:27 +00002973 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002974 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002975 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002976 return true;
2977}
2978
2979
2980
2981// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002982QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2983 SourceLocation Loc,
2984 QualType CompoundType) {
2985 // Verify that LHS is a modifiable lvalue, and emit error if not.
2986 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002987 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002988
2989 QualType LHSType = LHS->getType();
2990 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00002991
Chris Lattner5cf216b2008-01-04 18:04:52 +00002992 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002993 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00002994 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00002995 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner2c156472008-08-21 18:04:13 +00002996
2997 // If the RHS is a unary plus or minus, check to see if they = and + are
2998 // right next to each other. If so, the user may have typo'd "x =+ 4"
2999 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003000 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00003001 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3002 RHSCheck = ICE->getSubExpr();
3003 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3004 if ((UO->getOpcode() == UnaryOperator::Plus ||
3005 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003006 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00003007 // Only if the two operators are exactly adjacent.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003008 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003009 Diag(Loc, diag::warn_not_compound_assign)
3010 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3011 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner2c156472008-08-21 18:04:13 +00003012 }
3013 } else {
3014 // Compound assignment "x += y"
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003015 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00003016 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003017
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003018 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3019 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003020 return QualType();
3021
Reid Spencer5f016e22007-07-11 17:01:13 +00003022 // C99 6.5.16p3: The type of an assignment expression is the type of the
3023 // left operand unless the left operand has qualified type, in which case
3024 // it is the unqualified version of the type of the left operand.
3025 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3026 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003027 // C++ 5.17p1: the type of the assignment expression is that of its left
3028 // oprdu.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003029 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003030}
3031
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003032// C99 6.5.17
3033QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3034 // FIXME: what is required for LHS?
Chris Lattner53fcaa92008-07-25 20:54:07 +00003035
3036 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003037 DefaultFunctionArrayConversion(RHS);
3038 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003039}
3040
Steve Naroff49b45262007-07-13 16:58:59 +00003041/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3042/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003043QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3044 bool isInc) {
Chris Lattner3528d352008-11-21 07:05:48 +00003045 QualType ResType = Op->getType();
3046 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003047
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003048 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3049 // Decrement of bool is not allowed.
3050 if (!isInc) {
3051 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3052 return QualType();
3053 }
3054 // Increment of bool sets it to true, but is deprecated.
3055 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3056 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00003057 // OK!
3058 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3059 // C99 6.5.2.4p2, 6.5.6p2
3060 if (PT->getPointeeType()->isObjectType()) {
3061 // Pointer to object is ok!
3062 } else if (PT->getPointeeType()->isVoidType()) {
3063 // Pointer to void is extension.
3064 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3065 } else {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003066 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00003067 << ResType << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003068 return QualType();
3069 }
Chris Lattner3528d352008-11-21 07:05:48 +00003070 } else if (ResType->isComplexType()) {
3071 // C99 does not support ++/-- on complex types, we allow as an extension.
3072 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003073 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003074 } else {
3075 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00003076 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00003077 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003078 }
Steve Naroffdd10e022007-08-23 21:37:33 +00003079 // At this point, we know we have a real, complex or pointer type.
3080 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00003081 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00003082 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00003083 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00003084}
3085
Anders Carlsson369dee42008-02-01 07:15:58 +00003086/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00003087/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003088/// where the declaration is needed for type checking. We only need to
3089/// handle cases when the expression references a function designator
3090/// or is an lvalue. Here are some examples:
3091/// - &(x) => x
3092/// - &*****f => f for f a function designator.
3093/// - &s.xx => s
3094/// - &s.zz[1].yy -> s, if zz is an array
3095/// - *(x + 1) -> x, if x is an array
3096/// - &"123"[2] -> 0
3097/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003098static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00003099 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003100 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00003101 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003102 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003103 case Stmt::MemberExprClass:
Chris Lattnerf82228f2007-11-16 17:46:48 +00003104 // Fields cannot be declared with a 'register' storage class.
3105 // &X->f is always ok, even if X is declared register.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003106 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00003107 return 0;
Chris Lattnerf0467b32008-04-02 04:24:33 +00003108 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00003109 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003110 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson369dee42008-02-01 07:15:58 +00003111
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003112 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar48d04ae2008-10-21 21:22:32 +00003113 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlssonf2a4b842008-02-01 16:01:31 +00003114 if (!VD || VD->getType()->isPointerType())
Anders Carlsson369dee42008-02-01 07:15:58 +00003115 return 0;
3116 else
3117 return VD;
3118 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003119 case Stmt::UnaryOperatorClass: {
3120 UnaryOperator *UO = cast<UnaryOperator>(E);
3121
3122 switch(UO->getOpcode()) {
3123 case UnaryOperator::Deref: {
3124 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003125 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3126 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3127 if (!VD || VD->getType()->isPointerType())
3128 return 0;
3129 return VD;
3130 }
3131 return 0;
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00003132 }
3133 case UnaryOperator::Real:
3134 case UnaryOperator::Imag:
3135 case UnaryOperator::Extension:
3136 return getPrimaryDecl(UO->getSubExpr());
3137 default:
3138 return 0;
3139 }
3140 }
3141 case Stmt::BinaryOperatorClass: {
3142 BinaryOperator *BO = cast<BinaryOperator>(E);
3143
3144 // Handle cases involving pointer arithmetic. The result of an
3145 // Assign or AddAssign is not an lvalue so they can be ignored.
3146
3147 // (x + n) or (n + x) => x
3148 if (BO->getOpcode() == BinaryOperator::Add) {
3149 if (BO->getLHS()->getType()->isPointerType()) {
3150 return getPrimaryDecl(BO->getLHS());
3151 } else if (BO->getRHS()->getType()->isPointerType()) {
3152 return getPrimaryDecl(BO->getRHS());
3153 }
3154 }
3155
3156 return 0;
3157 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003158 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00003159 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00003160 case Stmt::ImplicitCastExprClass:
3161 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattnerf0467b32008-04-02 04:24:33 +00003162 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00003163 default:
3164 return 0;
3165 }
3166}
3167
3168/// CheckAddressOfOperand - The operand of & must be either a function
3169/// designator or an lvalue designating an object. If it is an lvalue, the
3170/// object cannot be declared with storage class register or be a bit field.
3171/// Note: The usual conversions are *not* applied to the operand of the &
3172/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor904eed32008-11-10 20:40:00 +00003173/// In C++, the operand might be an overloaded function name, in which case
3174/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00003175QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregor9103bb22008-12-17 22:52:20 +00003176 if (op->isTypeDependent())
3177 return Context.DependentTy;
3178
Steve Naroff08f19672008-01-13 17:10:08 +00003179 if (getLangOptions().C99) {
3180 // Implement C99-only parts of addressof rules.
3181 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3182 if (uOp->getOpcode() == UnaryOperator::Deref)
3183 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3184 // (assuming the deref expression is valid).
3185 return uOp->getSubExpr()->getType();
3186 }
3187 // Technically, there should be a check for array subscript
3188 // expressions here, but the result of one is always an lvalue anyway.
3189 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003190 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00003191 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00003192
Reid Spencer5f016e22007-07-11 17:01:13 +00003193 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnerf82228f2007-11-16 17:46:48 +00003194 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3195 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003196 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3197 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003198 return QualType();
3199 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003200 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor86f19402008-12-20 23:49:58 +00003201 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3202 if (Field->isBitField()) {
3203 Diag(OpLoc, diag::err_typecheck_address_of)
3204 << "bit-field" << op->getSourceRange();
3205 return QualType();
3206 }
Steve Naroffbcb2b612008-02-29 23:30:25 +00003207 }
3208 // Check for Apple extension for accessing vector components.
3209 } else if (isa<ArraySubscriptExpr>(op) &&
3210 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003211 Diag(OpLoc, diag::err_typecheck_address_of)
3212 << "vector" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00003213 return QualType();
3214 } else if (dcl) { // C99 6.5.3.2p1
Reid Spencer5f016e22007-07-11 17:01:13 +00003215 // We have an lvalue with a decl. Make sure the decl is not declared
3216 // with the register storage-class specifier.
3217 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3218 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003219 Diag(OpLoc, diag::err_typecheck_address_of)
3220 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003221 return QualType();
3222 }
Douglas Gregor29882052008-12-10 21:26:49 +00003223 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00003224 return Context.OverloadTy;
Douglas Gregor29882052008-12-10 21:26:49 +00003225 } else if (isa<FieldDecl>(dcl)) {
3226 // Okay: we can take the address of a field.
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003227 } else if (isa<FunctionDecl>(dcl)) {
3228 // Okay: we can take the address of a function.
Douglas Gregor29882052008-12-10 21:26:49 +00003229 }
Nuno Lopes6fea8d22008-12-16 22:58:26 +00003230 else
Reid Spencer5f016e22007-07-11 17:01:13 +00003231 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00003232 }
Chris Lattnerc36d4052008-07-27 00:48:22 +00003233
Reid Spencer5f016e22007-07-11 17:01:13 +00003234 // If the operand has type "type", the result has type "pointer to type".
3235 return Context.getPointerType(op->getType());
3236}
3237
Chris Lattner22caddc2008-11-23 09:13:29 +00003238QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3239 UsualUnaryConversions(Op);
3240 QualType Ty = Op->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003241
Chris Lattner22caddc2008-11-23 09:13:29 +00003242 // Note that per both C89 and C99, this is always legal, even if ptype is an
3243 // incomplete type or void. It would be possible to warn about dereferencing
3244 // a void pointer, but it's completely well-defined, and such a warning is
3245 // unlikely to catch any mistakes.
3246 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff08f19672008-01-13 17:10:08 +00003247 return PT->getPointeeType();
Chris Lattner22caddc2008-11-23 09:13:29 +00003248
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003249 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00003250 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003251 return QualType();
3252}
3253
3254static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3255 tok::TokenKind Kind) {
3256 BinaryOperator::Opcode Opc;
3257 switch (Kind) {
3258 default: assert(0 && "Unknown binop!");
3259 case tok::star: Opc = BinaryOperator::Mul; break;
3260 case tok::slash: Opc = BinaryOperator::Div; break;
3261 case tok::percent: Opc = BinaryOperator::Rem; break;
3262 case tok::plus: Opc = BinaryOperator::Add; break;
3263 case tok::minus: Opc = BinaryOperator::Sub; break;
3264 case tok::lessless: Opc = BinaryOperator::Shl; break;
3265 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3266 case tok::lessequal: Opc = BinaryOperator::LE; break;
3267 case tok::less: Opc = BinaryOperator::LT; break;
3268 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3269 case tok::greater: Opc = BinaryOperator::GT; break;
3270 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3271 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3272 case tok::amp: Opc = BinaryOperator::And; break;
3273 case tok::caret: Opc = BinaryOperator::Xor; break;
3274 case tok::pipe: Opc = BinaryOperator::Or; break;
3275 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3276 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3277 case tok::equal: Opc = BinaryOperator::Assign; break;
3278 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3279 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3280 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3281 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3282 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3283 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3284 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3285 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3286 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3287 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3288 case tok::comma: Opc = BinaryOperator::Comma; break;
3289 }
3290 return Opc;
3291}
3292
3293static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3294 tok::TokenKind Kind) {
3295 UnaryOperator::Opcode Opc;
3296 switch (Kind) {
3297 default: assert(0 && "Unknown unary op!");
3298 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3299 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3300 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3301 case tok::star: Opc = UnaryOperator::Deref; break;
3302 case tok::plus: Opc = UnaryOperator::Plus; break;
3303 case tok::minus: Opc = UnaryOperator::Minus; break;
3304 case tok::tilde: Opc = UnaryOperator::Not; break;
3305 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003306 case tok::kw___real: Opc = UnaryOperator::Real; break;
3307 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3308 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3309 }
3310 return Opc;
3311}
3312
Douglas Gregoreaebc752008-11-06 23:29:22 +00003313/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3314/// operator @p Opc at location @c TokLoc. This routine only supports
3315/// built-in operations; ActOnBinOp handles overloaded operators.
3316Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3317 unsigned Op,
3318 Expr *lhs, Expr *rhs) {
3319 QualType ResultTy; // Result type of the binary operator.
3320 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3321 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3322
3323 switch (Opc) {
3324 default:
3325 assert(0 && "Unknown binary expr!");
3326 case BinaryOperator::Assign:
3327 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3328 break;
3329 case BinaryOperator::Mul:
3330 case BinaryOperator::Div:
3331 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3332 break;
3333 case BinaryOperator::Rem:
3334 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3335 break;
3336 case BinaryOperator::Add:
3337 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3338 break;
3339 case BinaryOperator::Sub:
3340 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3341 break;
3342 case BinaryOperator::Shl:
3343 case BinaryOperator::Shr:
3344 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3345 break;
3346 case BinaryOperator::LE:
3347 case BinaryOperator::LT:
3348 case BinaryOperator::GE:
3349 case BinaryOperator::GT:
3350 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3351 break;
3352 case BinaryOperator::EQ:
3353 case BinaryOperator::NE:
3354 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3355 break;
3356 case BinaryOperator::And:
3357 case BinaryOperator::Xor:
3358 case BinaryOperator::Or:
3359 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3360 break;
3361 case BinaryOperator::LAnd:
3362 case BinaryOperator::LOr:
3363 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3364 break;
3365 case BinaryOperator::MulAssign:
3366 case BinaryOperator::DivAssign:
3367 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3368 if (!CompTy.isNull())
3369 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3370 break;
3371 case BinaryOperator::RemAssign:
3372 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3373 if (!CompTy.isNull())
3374 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3375 break;
3376 case BinaryOperator::AddAssign:
3377 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3378 if (!CompTy.isNull())
3379 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3380 break;
3381 case BinaryOperator::SubAssign:
3382 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3383 if (!CompTy.isNull())
3384 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3385 break;
3386 case BinaryOperator::ShlAssign:
3387 case BinaryOperator::ShrAssign:
3388 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3389 if (!CompTy.isNull())
3390 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3391 break;
3392 case BinaryOperator::AndAssign:
3393 case BinaryOperator::XorAssign:
3394 case BinaryOperator::OrAssign:
3395 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3396 if (!CompTy.isNull())
3397 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3398 break;
3399 case BinaryOperator::Comma:
3400 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3401 break;
3402 }
3403 if (ResultTy.isNull())
3404 return true;
3405 if (CompTy.isNull())
3406 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3407 else
3408 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3409}
3410
Reid Spencer5f016e22007-07-11 17:01:13 +00003411// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003412Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3413 tok::TokenKind Kind,
Reid Spencer5f016e22007-07-11 17:01:13 +00003414 ExprTy *LHS, ExprTy *RHS) {
3415 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3416 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3417
Steve Narofff69936d2007-09-16 03:34:24 +00003418 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3419 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00003420
Douglas Gregor898574e2008-12-05 23:32:09 +00003421 // If either expression is type-dependent, just build the AST.
3422 // FIXME: We'll need to perform some caching of the result of name
3423 // lookup for operator+.
3424 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3425 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3426 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3427 Context.DependentTy, TokLoc);
3428 else
3429 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3430 }
3431
Douglas Gregoreaebc752008-11-06 23:29:22 +00003432 if (getLangOptions().CPlusPlus &&
3433 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3434 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003435 // If this is one of the assignment operators, we only perform
3436 // overload resolution if the left-hand side is a class or
3437 // enumeration type (C++ [expr.ass]p3).
3438 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3439 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3440 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3441 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003442
3443 // Determine which overloaded operator we're dealing with.
3444 static const OverloadedOperatorKind OverOps[] = {
3445 OO_Star, OO_Slash, OO_Percent,
3446 OO_Plus, OO_Minus,
3447 OO_LessLess, OO_GreaterGreater,
3448 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3449 OO_EqualEqual, OO_ExclaimEqual,
3450 OO_Amp,
3451 OO_Caret,
3452 OO_Pipe,
3453 OO_AmpAmp,
3454 OO_PipePipe,
3455 OO_Equal, OO_StarEqual,
3456 OO_SlashEqual, OO_PercentEqual,
3457 OO_PlusEqual, OO_MinusEqual,
3458 OO_LessLessEqual, OO_GreaterGreaterEqual,
3459 OO_AmpEqual, OO_CaretEqual,
3460 OO_PipeEqual,
3461 OO_Comma
3462 };
3463 OverloadedOperatorKind OverOp = OverOps[Opc];
3464
Douglas Gregor96176b32008-11-18 23:14:02 +00003465 // Add the appropriate overloaded operators (C++ [over.match.oper])
3466 // to the candidate set.
Douglas Gregor74253732008-11-19 15:42:04 +00003467 OverloadCandidateSet CandidateSet;
Douglas Gregoreaebc752008-11-06 23:29:22 +00003468 Expr *Args[2] = { lhs, rhs };
Douglas Gregor96176b32008-11-18 23:14:02 +00003469 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregoreaebc752008-11-06 23:29:22 +00003470
3471 // Perform overload resolution.
3472 OverloadCandidateSet::iterator Best;
3473 switch (BestViableFunction(CandidateSet, Best)) {
3474 case OR_Success: {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003475 // We found a built-in operator or an overloaded operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003476 FunctionDecl *FnDecl = Best->Function;
3477
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003478 if (FnDecl) {
3479 // We matched an overloaded operator. Build a call to that
3480 // operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003481
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003482 // Convert the arguments.
Douglas Gregor96176b32008-11-18 23:14:02 +00003483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3484 if (PerformObjectArgumentInitialization(lhs, Method) ||
3485 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3486 "passing"))
3487 return true;
3488 } else {
3489 // Convert the arguments.
3490 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3491 "passing") ||
3492 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3493 "passing"))
3494 return true;
3495 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003496
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003497 // Determine the result type
3498 QualType ResultTy
3499 = FnDecl->getType()->getAsFunctionType()->getResultType();
3500 ResultTy = ResultTy.getNonReferenceType();
3501
3502 // Build the actual expression node.
Douglas Gregorb4609802008-11-14 16:09:21 +00003503 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3504 SourceLocation());
3505 UsualUnaryConversions(FnExpr);
3506
Douglas Gregorb4609802008-11-14 16:09:21 +00003507 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003508 } else {
3509 // We matched a built-in operator. Convert the arguments, then
3510 // break out so that we will build the appropriate built-in
3511 // operator node.
3512 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3513 "passing") ||
3514 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3515 "passing"))
3516 return true;
3517
3518 break;
3519 }
Douglas Gregoreaebc752008-11-06 23:29:22 +00003520 }
3521
3522 case OR_No_Viable_Function:
3523 // No viable function; fall through to handling this as a
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003524 // built-in operator, which will produce an error message for us.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003525 break;
3526
3527 case OR_Ambiguous:
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003528 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3529 << BinaryOperator::getOpcodeStr(Opc)
3530 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregoreaebc752008-11-06 23:29:22 +00003531 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3532 return true;
3533 }
3534
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003535 // Either we found no viable overloaded operator or we matched a
3536 // built-in operator. In either case, fall through to trying to
3537 // build a built-in operation.
Douglas Gregoreaebc752008-11-06 23:29:22 +00003538 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003539
Douglas Gregoreaebc752008-11-06 23:29:22 +00003540 // Build a built-in binary operation.
3541 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00003542}
3543
3544// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor74253732008-11-19 15:42:04 +00003545Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3546 tok::TokenKind Op, ExprTy *input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003547 Expr *Input = (Expr*)input;
3548 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor74253732008-11-19 15:42:04 +00003549
3550 if (getLangOptions().CPlusPlus &&
3551 (Input->getType()->isRecordType()
3552 || Input->getType()->isEnumeralType())) {
3553 // Determine which overloaded operator we're dealing with.
3554 static const OverloadedOperatorKind OverOps[] = {
3555 OO_None, OO_None,
3556 OO_PlusPlus, OO_MinusMinus,
3557 OO_Amp, OO_Star,
3558 OO_Plus, OO_Minus,
3559 OO_Tilde, OO_Exclaim,
3560 OO_None, OO_None,
3561 OO_None,
3562 OO_None
3563 };
3564 OverloadedOperatorKind OverOp = OverOps[Opc];
3565
3566 // Add the appropriate overloaded operators (C++ [over.match.oper])
3567 // to the candidate set.
3568 OverloadCandidateSet CandidateSet;
3569 if (OverOp != OO_None)
3570 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3571
3572 // Perform overload resolution.
3573 OverloadCandidateSet::iterator Best;
3574 switch (BestViableFunction(CandidateSet, Best)) {
3575 case OR_Success: {
3576 // We found a built-in operator or an overloaded operator.
3577 FunctionDecl *FnDecl = Best->Function;
3578
3579 if (FnDecl) {
3580 // We matched an overloaded operator. Build a call to that
3581 // operator.
3582
3583 // Convert the arguments.
3584 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3585 if (PerformObjectArgumentInitialization(Input, Method))
3586 return true;
3587 } else {
3588 // Convert the arguments.
3589 if (PerformCopyInitialization(Input,
3590 FnDecl->getParamDecl(0)->getType(),
3591 "passing"))
3592 return true;
3593 }
3594
3595 // Determine the result type
3596 QualType ResultTy
3597 = FnDecl->getType()->getAsFunctionType()->getResultType();
3598 ResultTy = ResultTy.getNonReferenceType();
3599
3600 // Build the actual expression node.
3601 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3602 SourceLocation());
3603 UsualUnaryConversions(FnExpr);
3604
3605 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3606 } else {
3607 // We matched a built-in operator. Convert the arguments, then
3608 // break out so that we will build the appropriate built-in
3609 // operator node.
3610 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3611 "passing"))
3612 return true;
3613
3614 break;
3615 }
3616 }
3617
3618 case OR_No_Viable_Function:
3619 // No viable function; fall through to handling this as a
3620 // built-in operator, which will produce an error message for us.
3621 break;
3622
3623 case OR_Ambiguous:
3624 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3625 << UnaryOperator::getOpcodeStr(Opc)
3626 << Input->getSourceRange();
3627 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3628 return true;
3629 }
3630
3631 // Either we found no viable overloaded operator or we matched a
3632 // built-in operator. In either case, fall through to trying to
3633 // build a built-in operation.
3634 }
3635
Reid Spencer5f016e22007-07-11 17:01:13 +00003636 QualType resultType;
3637 switch (Opc) {
3638 default:
3639 assert(0 && "Unimplemented unary expr!");
3640 case UnaryOperator::PreInc:
3641 case UnaryOperator::PreDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00003642 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3643 Opc == UnaryOperator::PreInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003644 break;
3645 case UnaryOperator::AddrOf:
3646 resultType = CheckAddressOfOperand(Input, OpLoc);
3647 break;
3648 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00003649 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00003650 resultType = CheckIndirectionOperand(Input, OpLoc);
3651 break;
3652 case UnaryOperator::Plus:
3653 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003654 UsualUnaryConversions(Input);
3655 resultType = Input->getType();
Douglas Gregor74253732008-11-19 15:42:04 +00003656 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3657 break;
3658 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3659 resultType->isEnumeralType())
3660 break;
3661 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3662 Opc == UnaryOperator::Plus &&
3663 resultType->isPointerType())
3664 break;
3665
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003666 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003667 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003668 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003669 UsualUnaryConversions(Input);
3670 resultType = Input->getType();
Chris Lattner02a65142008-07-25 23:52:49 +00003671 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3672 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3673 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003674 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00003675 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00003676 else if (!resultType->isIntegerType())
Chris Lattnerd3a94e22008-11-20 06:06:08 +00003677 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattnerd1625842008-11-24 06:25:27 +00003678 << resultType << Input->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003679 break;
3680 case UnaryOperator::LNot: // logical negation
3681 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003682 DefaultFunctionArrayConversion(Input);
3683 resultType = Input->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003684 if (!resultType->isScalarType()) // C99 6.5.3.3p1
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 // LNot always has type int. C99 6.5.3.3p5.
3688 resultType = Context.IntTy;
3689 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00003690 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00003691 case UnaryOperator::Imag:
Chris Lattner5d794252007-08-24 21:41:10 +00003692 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattnerdbb36972007-08-24 21:16:53 +00003693 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003694 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00003695 resultType = Input->getType();
3696 break;
3697 }
3698 if (resultType.isNull())
3699 return true;
3700 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3701}
3702
Steve Naroff1b273c42007-09-16 14:56:35 +00003703/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3704Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Reid Spencer5f016e22007-07-11 17:01:13 +00003705 SourceLocation LabLoc,
3706 IdentifierInfo *LabelII) {
3707 // Look up the record for this label identifier.
3708 LabelStmt *&LabelDecl = LabelMap[LabelII];
3709
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00003710 // If we haven't seen this label yet, create a forward reference. It
3711 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Reid Spencer5f016e22007-07-11 17:01:13 +00003712 if (LabelDecl == 0)
3713 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3714
3715 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattner6481a572007-08-03 17:31:20 +00003716 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3717 Context.getPointerType(Context.VoidTy));
Reid Spencer5f016e22007-07-11 17:01:13 +00003718}
3719
Steve Naroff1b273c42007-09-16 14:56:35 +00003720Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003721 SourceLocation RPLoc) { // "({..})"
3722 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3723 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3724 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3725
3726 // FIXME: there are a variety of strange constraints to enforce here, for
3727 // example, it is not possible to goto into a stmt expression apparently.
3728 // More semantic analysis is needed.
3729
3730 // FIXME: the last statement in the compount stmt has its value used. We
3731 // should not warn about it being unused.
3732
3733 // If there are sub stmts in the compound stmt, take the type of the last one
3734 // as the type of the stmtexpr.
3735 QualType Ty = Context.VoidTy;
3736
Chris Lattner611b2ec2008-07-26 19:51:01 +00003737 if (!Compound->body_empty()) {
3738 Stmt *LastStmt = Compound->body_back();
3739 // If LastStmt is a label, skip down through into the body.
3740 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3741 LastStmt = Label->getSubStmt();
3742
3743 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003744 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00003745 }
Chris Lattnerab18c4c2007-07-24 16:58:17 +00003746
3747 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3748}
Steve Naroffd34e9152007-08-01 22:05:33 +00003749
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003750Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3751 SourceLocation BuiltinLoc,
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003752 SourceLocation TypeLoc,
3753 TypeTy *argty,
3754 OffsetOfComponent *CompPtr,
3755 unsigned NumComponents,
3756 SourceLocation RPLoc) {
3757 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3758 assert(!ArgTy.isNull() && "Missing type argument!");
3759
3760 // We must have at least one component that refers to the type, and the first
3761 // one is known to be a field designator. Verify that the ArgTy represents
3762 // a struct/union/class.
3763 if (!ArgTy->isRecordType())
Chris Lattnerd1625842008-11-24 06:25:27 +00003764 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003765
3766 // Otherwise, create a compound literal expression as the base, and
3767 // iteratively process the offsetof designators.
Steve Naroffe9b12192008-01-14 18:19:28 +00003768 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003769
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003770 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3771 // GCC extension, diagnose them.
3772 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003773 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3774 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattner9e2b75c2007-08-31 21:49:13 +00003775
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003776 for (unsigned i = 0; i != NumComponents; ++i) {
3777 const OffsetOfComponent &OC = CompPtr[i];
3778 if (OC.isBrackets) {
3779 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003780 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003781 if (!AT) {
3782 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003783 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003784 }
3785
Chris Lattner704fe352007-08-30 17:59:59 +00003786 // FIXME: C++: Verify that operator[] isn't overloaded.
3787
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003788 // C99 6.5.2.1p1
3789 Expr *Idx = static_cast<Expr*>(OC.U.E);
3790 if (!Idx->getType()->isIntegerType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003791 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3792 << Idx->getSourceRange();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003793
3794 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3795 continue;
3796 }
3797
3798 const RecordType *RC = Res->getType()->getAsRecordType();
3799 if (!RC) {
3800 delete Res;
Chris Lattnerd1625842008-11-24 06:25:27 +00003801 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003802 }
3803
3804 // Get the decl corresponding to this.
3805 RecordDecl *RD = RC->getDecl();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00003806 FieldDecl *MemberDecl
3807 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3808 Decl::IDNS_Ordinary,
3809 S, RD, false, false));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003810 if (!MemberDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00003811 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3812 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner704fe352007-08-30 17:59:59 +00003813
3814 // FIXME: C++: Verify that MemberDecl isn't a static field.
3815 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman51019072008-02-06 22:48:16 +00003816 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3817 // matter here.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003818 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3819 MemberDecl->getType().getNonReferenceType());
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003820 }
3821
3822 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3823 BuiltinLoc);
3824}
3825
3826
Steve Naroff1b273c42007-09-16 14:56:35 +00003827Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroffd34e9152007-08-01 22:05:33 +00003828 TypeTy *arg1, TypeTy *arg2,
3829 SourceLocation RPLoc) {
3830 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3831 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3832
3833 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3834
Chris Lattner73d0d4f2007-08-30 17:45:32 +00003835 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroffd34e9152007-08-01 22:05:33 +00003836}
3837
Steve Naroff1b273c42007-09-16 14:56:35 +00003838Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroffd04fdd52007-08-03 21:21:27 +00003839 ExprTy *expr1, ExprTy *expr2,
3840 SourceLocation RPLoc) {
3841 Expr *CondExpr = static_cast<Expr*>(cond);
3842 Expr *LHSExpr = static_cast<Expr*>(expr1);
3843 Expr *RHSExpr = static_cast<Expr*>(expr2);
3844
3845 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3846
3847 // The conditional expression is required to be a constant expression.
3848 llvm::APSInt condEval(32);
3849 SourceLocation ExpLoc;
3850 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003851 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3852 << CondExpr->getSourceRange();
Steve Naroffd04fdd52007-08-03 21:21:27 +00003853
3854 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3855 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3856 RHSExpr->getType();
3857 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3858}
3859
Steve Naroff4eb206b2008-09-03 18:15:37 +00003860//===----------------------------------------------------------------------===//
3861// Clang Extensions.
3862//===----------------------------------------------------------------------===//
3863
3864/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00003865void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003866 // Analyze block parameters.
3867 BlockSemaInfo *BSI = new BlockSemaInfo();
3868
3869 // Add BSI to CurBlock.
3870 BSI->PrevBlockInfo = CurBlock;
3871 CurBlock = BSI;
3872
3873 BSI->ReturnType = 0;
3874 BSI->TheScope = BlockScope;
3875
Steve Naroff090276f2008-10-10 01:28:17 +00003876 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00003877 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00003878}
3879
3880void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00003881 // Analyze arguments to block.
3882 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3883 "Not a function declarator!");
3884 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3885
Steve Naroff090276f2008-10-10 01:28:17 +00003886 CurBlock->hasPrototype = FTI.hasPrototype;
3887 CurBlock->isVariadic = true;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003888
3889 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3890 // no arguments, not a function that takes a single void argument.
3891 if (FTI.hasPrototype &&
3892 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3893 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3894 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3895 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00003896 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003897 } else if (FTI.hasPrototype) {
3898 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff090276f2008-10-10 01:28:17 +00003899 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3900 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00003901 }
Steve Naroff090276f2008-10-10 01:28:17 +00003902 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3903
3904 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3905 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3906 // If this has an identifier, add it to the scope stack.
3907 if ((*AI)->getIdentifier())
3908 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003909}
3910
3911/// ActOnBlockError - If there is an error parsing a block, this callback
3912/// is invoked to pop the information about the block from the action impl.
3913void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3914 // Ensure that CurBlock is deleted.
3915 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3916
3917 // Pop off CurBlock, handle nested blocks.
3918 CurBlock = CurBlock->PrevBlockInfo;
3919
3920 // FIXME: Delete the ParmVarDecl objects as well???
3921
3922}
3923
3924/// ActOnBlockStmtExpr - This is called when the body of a block statement
3925/// literal was successfully completed. ^(int x){...}
3926Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3927 Scope *CurScope) {
3928 // Ensure that CurBlock is deleted.
3929 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3930 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3931
Steve Naroff090276f2008-10-10 01:28:17 +00003932 PopDeclContext();
3933
Steve Naroff4eb206b2008-09-03 18:15:37 +00003934 // Pop off CurBlock, handle nested blocks.
3935 CurBlock = CurBlock->PrevBlockInfo;
3936
3937 QualType RetTy = Context.VoidTy;
3938 if (BSI->ReturnType)
3939 RetTy = QualType(BSI->ReturnType, 0);
3940
3941 llvm::SmallVector<QualType, 8> ArgTypes;
3942 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3943 ArgTypes.push_back(BSI->Params[i]->getType());
3944
3945 QualType BlockTy;
3946 if (!BSI->hasPrototype)
3947 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3948 else
3949 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00003950 BSI->isVariadic, 0);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003951
3952 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff56ee6892008-10-08 17:01:13 +00003953
Steve Naroff1c90bfc2008-10-08 18:44:00 +00003954 BSI->TheDecl->setBody(Body.take());
3955 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff4eb206b2008-09-03 18:15:37 +00003956}
3957
Nate Begeman67295d02008-01-30 20:50:20 +00003958/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begemane2ce1d92008-01-17 17:46:27 +00003959/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begeman67295d02008-01-30 20:50:20 +00003960/// The number of arguments has already been validated to match the number of
3961/// arguments in FnType.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003962static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3963 ASTContext &Context) {
Nate Begemane2ce1d92008-01-17 17:46:27 +00003964 unsigned NumParams = FnType->getNumArgs();
Nate Begemand6595fa2008-04-18 23:35:14 +00003965 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00003966 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3967 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begemand6595fa2008-04-18 23:35:14 +00003968
3969 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begemane2ce1d92008-01-17 17:46:27 +00003970 return false;
Nate Begemand6595fa2008-04-18 23:35:14 +00003971 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00003972 return true;
3973}
3974
3975Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3976 SourceLocation *CommaLocs,
3977 SourceLocation BuiltinLoc,
3978 SourceLocation RParenLoc) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00003979 // __builtin_overload requires at least 2 arguments
3980 if (NumArgs < 2)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003981 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3982 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003983
Nate Begemane2ce1d92008-01-17 17:46:27 +00003984 // The first argument is required to be a constant expression. It tells us
3985 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begeman796ef3d2008-01-31 05:38:29 +00003986 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begemane2ce1d92008-01-17 17:46:27 +00003987 Expr *NParamsExpr = Args[0];
3988 llvm::APSInt constEval(32);
3989 SourceLocation ExpLoc;
3990 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003991 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3992 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003993
3994 // Verify that the number of parameters is > 0
3995 unsigned NumParams = constEval.getZExtValue();
3996 if (NumParams == 0)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00003997 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3998 << NParamsExpr->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00003999 // Verify that we have at least 1 + NumParams arguments to the builtin.
4000 if ((NumParams + 1) > NumArgs)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004001 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4002 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004003
4004 // Figure out the return type, by matching the args to one of the functions
Nate Begeman67295d02008-01-30 20:50:20 +00004005 // listed after the parameters.
Nate Begeman796ef3d2008-01-31 05:38:29 +00004006 OverloadExpr *OE = 0;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004007 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4008 // UsualUnaryConversions will convert the function DeclRefExpr into a
4009 // pointer to function.
4010 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerb77792e2008-07-26 22:17:49 +00004011 const FunctionTypeProto *FnType = 0;
4012 if (const PointerType *PT = Fn->getType()->getAsPointerType())
4013 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004014
4015 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4016 // parameters, and the number of parameters must match the value passed to
4017 // the builtin.
4018 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004019 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4020 << Fn->getSourceRange();
Nate Begemane2ce1d92008-01-17 17:46:27 +00004021
4022 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begeman67295d02008-01-30 20:50:20 +00004023 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begemane2ce1d92008-01-17 17:46:27 +00004024 // If they match, return a new OverloadExpr.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004025 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begeman796ef3d2008-01-31 05:38:29 +00004026 if (OE)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004027 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4028 << OE->getFn()->getSourceRange();
Nate Begeman796ef3d2008-01-31 05:38:29 +00004029 // Remember our match, and continue processing the remaining arguments
4030 // to catch any errors.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004031 OE = new OverloadExpr(Args, NumArgs, i,
4032 FnType->getResultType().getNonReferenceType(),
Nate Begeman796ef3d2008-01-31 05:38:29 +00004033 BuiltinLoc, RParenLoc);
4034 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004035 }
Nate Begeman796ef3d2008-01-31 05:38:29 +00004036 // Return the newly created OverloadExpr node, if we succeded in matching
4037 // exactly one of the candidate functions.
4038 if (OE)
4039 return OE;
Nate Begemane2ce1d92008-01-17 17:46:27 +00004040
4041 // If we didn't find a matching function Expr in the __builtin_overload list
4042 // the return an error.
4043 std::string typeNames;
Nate Begeman67295d02008-01-30 20:50:20 +00004044 for (unsigned i = 0; i != NumParams; ++i) {
4045 if (i != 0) typeNames += ", ";
4046 typeNames += Args[i+1]->getType().getAsString();
4047 }
Nate Begemane2ce1d92008-01-17 17:46:27 +00004048
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004049 return Diag(BuiltinLoc, diag::err_overload_no_match)
4050 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begemane2ce1d92008-01-17 17:46:27 +00004051}
4052
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004053Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4054 ExprTy *expr, TypeTy *type,
Chris Lattner5cf216b2008-01-04 18:04:52 +00004055 SourceLocation RPLoc) {
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004056 Expr *E = static_cast<Expr*>(expr);
4057 QualType T = QualType::getFromOpaquePtr(type);
4058
4059 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004060
4061 // Get the va_list type
4062 QualType VaListType = Context.getBuiltinVaListType();
4063 // Deal with implicit array decay; for example, on x86-64,
4064 // va_list is an array, but it's supposed to decay to
4065 // a pointer for va_arg.
4066 if (VaListType->isArrayType())
4067 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmanefbe85c2008-08-20 22:17:17 +00004068 // Make sure the input expression also decays appropriately.
4069 UsualUnaryConversions(E);
Eli Friedmanc34bcde2008-08-09 23:32:40 +00004070
4071 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004072 return Diag(E->getLocStart(),
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004073 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00004074 << E->getType() << E->getSourceRange();
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004075
4076 // FIXME: Warn if a non-POD type is passed in.
4077
Douglas Gregor9d293df2008-10-28 00:22:11 +00004078 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00004079}
4080
Douglas Gregor2d8b2732008-11-29 04:51:27 +00004081Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4082 // The type of __null will be int or long, depending on the size of
4083 // pointers on the target.
4084 QualType Ty;
4085 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4086 Ty = Context.IntTy;
4087 else
4088 Ty = Context.LongTy;
4089
4090 return new GNUNullExpr(Ty, TokenLoc);
4091}
4092
Chris Lattner5cf216b2008-01-04 18:04:52 +00004093bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4094 SourceLocation Loc,
4095 QualType DstType, QualType SrcType,
4096 Expr *SrcExpr, const char *Flavor) {
4097 // Decode the result (notice that AST's are still created for extensions).
4098 bool isInvalid = false;
4099 unsigned DiagKind;
4100 switch (ConvTy) {
4101 default: assert(0 && "Unknown conversion type");
4102 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004103 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00004104 DiagKind = diag::ext_typecheck_convert_pointer_int;
4105 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00004106 case IntToPointer:
4107 DiagKind = diag::ext_typecheck_convert_int_pointer;
4108 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004109 case IncompatiblePointer:
4110 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4111 break;
4112 case FunctionVoidPointer:
4113 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4114 break;
4115 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00004116 // If the qualifiers lost were because we were applying the
4117 // (deprecated) C++ conversion from a string literal to a char*
4118 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4119 // Ideally, this check would be performed in
4120 // CheckPointerTypesForAssignment. However, that would require a
4121 // bit of refactoring (so that the second argument is an
4122 // expression, rather than a type), which should be done as part
4123 // of a larger effort to fix CheckPointerTypesForAssignment for
4124 // C++ semantics.
4125 if (getLangOptions().CPlusPlus &&
4126 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4127 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004128 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4129 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004130 case IntToBlockPointer:
4131 DiagKind = diag::err_int_to_block_pointer;
4132 break;
4133 case IncompatibleBlockPointer:
Steve Naroffba80c9a2008-09-24 23:31:10 +00004134 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004135 break;
Steve Naroff39579072008-10-14 22:18:38 +00004136 case IncompatibleObjCQualifiedId:
4137 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4138 // it can give a more specific diagnostic.
4139 DiagKind = diag::warn_incompatible_qualified_id;
4140 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004141 case Incompatible:
4142 DiagKind = diag::err_typecheck_convert_incompatible;
4143 isInvalid = true;
4144 break;
4145 }
4146
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004147 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4148 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00004149 return isInvalid;
4150}
Anders Carlssone21555e2008-11-30 19:50:32 +00004151
4152bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4153{
4154 Expr::EvalResult EvalResult;
4155
4156 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4157 EvalResult.HasSideEffects) {
4158 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4159
4160 if (EvalResult.Diag) {
4161 // We only show the note if it's not the usual "invalid subexpression"
4162 // or if it's actually in a subexpression.
4163 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4164 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4165 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4166 }
4167
4168 return true;
4169 }
4170
4171 if (EvalResult.Diag) {
4172 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4173 E->getSourceRange();
4174
4175 // Print the reason it's not a constant.
4176 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4177 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4178 }
4179
4180 if (Result)
4181 *Result = EvalResult.Val.getInt();
4182 return false;
4183}