blob: 4088f443f75f0737dbc98edc1159af88feb5d611 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +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 Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
Chris Lattner299b8842008-07-25 21:10:04 +000029//===----------------------------------------------------------------------===//
30// Standard Promotions and Conversions
31//===----------------------------------------------------------------------===//
32
Chris Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +000038 if (Ty->isFunctionType())
39 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-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).
Argiris Kirtzidisf580b4d2008-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 Lattner2aa68822008-07-25 21:33:13 +000054 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
55 }
Chris Lattner299b8842008-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 Lattner299b8842008-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 Lattner9305c3d2008-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 Lattner299b8842008-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 Gregor70d26122008-11-12 17:17:38 +0000102
Chris Lattner299b8842008-07-25 21:10:04 +0000103 // For conversion purposes, we ignore any qualifiers.
104 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000105 QualType lhs =
106 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
107 QualType rhs =
108 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-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 Gregor3d4492e2008-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 Gregor70d26122008-11-12 17:17:38 +0000137
Chris Lattner299b8842008-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 Lattner299b8842008-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 Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000174 } else if (result < 0) { // The right side is bigger, convert lhs.
175 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000182 return rhs;
183 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-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 Carlsson488a0792008-12-10 23:30:05 +0000192 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000193 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000194 return lhs;
195 }
Anders Carlsson488a0792008-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 Lattner299b8842008-07-25 21:10:04 +0000201 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000202 return rhs;
203 }
Anders Carlsson488a0792008-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 Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000213 return lhs;
214 }
215 if (result < 0) { // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000216 return rhs;
217 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000218 assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
Chris Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000229 return lhs;
230 }
Chris Lattner299b8842008-07-25 21:10:04 +0000231 return rhs;
232 } else if (lhsComplexInt && rhs->isIntegerType()) {
233 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000234 return lhs;
235 } else if (rhsComplexInt && lhs->isIntegerType()) {
236 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-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 Lattner299b8842008-07-25 21:10:04 +0000265 return destType;
266}
267
268//===----------------------------------------------------------------------===//
269// Semantic Analysis for various Expression Types
270//===----------------------------------------------------------------------===//
271
272
Steve Naroff87d58b42007-09-16 03:34:24 +0000273/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroff87d58b42007-09-16 03:34:24 +0000280Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +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 Lattnera6dcce32008-02-11 00:02:17 +0000290
291 // Verify that pascal strings aren't too large.
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000292 if (Literal.Pascal && Literal.GetStringLength() > 256)
Chris Lattner8ba580c2008-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());
Chris Lattner4b009652007-07-25 00:24:17 +0000296
Chris Lattnera6dcce32008-02-11 00:02:17 +0000297 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000298 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000299 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-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 Lattnera6dcce32008-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
Chris Lattner4b009652007-07-25 00:24:17 +0000312 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
313 return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000314 Literal.AnyWide, StrTy,
Anders Carlsson55bfe0d2007-10-15 02:50:23 +0000315 StringToks[0].getLocation(),
Chris Lattner4b009652007-07-25 00:24:17 +0000316 StringToks[NumStringToks-1].getLocation());
317}
318
Chris Lattnerb2ebd482008-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 Naroff0acc9c92007-09-15 18:49:24 +0000349/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000350/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000351/// identifier is used in a function call context.
Argiris Kirtzidis054a2632008-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 Naroff0acc9c92007-09-15 18:49:24 +0000354Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000355 IdentifierInfo &II,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +0000356 bool HasTrailingLParen,
357 const CXXScopeSpec *SS) {
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000358 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS);
359}
360
361/// ActOnDeclarationNameExpr - The parser has read some kind of name
362/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
363/// performs lookup on that name and returns an expression that refers
364/// to that name. This routine isn't directly called from the parser,
365/// because the parser doesn't know about DeclarationName. Rather,
366/// this routine is called by ActOnIdentifierExpr,
367/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
368/// which form the DeclarationName from the corresponding syntactic
369/// forms.
370///
371/// HasTrailingLParen indicates whether this identifier is used in a
372/// function call context. LookupCtx is only used for a C++
373/// qualified-id (foo::bar) to indicate the class or namespace that
374/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000375///
376/// If ForceResolution is true, then we will attempt to resolve the
377/// name even if it looks like a dependent name. This option is off by
378/// default.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000379Sema::ExprResult Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
380 DeclarationName Name,
381 bool HasTrailingLParen,
Douglas Gregora133e262008-12-06 00:22:45 +0000382 const CXXScopeSpec *SS,
383 bool ForceResolution) {
384 if (S->getTemplateParamParent() && Name.getAsIdentifierInfo() &&
385 HasTrailingLParen && !SS && !ForceResolution) {
386 // We've seen something of the form
387 // identifier(
388 // and we are in a template, so it is likely that 's' is a
389 // dependent name. However, we won't know until we've parsed all
390 // of the call arguments. So, build a CXXDependentNameExpr node
391 // to represent this name. Then, if it turns out that none of the
392 // arguments are type-dependent, we'll force the resolution of the
393 // dependent name at that point.
394 return new CXXDependentNameExpr(Name.getAsIdentifierInfo(),
395 Context.DependentTy, Loc);
396 }
397
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000398 // Could be enum-constant, value decl, instance variable, etc.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000399 Decl *D;
400 if (SS && !SS->isEmpty()) {
401 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
402 if (DC == 0)
403 return true;
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000404 D = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000405 } else
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000406 D = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Douglas Gregora133e262008-12-06 00:22:45 +0000407
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000408 // If this reference is in an Objective-C method, then ivar lookup happens as
409 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000410 IdentifierInfo *II = Name.getAsIdentifierInfo();
411 if (II && getCurMethodDecl()) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000412 ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000413 // There are two cases to handle here. 1) scoped lookup could have failed,
414 // in which case we should look for an ivar. 2) scoped lookup could have
415 // found a decl, but that decl is outside the current method (i.e. a global
416 // variable). In these two cases, we do a lookup for an ivar with this
417 // name, if the lookup suceeds, we replace it our current decl.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000418 if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000419 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000420 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000421 // FIXME: This should use a new expr for a direct reference, don't turn
422 // this into Self->ivar, just return a BareIVarExpr or something.
423 IdentifierInfo &II = Context.Idents.get("self");
424 ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Fariborz Jahanianea944842008-12-18 17:29:46 +0000425 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), Loc,
426 static_cast<Expr*>(SelfExpr.Val), true, true);
427 Context.setFieldDecl(IFace, IV, MRef);
428 return MRef;
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000429 }
430 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000431 // Needed to implement property "super.method" notation.
Chris Lattner87fada82008-11-20 05:35:30 +0000432 if (SD == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000433 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000434 getCurMethodDecl()->getClassInterface()));
Douglas Gregord8606632008-11-04 14:56:14 +0000435 return new ObjCSuperExpr(Loc, T);
Steve Naroff6f786252008-06-02 23:03:37 +0000436 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000437 }
Chris Lattner4b009652007-07-25 00:24:17 +0000438 if (D == 0) {
439 // Otherwise, this could be an implicitly declared function reference (legal
440 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000441 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000442 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000443 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000444 else {
445 // If this name wasn't predeclared and if this is not a function call,
446 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000447 if (SS && !SS->isEmpty())
Chris Lattner77d52da2008-11-20 06:06:08 +0000448 return Diag(Loc, diag::err_typecheck_no_member)
Chris Lattnerb1753422008-11-23 21:45:46 +0000449 << Name << SS->getRange();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000450 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
451 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000452 return Diag(Loc, diag::err_undeclared_use) << Name.getAsString();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000453 else
Chris Lattnerb1753422008-11-23 21:45:46 +0000454 return Diag(Loc, diag::err_undeclared_var_use) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000455 }
456 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000457
Douglas Gregor3257fb52008-12-22 05:46:06 +0000458 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
459 if (!MD->isStatic()) {
460 // C++ [class.mfct.nonstatic]p2:
461 // [...] if name lookup (3.4.1) resolves the name in the
462 // id-expression to a nonstatic nontype member of class X or of
463 // a base class of X, the id-expression is transformed into a
464 // class member access expression (5.2.5) using (*this) (9.3.2)
465 // as the postfix-expression to the left of the '.' operator.
466 DeclContext *Ctx = 0;
467 QualType MemberType;
468 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
469 Ctx = FD->getDeclContext();
470 MemberType = FD->getType();
471
472 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
473 MemberType = RefType->getPointeeType();
474 else if (!FD->isMutable()) {
475 unsigned combinedQualifiers
476 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
477 MemberType = MemberType.getQualifiedType(combinedQualifiers);
478 }
479 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
480 if (!Method->isStatic()) {
481 Ctx = Method->getParent();
482 MemberType = Method->getType();
483 }
484 } else if (OverloadedFunctionDecl *Ovl
485 = dyn_cast<OverloadedFunctionDecl>(D)) {
486 for (OverloadedFunctionDecl::function_iterator
487 Func = Ovl->function_begin(),
488 FuncEnd = Ovl->function_end();
489 Func != FuncEnd; ++Func) {
490 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
491 if (!DMethod->isStatic()) {
492 Ctx = Ovl->getDeclContext();
493 MemberType = Context.OverloadTy;
494 break;
495 }
496 }
497 }
498
499 if (Ctx && Ctx->isCXXRecord()) {
500 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
501 QualType ThisType = Context.getTagDeclType(MD->getParent());
502 if ((Context.getCanonicalType(CtxType)
503 == Context.getCanonicalType(ThisType)) ||
504 IsDerivedFrom(ThisType, CtxType)) {
505 // Build the implicit member access expression.
506 Expr *This = new CXXThisExpr(SourceLocation(),
507 MD->getThisType(Context));
508 return new MemberExpr(This, true, cast<NamedDecl>(D),
509 SourceLocation(), MemberType);
510 }
511 }
512 }
513 }
514
Douglas Gregor8acb7272008-12-11 16:49:14 +0000515 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000516 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
517 if (MD->isStatic())
518 // "invalid use of member 'x' in static member function"
Chris Lattner8ba580c2008-11-19 05:08:23 +0000519 return Diag(Loc, diag::err_invalid_member_use_in_static_method)
Chris Lattner271d4c22008-11-24 05:29:24 +0000520 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000521 }
522
Douglas Gregor3257fb52008-12-22 05:46:06 +0000523 // Any other ways we could have found the field in a well-formed
524 // program would have been turned into implicit member expressions
525 // above.
Chris Lattner271d4c22008-11-24 05:29:24 +0000526 return Diag(Loc, diag::err_invalid_non_static_member_use)
527 << FD->getDeclName();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000528 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000529
Chris Lattner4b009652007-07-25 00:24:17 +0000530 if (isa<TypedefDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000531 return Diag(Loc, diag::err_unexpected_typedef) << Name;
Ted Kremenek42730c52008-01-07 19:49:32 +0000532 if (isa<ObjCInterfaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000533 return Diag(Loc, diag::err_unexpected_interface) << Name;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000534 if (isa<NamespaceDecl>(D))
Chris Lattner271d4c22008-11-24 05:29:24 +0000535 return Diag(Loc, diag::err_unexpected_namespace) << Name;
Chris Lattner4b009652007-07-25 00:24:17 +0000536
Steve Naroffd6163f32008-09-05 22:11:13 +0000537 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000538 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
539 return new DeclRefExpr(Ovl, Context.OverloadTy, Loc);
540
Steve Naroffd6163f32008-09-05 22:11:13 +0000541 ValueDecl *VD = cast<ValueDecl>(D);
542
543 // check if referencing an identifier with __attribute__((deprecated)).
544 if (VD->getAttr<DeprecatedAttr>())
Chris Lattner271d4c22008-11-24 05:29:24 +0000545 Diag(Loc, diag::warn_deprecated) << VD->getDeclName();
Douglas Gregor48840c72008-12-10 23:01:14 +0000546
547 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
548 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
549 Scope *CheckS = S;
550 while (CheckS) {
551 if (CheckS->isWithinElse() &&
552 CheckS->getControlParent()->isDeclScope(Var)) {
553 if (Var->getType()->isBooleanType())
554 Diag(Loc, diag::warn_value_always_false) << Var->getDeclName();
555 else
556 Diag(Loc, diag::warn_value_always_zero) << Var->getDeclName();
557 break;
558 }
559
560 // Move up one more control parent to check again.
561 CheckS = CheckS->getControlParent();
562 if (CheckS)
563 CheckS = CheckS->getParent();
564 }
565 }
566 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000567
568 // Only create DeclRefExpr's for valid Decl's.
569 if (VD->isInvalidDecl())
570 return true;
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000571
572 // If the identifier reference is inside a block, and it refers to a value
573 // that is outside the block, create a BlockDeclRefExpr instead of a
574 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
575 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000576 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000577 // We do not do this for things like enum constants, global variables, etc,
578 // as they do not get snapshotted.
579 //
580 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Steve Naroff52059382008-10-10 01:28:17 +0000581 // The BlocksAttr indicates the variable is bound by-reference.
582 if (VD->getAttr<BlocksAttr>())
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000583 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
584 Loc, true);
Steve Naroff52059382008-10-10 01:28:17 +0000585
586 // Variable will be bound by-copy, make it const within the closure.
587 VD->getType().addConst();
Douglas Gregor0d5d89d2008-10-28 00:22:11 +0000588 return new BlockDeclRefExpr(VD, VD->getType().getNonReferenceType(),
589 Loc, false);
Steve Naroff52059382008-10-10 01:28:17 +0000590 }
591 // If this reference is not in a block or if the referenced variable is
592 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000593
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000594 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000595 bool ValueDependent = false;
596 if (getLangOptions().CPlusPlus) {
597 // C++ [temp.dep.expr]p3:
598 // An id-expression is type-dependent if it contains:
599 // - an identifier that was declared with a dependent type,
600 if (VD->getType()->isDependentType())
601 TypeDependent = true;
602 // - FIXME: a template-id that is dependent,
603 // - a conversion-function-id that specifies a dependent type,
604 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
605 Name.getCXXNameType()->isDependentType())
606 TypeDependent = true;
607 // - a nested-name-specifier that contains a class-name that
608 // names a dependent type.
609 else if (SS && !SS->isEmpty()) {
610 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
611 DC; DC = DC->getParent()) {
612 // FIXME: could stop early at namespace scope.
613 if (DC->isCXXRecord()) {
614 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
615 if (Context.getTypeDeclType(Record)->isDependentType()) {
616 TypeDependent = true;
617 break;
618 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000619 }
620 }
621 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000622
Douglas Gregora5d84612008-12-10 20:57:37 +0000623 // C++ [temp.dep.constexpr]p2:
624 //
625 // An identifier is value-dependent if it is:
626 // - a name declared with a dependent type,
627 if (TypeDependent)
628 ValueDependent = true;
629 // - the name of a non-type template parameter,
630 else if (isa<NonTypeTemplateParmDecl>(VD))
631 ValueDependent = true;
632 // - a constant with integral or enumeration type and is
633 // initialized with an expression that is value-dependent
634 // (FIXME!).
635 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000636
637 return new DeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
638 TypeDependent, ValueDependent);
Chris Lattner4b009652007-07-25 00:24:17 +0000639}
640
Chris Lattner69909292008-08-10 01:53:14 +0000641Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
Chris Lattner4b009652007-07-25 00:24:17 +0000642 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000643 PredefinedExpr::IdentType IT;
Chris Lattner4b009652007-07-25 00:24:17 +0000644
645 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000646 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000647 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
648 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
649 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000650 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000651
Chris Lattner7e637512008-01-12 08:14:25 +0000652 // Pre-defined identifiers are of type char[x], where x is the length of the
653 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000654 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000655 if (FunctionDecl *FD = getCurFunctionDecl())
656 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000657 else if (ObjCMethodDecl *MD = getCurMethodDecl())
658 Length = MD->getSynthesizedMethodSize();
659 else {
660 Diag(Loc, diag::ext_predef_outside_function);
661 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
662 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
663 }
664
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000665
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000666 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000667 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000668 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Chris Lattner69909292008-08-10 01:53:14 +0000669 return new PredefinedExpr(Loc, ResTy, IT);
Chris Lattner4b009652007-07-25 00:24:17 +0000670}
671
Steve Naroff87d58b42007-09-16 03:34:24 +0000672Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000673 llvm::SmallString<16> CharBuffer;
674 CharBuffer.resize(Tok.getLength());
675 const char *ThisTokBegin = &CharBuffer[0];
676 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
677
678 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
679 Tok.getLocation(), PP);
680 if (Literal.hadError())
681 return ExprResult(true);
Chris Lattner6b22fb72008-03-01 08:32:21 +0000682
683 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
684
Chris Lattner1aaf71c2008-06-07 22:35:38 +0000685 return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
686 Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000687}
688
Steve Naroff87d58b42007-09-16 03:34:24 +0000689Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000690 // fast path for a single digit (which is quite common). A single digit
691 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
692 if (Tok.getLength() == 1) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000693 const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000694
Chris Lattner8cd0e932008-03-05 18:54:05 +0000695 unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
Chris Lattner48d7f382008-04-02 04:24:33 +0000696 return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
Chris Lattner4b009652007-07-25 00:24:17 +0000697 Context.IntTy,
698 Tok.getLocation()));
699 }
700 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +0000701 // Add padding so that NumericLiteralParser can overread by one character.
702 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +0000703 const char *ThisTokBegin = &IntegerBuffer[0];
704
705 // Get the spelling of the token, which eliminates trigraphs, etc.
706 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Chris Lattner2e6b4bf2008-09-30 20:51:14 +0000707
Chris Lattner4b009652007-07-25 00:24:17 +0000708 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
709 Tok.getLocation(), PP);
710 if (Literal.hadError)
711 return ExprResult(true);
712
Chris Lattner1de66eb2007-08-26 03:42:43 +0000713 Expr *Res;
714
715 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +0000716 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000717 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +0000718 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000719 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +0000720 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000721 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +0000722 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000723
724 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
725
Ted Kremenekddedbe22007-11-29 00:56:49 +0000726 // isExact will be set by GetFloatValue().
727 bool isExact = false;
Chris Lattner2a674dc2008-06-30 18:32:54 +0000728 Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
Ted Kremenekddedbe22007-11-29 00:56:49 +0000729 Ty, Tok.getLocation());
730
Chris Lattner1de66eb2007-08-26 03:42:43 +0000731 } else if (!Literal.isIntegerLiteral()) {
732 return ExprResult(true);
733 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +0000734 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +0000735
Neil Booth7421e9c2007-08-29 22:00:19 +0000736 // long long is a C99 feature.
737 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +0000738 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +0000739 Diag(Tok.getLocation(), diag::ext_longlong);
740
Chris Lattner4b009652007-07-25 00:24:17 +0000741 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +0000742 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000743
744 if (Literal.GetIntegerValue(ResultVal)) {
745 // If this value didn't fit into uintmax_t, warn and force to ull.
746 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +0000747 Ty = Context.UnsignedLongLongTy;
748 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +0000749 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +0000750 } else {
751 // If this value fits into a ULL, try to figure out what else it fits into
752 // according to the rules of C99 6.4.4.1p5.
753
754 // Octal, Hexadecimal, and integers with a U suffix are allowed to
755 // be an unsigned int.
756 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
757
758 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +0000759 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +0000760 if (!Literal.isLong && !Literal.isLongLong) {
761 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +0000762 unsigned IntSize = Context.Target.getIntWidth();
763
Chris Lattner4b009652007-07-25 00:24:17 +0000764 // Does it fit in a unsigned int?
765 if (ResultVal.isIntN(IntSize)) {
766 // Does it fit in a signed int?
767 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000768 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000769 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000770 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000771 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000772 }
Chris Lattner4b009652007-07-25 00:24:17 +0000773 }
774
775 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +0000776 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +0000777 unsigned LongSize = Context.Target.getLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000778
779 // Does it fit in a unsigned long?
780 if (ResultVal.isIntN(LongSize)) {
781 // Does it fit in a signed long?
782 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000783 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000784 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000785 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000786 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000787 }
Chris Lattner4b009652007-07-25 00:24:17 +0000788 }
789
790 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +0000791 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +0000792 unsigned LongLongSize = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000793
794 // Does it fit in a unsigned long long?
795 if (ResultVal.isIntN(LongLongSize)) {
796 // Does it fit in a signed long long?
797 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +0000798 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +0000799 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +0000800 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000801 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +0000802 }
803 }
804
805 // If we still couldn't decide a type, we probably have something that
806 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +0000807 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000808 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +0000809 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +0000810 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +0000811 }
Chris Lattnere4068872008-05-09 05:59:00 +0000812
813 if (ResultVal.getBitWidth() != Width)
814 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +0000815 }
816
Chris Lattner48d7f382008-04-02 04:24:33 +0000817 Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +0000818 }
Chris Lattner1de66eb2007-08-26 03:42:43 +0000819
820 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
821 if (Literal.isImaginary)
822 Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
823
824 return Res;
Chris Lattner4b009652007-07-25 00:24:17 +0000825}
826
Steve Naroff87d58b42007-09-16 03:34:24 +0000827Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
Chris Lattner4b009652007-07-25 00:24:17 +0000828 ExprTy *Val) {
Chris Lattner48d7f382008-04-02 04:24:33 +0000829 Expr *E = (Expr *)Val;
830 assert((E != 0) && "ActOnParenExpr() missing expr");
831 return new ParenExpr(L, R, E);
Chris Lattner4b009652007-07-25 00:24:17 +0000832}
833
834/// The UsualUnaryConversions() function is *not* called by this routine.
835/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000836bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
837 SourceLocation OpLoc,
838 const SourceRange &ExprRange,
839 bool isSizeof) {
Chris Lattner4b009652007-07-25 00:24:17 +0000840 // C99 6.5.3.4p1:
841 if (isa<FunctionType>(exprType) && isSizeof)
842 // alignof(function) is allowed.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000843 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
Chris Lattner4b009652007-07-25 00:24:17 +0000844 else if (exprType->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +0000845 Diag(OpLoc, diag::ext_sizeof_void_type)
846 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
847 else if (exprType->isIncompleteType())
848 return Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
849 diag::err_alignof_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000850 << exprType << ExprRange;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000851
852 return false;
Chris Lattner4b009652007-07-25 00:24:17 +0000853}
854
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000855/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
856/// the same for @c alignof and @c __alignof
857/// Note that the ArgRange is invalid if isType is false.
858Action::ExprResult
859Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
860 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +0000861 // If error parsing type, ignore.
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000862 if (TyOrEx == 0) return true;
Chris Lattner4b009652007-07-25 00:24:17 +0000863
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000864 QualType ArgTy;
865 SourceRange Range;
866 if (isType) {
867 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
868 Range = ArgRange;
869 } else {
870 // Get the end location.
871 Expr *ArgEx = (Expr *)TyOrEx;
872 Range = ArgEx->getSourceRange();
873 ArgTy = ArgEx->getType();
874 }
875
876 // Verify that the operand is valid.
877 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
Chris Lattner4b009652007-07-25 00:24:17 +0000878 return true;
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000879
880 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
881 return new SizeOfAlignOfExpr(isSizeof, isType, TyOrEx, Context.getSizeType(),
882 OpLoc, Range.getEnd());
Chris Lattner4b009652007-07-25 00:24:17 +0000883}
884
Chris Lattner5110ad52007-08-24 21:41:10 +0000885QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
Chris Lattner03931a72007-08-24 21:16:53 +0000886 DefaultFunctionArrayConversion(V);
887
Chris Lattnera16e42d2007-08-26 05:39:26 +0000888 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +0000889 if (const ComplexType *CT = V->getType()->getAsComplexType())
890 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000891
892 // Otherwise they pass through real integer and floating point types here.
893 if (V->getType()->isArithmeticType())
894 return V->getType();
895
896 // Reject anything else.
Chris Lattner4bfd2232008-11-24 06:25:27 +0000897 Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
Chris Lattnera16e42d2007-08-26 05:39:26 +0000898 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +0000899}
900
901
Chris Lattner4b009652007-07-25 00:24:17 +0000902
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000903Action::ExprResult Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +0000904 tok::TokenKind Kind,
905 ExprTy *Input) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000906 Expr *Arg = (Expr *)Input;
907
Chris Lattner4b009652007-07-25 00:24:17 +0000908 UnaryOperator::Opcode Opc;
909 switch (Kind) {
910 default: assert(0 && "Unknown unary op!");
911 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
912 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
913 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +0000914
915 if (getLangOptions().CPlusPlus &&
916 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
917 // Which overloaded operator?
918 OverloadedOperatorKind OverOp =
919 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
920
921 // C++ [over.inc]p1:
922 //
923 // [...] If the function is a member function with one
924 // parameter (which shall be of type int) or a non-member
925 // function with two parameters (the second of which shall be
926 // of type int), it defines the postfix increment operator ++
927 // for objects of that type. When the postfix increment is
928 // called as a result of using the ++ operator, the int
929 // argument will have value zero.
930 Expr *Args[2] = {
931 Arg,
932 new IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
933 /*isSigned=*/true),
934 Context.IntTy, SourceLocation())
935 };
936
937 // Build the candidate set for overloading
938 OverloadCandidateSet CandidateSet;
939 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
940
941 // Perform overload resolution.
942 OverloadCandidateSet::iterator Best;
943 switch (BestViableFunction(CandidateSet, Best)) {
944 case OR_Success: {
945 // We found a built-in operator or an overloaded operator.
946 FunctionDecl *FnDecl = Best->Function;
947
948 if (FnDecl) {
949 // We matched an overloaded operator. Build a call to that
950 // operator.
951
952 // Convert the arguments.
953 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
954 if (PerformObjectArgumentInitialization(Arg, Method))
955 return true;
956 } else {
957 // Convert the arguments.
958 if (PerformCopyInitialization(Arg,
959 FnDecl->getParamDecl(0)->getType(),
960 "passing"))
961 return true;
962 }
963
964 // Determine the result type
965 QualType ResultTy
966 = FnDecl->getType()->getAsFunctionType()->getResultType();
967 ResultTy = ResultTy.getNonReferenceType();
968
969 // Build the actual expression node.
970 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
971 SourceLocation());
972 UsualUnaryConversions(FnExpr);
973
974 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, OpLoc);
975 } else {
976 // We matched a built-in operator. Convert the arguments, then
977 // break out so that we will build the appropriate built-in
978 // operator node.
979 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
980 "passing"))
981 return true;
982
983 break;
984 }
985 }
986
987 case OR_No_Viable_Function:
988 // No viable function; fall through to handling this as a
989 // built-in operator, which will produce an error message for us.
990 break;
991
992 case OR_Ambiguous:
993 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
994 << UnaryOperator::getOpcodeStr(Opc)
995 << Arg->getSourceRange();
996 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
997 return true;
998 }
999
1000 // Either we found no viable overloaded operator or we matched a
1001 // built-in operator. In either case, fall through to trying to
1002 // build a built-in operation.
1003 }
1004
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001005 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1006 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001007 if (result.isNull())
1008 return true;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001009 return new UnaryOperator(Arg, Opc, result, OpLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001010}
1011
1012Action::ExprResult Sema::
Douglas Gregor80723c52008-11-19 17:17:41 +00001013ActOnArraySubscriptExpr(Scope *S, ExprTy *Base, SourceLocation LLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001014 ExprTy *Idx, SourceLocation RLoc) {
1015 Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
1016
Douglas Gregor80723c52008-11-19 17:17:41 +00001017 if (getLangOptions().CPlusPlus &&
Eli Friedmane658bf52008-12-15 22:34:21 +00001018 (LHSExp->getType()->isRecordType() ||
1019 LHSExp->getType()->isEnumeralType() ||
1020 RHSExp->getType()->isRecordType() ||
1021 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001022 // Add the appropriate overloaded operators (C++ [over.match.oper])
1023 // to the candidate set.
1024 OverloadCandidateSet CandidateSet;
1025 Expr *Args[2] = { LHSExp, RHSExp };
1026 AddOperatorCandidates(OO_Subscript, S, Args, 2, CandidateSet);
1027
1028 // Perform overload resolution.
1029 OverloadCandidateSet::iterator Best;
1030 switch (BestViableFunction(CandidateSet, Best)) {
1031 case OR_Success: {
1032 // We found a built-in operator or an overloaded operator.
1033 FunctionDecl *FnDecl = Best->Function;
1034
1035 if (FnDecl) {
1036 // We matched an overloaded operator. Build a call to that
1037 // operator.
1038
1039 // Convert the arguments.
1040 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1041 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1042 PerformCopyInitialization(RHSExp,
1043 FnDecl->getParamDecl(0)->getType(),
1044 "passing"))
1045 return true;
1046 } else {
1047 // Convert the arguments.
1048 if (PerformCopyInitialization(LHSExp,
1049 FnDecl->getParamDecl(0)->getType(),
1050 "passing") ||
1051 PerformCopyInitialization(RHSExp,
1052 FnDecl->getParamDecl(1)->getType(),
1053 "passing"))
1054 return true;
1055 }
1056
1057 // Determine the result type
1058 QualType ResultTy
1059 = FnDecl->getType()->getAsFunctionType()->getResultType();
1060 ResultTy = ResultTy.getNonReferenceType();
1061
1062 // Build the actual expression node.
1063 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
1064 SourceLocation());
1065 UsualUnaryConversions(FnExpr);
1066
1067 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, LLoc);
1068 } else {
1069 // We matched a built-in operator. Convert the arguments, then
1070 // break out so that we will build the appropriate built-in
1071 // operator node.
1072 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1073 "passing") ||
1074 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1075 "passing"))
1076 return true;
1077
1078 break;
1079 }
1080 }
1081
1082 case OR_No_Viable_Function:
1083 // No viable function; fall through to handling this as a
1084 // built-in operator, which will produce an error message for us.
1085 break;
1086
1087 case OR_Ambiguous:
1088 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1089 << "[]"
1090 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1091 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1092 return true;
1093 }
1094
1095 // Either we found no viable overloaded operator or we matched a
1096 // built-in operator. In either case, fall through to trying to
1097 // build a built-in operation.
1098 }
1099
Chris Lattner4b009652007-07-25 00:24:17 +00001100 // Perform default conversions.
1101 DefaultFunctionArrayConversion(LHSExp);
1102 DefaultFunctionArrayConversion(RHSExp);
1103
1104 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1105
1106 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001107 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Chris Lattner4b009652007-07-25 00:24:17 +00001108 // in the subscript position. As a result, we need to derive the array base
1109 // and index from the expression types.
1110 Expr *BaseExpr, *IndexExpr;
1111 QualType ResultType;
Chris Lattner7931f4a2007-07-31 16:53:04 +00001112 if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001113 BaseExpr = LHSExp;
1114 IndexExpr = RHSExp;
1115 // FIXME: need to deal with const...
1116 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001117 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001118 // Handle the uncommon case of "123[Ptr]".
1119 BaseExpr = RHSExp;
1120 IndexExpr = LHSExp;
1121 // FIXME: need to deal with const...
1122 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001123 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1124 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001125 IndexExpr = RHSExp;
Steve Naroff89345522007-08-03 22:40:33 +00001126
1127 // Component access limited to variables (reject vec4.rg[1]).
Nate Begemanc8e51f82008-05-09 06:41:27 +00001128 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1129 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001130 return Diag(LLoc, diag::err_ext_vector_component_access)
1131 << SourceRange(LLoc, RLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001132 // FIXME: need to deal with const...
1133 ResultType = VTy->getElementType();
1134 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001135 return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value)
1136 << RHSExp->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001137 }
1138 // C99 6.5.2.1p1
1139 if (!IndexExpr->getType()->isIntegerType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001140 return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript)
1141 << IndexExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001142
1143 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1144 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001145 // void (*)(int)) and pointers to incomplete types. Functions are not
1146 // objects in C99.
Chris Lattner4b009652007-07-25 00:24:17 +00001147 if (!ResultType->isObjectType())
1148 return Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001149 diag::err_typecheck_subscript_not_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001150 << BaseExpr->getType() << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001151
1152 return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
1153}
1154
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001155QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001156CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001157 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001158 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001159
1160 // This flag determines whether or not the component is to be treated as a
1161 // special name, or a regular GLSL-style component access.
1162 bool SpecialComponent = false;
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001163
1164 // The vector accessor can't exceed the number of elements.
1165 const char *compStr = CompName.getName();
1166 if (strlen(compStr) > vecType->getNumElements()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001167 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001168 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001169 return QualType();
1170 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001171
1172 // Check that we've found one of the special components, or that the component
1173 // names must come from the same set.
1174 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1175 !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
1176 SpecialComponent = true;
1177 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001178 do
1179 compStr++;
1180 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1181 } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
1182 do
1183 compStr++;
1184 while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
1185 } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
1186 do
1187 compStr++;
1188 while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
1189 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001190
Nate Begemanc8e51f82008-05-09 06:41:27 +00001191 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001192 // We didn't get to the end of the string. This means the component names
1193 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001194 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1195 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001196 return QualType();
1197 }
1198 // Each component accessor can't exceed the vector type.
1199 compStr = CompName.getName();
1200 while (*compStr) {
1201 if (vecType->isAccessorWithinNumElements(*compStr))
1202 compStr++;
1203 else
1204 break;
1205 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001206 if (!SpecialComponent && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001207 // We didn't get to the end of the string. This means a component accessor
1208 // exceeds the number of elements in the vector.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001209 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001210 << baseType << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001211 return QualType();
1212 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001213
1214 // If we have a special component name, verify that the current vector length
1215 // is an even number, since all special component names return exactly half
1216 // the elements.
1217 if (SpecialComponent && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001218 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001219 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001220 return QualType();
1221 }
1222
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001223 // The component accessor looks fine - now we need to compute the actual type.
1224 // The vector type is implied by the component accessor. For example,
1225 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001226 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1227 unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
Chris Lattner65cae292008-11-19 08:23:25 +00001228 : CompName.getLength();
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001229 if (CompSize == 1)
1230 return vecType->getElementType();
Steve Naroff82113e32007-07-29 16:33:31 +00001231
Nate Begemanaf6ed502008-04-18 23:10:10 +00001232 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Steve Naroff82113e32007-07-29 16:33:31 +00001233 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001234 // diagostics look bad. We want extended vector types to appear built-in.
1235 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1236 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1237 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001238 }
1239 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001240}
1241
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001242/// constructSetterName - Return the setter name for the given
1243/// identifier, i.e. "set" + Name where the initial character of Name
1244/// has been capitalized.
1245// FIXME: Merge with same routine in Parser. But where should this
1246// live?
1247static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1248 const IdentifierInfo *Name) {
1249 llvm::SmallString<100> SelectorName;
1250 SelectorName = "set";
1251 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1252 SelectorName[3] = toupper(SelectorName[3]);
1253 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1254}
1255
Chris Lattner4b009652007-07-25 00:24:17 +00001256Action::ExprResult Sema::
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001257ActOnMemberReferenceExpr(Scope *S, ExprTy *Base, SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001258 tok::TokenKind OpKind, SourceLocation MemberLoc,
1259 IdentifierInfo &Member) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001260 Expr *BaseExpr = static_cast<Expr *>(Base);
1261 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001262
1263 // Perform default conversions.
1264 DefaultFunctionArrayConversion(BaseExpr);
Chris Lattner4b009652007-07-25 00:24:17 +00001265
Steve Naroff2cb66382007-07-26 03:11:44 +00001266 QualType BaseType = BaseExpr->getType();
1267 assert(!BaseType.isNull() && "no type for member expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001268
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001269 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1270 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001271 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001272 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001273 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001274 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001275 return BuildOverloadedArrowExpr(S, BaseExpr, OpLoc, MemberLoc, Member);
Steve Naroff2cb66382007-07-26 03:11:44 +00001276 else
Chris Lattner8ba580c2008-11-19 05:08:23 +00001277 return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001278 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001279 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001280
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001281 // Handle field access to simple records. This also handles access to fields
1282 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001283 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001284 RecordDecl *RDecl = RTy->getDecl();
1285 if (RTy->isIncompleteType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001286 return Diag(OpLoc, diag::err_typecheck_incomplete_tag)
Chris Lattner271d4c22008-11-24 05:29:24 +00001287 << RDecl->getDeclName() << BaseExpr->getSourceRange();
Steve Naroff2cb66382007-07-26 03:11:44 +00001288 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001289 // FIXME: Qualified name lookup for C++ is a bit more complicated
1290 // than this.
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001291 Decl *MemberDecl = LookupDecl(DeclarationName(&Member), Decl::IDNS_Ordinary,
1292 S, RDecl, false, false);
1293 if (!MemberDecl)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001294 return Diag(MemberLoc, diag::err_typecheck_no_member)
Chris Lattner65cae292008-11-19 08:23:25 +00001295 << &Member << BaseExpr->getSourceRange();
Douglas Gregor8acb7272008-12-11 16:49:14 +00001296
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001297 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor82d44772008-12-20 23:49:58 +00001298 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1299 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001300 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001301 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1302 MemberType = Ref->getPointeeType();
1303 else {
1304 unsigned combinedQualifiers =
1305 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001306 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001307 combinedQualifiers &= ~QualType::Const;
1308 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1309 }
Eli Friedman76b49832008-02-06 22:48:16 +00001310
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001311 return new MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
Douglas Gregor82d44772008-12-20 23:49:58 +00001312 MemberLoc, MemberType);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001313 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001314 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Var, MemberLoc,
1315 Var->getType().getNonReferenceType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001316 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001317 return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberFn, MemberLoc,
1318 MemberFn->getType());
1319 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001320 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001321 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl, MemberLoc,
1322 Context.OverloadTy);
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001323 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001324 return new MemberExpr(BaseExpr, OpKind == tok::arrow, Enum, MemberLoc,
1325 Enum->getType());
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001326 else if (isa<TypeDecl>(MemberDecl))
Douglas Gregor82d44772008-12-20 23:49:58 +00001327 return Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1328 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Eli Friedman76b49832008-02-06 22:48:16 +00001329
Douglas Gregor82d44772008-12-20 23:49:58 +00001330 // We found a declaration kind that we didn't expect. This is a
1331 // generic error message that tells the user that she can't refer
1332 // to this member with '.' or '->'.
1333 return Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1334 << DeclarationName(&Member) << int(OpKind == tok::arrow);
Chris Lattnera57cf472008-07-21 04:28:12 +00001335 }
1336
Chris Lattnere9d71612008-07-21 04:59:05 +00001337 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1338 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001339 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001340 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Fariborz Jahanianea944842008-12-18 17:29:46 +00001341 ObjCIvarRefExpr *MRef= new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc,
1342 BaseExpr,
1343 OpKind == tok::arrow);
1344 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1345 return MRef;
Fariborz Jahanian09772392008-12-13 22:20:28 +00001346 }
Chris Lattner8ba580c2008-11-19 05:08:23 +00001347 return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Chris Lattner271d4c22008-11-24 05:29:24 +00001348 << IFTy->getDecl()->getDeclName() << &Member
Chris Lattner8ba580c2008-11-19 05:08:23 +00001349 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001350 }
1351
Chris Lattnere9d71612008-07-21 04:59:05 +00001352 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1353 // pointer to a (potentially qualified) interface type.
1354 const PointerType *PTy;
1355 const ObjCInterfaceType *IFTy;
1356 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1357 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1358 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001359
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001360 // Search for a declared property first.
Chris Lattnere9d71612008-07-21 04:59:05 +00001361 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1362 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
1363
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001364 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001365 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1366 E = IFTy->qual_end(); I != E; ++I)
1367 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1368 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001369
1370 // If that failed, look for an "implicit" property by seeing if the nullary
1371 // selector is implemented.
1372
1373 // FIXME: The logic for looking up nullary and unary selectors should be
1374 // shared with the code in ActOnInstanceMessage.
1375
1376 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1377 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1378
1379 // If this reference is in an @implementation, check for 'private' methods.
1380 if (!Getter)
1381 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1382 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1383 if (ObjCImplementationDecl *ImpDecl =
1384 ObjCImplementations[ClassDecl->getIdentifier()])
1385 Getter = ImpDecl->getInstanceMethod(Sel);
1386
Steve Naroff04151f32008-10-22 19:16:27 +00001387 // Look through local category implementations associated with the class.
1388 if (!Getter) {
1389 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1390 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1391 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1392 }
1393 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001394 if (Getter) {
1395 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001396 // will look for the matching setter, in case it is needed.
1397 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1398 &Member);
1399 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1400 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1401 if (!Setter) {
1402 // If this reference is in an @implementation, also check for 'private'
1403 // methods.
1404 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1405 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1406 if (ObjCImplementationDecl *ImpDecl =
1407 ObjCImplementations[ClassDecl->getIdentifier()])
1408 Setter = ImpDecl->getInstanceMethod(SetterSel);
1409 }
1410 // Look through local category implementations associated with the class.
1411 if (!Setter) {
1412 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1413 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1414 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1415 }
1416 }
1417
1418 // FIXME: we must check that the setter has property type.
1419 return new ObjCKVCRefExpr(Getter, Getter->getResultType(), Setter,
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00001420 MemberLoc, BaseExpr);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001421 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001422
1423 return Diag(MemberLoc, diag::err_property_not_found) <<
1424 &Member << BaseType;
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001425 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001426 // Handle properties on qualified "id" protocols.
1427 const ObjCQualifiedIdType *QIdTy;
1428 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1429 // Check protocols on qualified interfaces.
1430 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001431 E = QIdTy->qual_end(); I != E; ++I) {
Steve Naroffd1d44402008-10-20 22:53:06 +00001432 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1433 return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001434 // Also must look for a getter name which uses property syntax.
1435 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1436 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1437 return new ObjCMessageExpr(BaseExpr, Sel, OMD->getResultType(), OMD,
1438 OpLoc, MemberLoc, NULL, 0);
1439 }
1440 }
Anders Carlsson96095fc2008-12-19 17:27:57 +00001441
1442 return Diag(MemberLoc, diag::err_property_not_found) <<
1443 &Member << BaseType;
Steve Naroffd1d44402008-10-20 22:53:06 +00001444 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001445 // Handle 'field access' to vectors, such as 'V.xx'.
1446 if (BaseType->isExtVectorType() && OpKind == tok::period) {
1447 // Component access limited to variables (reject vec4.rg.g).
1448 if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
1449 !isa<ExtVectorElementExpr>(BaseExpr))
Chris Lattner8ba580c2008-11-19 05:08:23 +00001450 return Diag(MemberLoc, diag::err_ext_vector_component_access)
1451 << BaseExpr->getSourceRange();
Chris Lattnera57cf472008-07-21 04:28:12 +00001452 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1453 if (ret.isNull())
1454 return true;
1455 return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
1456 }
1457
Chris Lattner8ba580c2008-11-19 05:08:23 +00001458 return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001459 << BaseType << BaseExpr->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001460}
1461
Douglas Gregor3257fb52008-12-22 05:46:06 +00001462/// ConvertArgumentsForCall - Converts the arguments specified in
1463/// Args/NumArgs to the parameter types of the function FDecl with
1464/// function prototype Proto. Call is the call expression itself, and
1465/// Fn is the function expression. For a C++ member function, this
1466/// routine does not attempt to convert the object argument. Returns
1467/// true if the call is ill-formed.
1468bool
1469Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1470 FunctionDecl *FDecl,
1471 const FunctionTypeProto *Proto,
1472 Expr **Args, unsigned NumArgs,
1473 SourceLocation RParenLoc) {
1474 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1475 // assignment, to the types of the corresponding parameter, ...
1476 unsigned NumArgsInProto = Proto->getNumArgs();
1477 unsigned NumArgsToCheck = NumArgs;
1478
1479 // If too few arguments are available (and we don't have default
1480 // arguments for the remaining parameters), don't make the call.
1481 if (NumArgs < NumArgsInProto) {
1482 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1483 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1484 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1485 // Use default arguments for missing arguments
1486 NumArgsToCheck = NumArgsInProto;
1487 Call->setNumArgs(NumArgsInProto);
1488 }
1489
1490 // If too many are passed and not variadic, error on the extras and drop
1491 // them.
1492 if (NumArgs > NumArgsInProto) {
1493 if (!Proto->isVariadic()) {
1494 Diag(Args[NumArgsInProto]->getLocStart(),
1495 diag::err_typecheck_call_too_many_args)
1496 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1497 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1498 Args[NumArgs-1]->getLocEnd());
1499 // This deletes the extra arguments.
1500 Call->setNumArgs(NumArgsInProto);
1501 }
1502 NumArgsToCheck = NumArgsInProto;
1503 }
1504
1505 // Continue to check argument types (even if we have too few/many args).
1506 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1507 QualType ProtoArgType = Proto->getArgType(i);
1508
1509 Expr *Arg;
1510 if (i < NumArgs)
1511 Arg = Args[i];
1512 else
1513 Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1514 QualType ArgType = Arg->getType();
1515
1516 // Pass the argument.
1517 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1518 return true;
1519
1520 Call->setArg(i, Arg);
1521 }
1522
1523 // If this is a variadic call, handle args passed through "...".
1524 if (Proto->isVariadic()) {
1525 // Promote the arguments (C99 6.5.2.2p7).
1526 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1527 Expr *Arg = Args[i];
1528 DefaultArgumentPromotion(Arg);
1529 Call->setArg(i, Arg);
1530 }
1531 }
1532
1533 return false;
1534}
1535
Steve Naroff87d58b42007-09-16 03:34:24 +00001536/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00001537/// This provides the location of the left/right parens and a list of comma
1538/// locations.
Douglas Gregor3257fb52008-12-22 05:46:06 +00001539Action::ExprResult
1540Sema::ActOnCallExpr(Scope *S, ExprTy *fn, SourceLocation LParenLoc,
1541 ExprTy **args, unsigned NumArgs,
1542 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Chris Lattner4b009652007-07-25 00:24:17 +00001543 Expr *Fn = static_cast<Expr *>(fn);
1544 Expr **Args = reinterpret_cast<Expr**>(args);
1545 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00001546 FunctionDecl *FDecl = NULL;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001547 OverloadedFunctionDecl *Ovl = NULL;
1548
Douglas Gregora133e262008-12-06 00:22:45 +00001549 // Determine whether this is a dependent call inside a C++ template,
1550 // in which case we won't do any semantic analysis now.
1551 bool Dependent = false;
1552 if (Fn->isTypeDependent()) {
1553 if (CXXDependentNameExpr *FnName = dyn_cast<CXXDependentNameExpr>(Fn)) {
1554 if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1555 Dependent = true;
1556 else {
1557 // Resolve the CXXDependentNameExpr to an actual identifier;
1558 // it wasn't really a dependent name after all.
1559 ExprResult Resolved
1560 = ActOnDeclarationNameExpr(S, FnName->getLocation(), FnName->getName(),
1561 /*HasTrailingLParen=*/true,
1562 /*SS=*/0,
1563 /*ForceResolution=*/true);
1564 if (Resolved.isInvalid)
1565 return true;
1566 else {
1567 delete Fn;
1568 Fn = (Expr *)Resolved.Val;
1569 }
1570 }
1571 } else
1572 Dependent = true;
1573 } else
1574 Dependent = Expr::hasAnyTypeDependentArguments(Args, NumArgs);
1575
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001576 // FIXME: Will need to cache the results of name lookup (including
1577 // ADL) in Fn.
Douglas Gregora133e262008-12-06 00:22:45 +00001578 if (Dependent)
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001579 return new CallExpr(Fn, Args, NumArgs, Context.DependentTy, RParenLoc);
1580
Douglas Gregor3257fb52008-12-22 05:46:06 +00001581 // Determine whether this is a call to an object (C++ [over.call.object]).
1582 if (getLangOptions().CPlusPlus && Fn->getType()->isRecordType())
1583 return BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1584 CommaLocs, RParenLoc);
1585
1586 // Determine whether this is a call to a member function.
1587 if (getLangOptions().CPlusPlus) {
1588 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1589 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1590 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1591 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1592 CommaLocs, RParenLoc);
1593 }
1594
Douglas Gregord2baafd2008-10-21 16:13:35 +00001595 // If we're directly calling a function or a set of overloaded
1596 // functions, get the appropriate declaration.
1597 {
1598 DeclRefExpr *DRExpr = NULL;
1599 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1600 DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr());
1601 else
1602 DRExpr = dyn_cast<DeclRefExpr>(Fn);
1603
1604 if (DRExpr) {
1605 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1606 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1607 }
1608 }
1609
Douglas Gregord2baafd2008-10-21 16:13:35 +00001610 if (Ovl) {
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001611 FDecl = ResolveOverloadedCallFn(Fn, Ovl, LParenLoc, Args, NumArgs, CommaLocs,
1612 RParenLoc);
1613 if (!FDecl)
Douglas Gregord2baafd2008-10-21 16:13:35 +00001614 return true;
1615
Douglas Gregorbf4f0582008-11-26 06:01:48 +00001616 // Update Fn to refer to the actual function selected.
1617 Expr *NewFn = new DeclRefExpr(FDecl, FDecl->getType(),
1618 Fn->getSourceRange().getBegin());
1619 Fn->Destroy(Context);
1620 Fn = NewFn;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001621 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001622
1623 // Promote the function operand.
1624 UsualUnaryConversions(Fn);
1625
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001626 // Make the call expr early, before semantic checks. This guarantees cleanup
1627 // of arguments and function on error.
Chris Lattner97316c02008-04-10 02:22:51 +00001628 llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001629 Context.BoolTy, RParenLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001630
Steve Naroffd6163f32008-09-05 22:11:13 +00001631 const FunctionType *FuncT;
1632 if (!Fn->getType()->isBlockPointerType()) {
1633 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1634 // have type pointer to function".
1635 const PointerType *PT = Fn->getType()->getAsPointerType();
1636 if (PT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001637 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001638 << Fn->getType() << Fn->getSourceRange();
Steve Naroffd6163f32008-09-05 22:11:13 +00001639 FuncT = PT->getPointeeType()->getAsFunctionType();
1640 } else { // This is a block call.
1641 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1642 getAsFunctionType();
1643 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001644 if (FuncT == 0)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001645 return Diag(LParenLoc, diag::err_typecheck_call_not_function)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001646 << Fn->getType() << Fn->getSourceRange();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001647
1648 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00001649 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Chris Lattner4b009652007-07-25 00:24:17 +00001650
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001651 if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001652 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1653 RParenLoc))
1654 return true;
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001655 } else {
1656 assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1657
Steve Naroffdb65e052007-08-28 23:30:39 +00001658 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001659 for (unsigned i = 0; i != NumArgs; i++) {
1660 Expr *Arg = Args[i];
1661 DefaultArgumentPromotion(Arg);
1662 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00001663 }
Chris Lattner4b009652007-07-25 00:24:17 +00001664 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001665
Douglas Gregor3257fb52008-12-22 05:46:06 +00001666 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1667 if (!Method->isStatic())
1668 return Diag(LParenLoc, diag::err_member_call_without_object)
1669 << Fn->getSourceRange();
1670
Chris Lattner2e64c072007-08-10 20:18:51 +00001671 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00001672 if (FDecl)
1673 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00001674
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001675 return TheCall.take();
Chris Lattner4b009652007-07-25 00:24:17 +00001676}
1677
1678Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001679ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001680 SourceLocation RParenLoc, ExprTy *InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001681 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00001682 QualType literalType = QualType::getFromOpaquePtr(Ty);
1683 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00001684 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Chris Lattner4b009652007-07-25 00:24:17 +00001685 Expr *literalExpr = static_cast<Expr*>(InitExpr);
Anders Carlsson9374b852007-12-05 07:24:19 +00001686
Eli Friedman8c2173d2008-05-20 05:22:08 +00001687 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001688 if (literalType->isVariableArrayType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00001689 return Diag(LParenLoc, diag::err_variable_object_no_init)
1690 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001691 } else if (literalType->isIncompleteType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001692 return Diag(LParenLoc, diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +00001693 << literalType
Chris Lattner8ba580c2008-11-19 05:08:23 +00001694 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd());
Eli Friedman8c2173d2008-05-20 05:22:08 +00001695 }
1696
Douglas Gregor6428e762008-11-05 15:29:30 +00001697 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001698 DeclarationName()))
Steve Naroff92590f92008-01-09 20:58:06 +00001699 return true;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001700
Chris Lattnere5cb5862008-12-04 23:50:19 +00001701 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00001702 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00001703 if (CheckForConstantInitializer(literalExpr, literalType))
1704 return true;
1705 }
Chris Lattnerce236e72008-10-26 23:35:51 +00001706 return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr,
1707 isFileScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001708}
1709
1710Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001711ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
Chris Lattnerce236e72008-10-26 23:35:51 +00001712 InitListDesignations &Designators,
Anders Carlsson762b7c72007-08-31 04:56:16 +00001713 SourceLocation RBraceLoc) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001714 Expr **InitList = reinterpret_cast<Expr**>(initlist);
Anders Carlsson762b7c72007-08-31 04:56:16 +00001715
Steve Naroff0acc9c92007-09-15 18:49:24 +00001716 // Semantic analysis for initializers is done by ActOnDeclarator() and
Steve Naroff1c9de712007-09-03 01:24:23 +00001717 // CheckInitializer() - it requires knowledge of the object being intialized.
Anders Carlsson762b7c72007-08-31 04:56:16 +00001718
Chris Lattner71ca8c82008-10-26 23:43:26 +00001719 InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc,
1720 Designators.hasAnyDesignators());
Chris Lattner48d7f382008-04-02 04:24:33 +00001721 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1722 return E;
Chris Lattner4b009652007-07-25 00:24:17 +00001723}
1724
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001725/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00001726bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001727 UsualUnaryConversions(castExpr);
1728
1729 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1730 // type needs to be scalar.
1731 if (castType->isVoidType()) {
1732 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001733 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
1734 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001735 } else if (!castType->isScalarType() && !castType->isVectorType()) {
1736 // GCC struct/union extension: allow cast to self.
1737 if (Context.getCanonicalType(castType) !=
1738 Context.getCanonicalType(castExpr->getType()) ||
1739 (!castType->isStructureType() && !castType->isUnionType())) {
1740 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001741 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001742 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001743 }
1744
1745 // accept this, but emit an ext-warn.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001746 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001747 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001748 } else if (!castExpr->getType()->isScalarType() &&
1749 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001750 return Diag(castExpr->getLocStart(),
1751 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001752 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001753 } else if (castExpr->getType()->isVectorType()) {
1754 if (CheckVectorCast(TyR, castExpr->getType(), castType))
1755 return true;
1756 } else if (castType->isVectorType()) {
1757 if (CheckVectorCast(TyR, castType, castExpr->getType()))
1758 return true;
1759 }
1760 return false;
1761}
1762
Chris Lattnerd1f26b32007-12-20 00:44:32 +00001763bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001764 assert(VectorTy->isVectorType() && "Not a vector type!");
1765
1766 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00001767 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001768 return Diag(R.getBegin(),
1769 Ty->isVectorType() ?
1770 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00001771 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001772 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001773 } else
1774 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001775 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001776 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00001777
1778 return false;
1779}
1780
Chris Lattner4b009652007-07-25 00:24:17 +00001781Action::ExprResult Sema::
Steve Naroff87d58b42007-09-16 03:34:24 +00001782ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
Chris Lattner4b009652007-07-25 00:24:17 +00001783 SourceLocation RParenLoc, ExprTy *Op) {
Steve Naroff87d58b42007-09-16 03:34:24 +00001784 assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00001785
1786 Expr *castExpr = static_cast<Expr*>(Op);
1787 QualType castType = QualType::getFromOpaquePtr(Ty);
1788
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00001789 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1790 return true;
Steve Naroff7f1412d2008-11-03 23:29:32 +00001791 return new CStyleCastExpr(castType, castExpr, castType, LParenLoc, RParenLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00001792}
1793
Chris Lattner98a425c2007-11-26 01:40:58 +00001794/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1795/// In that case, lex = cond.
Chris Lattner4b009652007-07-25 00:24:17 +00001796inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1797 Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1798 UsualUnaryConversions(cond);
1799 UsualUnaryConversions(lex);
1800 UsualUnaryConversions(rex);
1801 QualType condT = cond->getType();
1802 QualType lexT = lex->getType();
1803 QualType rexT = rex->getType();
1804
1805 // first, check the condition.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001806 if (!cond->isTypeDependent()) {
1807 if (!condT->isScalarType()) { // C99 6.5.15p2
1808 Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
1809 return QualType();
1810 }
Chris Lattner4b009652007-07-25 00:24:17 +00001811 }
Chris Lattner992ae932008-01-06 22:42:25 +00001812
1813 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001814 if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
1815 return Context.DependentTy;
1816
Chris Lattner992ae932008-01-06 22:42:25 +00001817 // If both operands have arithmetic type, do the usual arithmetic conversions
1818 // to find a common type: C99 6.5.15p3,5.
1819 if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001820 UsualArithmeticConversions(lex, rex);
1821 return lex->getType();
1822 }
Chris Lattner992ae932008-01-06 22:42:25 +00001823
1824 // If both operands are the same structure or union type, the result is that
1825 // type.
Chris Lattner71225142007-07-31 21:27:01 +00001826 if (const RecordType *LHSRT = lexT->getAsRecordType()) { // C99 6.5.15p3
Chris Lattner992ae932008-01-06 22:42:25 +00001827 if (const RecordType *RHSRT = rexT->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00001828 if (LHSRT->getDecl() == RHSRT->getDecl())
Chris Lattner992ae932008-01-06 22:42:25 +00001829 // "If both the operands have structure or union type, the result has
1830 // that type." This implies that CV qualifiers are dropped.
1831 return lexT.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00001832 }
Chris Lattner992ae932008-01-06 22:42:25 +00001833
1834 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00001835 // The following || allows only one side to be void (a GCC-ism).
1836 if (lexT->isVoidType() || rexT->isVoidType()) {
Eli Friedmanf025aac2008-06-04 19:47:51 +00001837 if (!lexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001838 Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
1839 << rex->getSourceRange();
Steve Naroff95cb3892008-05-12 21:44:38 +00001840 if (!rexT->isVoidType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001841 Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
1842 << lex->getSourceRange();
Eli Friedmanf025aac2008-06-04 19:47:51 +00001843 ImpCastExprToType(lex, Context.VoidTy);
1844 ImpCastExprToType(rex, Context.VoidTy);
1845 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00001846 }
Steve Naroff12ebf272008-01-08 01:11:38 +00001847 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1848 // the type of the other operand."
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001849 if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1850 Context.isObjCObjectPointerType(lexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001851 rex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001852 ImpCastExprToType(rex, lexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001853 return lexT;
1854 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001855 if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1856 Context.isObjCObjectPointerType(rexT)) &&
Anders Carlssonf8aa8702008-12-01 06:28:23 +00001857 lex->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00001858 ImpCastExprToType(lex, rexT); // promote the null to a pointer.
Steve Naroff12ebf272008-01-08 01:11:38 +00001859 return rexT;
1860 }
Chris Lattner0ac51632008-01-06 22:50:31 +00001861 // Handle the case where both operands are pointers before we handle null
1862 // pointer constants in case both operands are null pointer constants.
Chris Lattner71225142007-07-31 21:27:01 +00001863 if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1864 if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1865 // get the "pointed to" types
1866 QualType lhptee = LHSPT->getPointeeType();
1867 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001868
Chris Lattner71225142007-07-31 21:27:01 +00001869 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1870 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00001871 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001872 // Figure out necessary qualifiers (C99 6.5.15p6)
1873 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001874 QualType destType = Context.getPointerType(destPointee);
1875 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1876 ImpCastExprToType(rex, destType); // promote to void*
1877 return destType;
1878 }
Chris Lattner9db553e2008-04-02 06:59:01 +00001879 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00001880 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00001881 QualType destType = Context.getPointerType(destPointee);
1882 ImpCastExprToType(lex, destType); // add qualifiers if necessary
1883 ImpCastExprToType(rex, destType); // promote to void*
1884 return destType;
1885 }
Chris Lattner4b009652007-07-25 00:24:17 +00001886
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001887 QualType compositeType = lexT;
1888
1889 // If either type is an Objective-C object type then check
1890 // compatibility according to Objective-C.
1891 if (Context.isObjCObjectPointerType(lexT) ||
1892 Context.isObjCObjectPointerType(rexT)) {
1893 // If both operands are interfaces and either operand can be
1894 // assigned to the other, use that type as the composite
1895 // type. This allows
1896 // xxx ? (A*) a : (B*) b
1897 // where B is a subclass of A.
1898 //
1899 // Additionally, as for assignment, if either type is 'id'
1900 // allow silent coercion. Finally, if the types are
1901 // incompatible then make sure to use 'id' as the composite
1902 // type so the result is acceptable for sending messages to.
1903
1904 // FIXME: This code should not be localized to here. Also this
1905 // should use a compatible check instead of abusing the
1906 // canAssignObjCInterfaces code.
1907 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1908 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1909 if (LHSIface && RHSIface &&
1910 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1911 compositeType = lexT;
1912 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00001913 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001914 compositeType = rexT;
1915 } else if (Context.isObjCIdType(lhptee) ||
1916 Context.isObjCIdType(rhptee)) {
1917 // FIXME: This code looks wrong, because isObjCIdType checks
1918 // the struct but getObjCIdType returns the pointer to
1919 // struct. This is horrible and should be fixed.
1920 compositeType = Context.getObjCIdType();
1921 } else {
1922 QualType incompatTy = Context.getObjCIdType();
1923 ImpCastExprToType(lex, incompatTy);
1924 ImpCastExprToType(rex, incompatTy);
1925 return incompatTy;
1926 }
1927 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1928 rhptee.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00001929 Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001930 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001931 // In this situation, we assume void* type. No especially good
1932 // reason, but this is what gcc does, and we do have to pick
1933 // to get a consistent AST.
1934 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00001935 ImpCastExprToType(lex, incompatTy);
1936 ImpCastExprToType(rex, incompatTy);
1937 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00001938 }
1939 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001940 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1941 // differently qualified versions of compatible types, the result type is
1942 // a pointer to an appropriately qualified version of the *composite*
1943 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00001944 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00001945 // FIXME: Need to add qualifiers
Eli Friedmane38150e2008-05-16 20:37:07 +00001946 ImpCastExprToType(lex, compositeType);
1947 ImpCastExprToType(rex, compositeType);
1948 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00001949 }
Chris Lattner4b009652007-07-25 00:24:17 +00001950 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00001951 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1952 // evaluates to "struct objc_object *" (and is handled above when comparing
1953 // id with statically typed objects).
1954 if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1955 // GCC allows qualified id and any Objective-C type to devolve to
1956 // id. Currently localizing to here until clear this should be
1957 // part of ObjCQualifiedIdTypesAreCompatible.
1958 if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1959 (lexT->isObjCQualifiedIdType() &&
1960 Context.isObjCObjectPointerType(rexT)) ||
1961 (rexT->isObjCQualifiedIdType() &&
1962 Context.isObjCObjectPointerType(lexT))) {
1963 // FIXME: This is not the correct composite type. This only
1964 // happens to work because id can more or less be used anywhere,
1965 // however this may change the type of method sends.
1966 // FIXME: gcc adds some type-checking of the arguments and emits
1967 // (confusing) incompatible comparison warnings in some
1968 // cases. Investigate.
1969 QualType compositeType = Context.getObjCIdType();
1970 ImpCastExprToType(lex, compositeType);
1971 ImpCastExprToType(rex, compositeType);
1972 return compositeType;
1973 }
1974 }
1975
Steve Naroff3eac7692008-09-10 19:17:48 +00001976 // Selection between block pointer types is ok as long as they are the same.
1977 if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1978 Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1979 return lexT;
1980
Chris Lattner992ae932008-01-06 22:42:25 +00001981 // Otherwise, the operands are not compatible.
Chris Lattner70b93d82008-11-18 22:52:51 +00001982 Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001983 << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001984 return QualType();
1985}
1986
Steve Naroff87d58b42007-09-16 03:34:24 +00001987/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00001988/// in the case of a the GNU conditional expr extension.
Steve Naroff87d58b42007-09-16 03:34:24 +00001989Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00001990 SourceLocation ColonLoc,
1991 ExprTy *Cond, ExprTy *LHS,
1992 ExprTy *RHS) {
1993 Expr *CondExpr = (Expr *) Cond;
1994 Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
Chris Lattner98a425c2007-11-26 01:40:58 +00001995
1996 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1997 // was the condition.
1998 bool isLHSNull = LHSExpr == 0;
1999 if (isLHSNull)
2000 LHSExpr = CondExpr;
2001
Chris Lattner4b009652007-07-25 00:24:17 +00002002 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2003 RHSExpr, QuestionLoc);
2004 if (result.isNull())
2005 return true;
Chris Lattner98a425c2007-11-26 01:40:58 +00002006 return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
2007 RHSExpr, result);
Chris Lattner4b009652007-07-25 00:24:17 +00002008}
2009
Chris Lattner4b009652007-07-25 00:24:17 +00002010
2011// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2012// being closely modeled after the C99 spec:-). The odd characteristic of this
2013// routine is it effectively iqnores the qualifiers on the top level pointee.
2014// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2015// FIXME: add a couple examples in this comment.
Chris Lattner005ed752008-01-04 18:04:52 +00002016Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002017Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2018 QualType lhptee, rhptee;
2019
2020 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002021 lhptee = lhsType->getAsPointerType()->getPointeeType();
2022 rhptee = rhsType->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002023
2024 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002025 lhptee = Context.getCanonicalType(lhptee);
2026 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002027
Chris Lattner005ed752008-01-04 18:04:52 +00002028 AssignConvertType ConvTy = Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002029
2030 // C99 6.5.16.1p1: This following citation is common to constraints
2031 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2032 // qualifiers of the type *pointed to* by the right;
Chris Lattner35fef522008-02-20 20:55:12 +00002033 // FIXME: Handle ASQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002034 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002035 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002036
2037 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2038 // incomplete type and the other is a pointer to a qualified or unqualified
2039 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002040 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002041 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002042 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002043
2044 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002045 assert(rhptee->isFunctionType());
2046 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002047 }
2048
2049 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002050 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002051 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002052
2053 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002054 assert(lhptee->isFunctionType());
2055 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002056 }
Eli Friedman0d9549b2008-08-22 00:56:42 +00002057
2058 // Check for ObjC interfaces
2059 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2060 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2061 if (LHSIface && RHSIface &&
2062 Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2063 return ConvTy;
2064
2065 // ID acts sort of like void* for ObjC interfaces
2066 if (LHSIface && Context.isObjCIdType(rhptee))
2067 return ConvTy;
2068 if (RHSIface && Context.isObjCIdType(lhptee))
2069 return ConvTy;
2070
Chris Lattner4b009652007-07-25 00:24:17 +00002071 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2072 // unqualified versions of compatible types, ...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002073 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2074 rhptee.getUnqualifiedType()))
2075 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002076 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002077}
2078
Steve Naroff3454b6c2008-09-04 15:10:53 +00002079/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2080/// block pointer types are compatible or whether a block and normal pointer
2081/// are compatible. It is more restrict than comparing two function pointer
2082// types.
2083Sema::AssignConvertType
2084Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2085 QualType rhsType) {
2086 QualType lhptee, rhptee;
2087
2088 // get the "pointed to" type (ignoring qualifiers at the top level)
2089 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2090 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2091
2092 // make sure we operate on the canonical type
2093 lhptee = Context.getCanonicalType(lhptee);
2094 rhptee = Context.getCanonicalType(rhptee);
2095
2096 AssignConvertType ConvTy = Compatible;
2097
2098 // For blocks we enforce that qualifiers are identical.
2099 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2100 ConvTy = CompatiblePointerDiscardsQualifiers;
2101
2102 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2103 return IncompatibleBlockPointer;
2104 return ConvTy;
2105}
2106
Chris Lattner4b009652007-07-25 00:24:17 +00002107/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2108/// has code to accommodate several GCC extensions when type checking
2109/// pointers. Here are some objectionable examples that GCC considers warnings:
2110///
2111/// int a, *pint;
2112/// short *pshort;
2113/// struct foo *pfoo;
2114///
2115/// pint = pshort; // warning: assignment from incompatible pointer type
2116/// a = pint; // warning: assignment makes integer from pointer without a cast
2117/// pint = a; // warning: assignment makes pointer from integer without a cast
2118/// pint = pfoo; // warning: assignment from incompatible pointer type
2119///
2120/// As a result, the code for dealing with pointers is more complex than the
2121/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002122///
Chris Lattner005ed752008-01-04 18:04:52 +00002123Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002124Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002125 // Get canonical types. We're not formatting these types, just comparing
2126 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002127 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2128 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002129
2130 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002131 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002132
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002133 // If the left-hand side is a reference type, then we are in a
2134 // (rare!) case where we've allowed the use of references in C,
2135 // e.g., as a parameter type in a built-in function. In this case,
2136 // just make sure that the type referenced is compatible with the
2137 // right-hand side type. The caller is responsible for adjusting
2138 // lhsType so that the resulting expression does not have reference
2139 // type.
2140 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2141 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002142 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002143 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002144 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002145
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002146 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2147 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002148 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002149 // Relax integer conversions like we do for pointers below.
2150 if (rhsType->isIntegerType())
2151 return IntToPointer;
2152 if (lhsType->isIntegerType())
2153 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002154 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002155 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002156
Nate Begemanc5f0f652008-07-14 18:02:46 +00002157 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002158 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002159 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2160 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002161 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002162
Nate Begemanc5f0f652008-07-14 18:02:46 +00002163 // If we are allowing lax vector conversions, and LHS and RHS are both
2164 // vectors, the total size only needs to be the same. This is a bitcast;
2165 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002166 if (getLangOptions().LaxVectorConversions &&
2167 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002168 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2169 return Compatible;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002170 }
2171 return Incompatible;
2172 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002173
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002174 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002175 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002176
Chris Lattner390564e2008-04-07 06:49:41 +00002177 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002178 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002179 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002180
Chris Lattner390564e2008-04-07 06:49:41 +00002181 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002182 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002183
Steve Naroffa982c712008-09-29 18:10:17 +00002184 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002185 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002186 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002187
2188 // Treat block pointers as objects.
2189 if (getLangOptions().ObjC1 &&
2190 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2191 return Compatible;
2192 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002193 return Incompatible;
2194 }
2195
2196 if (isa<BlockPointerType>(lhsType)) {
2197 if (rhsType->isIntegerType())
2198 return IntToPointer;
2199
Steve Naroffa982c712008-09-29 18:10:17 +00002200 // Treat block pointers as objects.
2201 if (getLangOptions().ObjC1 &&
2202 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2203 return Compatible;
2204
Steve Naroff3454b6c2008-09-04 15:10:53 +00002205 if (rhsType->isBlockPointerType())
2206 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2207
2208 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2209 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002210 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002211 }
Chris Lattner1853da22008-01-04 23:18:45 +00002212 return Incompatible;
2213 }
2214
Chris Lattner390564e2008-04-07 06:49:41 +00002215 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002216 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002217 if (lhsType == Context.BoolTy)
2218 return Compatible;
2219
2220 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002221 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002222
Chris Lattner390564e2008-04-07 06:49:41 +00002223 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002224 return CheckPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff3454b6c2008-09-04 15:10:53 +00002225
2226 if (isa<BlockPointerType>(lhsType) &&
2227 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002228 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002229 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002230 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002231
Chris Lattner1853da22008-01-04 23:18:45 +00002232 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002233 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002234 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002235 }
2236 return Incompatible;
2237}
2238
Chris Lattner005ed752008-01-04 18:04:52 +00002239Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002240Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002241 if (getLangOptions().CPlusPlus) {
2242 if (!lhsType->isRecordType()) {
2243 // C++ 5.17p3: If the left operand is not of class type, the
2244 // expression is implicitly converted (C++ 4) to the
2245 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002246 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2247 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002248 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002249 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002250 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002251 }
2252
2253 // FIXME: Currently, we fall through and treat C++ classes like C
2254 // structures.
2255 }
2256
Steve Naroffcdee22d2007-11-27 17:58:44 +00002257 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2258 // a null pointer constant.
Steve Naroff4fea7b62008-09-04 16:56:14 +00002259 if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2260 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002261 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002262 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002263 return Compatible;
2264 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002265
2266 // We don't allow conversion of non-null-pointer constants to integers.
2267 if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2268 return IntToBlockPointer;
2269
Chris Lattner5f505bf2007-10-16 02:55:40 +00002270 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002271 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002272 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002273 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002274 //
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002275 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002276 if (!lhsType->isReferenceType())
2277 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002278
Chris Lattner005ed752008-01-04 18:04:52 +00002279 Sema::AssignConvertType result =
2280 CheckAssignmentConstraints(lhsType, rExpr->getType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002281
2282 // C99 6.5.16.1p2: The value of the right operand is converted to the
2283 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002284 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2285 // so that we can use references in built-in functions even in C.
2286 // The getNonReferenceType() call makes sure that the resulting expression
2287 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002288 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002289 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002290 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002291}
2292
Chris Lattner005ed752008-01-04 18:04:52 +00002293Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002294Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2295 return CheckAssignmentConstraints(lhsType, rhsType);
2296}
2297
Chris Lattner1eafdea2008-11-18 01:30:42 +00002298QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002299 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002300 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002301 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002302 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002303}
2304
Chris Lattner1eafdea2008-11-18 01:30:42 +00002305inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002306 Expr *&rex) {
Nate Begeman03105572008-04-04 01:30:25 +00002307 // For conversion purposes, we ignore any qualifiers.
2308 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002309 QualType lhsType =
2310 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2311 QualType rhsType =
2312 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002313
Nate Begemanc5f0f652008-07-14 18:02:46 +00002314 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002315 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002316 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002317
Nate Begemanc5f0f652008-07-14 18:02:46 +00002318 // Handle the case of a vector & extvector type of the same size and element
2319 // type. It would be nice if we only had one vector type someday.
2320 if (getLangOptions().LaxVectorConversions)
2321 if (const VectorType *LV = lhsType->getAsVectorType())
2322 if (const VectorType *RV = rhsType->getAsVectorType())
2323 if (LV->getElementType() == RV->getElementType() &&
2324 LV->getNumElements() == RV->getNumElements())
2325 return lhsType->isExtVectorType() ? lhsType : rhsType;
2326
2327 // If the lhs is an extended vector and the rhs is a scalar of the same type
2328 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002329 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002330 QualType eltType = V->getElementType();
2331
2332 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2333 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2334 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002335 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002336 return lhsType;
2337 }
2338 }
2339
Nate Begemanc5f0f652008-07-14 18:02:46 +00002340 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002341 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002342 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002343 QualType eltType = V->getElementType();
2344
2345 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2346 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2347 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002348 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002349 return rhsType;
2350 }
2351 }
2352
Chris Lattner4b009652007-07-25 00:24:17 +00002353 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002354 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002355 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002356 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002357 return QualType();
2358}
2359
2360inline QualType Sema::CheckMultiplyDivideOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002361 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002362{
2363 QualType lhsType = lex->getType(), rhsType = rex->getType();
2364
2365 if (lhsType->isVectorType() || rhsType->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002366 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002367
Steve Naroff8f708362007-08-24 19:07:16 +00002368 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002369
Chris Lattner4b009652007-07-25 00:24:17 +00002370 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002371 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002372 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002373}
2374
2375inline QualType Sema::CheckRemainderOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002376 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002377{
2378 QualType lhsType = lex->getType(), rhsType = rex->getType();
2379
Steve Naroff8f708362007-08-24 19:07:16 +00002380 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002381
Chris Lattner4b009652007-07-25 00:24:17 +00002382 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002383 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002384 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002385}
2386
2387inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Chris Lattner1eafdea2008-11-18 01:30:42 +00002388 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002389{
2390 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002391 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002392
Steve Naroff8f708362007-08-24 19:07:16 +00002393 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002394
Chris Lattner4b009652007-07-25 00:24:17 +00002395 // handle the common case first (both operands are arithmetic).
2396 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002397 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002398
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002399 // Put any potential pointer into PExp
2400 Expr* PExp = lex, *IExp = rex;
2401 if (IExp->getType()->isPointerType())
2402 std::swap(PExp, IExp);
2403
2404 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2405 if (IExp->getType()->isIntegerType()) {
2406 // Check for arithmetic on pointers to incomplete types
2407 if (!PTy->getPointeeType()->isObjectType()) {
2408 if (PTy->getPointeeType()->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002409 Diag(Loc, diag::ext_gnu_void_ptr)
2410 << lex->getSourceRange() << rex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002411 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002412 Diag(Loc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002413 << lex->getType() << lex->getSourceRange();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002414 return QualType();
2415 }
2416 }
2417 return PExp->getType();
2418 }
2419 }
2420
Chris Lattner1eafdea2008-11-18 01:30:42 +00002421 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002422}
2423
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002424// C99 6.5.6
2425QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002426 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002427 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002428 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002429
Steve Naroff8f708362007-08-24 19:07:16 +00002430 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002431
Chris Lattnerf6da2912007-12-09 21:53:25 +00002432 // Enforce type constraints: C99 6.5.6p3.
2433
2434 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002435 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002436 return compType;
Chris Lattnerf6da2912007-12-09 21:53:25 +00002437
2438 // Either ptr - int or ptr - ptr.
2439 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002440 QualType lpointee = LHSPTy->getPointeeType();
Eli Friedman50727042008-02-08 01:19:44 +00002441
Chris Lattnerf6da2912007-12-09 21:53:25 +00002442 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002443 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002444 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002445 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002446 Diag(Loc, diag::ext_gnu_void_ptr)
2447 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002448 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002449 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002450 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002451 return QualType();
2452 }
2453 }
2454
2455 // The result type of a pointer-int computation is the pointer type.
2456 if (rex->getType()->isIntegerType())
2457 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002458
Chris Lattnerf6da2912007-12-09 21:53:25 +00002459 // Handle pointer-pointer subtractions.
2460 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00002461 QualType rpointee = RHSPTy->getPointeeType();
2462
Chris Lattnerf6da2912007-12-09 21:53:25 +00002463 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00002464 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002465 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002466 if (rpointee->isVoidType()) {
2467 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00002468 Diag(Loc, diag::ext_gnu_void_ptr)
2469 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002470 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002471 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002472 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002473 return QualType();
2474 }
2475 }
2476
2477 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00002478 if (!Context.typesAreCompatible(
2479 Context.getCanonicalType(lpointee).getUnqualifiedType(),
2480 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002481 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002482 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002483 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00002484 return QualType();
2485 }
2486
2487 return Context.getPointerDiffType();
2488 }
2489 }
2490
Chris Lattner1eafdea2008-11-18 01:30:42 +00002491 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002492}
2493
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002494// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00002495QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002496 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00002497 // C99 6.5.7p2: Each of the operands shall have integer type.
2498 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002499 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002500
Chris Lattner2c8bff72007-12-12 05:47:28 +00002501 // Shifts don't perform usual arithmetic conversions, they just do integer
2502 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00002503 if (!isCompAssign)
2504 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00002505 UsualUnaryConversions(rex);
2506
2507 // "The type of the result is that of the promoted left operand."
2508 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002509}
2510
Eli Friedman0d9549b2008-08-22 00:56:42 +00002511static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2512 ASTContext& Context) {
2513 const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2514 const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2515 // ID acts sort of like void* for ObjC interfaces
2516 if (LHSIface && Context.isObjCIdType(RHS))
2517 return true;
2518 if (RHSIface && Context.isObjCIdType(LHS))
2519 return true;
2520 if (!LHSIface || !RHSIface)
2521 return false;
2522 return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2523 Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2524}
2525
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002526// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00002527QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002528 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002529 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002530 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002531
Chris Lattner254f3bc2007-08-26 01:18:55 +00002532 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00002533 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2534 UsualArithmeticConversions(lex, rex);
2535 else {
2536 UsualUnaryConversions(lex);
2537 UsualUnaryConversions(rex);
2538 }
Chris Lattner4b009652007-07-25 00:24:17 +00002539 QualType lType = lex->getType();
2540 QualType rType = rex->getType();
2541
Ted Kremenek486509e2007-10-29 17:13:39 +00002542 // For non-floating point types, check for self-comparisons of the form
2543 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2544 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002545 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00002546 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2547 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002548 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002549 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00002550 }
2551
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002552 // The result of comparisons is 'bool' in C++, 'int' in C.
2553 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2554
Chris Lattner254f3bc2007-08-26 01:18:55 +00002555 if (isRelational) {
2556 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002557 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002558 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00002559 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00002560 if (lType->isFloatingType()) {
2561 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002562 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00002563 }
2564
Chris Lattner254f3bc2007-08-26 01:18:55 +00002565 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002566 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00002567 }
Chris Lattner4b009652007-07-25 00:24:17 +00002568
Chris Lattner22be8422007-08-26 01:10:14 +00002569 bool LHSIsNull = lex->isNullPointerConstant(Context);
2570 bool RHSIsNull = rex->isNullPointerConstant(Context);
2571
Chris Lattner254f3bc2007-08-26 01:18:55 +00002572 // All of the following pointer related warnings are GCC extensions, except
2573 // when handling null pointer constants. One day, we can consider making them
2574 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00002575 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002576 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002577 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00002578 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002579 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Eli Friedman50727042008-02-08 01:19:44 +00002580
Steve Naroff3b435622007-11-13 14:57:38 +00002581 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00002582 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2583 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00002584 RCanPointeeTy.getUnqualifiedType()) &&
2585 !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002586 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002587 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002588 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00002589 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002590 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002591 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002592 // Handle block pointer types.
2593 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2594 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2595 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2596
2597 if (!LHSIsNull && !RHSIsNull &&
2598 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002599 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002600 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00002601 }
2602 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002603 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002604 }
Steve Narofff85d66c2008-09-28 01:11:11 +00002605 // Allow block pointers to be compared with null pointer constants.
2606 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2607 (lType->isPointerType() && rType->isBlockPointerType())) {
2608 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002609 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002610 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00002611 }
2612 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002613 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00002614 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002615
Steve Naroff936c4362008-06-03 14:04:54 +00002616 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00002617 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00002618 const PointerType *LPT = lType->getAsPointerType();
2619 const PointerType *RPT = rType->getAsPointerType();
2620 bool LPtrToVoid = LPT ?
2621 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
2622 bool RPtrToVoid = RPT ?
2623 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
2624
2625 if (!LPtrToVoid && !RPtrToVoid &&
2626 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002627 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002628 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00002629 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002630 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00002631 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002632 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002633 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00002634 }
Steve Naroff936c4362008-06-03 14:04:54 +00002635 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2636 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002637 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002638 } else {
2639 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002640 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00002641 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00002642 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002643 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00002644 }
Steve Naroff936c4362008-06-03 14:04:54 +00002645 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00002646 }
Steve Naroff936c4362008-06-03 14:04:54 +00002647 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2648 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00002649 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002650 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002651 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002652 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002653 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00002654 }
Steve Naroff936c4362008-06-03 14:04:54 +00002655 if (lType->isIntegerType() &&
2656 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00002657 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002658 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002659 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00002660 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002661 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002662 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00002663 // Handle block pointers.
2664 if (lType->isBlockPointerType() && rType->isIntegerType()) {
2665 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002666 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002667 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002668 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002669 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002670 }
2671 if (lType->isIntegerType() && rType->isBlockPointerType()) {
2672 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00002673 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002674 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00002675 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00002676 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00002677 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00002678 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002679}
2680
Nate Begemanc5f0f652008-07-14 18:02:46 +00002681/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2682/// operates on extended vector types. Instead of producing an IntTy result,
2683/// like a scalar comparison, a vector comparison produces a vector of integer
2684/// types.
2685QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002686 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00002687 bool isRelational) {
2688 // Check to make sure we're operating on vectors of the same type and width,
2689 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002690 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002691 if (vType.isNull())
2692 return vType;
2693
2694 QualType lType = lex->getType();
2695 QualType rType = rex->getType();
2696
2697 // For non-floating point types, check for self-comparisons of the form
2698 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
2699 // often indicate logic errors in the program.
2700 if (!lType->isFloatingType()) {
2701 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2702 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2703 if (DRL->getDecl() == DRR->getDecl())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002704 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002705 }
2706
2707 // Check for comparisons of floating point operands using != and ==.
2708 if (!isRelational && lType->isFloatingType()) {
2709 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00002710 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00002711 }
2712
2713 // Return the type for the comparison, which is the same as vector type for
2714 // integer vectors, or an integer type of identical size and number of
2715 // elements for floating point vectors.
2716 if (lType->isIntegerType())
2717 return lType;
2718
2719 const VectorType *VTy = lType->getAsVectorType();
2720
2721 // FIXME: need to deal with non-32b int / non-64b long long
2722 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2723 if (TypeSize == 32) {
2724 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2725 }
2726 assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2727 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2728}
2729
Chris Lattner4b009652007-07-25 00:24:17 +00002730inline QualType Sema::CheckBitwiseOperands(
Chris Lattner1eafdea2008-11-18 01:30:42 +00002731 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002732{
2733 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002734 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002735
Steve Naroff8f708362007-08-24 19:07:16 +00002736 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Chris Lattner4b009652007-07-25 00:24:17 +00002737
2738 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002739 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002740 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002741}
2742
2743inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Chris Lattner1eafdea2008-11-18 01:30:42 +00002744 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00002745{
2746 UsualUnaryConversions(lex);
2747 UsualUnaryConversions(rex);
2748
Eli Friedmanbea3f842008-05-13 20:16:47 +00002749 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00002750 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002751 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002752}
2753
Chris Lattner4c2642c2008-11-18 01:22:49 +00002754/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
2755/// emit an error and return true. If so, return false.
2756static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
2757 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
2758 if (IsLV == Expr::MLV_Valid)
2759 return false;
2760
2761 unsigned Diag = 0;
2762 bool NeedType = false;
2763 switch (IsLV) { // C99 6.5.16p2
2764 default: assert(0 && "Unknown result from isModifiableLvalue!");
2765 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Chris Lattner005ed752008-01-04 18:04:52 +00002766 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002767 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
2768 NeedType = true;
2769 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002770 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002771 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
2772 NeedType = true;
2773 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00002774 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002775 Diag = diag::err_typecheck_lvalue_casts_not_supported;
2776 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002777 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002778 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
2779 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002780 case Expr::MLV_IncompleteType:
2781 case Expr::MLV_IncompleteVoidType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002782 Diag = diag::err_typecheck_incomplete_type_not_modifiable_lvalue;
2783 NeedType = true;
2784 break;
Chris Lattner005ed752008-01-04 18:04:52 +00002785 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002786 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
2787 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00002788 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00002789 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
2790 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00002791 case Expr::MLV_ReadonlyProperty:
2792 Diag = diag::error_readonly_property_assignment;
2793 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002794 case Expr::MLV_NoSetterProperty:
2795 Diag = diag::error_nosetter_property_assignment;
2796 break;
Chris Lattner4b009652007-07-25 00:24:17 +00002797 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00002798
Chris Lattner4c2642c2008-11-18 01:22:49 +00002799 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002800 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002801 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00002802 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00002803 return true;
2804}
2805
2806
2807
2808// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00002809QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
2810 SourceLocation Loc,
2811 QualType CompoundType) {
2812 // Verify that LHS is a modifiable lvalue, and emit error if not.
2813 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00002814 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00002815
2816 QualType LHSType = LHS->getType();
2817 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Chris Lattner4c2642c2008-11-18 01:22:49 +00002818
Chris Lattner005ed752008-01-04 18:04:52 +00002819 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002820 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00002821 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002822 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Chris Lattner34c85082008-08-21 18:04:13 +00002823
2824 // If the RHS is a unary plus or minus, check to see if they = and + are
2825 // right next to each other. If so, the user may have typo'd "x =+ 4"
2826 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00002827 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00002828 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2829 RHSCheck = ICE->getSubExpr();
2830 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2831 if ((UO->getOpcode() == UnaryOperator::Plus ||
2832 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00002833 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00002834 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002835 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00002836 Diag(Loc, diag::warn_not_compound_assign)
2837 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
2838 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00002839 }
2840 } else {
2841 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00002842 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00002843 }
Chris Lattner005ed752008-01-04 18:04:52 +00002844
Chris Lattner1eafdea2008-11-18 01:30:42 +00002845 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
2846 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00002847 return QualType();
2848
Chris Lattner4b009652007-07-25 00:24:17 +00002849 // C99 6.5.16p3: The type of an assignment expression is the type of the
2850 // left operand unless the left operand has qualified type, in which case
2851 // it is the unqualified version of the type of the left operand.
2852 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2853 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002854 // C++ 5.17p1: the type of the assignment expression is that of its left
2855 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002856 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002857}
2858
Chris Lattner1eafdea2008-11-18 01:30:42 +00002859// C99 6.5.17
2860QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
2861 // FIXME: what is required for LHS?
Chris Lattner03c430f2008-07-25 20:54:07 +00002862
2863 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00002864 DefaultFunctionArrayConversion(RHS);
2865 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002866}
2867
2868/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2869/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00002870QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
2871 bool isInc) {
Chris Lattnere65182c2008-11-21 07:05:48 +00002872 QualType ResType = Op->getType();
2873 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00002874
Sebastian Redl0440c8c2008-12-20 09:35:34 +00002875 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
2876 // Decrement of bool is not allowed.
2877 if (!isInc) {
2878 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
2879 return QualType();
2880 }
2881 // Increment of bool sets it to true, but is deprecated.
2882 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
2883 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00002884 // OK!
2885 } else if (const PointerType *PT = ResType->getAsPointerType()) {
2886 // C99 6.5.2.4p2, 6.5.6p2
2887 if (PT->getPointeeType()->isObjectType()) {
2888 // Pointer to object is ok!
2889 } else if (PT->getPointeeType()->isVoidType()) {
2890 // Pointer to void is extension.
2891 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
2892 } else {
Chris Lattner9d2cf082008-11-19 05:27:50 +00002893 Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002894 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002895 return QualType();
2896 }
Chris Lattnere65182c2008-11-21 07:05:48 +00002897 } else if (ResType->isComplexType()) {
2898 // C99 does not support ++/-- on complex types, we allow as an extension.
2899 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002900 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002901 } else {
2902 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002903 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00002904 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002905 }
Steve Naroff6acc0f42007-08-23 21:37:33 +00002906 // At this point, we know we have a real, complex or pointer type.
2907 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00002908 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00002909 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00002910 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00002911}
2912
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002913/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00002914/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002915/// where the declaration is needed for type checking. We only need to
2916/// handle cases when the expression references a function designator
2917/// or is an lvalue. Here are some examples:
2918/// - &(x) => x
2919/// - &*****f => f for f a function designator.
2920/// - &s.xx => s
2921/// - &s.zz[1].yy -> s, if zz is an array
2922/// - *(x + 1) -> x, if x is an array
2923/// - &"123"[2] -> 0
2924/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00002925static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00002926 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002927 case Stmt::DeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002928 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002929 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00002930 // Fields cannot be declared with a 'register' storage class.
2931 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00002932 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00002933 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00002934 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002935 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002936 // &X[4] and &4[X] refers to X if X is not a pointer.
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002937
Douglas Gregord2baafd2008-10-21 16:13:35 +00002938 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00002939 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00002940 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00002941 return 0;
2942 else
2943 return VD;
2944 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002945 case Stmt::UnaryOperatorClass: {
2946 UnaryOperator *UO = cast<UnaryOperator>(E);
2947
2948 switch(UO->getOpcode()) {
2949 case UnaryOperator::Deref: {
2950 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00002951 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
2952 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2953 if (!VD || VD->getType()->isPointerType())
2954 return 0;
2955 return VD;
2956 }
2957 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00002958 }
2959 case UnaryOperator::Real:
2960 case UnaryOperator::Imag:
2961 case UnaryOperator::Extension:
2962 return getPrimaryDecl(UO->getSubExpr());
2963 default:
2964 return 0;
2965 }
2966 }
2967 case Stmt::BinaryOperatorClass: {
2968 BinaryOperator *BO = cast<BinaryOperator>(E);
2969
2970 // Handle cases involving pointer arithmetic. The result of an
2971 // Assign or AddAssign is not an lvalue so they can be ignored.
2972
2973 // (x + n) or (n + x) => x
2974 if (BO->getOpcode() == BinaryOperator::Add) {
2975 if (BO->getLHS()->getType()->isPointerType()) {
2976 return getPrimaryDecl(BO->getLHS());
2977 } else if (BO->getRHS()->getType()->isPointerType()) {
2978 return getPrimaryDecl(BO->getRHS());
2979 }
2980 }
2981
2982 return 0;
2983 }
Chris Lattner4b009652007-07-25 00:24:17 +00002984 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00002985 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00002986 case Stmt::ImplicitCastExprClass:
2987 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00002988 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00002989 default:
2990 return 0;
2991 }
2992}
2993
2994/// CheckAddressOfOperand - The operand of & must be either a function
2995/// designator or an lvalue designating an object. If it is an lvalue, the
2996/// object cannot be declared with storage class register or be a bit field.
2997/// Note: The usual conversions are *not* applied to the operand of the &
2998/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Douglas Gregor45014fd2008-11-10 20:40:00 +00002999/// In C++, the operand might be an overloaded function name, in which case
3000/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003001QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003002 if (op->isTypeDependent())
3003 return Context.DependentTy;
3004
Steve Naroff9c6c3592008-01-13 17:10:08 +00003005 if (getLangOptions().C99) {
3006 // Implement C99-only parts of addressof rules.
3007 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3008 if (uOp->getOpcode() == UnaryOperator::Deref)
3009 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3010 // (assuming the deref expression is valid).
3011 return uOp->getSubExpr()->getType();
3012 }
3013 // Technically, there should be a check for array subscript
3014 // expressions here, but the result of one is always an lvalue anyway.
3015 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003016 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003017 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003018
Chris Lattner4b009652007-07-25 00:24:17 +00003019 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003020 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3021 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003022 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3023 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003024 return QualType();
3025 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003026 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003027 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3028 if (Field->isBitField()) {
3029 Diag(OpLoc, diag::err_typecheck_address_of)
3030 << "bit-field" << op->getSourceRange();
3031 return QualType();
3032 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003033 }
3034 // Check for Apple extension for accessing vector components.
3035 } else if (isa<ArraySubscriptExpr>(op) &&
3036 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003037 Diag(OpLoc, diag::err_typecheck_address_of)
3038 << "vector" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003039 return QualType();
3040 } else if (dcl) { // C99 6.5.3.2p1
Chris Lattner4b009652007-07-25 00:24:17 +00003041 // We have an lvalue with a decl. Make sure the decl is not declared
3042 // with the register storage-class specifier.
3043 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3044 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003045 Diag(OpLoc, diag::err_typecheck_address_of)
3046 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003047 return QualType();
3048 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003049 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003050 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003051 } else if (isa<FieldDecl>(dcl)) {
3052 // Okay: we can take the address of a field.
Nuno Lopesdf239522008-12-16 22:58:26 +00003053 } else if (isa<FunctionDecl>(dcl)) {
3054 // Okay: we can take the address of a function.
Douglas Gregor5b82d612008-12-10 21:26:49 +00003055 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003056 else
Chris Lattner4b009652007-07-25 00:24:17 +00003057 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003058 }
Chris Lattnera55e3212008-07-27 00:48:22 +00003059
Chris Lattner4b009652007-07-25 00:24:17 +00003060 // If the operand has type "type", the result has type "pointer to type".
3061 return Context.getPointerType(op->getType());
3062}
3063
Chris Lattnerda5c0872008-11-23 09:13:29 +00003064QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3065 UsualUnaryConversions(Op);
3066 QualType Ty = Op->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003067
Chris Lattnerda5c0872008-11-23 09:13:29 +00003068 // Note that per both C89 and C99, this is always legal, even if ptype is an
3069 // incomplete type or void. It would be possible to warn about dereferencing
3070 // a void pointer, but it's completely well-defined, and such a warning is
3071 // unlikely to catch any mistakes.
3072 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003073 return PT->getPointeeType();
Chris Lattnerda5c0872008-11-23 09:13:29 +00003074
Chris Lattner77d52da2008-11-20 06:06:08 +00003075 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003076 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003077 return QualType();
3078}
3079
3080static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3081 tok::TokenKind Kind) {
3082 BinaryOperator::Opcode Opc;
3083 switch (Kind) {
3084 default: assert(0 && "Unknown binop!");
3085 case tok::star: Opc = BinaryOperator::Mul; break;
3086 case tok::slash: Opc = BinaryOperator::Div; break;
3087 case tok::percent: Opc = BinaryOperator::Rem; break;
3088 case tok::plus: Opc = BinaryOperator::Add; break;
3089 case tok::minus: Opc = BinaryOperator::Sub; break;
3090 case tok::lessless: Opc = BinaryOperator::Shl; break;
3091 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3092 case tok::lessequal: Opc = BinaryOperator::LE; break;
3093 case tok::less: Opc = BinaryOperator::LT; break;
3094 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3095 case tok::greater: Opc = BinaryOperator::GT; break;
3096 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3097 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3098 case tok::amp: Opc = BinaryOperator::And; break;
3099 case tok::caret: Opc = BinaryOperator::Xor; break;
3100 case tok::pipe: Opc = BinaryOperator::Or; break;
3101 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3102 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3103 case tok::equal: Opc = BinaryOperator::Assign; break;
3104 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3105 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3106 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3107 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3108 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3109 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3110 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3111 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3112 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3113 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3114 case tok::comma: Opc = BinaryOperator::Comma; break;
3115 }
3116 return Opc;
3117}
3118
3119static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3120 tok::TokenKind Kind) {
3121 UnaryOperator::Opcode Opc;
3122 switch (Kind) {
3123 default: assert(0 && "Unknown unary op!");
3124 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3125 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3126 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3127 case tok::star: Opc = UnaryOperator::Deref; break;
3128 case tok::plus: Opc = UnaryOperator::Plus; break;
3129 case tok::minus: Opc = UnaryOperator::Minus; break;
3130 case tok::tilde: Opc = UnaryOperator::Not; break;
3131 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003132 case tok::kw___real: Opc = UnaryOperator::Real; break;
3133 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3134 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3135 }
3136 return Opc;
3137}
3138
Douglas Gregord7f915e2008-11-06 23:29:22 +00003139/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3140/// operator @p Opc at location @c TokLoc. This routine only supports
3141/// built-in operations; ActOnBinOp handles overloaded operators.
3142Action::ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3143 unsigned Op,
3144 Expr *lhs, Expr *rhs) {
3145 QualType ResultTy; // Result type of the binary operator.
3146 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3147 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3148
3149 switch (Opc) {
3150 default:
3151 assert(0 && "Unknown binary expr!");
3152 case BinaryOperator::Assign:
3153 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3154 break;
3155 case BinaryOperator::Mul:
3156 case BinaryOperator::Div:
3157 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3158 break;
3159 case BinaryOperator::Rem:
3160 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3161 break;
3162 case BinaryOperator::Add:
3163 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3164 break;
3165 case BinaryOperator::Sub:
3166 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3167 break;
3168 case BinaryOperator::Shl:
3169 case BinaryOperator::Shr:
3170 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3171 break;
3172 case BinaryOperator::LE:
3173 case BinaryOperator::LT:
3174 case BinaryOperator::GE:
3175 case BinaryOperator::GT:
3176 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3177 break;
3178 case BinaryOperator::EQ:
3179 case BinaryOperator::NE:
3180 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3181 break;
3182 case BinaryOperator::And:
3183 case BinaryOperator::Xor:
3184 case BinaryOperator::Or:
3185 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3186 break;
3187 case BinaryOperator::LAnd:
3188 case BinaryOperator::LOr:
3189 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3190 break;
3191 case BinaryOperator::MulAssign:
3192 case BinaryOperator::DivAssign:
3193 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3194 if (!CompTy.isNull())
3195 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3196 break;
3197 case BinaryOperator::RemAssign:
3198 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3199 if (!CompTy.isNull())
3200 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3201 break;
3202 case BinaryOperator::AddAssign:
3203 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3204 if (!CompTy.isNull())
3205 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3206 break;
3207 case BinaryOperator::SubAssign:
3208 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3209 if (!CompTy.isNull())
3210 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3211 break;
3212 case BinaryOperator::ShlAssign:
3213 case BinaryOperator::ShrAssign:
3214 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3215 if (!CompTy.isNull())
3216 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3217 break;
3218 case BinaryOperator::AndAssign:
3219 case BinaryOperator::XorAssign:
3220 case BinaryOperator::OrAssign:
3221 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3222 if (!CompTy.isNull())
3223 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3224 break;
3225 case BinaryOperator::Comma:
3226 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3227 break;
3228 }
3229 if (ResultTy.isNull())
3230 return true;
3231 if (CompTy.isNull())
3232 return new BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc);
3233 else
3234 return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, OpLoc);
3235}
3236
Chris Lattner4b009652007-07-25 00:24:17 +00003237// Binary Operators. 'Tok' is the token for the operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003238Action::ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3239 tok::TokenKind Kind,
Chris Lattner4b009652007-07-25 00:24:17 +00003240 ExprTy *LHS, ExprTy *RHS) {
3241 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3242 Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
3243
Steve Naroff87d58b42007-09-16 03:34:24 +00003244 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3245 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003246
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003247 // If either expression is type-dependent, just build the AST.
3248 // FIXME: We'll need to perform some caching of the result of name
3249 // lookup for operator+.
3250 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3251 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3252 return new CompoundAssignOperator(lhs, rhs, Opc, Context.DependentTy,
3253 Context.DependentTy, TokLoc);
3254 else
3255 return new BinaryOperator(lhs, rhs, Opc, Context.DependentTy, TokLoc);
3256 }
3257
Douglas Gregord7f915e2008-11-06 23:29:22 +00003258 if (getLangOptions().CPlusPlus &&
3259 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3260 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003261 // If this is one of the assignment operators, we only perform
3262 // overload resolution if the left-hand side is a class or
3263 // enumeration type (C++ [expr.ass]p3).
3264 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3265 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3266 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3267 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003268
3269 // Determine which overloaded operator we're dealing with.
3270 static const OverloadedOperatorKind OverOps[] = {
3271 OO_Star, OO_Slash, OO_Percent,
3272 OO_Plus, OO_Minus,
3273 OO_LessLess, OO_GreaterGreater,
3274 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3275 OO_EqualEqual, OO_ExclaimEqual,
3276 OO_Amp,
3277 OO_Caret,
3278 OO_Pipe,
3279 OO_AmpAmp,
3280 OO_PipePipe,
3281 OO_Equal, OO_StarEqual,
3282 OO_SlashEqual, OO_PercentEqual,
3283 OO_PlusEqual, OO_MinusEqual,
3284 OO_LessLessEqual, OO_GreaterGreaterEqual,
3285 OO_AmpEqual, OO_CaretEqual,
3286 OO_PipeEqual,
3287 OO_Comma
3288 };
3289 OverloadedOperatorKind OverOp = OverOps[Opc];
3290
Douglas Gregor5ed15042008-11-18 23:14:02 +00003291 // Add the appropriate overloaded operators (C++ [over.match.oper])
3292 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003293 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003294 Expr *Args[2] = { lhs, rhs };
Douglas Gregor5ed15042008-11-18 23:14:02 +00003295 AddOperatorCandidates(OverOp, S, Args, 2, CandidateSet);
Douglas Gregord7f915e2008-11-06 23:29:22 +00003296
3297 // Perform overload resolution.
3298 OverloadCandidateSet::iterator Best;
3299 switch (BestViableFunction(CandidateSet, Best)) {
3300 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003301 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003302 FunctionDecl *FnDecl = Best->Function;
3303
Douglas Gregor70d26122008-11-12 17:17:38 +00003304 if (FnDecl) {
3305 // We matched an overloaded operator. Build a call to that
3306 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003307
Douglas Gregor70d26122008-11-12 17:17:38 +00003308 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003309 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3310 if (PerformObjectArgumentInitialization(lhs, Method) ||
3311 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3312 "passing"))
3313 return true;
3314 } else {
3315 // Convert the arguments.
3316 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3317 "passing") ||
3318 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3319 "passing"))
3320 return true;
3321 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003322
Douglas Gregor70d26122008-11-12 17:17:38 +00003323 // Determine the result type
3324 QualType ResultTy
3325 = FnDecl->getType()->getAsFunctionType()->getResultType();
3326 ResultTy = ResultTy.getNonReferenceType();
3327
3328 // Build the actual expression node.
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003329 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3330 SourceLocation());
3331 UsualUnaryConversions(FnExpr);
3332
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003333 return new CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy, TokLoc);
Douglas Gregor70d26122008-11-12 17:17:38 +00003334 } else {
3335 // We matched a built-in operator. Convert the arguments, then
3336 // break out so that we will build the appropriate built-in
3337 // operator node.
3338 if (PerformCopyInitialization(lhs, Best->BuiltinTypes.ParamTypes[0],
3339 "passing") ||
3340 PerformCopyInitialization(rhs, Best->BuiltinTypes.ParamTypes[1],
3341 "passing"))
3342 return true;
3343
3344 break;
3345 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003346 }
3347
3348 case OR_No_Viable_Function:
3349 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003350 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003351 break;
3352
3353 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003354 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3355 << BinaryOperator::getOpcodeStr(Opc)
3356 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003357 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3358 return true;
3359 }
3360
Douglas Gregor70d26122008-11-12 17:17:38 +00003361 // Either we found no viable overloaded operator or we matched a
3362 // built-in operator. In either case, fall through to trying to
3363 // build a built-in operation.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003364 }
Chris Lattner4b009652007-07-25 00:24:17 +00003365
Douglas Gregord7f915e2008-11-06 23:29:22 +00003366 // Build a built-in binary operation.
3367 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00003368}
3369
3370// Unary Operators. 'Tok' is the token for the operator.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003371Action::ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3372 tok::TokenKind Op, ExprTy *input) {
Chris Lattner4b009652007-07-25 00:24:17 +00003373 Expr *Input = (Expr*)input;
3374 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003375
3376 if (getLangOptions().CPlusPlus &&
3377 (Input->getType()->isRecordType()
3378 || Input->getType()->isEnumeralType())) {
3379 // Determine which overloaded operator we're dealing with.
3380 static const OverloadedOperatorKind OverOps[] = {
3381 OO_None, OO_None,
3382 OO_PlusPlus, OO_MinusMinus,
3383 OO_Amp, OO_Star,
3384 OO_Plus, OO_Minus,
3385 OO_Tilde, OO_Exclaim,
3386 OO_None, OO_None,
3387 OO_None,
3388 OO_None
3389 };
3390 OverloadedOperatorKind OverOp = OverOps[Opc];
3391
3392 // Add the appropriate overloaded operators (C++ [over.match.oper])
3393 // to the candidate set.
3394 OverloadCandidateSet CandidateSet;
3395 if (OverOp != OO_None)
3396 AddOperatorCandidates(OverOp, S, &Input, 1, CandidateSet);
3397
3398 // Perform overload resolution.
3399 OverloadCandidateSet::iterator Best;
3400 switch (BestViableFunction(CandidateSet, Best)) {
3401 case OR_Success: {
3402 // We found a built-in operator or an overloaded operator.
3403 FunctionDecl *FnDecl = Best->Function;
3404
3405 if (FnDecl) {
3406 // We matched an overloaded operator. Build a call to that
3407 // operator.
3408
3409 // Convert the arguments.
3410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3411 if (PerformObjectArgumentInitialization(Input, Method))
3412 return true;
3413 } else {
3414 // Convert the arguments.
3415 if (PerformCopyInitialization(Input,
3416 FnDecl->getParamDecl(0)->getType(),
3417 "passing"))
3418 return true;
3419 }
3420
3421 // Determine the result type
3422 QualType ResultTy
3423 = FnDecl->getType()->getAsFunctionType()->getResultType();
3424 ResultTy = ResultTy.getNonReferenceType();
3425
3426 // Build the actual expression node.
3427 Expr *FnExpr = new DeclRefExpr(FnDecl, FnDecl->getType(),
3428 SourceLocation());
3429 UsualUnaryConversions(FnExpr);
3430
3431 return new CXXOperatorCallExpr(FnExpr, &Input, 1, ResultTy, OpLoc);
3432 } else {
3433 // We matched a built-in operator. Convert the arguments, then
3434 // break out so that we will build the appropriate built-in
3435 // operator node.
3436 if (PerformCopyInitialization(Input, Best->BuiltinTypes.ParamTypes[0],
3437 "passing"))
3438 return true;
3439
3440 break;
3441 }
3442 }
3443
3444 case OR_No_Viable_Function:
3445 // No viable function; fall through to handling this as a
3446 // built-in operator, which will produce an error message for us.
3447 break;
3448
3449 case OR_Ambiguous:
3450 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
3451 << UnaryOperator::getOpcodeStr(Opc)
3452 << Input->getSourceRange();
3453 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3454 return true;
3455 }
3456
3457 // Either we found no viable overloaded operator or we matched a
3458 // built-in operator. In either case, fall through to trying to
3459 // build a built-in operation.
3460 }
3461
Chris Lattner4b009652007-07-25 00:24:17 +00003462 QualType resultType;
3463 switch (Opc) {
3464 default:
3465 assert(0 && "Unimplemented unary expr!");
3466 case UnaryOperator::PreInc:
3467 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003468 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3469 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00003470 break;
3471 case UnaryOperator::AddrOf:
3472 resultType = CheckAddressOfOperand(Input, OpLoc);
3473 break;
3474 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00003475 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00003476 resultType = CheckIndirectionOperand(Input, OpLoc);
3477 break;
3478 case UnaryOperator::Plus:
3479 case UnaryOperator::Minus:
3480 UsualUnaryConversions(Input);
3481 resultType = Input->getType();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003482 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3483 break;
3484 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3485 resultType->isEnumeralType())
3486 break;
3487 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3488 Opc == UnaryOperator::Plus &&
3489 resultType->isPointerType())
3490 break;
3491
Chris Lattner77d52da2008-11-20 06:06:08 +00003492 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003493 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003494 case UnaryOperator::Not: // bitwise complement
3495 UsualUnaryConversions(Input);
3496 resultType = Input->getType();
Chris Lattnerbd695022008-07-25 23:52:49 +00003497 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3498 if (resultType->isComplexType() || resultType->isComplexIntegerType())
3499 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00003500 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003501 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00003502 else if (!resultType->isIntegerType())
Chris Lattner77d52da2008-11-20 06:06:08 +00003503 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003504 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003505 break;
3506 case UnaryOperator::LNot: // logical negation
3507 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3508 DefaultFunctionArrayConversion(Input);
3509 resultType = Input->getType();
3510 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Chris Lattner77d52da2008-11-20 06:06:08 +00003511 return Diag(OpLoc, diag::err_typecheck_unary_expr)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003512 << resultType << Input->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003513 // LNot always has type int. C99 6.5.3.3p5.
3514 resultType = Context.IntTy;
3515 break;
Chris Lattner03931a72007-08-24 21:16:53 +00003516 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00003517 case UnaryOperator::Imag:
Chris Lattner5110ad52007-08-24 21:41:10 +00003518 resultType = CheckRealImagOperand(Input, OpLoc);
Chris Lattner03931a72007-08-24 21:16:53 +00003519 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003520 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00003521 resultType = Input->getType();
3522 break;
3523 }
3524 if (resultType.isNull())
3525 return true;
3526 return new UnaryOperator(Input, Opc, resultType, OpLoc);
3527}
3528
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003529/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3530Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00003531 SourceLocation LabLoc,
3532 IdentifierInfo *LabelII) {
3533 // Look up the record for this label identifier.
3534 LabelStmt *&LabelDecl = LabelMap[LabelII];
3535
Daniel Dunbar879788d2008-08-04 16:51:22 +00003536 // If we haven't seen this label yet, create a forward reference. It
3537 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Chris Lattner4b009652007-07-25 00:24:17 +00003538 if (LabelDecl == 0)
3539 LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
3540
3541 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnera0d03a72007-08-03 17:31:20 +00003542 return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
3543 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00003544}
3545
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003546Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00003547 SourceLocation RPLoc) { // "({..})"
3548 Stmt *SubStmt = static_cast<Stmt*>(substmt);
3549 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
3550 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
3551
3552 // FIXME: there are a variety of strange constraints to enforce here, for
3553 // example, it is not possible to goto into a stmt expression apparently.
3554 // More semantic analysis is needed.
3555
3556 // FIXME: the last statement in the compount stmt has its value used. We
3557 // should not warn about it being unused.
3558
3559 // If there are sub stmts in the compound stmt, take the type of the last one
3560 // as the type of the stmtexpr.
3561 QualType Ty = Context.VoidTy;
3562
Chris Lattner200964f2008-07-26 19:51:01 +00003563 if (!Compound->body_empty()) {
3564 Stmt *LastStmt = Compound->body_back();
3565 // If LastStmt is a label, skip down through into the body.
3566 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
3567 LastStmt = Label->getSubStmt();
3568
3569 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00003570 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00003571 }
Chris Lattner4b009652007-07-25 00:24:17 +00003572
3573 return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
3574}
Steve Naroff63bad2d2007-08-01 22:05:33 +00003575
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003576Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
3577 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003578 SourceLocation TypeLoc,
3579 TypeTy *argty,
3580 OffsetOfComponent *CompPtr,
3581 unsigned NumComponents,
3582 SourceLocation RPLoc) {
3583 QualType ArgTy = QualType::getFromOpaquePtr(argty);
3584 assert(!ArgTy.isNull() && "Missing type argument!");
3585
3586 // We must have at least one component that refers to the type, and the first
3587 // one is known to be a field designator. Verify that the ArgTy represents
3588 // a struct/union/class.
3589 if (!ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00003590 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003591
3592 // Otherwise, create a compound literal expression as the base, and
3593 // iteratively process the offsetof designators.
Steve Naroffbe37fc02008-01-14 18:19:28 +00003594 Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003595
Chris Lattnerb37522e2007-08-31 21:49:13 +00003596 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
3597 // GCC extension, diagnose them.
3598 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003599 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
3600 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Chris Lattnerb37522e2007-08-31 21:49:13 +00003601
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003602 for (unsigned i = 0; i != NumComponents; ++i) {
3603 const OffsetOfComponent &OC = CompPtr[i];
3604 if (OC.isBrackets) {
3605 // Offset of an array sub-field. TODO: Should we allow vector elements?
Chris Lattnera1923f62008-08-04 07:31:14 +00003606 const ArrayType *AT = Context.getAsArrayType(Res->getType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003607 if (!AT) {
3608 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003609 return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003610 }
3611
Chris Lattner2af6a802007-08-30 17:59:59 +00003612 // FIXME: C++: Verify that operator[] isn't overloaded.
3613
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003614 // C99 6.5.2.1p1
3615 Expr *Idx = static_cast<Expr*>(OC.U.E);
3616 if (!Idx->getType()->isIntegerType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00003617 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
3618 << Idx->getSourceRange();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003619
3620 Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
3621 continue;
3622 }
3623
3624 const RecordType *RC = Res->getType()->getAsRecordType();
3625 if (!RC) {
3626 delete Res;
Chris Lattner4bfd2232008-11-24 06:25:27 +00003627 return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003628 }
3629
3630 // Get the decl corresponding to this.
3631 RecordDecl *RD = RC->getDecl();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00003632 FieldDecl *MemberDecl
3633 = dyn_cast_or_null<FieldDecl>(LookupDecl(OC.U.IdentInfo,
3634 Decl::IDNS_Ordinary,
3635 S, RD, false, false));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003636 if (!MemberDecl)
Chris Lattner65cae292008-11-19 08:23:25 +00003637 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
3638 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Chris Lattner2af6a802007-08-30 17:59:59 +00003639
3640 // FIXME: C++: Verify that MemberDecl isn't a static field.
3641 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman76b49832008-02-06 22:48:16 +00003642 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
3643 // matter here.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003644 Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd,
3645 MemberDecl->getType().getNonReferenceType());
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003646 }
3647
3648 return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
3649 BuiltinLoc);
3650}
3651
3652
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003653Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00003654 TypeTy *arg1, TypeTy *arg2,
3655 SourceLocation RPLoc) {
3656 QualType argT1 = QualType::getFromOpaquePtr(arg1);
3657 QualType argT2 = QualType::getFromOpaquePtr(arg2);
3658
3659 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
3660
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003661 return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00003662}
3663
Steve Naroff5cbb02f2007-09-16 14:56:35 +00003664Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00003665 ExprTy *expr1, ExprTy *expr2,
3666 SourceLocation RPLoc) {
3667 Expr *CondExpr = static_cast<Expr*>(cond);
3668 Expr *LHSExpr = static_cast<Expr*>(expr1);
3669 Expr *RHSExpr = static_cast<Expr*>(expr2);
3670
3671 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
3672
3673 // The conditional expression is required to be a constant expression.
3674 llvm::APSInt condEval(32);
3675 SourceLocation ExpLoc;
3676 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003677 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
3678 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00003679
3680 // If the condition is > zero, then the AST type is the same as the LSHExpr.
3681 QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
3682 RHSExpr->getType();
3683 return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
3684}
3685
Steve Naroff52a81c02008-09-03 18:15:37 +00003686//===----------------------------------------------------------------------===//
3687// Clang Extensions.
3688//===----------------------------------------------------------------------===//
3689
3690/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00003691void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003692 // Analyze block parameters.
3693 BlockSemaInfo *BSI = new BlockSemaInfo();
3694
3695 // Add BSI to CurBlock.
3696 BSI->PrevBlockInfo = CurBlock;
3697 CurBlock = BSI;
3698
3699 BSI->ReturnType = 0;
3700 BSI->TheScope = BlockScope;
3701
Steve Naroff52059382008-10-10 01:28:17 +00003702 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00003703 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00003704}
3705
3706void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
Steve Naroff52a81c02008-09-03 18:15:37 +00003707 // Analyze arguments to block.
3708 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
3709 "Not a function declarator!");
3710 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
3711
Steve Naroff52059382008-10-10 01:28:17 +00003712 CurBlock->hasPrototype = FTI.hasPrototype;
3713 CurBlock->isVariadic = true;
Steve Naroff52a81c02008-09-03 18:15:37 +00003714
3715 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
3716 // no arguments, not a function that takes a single void argument.
3717 if (FTI.hasPrototype &&
3718 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
3719 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
3720 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
3721 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00003722 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00003723 } else if (FTI.hasPrototype) {
3724 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00003725 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
3726 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00003727 }
Steve Naroff52059382008-10-10 01:28:17 +00003728 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
3729
3730 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
3731 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
3732 // If this has an identifier, add it to the scope stack.
3733 if ((*AI)->getIdentifier())
3734 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00003735}
3736
3737/// ActOnBlockError - If there is an error parsing a block, this callback
3738/// is invoked to pop the information about the block from the action impl.
3739void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
3740 // Ensure that CurBlock is deleted.
3741 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
3742
3743 // Pop off CurBlock, handle nested blocks.
3744 CurBlock = CurBlock->PrevBlockInfo;
3745
3746 // FIXME: Delete the ParmVarDecl objects as well???
3747
3748}
3749
3750/// ActOnBlockStmtExpr - This is called when the body of a block statement
3751/// literal was successfully completed. ^(int x){...}
3752Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
3753 Scope *CurScope) {
3754 // Ensure that CurBlock is deleted.
3755 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
3756 llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
3757
Steve Naroff52059382008-10-10 01:28:17 +00003758 PopDeclContext();
3759
Steve Naroff52a81c02008-09-03 18:15:37 +00003760 // Pop off CurBlock, handle nested blocks.
3761 CurBlock = CurBlock->PrevBlockInfo;
3762
3763 QualType RetTy = Context.VoidTy;
3764 if (BSI->ReturnType)
3765 RetTy = QualType(BSI->ReturnType, 0);
3766
3767 llvm::SmallVector<QualType, 8> ArgTypes;
3768 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
3769 ArgTypes.push_back(BSI->Params[i]->getType());
3770
3771 QualType BlockTy;
3772 if (!BSI->hasPrototype)
3773 BlockTy = Context.getFunctionTypeNoProto(RetTy);
3774 else
3775 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00003776 BSI->isVariadic, 0);
Steve Naroff52a81c02008-09-03 18:15:37 +00003777
3778 BlockTy = Context.getBlockPointerType(BlockTy);
Steve Naroff9ac456d2008-10-08 17:01:13 +00003779
Steve Naroff95029d92008-10-08 18:44:00 +00003780 BSI->TheDecl->setBody(Body.take());
3781 return new BlockExpr(BSI->TheDecl, BlockTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00003782}
3783
Nate Begemanbd881ef2008-01-30 20:50:20 +00003784/// ExprsMatchFnType - return true if the Exprs in array Args have
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003785/// QualTypes that match the QualTypes of the arguments of the FnType.
Nate Begemanbd881ef2008-01-30 20:50:20 +00003786/// The number of arguments has already been validated to match the number of
3787/// arguments in FnType.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003788static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
3789 ASTContext &Context) {
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003790 unsigned NumParams = FnType->getNumArgs();
Nate Begeman778fd3b2008-04-18 23:35:14 +00003791 for (unsigned i = 0; i != NumParams; ++i) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003792 QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
3793 QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
Nate Begeman778fd3b2008-04-18 23:35:14 +00003794
3795 if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003796 return false;
Nate Begeman778fd3b2008-04-18 23:35:14 +00003797 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003798 return true;
3799}
3800
3801Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
3802 SourceLocation *CommaLocs,
3803 SourceLocation BuiltinLoc,
3804 SourceLocation RParenLoc) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003805 // __builtin_overload requires at least 2 arguments
3806 if (NumArgs < 2)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003807 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3808 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003809
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003810 // The first argument is required to be a constant expression. It tells us
3811 // the number of arguments to pass to each of the functions to be overloaded.
Nate Begemanc6078c92008-01-31 05:38:29 +00003812 Expr **Args = reinterpret_cast<Expr**>(args);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003813 Expr *NParamsExpr = Args[0];
3814 llvm::APSInt constEval(32);
3815 SourceLocation ExpLoc;
3816 if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003817 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3818 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003819
3820 // Verify that the number of parameters is > 0
3821 unsigned NumParams = constEval.getZExtValue();
3822 if (NumParams == 0)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003823 return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
3824 << NParamsExpr->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003825 // Verify that we have at least 1 + NumParams arguments to the builtin.
3826 if ((NumParams + 1) > NumArgs)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003827 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3828 << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003829
3830 // Figure out the return type, by matching the args to one of the functions
Nate Begemanbd881ef2008-01-30 20:50:20 +00003831 // listed after the parameters.
Nate Begemanc6078c92008-01-31 05:38:29 +00003832 OverloadExpr *OE = 0;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003833 for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
3834 // UsualUnaryConversions will convert the function DeclRefExpr into a
3835 // pointer to function.
3836 Expr *Fn = UsualUnaryConversions(Args[i]);
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003837 const FunctionTypeProto *FnType = 0;
3838 if (const PointerType *PT = Fn->getType()->getAsPointerType())
3839 FnType = PT->getPointeeType()->getAsFunctionTypeProto();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003840
3841 // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
3842 // parameters, and the number of parameters must match the value passed to
3843 // the builtin.
3844 if (!FnType || (FnType->getNumArgs() != NumParams))
Chris Lattner9d2cf082008-11-19 05:27:50 +00003845 return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
3846 << Fn->getSourceRange();
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003847
3848 // Scan the parameter list for the FunctionType, checking the QualType of
Nate Begemanbd881ef2008-01-30 20:50:20 +00003849 // each parameter against the QualTypes of the arguments to the builtin.
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003850 // If they match, return a new OverloadExpr.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003851 if (ExprsMatchFnType(Args+1, FnType, Context)) {
Nate Begemanc6078c92008-01-31 05:38:29 +00003852 if (OE)
Chris Lattner9d2cf082008-11-19 05:27:50 +00003853 return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
3854 << OE->getFn()->getSourceRange();
Nate Begemanc6078c92008-01-31 05:38:29 +00003855 // Remember our match, and continue processing the remaining arguments
3856 // to catch any errors.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003857 OE = new OverloadExpr(Args, NumArgs, i,
3858 FnType->getResultType().getNonReferenceType(),
Nate Begemanc6078c92008-01-31 05:38:29 +00003859 BuiltinLoc, RParenLoc);
3860 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003861 }
Nate Begemanc6078c92008-01-31 05:38:29 +00003862 // Return the newly created OverloadExpr node, if we succeded in matching
3863 // exactly one of the candidate functions.
3864 if (OE)
3865 return OE;
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003866
3867 // If we didn't find a matching function Expr in the __builtin_overload list
3868 // the return an error.
3869 std::string typeNames;
Nate Begemanbd881ef2008-01-30 20:50:20 +00003870 for (unsigned i = 0; i != NumParams; ++i) {
3871 if (i != 0) typeNames += ", ";
3872 typeNames += Args[i+1]->getType().getAsString();
3873 }
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003874
Chris Lattner77d52da2008-11-20 06:06:08 +00003875 return Diag(BuiltinLoc, diag::err_overload_no_match)
3876 << typeNames << SourceRange(BuiltinLoc, RParenLoc);
Nate Begeman9f3bfb72008-01-17 17:46:27 +00003877}
3878
Anders Carlsson36760332007-10-15 20:28:48 +00003879Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3880 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00003881 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00003882 Expr *E = static_cast<Expr*>(expr);
3883 QualType T = QualType::getFromOpaquePtr(type);
3884
3885 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003886
3887 // Get the va_list type
3888 QualType VaListType = Context.getBuiltinVaListType();
3889 // Deal with implicit array decay; for example, on x86-64,
3890 // va_list is an array, but it's supposed to decay to
3891 // a pointer for va_arg.
3892 if (VaListType->isArrayType())
3893 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00003894 // Make sure the input expression also decays appropriately.
3895 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00003896
3897 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00003898 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00003899 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003900 << E->getType() << E->getSourceRange();
Anders Carlsson36760332007-10-15 20:28:48 +00003901
3902 // FIXME: Warn if a non-POD type is passed in.
3903
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003904 return new VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00003905}
3906
Douglas Gregorad4b3792008-11-29 04:51:27 +00003907Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
3908 // The type of __null will be int or long, depending on the size of
3909 // pointers on the target.
3910 QualType Ty;
3911 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
3912 Ty = Context.IntTy;
3913 else
3914 Ty = Context.LongTy;
3915
3916 return new GNUNullExpr(Ty, TokenLoc);
3917}
3918
Chris Lattner005ed752008-01-04 18:04:52 +00003919bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3920 SourceLocation Loc,
3921 QualType DstType, QualType SrcType,
3922 Expr *SrcExpr, const char *Flavor) {
3923 // Decode the result (notice that AST's are still created for extensions).
3924 bool isInvalid = false;
3925 unsigned DiagKind;
3926 switch (ConvTy) {
3927 default: assert(0 && "Unknown conversion type");
3928 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003929 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00003930 DiagKind = diag::ext_typecheck_convert_pointer_int;
3931 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003932 case IntToPointer:
3933 DiagKind = diag::ext_typecheck_convert_int_pointer;
3934 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003935 case IncompatiblePointer:
3936 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3937 break;
3938 case FunctionVoidPointer:
3939 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3940 break;
3941 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00003942 // If the qualifiers lost were because we were applying the
3943 // (deprecated) C++ conversion from a string literal to a char*
3944 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
3945 // Ideally, this check would be performed in
3946 // CheckPointerTypesForAssignment. However, that would require a
3947 // bit of refactoring (so that the second argument is an
3948 // expression, rather than a type), which should be done as part
3949 // of a larger effort to fix CheckPointerTypesForAssignment for
3950 // C++ semantics.
3951 if (getLangOptions().CPlusPlus &&
3952 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3953 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00003954 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3955 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003956 case IntToBlockPointer:
3957 DiagKind = diag::err_int_to_block_pointer;
3958 break;
3959 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00003960 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003961 break;
Steve Naroff19608432008-10-14 22:18:38 +00003962 case IncompatibleObjCQualifiedId:
3963 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
3964 // it can give a more specific diagnostic.
3965 DiagKind = diag::warn_incompatible_qualified_id;
3966 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003967 case Incompatible:
3968 DiagKind = diag::err_typecheck_convert_incompatible;
3969 isInvalid = true;
3970 break;
3971 }
3972
Chris Lattner271d4c22008-11-24 05:29:24 +00003973 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
3974 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00003975 return isInvalid;
3976}
Anders Carlssond5201b92008-11-30 19:50:32 +00003977
3978bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
3979{
3980 Expr::EvalResult EvalResult;
3981
3982 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
3983 EvalResult.HasSideEffects) {
3984 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
3985
3986 if (EvalResult.Diag) {
3987 // We only show the note if it's not the usual "invalid subexpression"
3988 // or if it's actually in a subexpression.
3989 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
3990 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
3991 Diag(EvalResult.DiagLoc, EvalResult.Diag);
3992 }
3993
3994 return true;
3995 }
3996
3997 if (EvalResult.Diag) {
3998 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
3999 E->getSourceRange();
4000
4001 // Print the reason it's not a constant.
4002 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4003 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4004 }
4005
4006 if (Result)
4007 *Result = EvalResult.Val.getInt();
4008 return false;
4009}