blob: 32ef0f7b35190b5da900323ed01112f0600b3466 [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"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#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
Douglas Gregoraa57e862009-02-18 21:56:37 +000029/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000043 // Implementing deprecated stuff requires referencing deprecated
44 // stuff. Don't warn if we are implementing a deprecated
45 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
51 isSilenced = ND->getAttr<DeprecatedAttr>();
52
53 // If this is an Objective-C method implementation, check to see if the
54 // method was deprecated on the declaration, not the definition.
55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56 // The semantic decl context of a ObjCMethodDecl is the
57 // ObjCImplementationDecl.
58 if (ObjCImplementationDecl *Impl
59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
61 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
62 MD->isInstanceMethod());
63 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
64 }
65 }
66 }
67
68 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000069 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
70 }
71
Douglas Gregoraa57e862009-02-18 21:56:37 +000072 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000073 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000074 if (FD->isDeleted()) {
75 Diag(Loc, diag::err_deleted_function_use);
76 Diag(D->getLocation(), diag::note_unavailable_here) << true;
77 return true;
78 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000079 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000080
81 // See if the decl is unavailable
82 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000083 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000084 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
85 }
86
Douglas Gregoraa57e862009-02-18 21:56:37 +000087 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000088}
89
Douglas Gregor3bb30002009-02-26 21:00:50 +000090SourceRange Sema::getExprRange(ExprTy *E) const {
91 Expr *Ex = (Expr *)E;
92 return Ex? Ex->getSourceRange() : SourceRange();
93}
94
Chris Lattner299b8842008-07-25 21:10:04 +000095//===----------------------------------------------------------------------===//
96// Standard Promotions and Conversions
97//===----------------------------------------------------------------------===//
98
Chris Lattner299b8842008-07-25 21:10:04 +000099/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
100void Sema::DefaultFunctionArrayConversion(Expr *&E) {
101 QualType Ty = E->getType();
102 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
103
Chris Lattner299b8842008-07-25 21:10:04 +0000104 if (Ty->isFunctionType())
105 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000106 else if (Ty->isArrayType()) {
107 // In C90 mode, arrays only promote to pointers if the array expression is
108 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
109 // type 'array of type' is converted to an expression that has type 'pointer
110 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
111 // that has type 'array of type' ...". The relevant change is "an lvalue"
112 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000113 //
114 // C++ 4.2p1:
115 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
116 // T" can be converted to an rvalue of type "pointer to T".
117 //
118 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
119 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000120 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
121 }
Chris Lattner299b8842008-07-25 21:10:04 +0000122}
123
124/// UsualUnaryConversions - Performs various conversions that are common to most
125/// operators (C99 6.3). The conversions of array and function types are
126/// sometimes surpressed. For example, the array->pointer conversion doesn't
127/// apply if the array is an argument to the sizeof or address (&) operators.
128/// In these instances, this routine should *not* be called.
129Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
130 QualType Ty = Expr->getType();
131 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
132
Chris Lattner299b8842008-07-25 21:10:04 +0000133 if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
134 ImpCastExprToType(Expr, Context.IntTy);
135 else
136 DefaultFunctionArrayConversion(Expr);
137
138 return Expr;
139}
140
Chris Lattner9305c3d2008-07-25 22:25:12 +0000141/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
142/// do not have a prototype. Arguments that have type float are promoted to
143/// double. All other argument types are converted by UsualUnaryConversions().
144void Sema::DefaultArgumentPromotion(Expr *&Expr) {
145 QualType Ty = Expr->getType();
146 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
147
148 // If this is a 'float' (CVR qualified or typedef) promote to double.
149 if (const BuiltinType *BT = Ty->getAsBuiltinType())
150 if (BT->getKind() == BuiltinType::Float)
151 return ImpCastExprToType(Expr, Context.DoubleTy);
152
153 UsualUnaryConversions(Expr);
154}
155
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000156// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
157// will warn if the resulting type is not a POD type.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000158void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000159 DefaultArgumentPromotion(Expr);
160
161 if (!Expr->getType()->isPODType()) {
162 Diag(Expr->getLocStart(),
163 diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
164 Expr->getType() << CT;
165 }
166}
167
168
Chris Lattner299b8842008-07-25 21:10:04 +0000169/// UsualArithmeticConversions - Performs various conversions that are common to
170/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
171/// routine returns the first non-arithmetic type found. The client is
172/// responsible for emitting appropriate error diagnostics.
173/// FIXME: verify the conversion rules for "complex int" are consistent with
174/// GCC.
175QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
176 bool isCompAssign) {
177 if (!isCompAssign) {
178 UsualUnaryConversions(lhsExpr);
179 UsualUnaryConversions(rhsExpr);
180 }
Douglas Gregor70d26122008-11-12 17:17:38 +0000181
Chris Lattner299b8842008-07-25 21:10:04 +0000182 // For conversion purposes, we ignore any qualifiers.
183 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000184 QualType lhs =
185 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
186 QualType rhs =
187 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000188
189 // If both types are identical, no conversion is needed.
190 if (lhs == rhs)
191 return lhs;
192
193 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
194 // The caller can deal with this (e.g. pointer + int).
195 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
196 return lhs;
197
198 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
199 if (!isCompAssign) {
200 ImpCastExprToType(lhsExpr, destType);
201 ImpCastExprToType(rhsExpr, destType);
202 }
203 return destType;
204}
205
206QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
207 // Perform the usual unary conversions. We do this early so that
208 // integral promotions to "int" can allow us to exit early, in the
209 // lhs == rhs check. Also, for conversion purposes, we ignore any
210 // qualifiers. For example, "const float" and "float" are
211 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000212 if (lhs->isPromotableIntegerType())
213 lhs = Context.IntTy;
214 else
215 lhs = lhs.getUnqualifiedType();
216 if (rhs->isPromotableIntegerType())
217 rhs = Context.IntTy;
218 else
219 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000220
Chris Lattner299b8842008-07-25 21:10:04 +0000221 // If both types are identical, no conversion is needed.
222 if (lhs == rhs)
223 return lhs;
224
225 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
226 // The caller can deal with this (e.g. pointer + int).
227 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
228 return lhs;
229
230 // At this point, we have two different arithmetic types.
231
232 // Handle complex types first (C99 6.3.1.8p1).
233 if (lhs->isComplexType() || rhs->isComplexType()) {
234 // if we have an integer operand, the result is the complex type.
235 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
236 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000237 return lhs;
238 }
239 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
240 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000241 return rhs;
242 }
243 // This handles complex/complex, complex/float, or float/complex.
244 // When both operands are complex, the shorter operand is converted to the
245 // type of the longer, and that is the type of the result. This corresponds
246 // to what is done when combining two real floating-point operands.
247 // The fun begins when size promotion occur across type domains.
248 // From H&S 6.3.4: When one operand is complex and the other is a real
249 // floating-point type, the less precise type is converted, within it's
250 // real or complex domain, to the precision of the other type. For example,
251 // when combining a "long double" with a "double _Complex", the
252 // "double _Complex" is promoted to "long double _Complex".
253 int result = Context.getFloatingTypeOrder(lhs, rhs);
254
255 if (result > 0) { // The left side is bigger, convert rhs.
256 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000257 } else if (result < 0) { // The right side is bigger, convert lhs.
258 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000259 }
260 // At this point, lhs and rhs have the same rank/size. Now, make sure the
261 // domains match. This is a requirement for our implementation, C99
262 // does not require this promotion.
263 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
264 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000265 return rhs;
266 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000267 return lhs;
268 }
269 }
270 return lhs; // The domain/size match exactly.
271 }
272 // Now handle "real" floating types (i.e. float, double, long double).
273 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
274 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000275 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000276 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000277 return lhs;
278 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000279 if (rhs->isComplexIntegerType()) {
280 // convert rhs to the complex floating point type.
281 return Context.getComplexType(lhs);
282 }
283 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000284 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000285 return rhs;
286 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000287 if (lhs->isComplexIntegerType()) {
288 // convert lhs to the complex floating point type.
289 return Context.getComplexType(rhs);
290 }
Chris Lattner299b8842008-07-25 21:10:04 +0000291 // We have two real floating types, float/complex combos were handled above.
292 // Convert the smaller operand to the bigger result.
293 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000294 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000295 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000296 assert(result < 0 && "illegal float comparison");
297 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000298 }
299 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
300 // Handle GCC complex int extension.
301 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
302 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
303
304 if (lhsComplexInt && rhsComplexInt) {
305 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000306 rhsComplexInt->getElementType()) >= 0)
307 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000308 return rhs;
309 } else if (lhsComplexInt && rhs->isIntegerType()) {
310 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000311 return lhs;
312 } else if (rhsComplexInt && lhs->isIntegerType()) {
313 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000314 return rhs;
315 }
316 }
317 // Finally, we have two differing integer types.
318 // The rules for this case are in C99 6.3.1.8
319 int compare = Context.getIntegerTypeOrder(lhs, rhs);
320 bool lhsSigned = lhs->isSignedIntegerType(),
321 rhsSigned = rhs->isSignedIntegerType();
322 QualType destType;
323 if (lhsSigned == rhsSigned) {
324 // Same signedness; use the higher-ranked type
325 destType = compare >= 0 ? lhs : rhs;
326 } else if (compare != (lhsSigned ? 1 : -1)) {
327 // The unsigned type has greater than or equal rank to the
328 // signed type, so use the unsigned type
329 destType = lhsSigned ? rhs : lhs;
330 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
331 // The two types are different widths; if we are here, that
332 // means the signed type is larger than the unsigned type, so
333 // use the signed type.
334 destType = lhsSigned ? lhs : rhs;
335 } else {
336 // The signed type is higher-ranked than the unsigned type,
337 // but isn't actually any bigger (like unsigned int and long
338 // on most 32-bit systems). Use the unsigned type corresponding
339 // to the signed type.
340 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
341 }
Chris Lattner299b8842008-07-25 21:10:04 +0000342 return destType;
343}
344
345//===----------------------------------------------------------------------===//
346// Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
Steve Naroff87d58b42007-09-16 03:34:24 +0000350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000351/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
353/// multiple tokens. However, the common case is that StringToks points to one
354/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000355///
356Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000358 assert(NumStringToks && "Must have at least one string!");
359
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000360 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000361 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000362 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000363
364 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
365 for (unsigned i = 0; i != NumStringToks; ++i)
366 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000367
Chris Lattnera6dcce32008-02-11 00:02:17 +0000368 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000369 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000370 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000371
372 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
373 if (getLangOptions().CPlusPlus)
374 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000375
Chris Lattnera6dcce32008-02-11 00:02:17 +0000376 // Get an array type for the string, according to C99 6.4.5. This includes
377 // the nul terminator character as well as the string length for pascal
378 // strings.
379 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000380 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000381 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000382
Chris Lattner4b009652007-07-25 00:24:17 +0000383 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000384 return Owned(StringLiteral::Create(Context, Literal.GetString(),
385 Literal.GetStringLength(),
386 Literal.AnyWide, StrTy,
387 &StringTokLocs[0],
388 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000389}
390
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
392/// CurBlock to VD should cause it to be snapshotted (as we do for auto
393/// variables defined outside the block) or false if this is not needed (e.g.
394/// for values inside the block or for globals).
395///
396/// FIXME: This will create BlockDeclRefExprs for global variables,
397/// function references, etc which is suboptimal :) and breaks
398/// things like "integer constant expression" tests.
399static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
400 ValueDecl *VD) {
401 // If the value is defined inside the block, we couldn't snapshot it even if
402 // we wanted to.
403 if (CurBlock->TheDecl == VD->getDeclContext())
404 return false;
405
406 // If this is an enum constant or function, it is constant, don't snapshot.
407 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
408 return false;
409
410 // If this is a reference to an extern, static, or global variable, no need to
411 // snapshot it.
412 // FIXME: What about 'const' variables in C++?
413 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
414 return Var->hasLocalStorage();
415
416 return true;
417}
418
419
420
Steve Naroff0acc9c92007-09-15 18:49:24 +0000421/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000422/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000423/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000424/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000425/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000426Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
427 IdentifierInfo &II,
428 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000429 const CXXScopeSpec *SS,
430 bool isAddressOfOperand) {
431 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000432 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000433}
434
Douglas Gregor566782a2009-01-06 05:10:23 +0000435/// BuildDeclRefExpr - Build either a DeclRefExpr or a
436/// QualifiedDeclRefExpr based on whether or not SS is a
437/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000438DeclRefExpr *
439Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
440 bool TypeDependent, bool ValueDependent,
441 const CXXScopeSpec *SS) {
Steve Naroff774e4152009-01-21 00:14:39 +0000442 if (SS && !SS->isEmpty())
443 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Mike Stump9afab102009-02-19 03:04:26 +0000444 ValueDependent,
445 SS->getRange().getBegin());
Steve Naroff774e4152009-01-21 00:14:39 +0000446 else
447 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000448}
449
Douglas Gregor723d3332009-01-07 00:43:41 +0000450/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
451/// variable corresponding to the anonymous union or struct whose type
452/// is Record.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000453static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000454 assert(Record->isAnonymousStructOrUnion() &&
455 "Record must be an anonymous struct or union!");
456
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000457 // FIXME: Once Decls are directly linked together, this will
Douglas Gregor723d3332009-01-07 00:43:41 +0000458 // be an O(1) operation rather than a slow walk through DeclContext's
459 // vector (which itself will be eliminated). DeclGroups might make
460 // this even better.
461 DeclContext *Ctx = Record->getDeclContext();
462 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
463 DEnd = Ctx->decls_end();
464 D != DEnd; ++D) {
465 if (*D == Record) {
466 // The object for the anonymous struct/union directly
467 // follows its type in the list of declarations.
468 ++D;
469 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000470 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000471 return *D;
472 }
473 }
474
475 assert(false && "Missing object for anonymous record");
476 return 0;
477}
478
Sebastian Redlcd883f72009-01-18 18:53:16 +0000479Sema::OwningExprResult
Douglas Gregor723d3332009-01-07 00:43:41 +0000480Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
481 FieldDecl *Field,
482 Expr *BaseObjectExpr,
483 SourceLocation OpLoc) {
484 assert(Field->getDeclContext()->isRecord() &&
485 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
486 && "Field must be stored inside an anonymous struct or union");
487
488 // Construct the sequence of field member references
489 // we'll have to perform to get to the field in the anonymous
490 // union/struct. The list of members is built from the field
491 // outward, so traverse it backwards to go from an object in
492 // the current context to the field we found.
493 llvm::SmallVector<FieldDecl *, 4> AnonFields;
494 AnonFields.push_back(Field);
495 VarDecl *BaseObject = 0;
496 DeclContext *Ctx = Field->getDeclContext();
497 do {
498 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000499 Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000500 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
501 AnonFields.push_back(AnonField);
502 else {
503 BaseObject = cast<VarDecl>(AnonObject);
504 break;
505 }
506 Ctx = Ctx->getParent();
507 } while (Ctx->isRecord() &&
508 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
509
510 // Build the expression that refers to the base object, from
511 // which we will build a sequence of member references to each
512 // of the anonymous union objects and, eventually, the field we
513 // found via name lookup.
514 bool BaseObjectIsPointer = false;
515 unsigned ExtraQuals = 0;
516 if (BaseObject) {
517 // BaseObject is an anonymous struct/union variable (and is,
518 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000519 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000520 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000521 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000522 ExtraQuals
523 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
524 } else if (BaseObjectExpr) {
525 // The caller provided the base object expression. Determine
526 // whether its a pointer and whether it adds any qualifiers to the
527 // anonymous struct/union fields we're looking into.
528 QualType ObjectType = BaseObjectExpr->getType();
529 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
530 BaseObjectIsPointer = true;
531 ObjectType = ObjectPtr->getPointeeType();
532 }
533 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
534 } else {
535 // We've found a member of an anonymous struct/union that is
536 // inside a non-anonymous struct/union, so in a well-formed
537 // program our base object expression is "this".
538 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
539 if (!MD->isStatic()) {
540 QualType AnonFieldType
541 = Context.getTagDeclType(
542 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
543 QualType ThisType = Context.getTagDeclType(MD->getParent());
544 if ((Context.getCanonicalType(AnonFieldType)
545 == Context.getCanonicalType(ThisType)) ||
546 IsDerivedFrom(ThisType, AnonFieldType)) {
547 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000548 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000549 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000550 BaseObjectIsPointer = true;
551 }
552 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000553 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
554 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000555 }
556 ExtraQuals = MD->getTypeQualifiers();
557 }
558
559 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000560 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
561 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000562 }
563
564 // Build the implicit member references to the field of the
565 // anonymous struct/union.
566 Expr *Result = BaseObjectExpr;
567 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
568 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
569 FI != FIEnd; ++FI) {
570 QualType MemberType = (*FI)->getType();
571 if (!(*FI)->isMutable()) {
572 unsigned combinedQualifiers
573 = MemberType.getCVRQualifiers() | ExtraQuals;
574 MemberType = MemberType.getQualifiedType(combinedQualifiers);
575 }
Steve Naroff774e4152009-01-21 00:14:39 +0000576 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
577 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000578 BaseObjectIsPointer = false;
579 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000580 }
581
Sebastian Redlcd883f72009-01-18 18:53:16 +0000582 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000583}
584
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000585/// ActOnDeclarationNameExpr - The parser has read some kind of name
586/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
587/// performs lookup on that name and returns an expression that refers
588/// to that name. This routine isn't directly called from the parser,
589/// because the parser doesn't know about DeclarationName. Rather,
590/// this routine is called by ActOnIdentifierExpr,
591/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
592/// which form the DeclarationName from the corresponding syntactic
593/// forms.
594///
595/// HasTrailingLParen indicates whether this identifier is used in a
596/// function call context. LookupCtx is only used for a C++
597/// qualified-id (foo::bar) to indicate the class or namespace that
598/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000599///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000600/// isAddressOfOperand means that this expression is the direct operand
601/// of an address-of operator. This matters because this is the only
602/// situation where a qualified name referencing a non-static member may
603/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000604Sema::OwningExprResult
605Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
606 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000607 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000608 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000609 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000610 if (SS && SS->isInvalid())
611 return ExprError();
Douglas Gregor411889e2009-02-13 23:20:09 +0000612 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
613 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000614
Douglas Gregor09be81b2009-02-04 17:27:36 +0000615 NamedDecl *D = 0;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000616 if (Lookup.isAmbiguous()) {
617 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
618 SS && SS->isSet() ? SS->getRange()
619 : SourceRange());
620 return ExprError();
621 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000622 D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000623
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000624 // If this reference is in an Objective-C method, then ivar lookup happens as
625 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000626 IdentifierInfo *II = Name.getAsIdentifierInfo();
627 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000628 // There are two cases to handle here. 1) scoped lookup could have failed,
629 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000630 // found a decl, but that decl is outside the current instance method (i.e.
631 // a global variable). In these two cases, we do a lookup for an ivar with
632 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000633 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000634 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000635 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000636 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000637 if (DiagnoseUseOfDecl(IV, Loc))
638 return ExprError();
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000639 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
640 // If a class method attemps to use a free standing ivar, this is
641 // an error.
642 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
643 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
644 << IV->getDeclName());
645 // If a class method uses a global variable, even if an ivar with
646 // same name exists, use the global.
647 if (!IsClsMethod) {
648 // FIXME: This should use a new expr for a direct reference, don't turn
649 // this into Self->ivar, just return a BareIVarExpr or something.
650 IdentifierInfo &II = Context.Idents.get("self");
651 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
652 ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
653 Loc, static_cast<Expr*>(SelfExpr.release()),
654 true, true);
655 Context.setFieldDecl(IFace, IV, MRef);
656 return Owned(MRef);
657 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000658 }
659 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000660 else if (getCurMethodDecl()->isInstanceMethod()) {
661 // We should warn if a local variable hides an ivar.
662 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
663 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II))
664 Diag(Loc, diag::warn_ivar_use_hidden)<<IV->getDeclName();
665 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000666 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000667 if (D == 0 && II->isStr("super")) {
Steve Naroff6f786252008-06-02 23:03:37 +0000668 QualType T = Context.getPointerType(Context.getObjCInterfaceType(
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000669 getCurMethodDecl()->getClassInterface()));
Steve Naroff774e4152009-01-21 00:14:39 +0000670 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000671 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000672 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000673
Douglas Gregoraa57e862009-02-18 21:56:37 +0000674 // Determine whether this name might be a candidate for
675 // argument-dependent lookup.
676 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
677 HasTrailingLParen;
678
679 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000680 // We've seen something of the form
681 //
682 // identifier(
683 //
684 // and we did not find any entity by the name
685 // "identifier". However, this identifier is still subject to
686 // argument-dependent lookup, so keep track of the name.
687 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
688 Context.OverloadTy,
689 Loc));
690 }
691
Chris Lattner4b009652007-07-25 00:24:17 +0000692 if (D == 0) {
693 // Otherwise, this could be an implicitly declared function reference (legal
694 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000695 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000696 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000697 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000698 else {
699 // If this name wasn't predeclared and if this is not a function call,
700 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000701 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000702 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
703 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000704 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
705 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000706 return ExprError(Diag(Loc, diag::err_undeclared_use)
707 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000708 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000709 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000710 }
711 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000712
Sebastian Redl0c9da212009-02-03 20:19:35 +0000713 // If this is an expression of the form &Class::member, don't build an
714 // implicit member ref, because we want a pointer to the member in general,
715 // not any specific instance's member.
716 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000717 DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
Douglas Gregor09be81b2009-02-04 17:27:36 +0000718 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000719 QualType DType;
720 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
721 DType = FD->getType().getNonReferenceType();
722 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
723 DType = Method->getType();
724 } else if (isa<OverloadedFunctionDecl>(D)) {
725 DType = Context.OverloadTy;
726 }
727 // Could be an inner type. That's diagnosed below, so ignore it here.
728 if (!DType.isNull()) {
729 // The pointer is type- and value-dependent if it points into something
730 // dependent.
731 bool Dependent = false;
732 for (; DC; DC = DC->getParent()) {
733 // FIXME: could stop early at namespace scope.
734 if (DC->isRecord()) {
735 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
736 if (Context.getTypeDeclType(Record)->isDependentType()) {
737 Dependent = true;
738 break;
739 }
740 }
741 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000742 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000743 }
744 }
745 }
746
Douglas Gregor723d3332009-01-07 00:43:41 +0000747 // We may have found a field within an anonymous union or struct
748 // (C++ [class.union]).
749 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
750 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
751 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000752
Douglas Gregor3257fb52008-12-22 05:46:06 +0000753 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
754 if (!MD->isStatic()) {
755 // C++ [class.mfct.nonstatic]p2:
756 // [...] if name lookup (3.4.1) resolves the name in the
757 // id-expression to a nonstatic nontype member of class X or of
758 // a base class of X, the id-expression is transformed into a
759 // class member access expression (5.2.5) using (*this) (9.3.2)
760 // as the postfix-expression to the left of the '.' operator.
761 DeclContext *Ctx = 0;
762 QualType MemberType;
763 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
764 Ctx = FD->getDeclContext();
765 MemberType = FD->getType();
766
767 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
768 MemberType = RefType->getPointeeType();
769 else if (!FD->isMutable()) {
770 unsigned combinedQualifiers
771 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
772 MemberType = MemberType.getQualifiedType(combinedQualifiers);
773 }
774 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
775 if (!Method->isStatic()) {
776 Ctx = Method->getParent();
777 MemberType = Method->getType();
778 }
779 } else if (OverloadedFunctionDecl *Ovl
780 = dyn_cast<OverloadedFunctionDecl>(D)) {
781 for (OverloadedFunctionDecl::function_iterator
782 Func = Ovl->function_begin(),
783 FuncEnd = Ovl->function_end();
784 Func != FuncEnd; ++Func) {
785 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
786 if (!DMethod->isStatic()) {
787 Ctx = Ovl->getDeclContext();
788 MemberType = Context.OverloadTy;
789 break;
790 }
791 }
792 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000793
794 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +0000795 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
796 QualType ThisType = Context.getTagDeclType(MD->getParent());
797 if ((Context.getCanonicalType(CtxType)
798 == Context.getCanonicalType(ThisType)) ||
799 IsDerivedFrom(ThisType, CtxType)) {
800 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +0000801 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000802 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +0000803 return Owned(new (Context) MemberExpr(This, true, D,
Mike Stump9afab102009-02-19 03:04:26 +0000804 SourceLocation(), MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +0000805 }
806 }
807 }
808 }
809
Douglas Gregor8acb7272008-12-11 16:49:14 +0000810 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000811 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
812 if (MD->isStatic())
813 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +0000814 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
815 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000816 }
817
Douglas Gregor3257fb52008-12-22 05:46:06 +0000818 // Any other ways we could have found the field in a well-formed
819 // program would have been turned into implicit member expressions
820 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000821 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
822 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000823 }
Douglas Gregor3257fb52008-12-22 05:46:06 +0000824
Chris Lattner4b009652007-07-25 00:24:17 +0000825 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000826 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +0000827 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000828 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +0000829 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000830 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000831
Steve Naroffd6163f32008-09-05 22:11:13 +0000832 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000833 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +0000834 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
835 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +0000836 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
837 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
838 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +0000839 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000840
Douglas Gregoraa57e862009-02-18 21:56:37 +0000841 // Check whether this declaration can be used. Note that we suppress
842 // this check when we're going to perform argument-dependent lookup
843 // on this function name, because this might not be the function
844 // that overload resolution actually selects.
845 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
846 return ExprError();
847
Douglas Gregor48840c72008-12-10 23:01:14 +0000848 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000849 // Warn about constructs like:
850 // if (void *X = foo()) { ... } else { X }.
851 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +0000852 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
853 Scope *CheckS = S;
854 while (CheckS) {
855 if (CheckS->isWithinElse() &&
856 CheckS->getControlParent()->isDeclScope(Var)) {
857 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000858 ExprError(Diag(Loc, diag::warn_value_always_false)
859 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000860 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000861 ExprError(Diag(Loc, diag::warn_value_always_zero)
862 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +0000863 break;
864 }
865
866 // Move up one more control parent to check again.
867 CheckS = CheckS->getControlParent();
868 if (CheckS)
869 CheckS = CheckS->getParent();
870 }
871 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000872 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
873 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
874 // C99 DR 316 says that, if a function type comes from a
875 // function definition (without a prototype), that type is only
876 // used for checking compatibility. Therefore, when referencing
877 // the function, we pretend that we don't have the full function
878 // type.
879 QualType T = Func->getType();
880 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +0000881 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
882 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +0000883 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
884 }
Douglas Gregor48840c72008-12-10 23:01:14 +0000885 }
Steve Naroffd6163f32008-09-05 22:11:13 +0000886
887 // Only create DeclRefExpr's for valid Decl's.
888 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000889 return ExprError();
890
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000891 // If the identifier reference is inside a block, and it refers to a value
892 // that is outside the block, create a BlockDeclRefExpr instead of a
893 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
894 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +0000895 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000896 // We do not do this for things like enum constants, global variables, etc,
897 // as they do not get snapshotted.
898 //
899 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stumpae93d652009-02-19 22:01:56 +0000900 // Blocks that have these can't be constant.
901 CurBlock->hasBlockDeclRefExprs = true;
902
Steve Naroff52059382008-10-10 01:28:17 +0000903 // The BlocksAttr indicates the variable is bound by-reference.
904 if (VD->getAttr<BlocksAttr>())
Steve Naroff774e4152009-01-21 00:14:39 +0000905 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000906 VD->getType().getNonReferenceType(), Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +0000907
Steve Naroff52059382008-10-10 01:28:17 +0000908 // Variable will be bound by-copy, make it const within the closure.
909 VD->getType().addConst();
Steve Naroff774e4152009-01-21 00:14:39 +0000910 return Owned(new (Context) BlockDeclRefExpr(VD,
Steve Naroffe5f128a2009-01-20 19:53:53 +0000911 VD->getType().getNonReferenceType(), Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +0000912 }
913 // If this reference is not in a block or if the referenced variable is
914 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000915
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000916 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +0000917 bool ValueDependent = false;
918 if (getLangOptions().CPlusPlus) {
919 // C++ [temp.dep.expr]p3:
920 // An id-expression is type-dependent if it contains:
921 // - an identifier that was declared with a dependent type,
922 if (VD->getType()->isDependentType())
923 TypeDependent = true;
924 // - FIXME: a template-id that is dependent,
925 // - a conversion-function-id that specifies a dependent type,
926 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
927 Name.getCXXNameType()->isDependentType())
928 TypeDependent = true;
929 // - a nested-name-specifier that contains a class-name that
930 // names a dependent type.
931 else if (SS && !SS->isEmpty()) {
932 for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
933 DC; DC = DC->getParent()) {
934 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +0000935 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +0000936 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
937 if (Context.getTypeDeclType(Record)->isDependentType()) {
938 TypeDependent = true;
939 break;
940 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000941 }
942 }
943 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000944
Douglas Gregora5d84612008-12-10 20:57:37 +0000945 // C++ [temp.dep.constexpr]p2:
946 //
947 // An identifier is value-dependent if it is:
948 // - a name declared with a dependent type,
949 if (TypeDependent)
950 ValueDependent = true;
951 // - the name of a non-type template parameter,
952 else if (isa<NonTypeTemplateParmDecl>(VD))
953 ValueDependent = true;
954 // - a constant with integral or enumeration type and is
955 // initialized with an expression that is value-dependent
956 // (FIXME!).
957 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +0000958
Sebastian Redlcd883f72009-01-18 18:53:16 +0000959 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
960 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +0000961}
962
Sebastian Redlcd883f72009-01-18 18:53:16 +0000963Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
964 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +0000965 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +0000966
Chris Lattner4b009652007-07-25 00:24:17 +0000967 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000968 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +0000969 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
970 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
971 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +0000972 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000973
Chris Lattner7e637512008-01-12 08:14:25 +0000974 // Pre-defined identifiers are of type char[x], where x is the length of the
975 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000976 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000977 if (FunctionDecl *FD = getCurFunctionDecl())
978 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +0000979 else if (ObjCMethodDecl *MD = getCurMethodDecl())
980 Length = MD->getSynthesizedMethodSize();
981 else {
982 Diag(Loc, diag::ext_predef_outside_function);
983 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
984 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
985 }
Sebastian Redlcd883f72009-01-18 18:53:16 +0000986
987
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000988 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +0000989 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +0000990 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +0000991 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +0000992}
993
Sebastian Redlcd883f72009-01-18 18:53:16 +0000994Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +0000995 llvm::SmallString<16> CharBuffer;
996 CharBuffer.resize(Tok.getLength());
997 const char *ThisTokBegin = &CharBuffer[0];
998 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000999
Chris Lattner4b009652007-07-25 00:24:17 +00001000 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1001 Tok.getLocation(), PP);
1002 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001003 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001004
1005 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1006
Sebastian Redl75324932009-01-20 22:23:13 +00001007 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1008 Literal.isWide(),
1009 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001010}
1011
Sebastian Redlcd883f72009-01-18 18:53:16 +00001012Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1013 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001014 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1015 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001016 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001017 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001018 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001019 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001020 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001021
Chris Lattner4b009652007-07-25 00:24:17 +00001022 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001023 // Add padding so that NumericLiteralParser can overread by one character.
1024 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001025 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001026
Chris Lattner4b009652007-07-25 00:24:17 +00001027 // Get the spelling of the token, which eliminates trigraphs, etc.
1028 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001029
Chris Lattner4b009652007-07-25 00:24:17 +00001030 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1031 Tok.getLocation(), PP);
1032 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001033 return ExprError();
1034
Chris Lattner1de66eb2007-08-26 03:42:43 +00001035 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001036
Chris Lattner1de66eb2007-08-26 03:42:43 +00001037 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001038 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001039 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001040 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001041 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001042 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001043 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001044 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001045
1046 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1047
Ted Kremenekddedbe22007-11-29 00:56:49 +00001048 // isExact will be set by GetFloatValue().
1049 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001050 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1051 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001052
Chris Lattner1de66eb2007-08-26 03:42:43 +00001053 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001054 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001055 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001056 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001057
Neil Booth7421e9c2007-08-29 22:00:19 +00001058 // long long is a C99 feature.
1059 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001060 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001061 Diag(Tok.getLocation(), diag::ext_longlong);
1062
Chris Lattner4b009652007-07-25 00:24:17 +00001063 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001064 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001065
Chris Lattner4b009652007-07-25 00:24:17 +00001066 if (Literal.GetIntegerValue(ResultVal)) {
1067 // If this value didn't fit into uintmax_t, warn and force to ull.
1068 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001069 Ty = Context.UnsignedLongLongTy;
1070 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001071 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001072 } else {
1073 // If this value fits into a ULL, try to figure out what else it fits into
1074 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001075
Chris Lattner4b009652007-07-25 00:24:17 +00001076 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1077 // be an unsigned int.
1078 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1079
1080 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001081 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001082 if (!Literal.isLong && !Literal.isLongLong) {
1083 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001084 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001085
Chris Lattner4b009652007-07-25 00:24:17 +00001086 // Does it fit in a unsigned int?
1087 if (ResultVal.isIntN(IntSize)) {
1088 // Does it fit in a signed int?
1089 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001090 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001091 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001092 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001093 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001094 }
Chris Lattner4b009652007-07-25 00:24:17 +00001095 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001096
Chris Lattner4b009652007-07-25 00:24:17 +00001097 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001098 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001099 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001100
Chris Lattner4b009652007-07-25 00:24:17 +00001101 // Does it fit in a unsigned long?
1102 if (ResultVal.isIntN(LongSize)) {
1103 // Does it fit in a signed long?
1104 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001105 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001106 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001107 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001108 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001109 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001110 }
1111
Chris Lattner4b009652007-07-25 00:24:17 +00001112 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001113 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001114 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001115
Chris Lattner4b009652007-07-25 00:24:17 +00001116 // Does it fit in a unsigned long long?
1117 if (ResultVal.isIntN(LongLongSize)) {
1118 // Does it fit in a signed long long?
1119 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001120 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001121 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001122 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001123 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001124 }
1125 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001126
Chris Lattner4b009652007-07-25 00:24:17 +00001127 // If we still couldn't decide a type, we probably have something that
1128 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001129 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001130 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001131 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001132 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001133 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001134
Chris Lattnere4068872008-05-09 05:59:00 +00001135 if (ResultVal.getBitWidth() != Width)
1136 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001137 }
Sebastian Redl75324932009-01-20 22:23:13 +00001138 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001139 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001140
Chris Lattner1de66eb2007-08-26 03:42:43 +00001141 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1142 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001143 Res = new (Context) ImaginaryLiteral(Res,
1144 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001145
1146 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001147}
1148
Sebastian Redlcd883f72009-01-18 18:53:16 +00001149Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1150 SourceLocation R, ExprArg Val) {
1151 Expr *E = (Expr *)Val.release();
Chris Lattner48d7f382008-04-02 04:24:33 +00001152 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001153 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001154}
1155
1156/// The UsualUnaryConversions() function is *not* called by this routine.
1157/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001158bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001159 SourceLocation OpLoc,
1160 const SourceRange &ExprRange,
1161 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001162 if (exprType->isDependentType())
1163 return false;
1164
Chris Lattner4b009652007-07-25 00:24:17 +00001165 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001166 if (isa<FunctionType>(exprType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001167 // alignof(function) is allowed.
Chris Lattner159fe082009-01-24 19:46:37 +00001168 if (isSizeof)
1169 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1170 return false;
1171 }
1172
1173 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001174 Diag(OpLoc, diag::ext_sizeof_void_type)
1175 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001176 return false;
1177 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001178
Chris Lattner159fe082009-01-24 19:46:37 +00001179 return DiagnoseIncompleteType(OpLoc, exprType,
1180 isSizeof ? diag::err_sizeof_incomplete_type :
1181 diag::err_alignof_incomplete_type,
1182 ExprRange);
Chris Lattner4b009652007-07-25 00:24:17 +00001183}
1184
Chris Lattner8d9f7962009-01-24 20:17:12 +00001185bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1186 const SourceRange &ExprRange) {
1187 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001188
Chris Lattner8d9f7962009-01-24 20:17:12 +00001189 // alignof decl is always ok.
1190 if (isa<DeclRefExpr>(E))
1191 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001192
1193 // Cannot know anything else if the expression is dependent.
1194 if (E->isTypeDependent())
1195 return false;
1196
Chris Lattner8d9f7962009-01-24 20:17:12 +00001197 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1198 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1199 if (FD->isBitField()) {
Chris Lattner364a42d2009-01-24 21:29:22 +00001200 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001201 return true;
1202 }
1203 // Other fields are ok.
1204 return false;
1205 }
1206 }
1207 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1208}
1209
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001210/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1211/// the same for @c alignof and @c __alignof
1212/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001213Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001214Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1215 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001216 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001217 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001218
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001219 QualType ArgTy;
1220 SourceRange Range;
1221 if (isType) {
1222 ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1223 Range = ArgRange;
Chris Lattnera78909b2009-01-24 19:49:13 +00001224
1225 // Verify that the operand is valid.
1226 if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1227 return ExprError();
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001228 } else {
1229 // Get the end location.
1230 Expr *ArgEx = (Expr *)TyOrEx;
1231 Range = ArgEx->getSourceRange();
1232 ArgTy = ArgEx->getType();
Chris Lattnera78909b2009-01-24 19:49:13 +00001233
1234 // Verify that the operand is valid.
Chris Lattner8d9f7962009-01-24 20:17:12 +00001235 bool isInvalid;
Chris Lattner364a42d2009-01-24 21:29:22 +00001236 if (!isSizeof) {
Chris Lattner8d9f7962009-01-24 20:17:12 +00001237 isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
Chris Lattner364a42d2009-01-24 21:29:22 +00001238 } else if (ArgEx->isBitField()) { // C99 6.5.3.4p1.
1239 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1240 isInvalid = true;
1241 } else {
1242 isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1243 }
Chris Lattner8d9f7962009-01-24 20:17:12 +00001244
1245 if (isInvalid) {
Chris Lattnera78909b2009-01-24 19:49:13 +00001246 DeleteExpr(ArgEx);
1247 return ExprError();
1248 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001249 }
1250
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001251 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Steve Naroff774e4152009-01-21 00:14:39 +00001252 return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
Chris Lattner159fe082009-01-24 19:46:37 +00001253 Context.getSizeType(), OpLoc,
1254 Range.getEnd()));
Chris Lattner4b009652007-07-25 00:24:17 +00001255}
1256
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001257QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001258 if (V->isTypeDependent())
1259 return Context.DependentTy;
1260
Chris Lattner03931a72007-08-24 21:16:53 +00001261 DefaultFunctionArrayConversion(V);
1262
Chris Lattnera16e42d2007-08-26 05:39:26 +00001263 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001264 if (const ComplexType *CT = V->getType()->getAsComplexType())
1265 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001266
1267 // Otherwise they pass through real integer and floating point types here.
1268 if (V->getType()->isArithmeticType())
1269 return V->getType();
1270
1271 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001272 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1273 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001274 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001275}
1276
1277
Chris Lattner4b009652007-07-25 00:24:17 +00001278
Sebastian Redl8b769972009-01-19 00:08:26 +00001279Action::OwningExprResult
1280Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1281 tok::TokenKind Kind, ExprArg Input) {
1282 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001283
Chris Lattner4b009652007-07-25 00:24:17 +00001284 UnaryOperator::Opcode Opc;
1285 switch (Kind) {
1286 default: assert(0 && "Unknown unary op!");
1287 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1288 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1289 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001290
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001291 if (getLangOptions().CPlusPlus &&
1292 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1293 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001294 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001295 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1296
1297 // C++ [over.inc]p1:
1298 //
1299 // [...] If the function is a member function with one
1300 // parameter (which shall be of type int) or a non-member
1301 // function with two parameters (the second of which shall be
1302 // of type int), it defines the postfix increment operator ++
1303 // for objects of that type. When the postfix increment is
1304 // called as a result of using the ++ operator, the int
1305 // argument will have value zero.
1306 Expr *Args[2] = {
1307 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001308 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1309 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001310 };
1311
1312 // Build the candidate set for overloading
1313 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00001314 if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1315 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001316
1317 // Perform overload resolution.
1318 OverloadCandidateSet::iterator Best;
1319 switch (BestViableFunction(CandidateSet, Best)) {
1320 case OR_Success: {
1321 // We found a built-in operator or an overloaded operator.
1322 FunctionDecl *FnDecl = Best->Function;
1323
1324 if (FnDecl) {
1325 // We matched an overloaded operator. Build a call to that
1326 // operator.
1327
1328 // Convert the arguments.
1329 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1330 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001331 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001332 } else {
1333 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001334 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001335 FnDecl->getParamDecl(0)->getType(),
1336 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001337 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001338 }
1339
1340 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001341 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001342 = FnDecl->getType()->getAsFunctionType()->getResultType();
1343 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001344
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001345 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001346 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001347 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001348 UsualUnaryConversions(FnExpr);
1349
Sebastian Redl8b769972009-01-19 00:08:26 +00001350 Input.release();
Ted Kremenek362abcd2009-02-09 20:51:47 +00001351 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
1352 ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001353 } else {
1354 // We matched a built-in operator. Convert the arguments, then
1355 // break out so that we will build the appropriate built-in
1356 // operator node.
1357 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1358 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001359 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001360
1361 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001362 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001363 }
1364
1365 case OR_No_Viable_Function:
1366 // No viable function; fall through to handling this as a
1367 // built-in operator, which will produce an error message for us.
1368 break;
1369
1370 case OR_Ambiguous:
1371 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1372 << UnaryOperator::getOpcodeStr(Opc)
1373 << Arg->getSourceRange();
1374 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001375 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001376
1377 case OR_Deleted:
1378 Diag(OpLoc, diag::err_ovl_deleted_oper)
1379 << Best->Function->isDeleted()
1380 << UnaryOperator::getOpcodeStr(Opc)
1381 << Arg->getSourceRange();
1382 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1383 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001384 }
1385
1386 // Either we found no viable overloaded operator or we matched a
1387 // built-in operator. In either case, fall through to trying to
1388 // build a built-in operation.
1389 }
1390
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001391 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1392 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001393 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001394 return ExprError();
1395 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001396 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001397}
1398
Sebastian Redl8b769972009-01-19 00:08:26 +00001399Action::OwningExprResult
1400Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1401 ExprArg Idx, SourceLocation RLoc) {
1402 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1403 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001404
Douglas Gregor80723c52008-11-19 17:17:41 +00001405 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001406 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001407 LHSExp->getType()->isEnumeralType() ||
1408 RHSExp->getType()->isRecordType() ||
1409 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001410 // Add the appropriate overloaded operators (C++ [over.match.oper])
1411 // to the candidate set.
1412 OverloadCandidateSet CandidateSet;
1413 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor48a87322009-02-04 16:44:47 +00001414 if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1415 SourceRange(LLoc, RLoc)))
1416 return ExprError();
Sebastian Redl8b769972009-01-19 00:08:26 +00001417
Douglas Gregor80723c52008-11-19 17:17:41 +00001418 // Perform overload resolution.
1419 OverloadCandidateSet::iterator Best;
1420 switch (BestViableFunction(CandidateSet, Best)) {
1421 case OR_Success: {
1422 // We found a built-in operator or an overloaded operator.
1423 FunctionDecl *FnDecl = Best->Function;
1424
1425 if (FnDecl) {
1426 // We matched an overloaded operator. Build a call to that
1427 // operator.
1428
1429 // Convert the arguments.
1430 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1431 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1432 PerformCopyInitialization(RHSExp,
1433 FnDecl->getParamDecl(0)->getType(),
1434 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001435 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001436 } else {
1437 // Convert the arguments.
1438 if (PerformCopyInitialization(LHSExp,
1439 FnDecl->getParamDecl(0)->getType(),
1440 "passing") ||
1441 PerformCopyInitialization(RHSExp,
1442 FnDecl->getParamDecl(1)->getType(),
1443 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001444 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001445 }
1446
1447 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001448 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001449 = FnDecl->getType()->getAsFunctionType()->getResultType();
1450 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001451
Douglas Gregor80723c52008-11-19 17:17:41 +00001452 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001453 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1454 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001455 UsualUnaryConversions(FnExpr);
1456
Sebastian Redl8b769972009-01-19 00:08:26 +00001457 Base.release();
1458 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001459 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001460 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001461 } else {
1462 // We matched a built-in operator. Convert the arguments, then
1463 // break out so that we will build the appropriate built-in
1464 // operator node.
1465 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1466 "passing") ||
1467 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1468 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001469 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001470
1471 break;
1472 }
1473 }
1474
1475 case OR_No_Viable_Function:
1476 // No viable function; fall through to handling this as a
1477 // built-in operator, which will produce an error message for us.
1478 break;
1479
1480 case OR_Ambiguous:
1481 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1482 << "[]"
1483 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1484 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001485 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001486
1487 case OR_Deleted:
1488 Diag(LLoc, diag::err_ovl_deleted_oper)
1489 << Best->Function->isDeleted()
1490 << "[]"
1491 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1492 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1493 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001494 }
1495
1496 // Either we found no viable overloaded operator or we matched a
1497 // built-in operator. In either case, fall through to trying to
1498 // build a built-in operation.
1499 }
1500
Chris Lattner4b009652007-07-25 00:24:17 +00001501 // Perform default conversions.
1502 DefaultFunctionArrayConversion(LHSExp);
1503 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001504
Chris Lattner4b009652007-07-25 00:24:17 +00001505 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1506
1507 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001508 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001509 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001510 // and index from the expression types.
1511 Expr *BaseExpr, *IndexExpr;
1512 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001513 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1514 BaseExpr = LHSExp;
1515 IndexExpr = RHSExp;
1516 ResultType = Context.DependentTy;
1517 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001518 BaseExpr = LHSExp;
1519 IndexExpr = RHSExp;
1520 // FIXME: need to deal with const...
1521 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001522 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001523 // Handle the uncommon case of "123[Ptr]".
1524 BaseExpr = RHSExp;
1525 IndexExpr = LHSExp;
1526 // FIXME: need to deal with const...
1527 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001528 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1529 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001530 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001531
Chris Lattner4b009652007-07-25 00:24:17 +00001532 // FIXME: need to deal with const...
1533 ResultType = VTy->getElementType();
1534 } else {
Sebastian Redl8b769972009-01-19 00:08:26 +00001535 return ExprError(Diag(LHSExp->getLocStart(),
1536 diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1537 }
Chris Lattner4b009652007-07-25 00:24:17 +00001538 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001539 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Sebastian Redl8b769972009-01-19 00:08:26 +00001540 return ExprError(Diag(IndexExpr->getLocStart(),
1541 diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001542
1543 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". In practice,
1544 // the following check catches trying to index a pointer to a function (e.g.
Chris Lattner9db553e2008-04-02 06:59:01 +00001545 // void (*)(int)) and pointers to incomplete types. Functions are not
1546 // objects in C99.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001547 if (!ResultType->isObjectType() && !ResultType->isDependentType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001548 return ExprError(Diag(BaseExpr->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001549 diag::err_typecheck_subscript_not_object)
Sebastian Redl8b769972009-01-19 00:08:26 +00001550 << BaseExpr->getType() << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001551
Sebastian Redl8b769972009-01-19 00:08:26 +00001552 Base.release();
1553 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001554 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001555 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001556}
1557
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001558QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001559CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001560 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001561 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001562
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001563 // The vector accessor can't exceed the number of elements.
1564 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001565
Mike Stump9afab102009-02-19 03:04:26 +00001566 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001567 // special names that indicate a subset of exactly half the elements are
1568 // to be selected.
1569 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001570
Nate Begeman1486b502009-01-18 01:47:54 +00001571 // This flag determines whether or not CompName has an 's' char prefix,
1572 // indicating that it is a string of hex values to be used as vector indices.
1573 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001574
1575 // Check that we've found one of the special components, or that the component
1576 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001577 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001578 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1579 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001580 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001581 do
1582 compStr++;
1583 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001584 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001585 do
1586 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001587 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001588 }
Nate Begeman1486b502009-01-18 01:47:54 +00001589
Mike Stump9afab102009-02-19 03:04:26 +00001590 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001591 // We didn't get to the end of the string. This means the component names
1592 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001593 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1594 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001595 return QualType();
1596 }
Mike Stump9afab102009-02-19 03:04:26 +00001597
Nate Begeman1486b502009-01-18 01:47:54 +00001598 // Ensure no component accessor exceeds the width of the vector type it
1599 // operates on.
1600 if (!HalvingSwizzle) {
1601 compStr = CompName.getName();
1602
1603 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001604 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001605
1606 while (*compStr) {
1607 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1608 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1609 << baseType << SourceRange(CompLoc);
1610 return QualType();
1611 }
1612 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001613 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001614
Nate Begeman1486b502009-01-18 01:47:54 +00001615 // If this is a halving swizzle, verify that the base type has an even
1616 // number of elements.
1617 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001618 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001619 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001620 return QualType();
1621 }
Mike Stump9afab102009-02-19 03:04:26 +00001622
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001623 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001624 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001625 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001626 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001627 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001628 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1629 : CompName.getLength();
1630 if (HexSwizzle)
1631 CompSize--;
1632
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001633 if (CompSize == 1)
1634 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001635
Nate Begemanaf6ed502008-04-18 23:10:10 +00001636 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001637 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001638 // diagostics look bad. We want extended vector types to appear built-in.
1639 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1640 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1641 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001642 }
1643 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001644}
1645
Chris Lattner2cb744b2009-02-15 22:43:40 +00001646
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001647/// constructSetterName - Return the setter name for the given
1648/// identifier, i.e. "set" + Name where the initial character of Name
1649/// has been capitalized.
1650// FIXME: Merge with same routine in Parser. But where should this
1651// live?
1652static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1653 const IdentifierInfo *Name) {
1654 llvm::SmallString<100> SelectorName;
1655 SelectorName = "set";
1656 SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1657 SelectorName[3] = toupper(SelectorName[3]);
1658 return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1659}
1660
Sebastian Redl8b769972009-01-19 00:08:26 +00001661Action::OwningExprResult
1662Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1663 tok::TokenKind OpKind, SourceLocation MemberLoc,
1664 IdentifierInfo &Member) {
1665 Expr *BaseExpr = static_cast<Expr *>(Base.release());
Steve Naroff2cb66382007-07-26 03:11:44 +00001666 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00001667
1668 // Perform default conversions.
1669 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00001670
Steve Naroff2cb66382007-07-26 03:11:44 +00001671 QualType BaseType = BaseExpr->getType();
1672 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00001673
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001674 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
1675 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00001676 if (OpKind == tok::arrow) {
Chris Lattner7931f4a2007-07-31 16:53:04 +00001677 if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00001678 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00001679 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00001680 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1681 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00001682 else
Sebastian Redl8b769972009-01-19 00:08:26 +00001683 return ExprError(Diag(MemberLoc,
1684 diag::err_typecheck_member_reference_arrow)
1685 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001686 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001687
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001688 // Handle field access to simple records. This also handles access to fields
1689 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00001690 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00001691 RecordDecl *RDecl = RTy->getDecl();
Mike Stump9afab102009-02-19 03:04:26 +00001692 if (DiagnoseIncompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00001693 diag::err_typecheck_incomplete_tag,
1694 BaseExpr->getSourceRange()))
1695 return ExprError();
1696
Steve Naroff2cb66382007-07-26 03:11:44 +00001697 // The record definition is complete, now make sure the member is valid.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001698 // FIXME: Qualified name lookup for C++ is a bit more complicated
1699 // than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00001700 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00001701 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00001702 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001703
Douglas Gregor09be81b2009-02-04 17:27:36 +00001704 NamedDecl *MemberDecl = 0;
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001705 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00001706 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1707 << &Member << BaseExpr->getSourceRange());
1708 else if (Result.isAmbiguous()) {
1709 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1710 MemberLoc, BaseExpr->getSourceRange());
1711 return ExprError();
1712 } else
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00001713 MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001714
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001715 // If the decl being referenced had an error, return an error for this
1716 // sub-expr without emitting another error, in order to avoid cascading
1717 // error cases.
1718 if (MemberDecl->isInvalidDecl())
1719 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001720
Douglas Gregoraa57e862009-02-18 21:56:37 +00001721 // Check the use of this field
1722 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1723 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001724
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001725 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001726 // We may have found a field within an anonymous union or struct
1727 // (C++ [class.union]).
1728 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001729 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00001730 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00001731
Douglas Gregor82d44772008-12-20 23:49:58 +00001732 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1733 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001734 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00001735 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1736 MemberType = Ref->getPointeeType();
1737 else {
1738 unsigned combinedQualifiers =
1739 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001740 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00001741 combinedQualifiers &= ~QualType::Const;
1742 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1743 }
Eli Friedman76b49832008-02-06 22:48:16 +00001744
Steve Naroff774e4152009-01-21 00:14:39 +00001745 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1746 MemberLoc, MemberType));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001747 } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001748 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Sebastian Redl8b769972009-01-19 00:08:26 +00001749 Var, MemberLoc,
1750 Var->getType().getNonReferenceType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001751 else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001752 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Steve Naroff774e4152009-01-21 00:14:39 +00001753 MemberFn, MemberLoc, MemberFn->getType()));
Sebastian Redl8b769972009-01-19 00:08:26 +00001754 else if (OverloadedFunctionDecl *Ovl
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001755 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00001756 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Sebastian Redl8b769972009-01-19 00:08:26 +00001757 MemberLoc, Context.OverloadTy));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001758 else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00001759 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1760 Enum, MemberLoc, Enum->getType()));
Douglas Gregorddfd9d52008-12-23 00:26:44 +00001761 else if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00001762 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1763 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00001764
Douglas Gregor82d44772008-12-20 23:49:58 +00001765 // We found a declaration kind that we didn't expect. This is a
1766 // generic error message that tells the user that she can't refer
1767 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00001768 return ExprError(Diag(MemberLoc,
1769 diag::err_typecheck_member_reference_unknown)
1770 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00001771 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001772
Chris Lattnere9d71612008-07-21 04:59:05 +00001773 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1774 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00001775 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahanian09772392008-12-13 22:20:28 +00001776 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00001777 // If the decl being referenced had an error, return an error for this
1778 // sub-expr without emitting another error, in order to avoid cascading
1779 // error cases.
1780 if (IV->isInvalidDecl())
1781 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001782
1783 // Check whether we can reference this field.
1784 if (DiagnoseUseOfDecl(IV, MemberLoc))
1785 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001786
1787 ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001788 MemberLoc, BaseExpr,
Fariborz Jahanianea944842008-12-18 17:29:46 +00001789 OpKind == tok::arrow);
1790 Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
Sebastian Redl8b769972009-01-19 00:08:26 +00001791 return Owned(MRef);
Fariborz Jahanian09772392008-12-13 22:20:28 +00001792 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001793 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1794 << IFTy->getDecl()->getDeclName() << &Member
1795 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00001796 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001797
Chris Lattnere9d71612008-07-21 04:59:05 +00001798 // Handle Objective-C property access, which is "Obj.property" where Obj is a
1799 // pointer to a (potentially qualified) interface type.
1800 const PointerType *PTy;
1801 const ObjCInterfaceType *IFTy;
1802 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1803 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1804 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00001805
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001806 // Search for a declared property first.
Chris Lattner51f6fb32009-02-16 18:35:08 +00001807 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001808 // Check whether we can reference this property.
1809 if (DiagnoseUseOfDecl(PD, MemberLoc))
1810 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001811
Steve Naroff774e4152009-01-21 00:14:39 +00001812 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001813 MemberLoc, BaseExpr));
1814 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001815
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001816 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00001817 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1818 E = IFTy->qual_end(); I != E; ++I)
Chris Lattner51f6fb32009-02-16 18:35:08 +00001819 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001820 // Check whether we can reference this property.
1821 if (DiagnoseUseOfDecl(PD, MemberLoc))
1822 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00001823
Steve Naroff774e4152009-01-21 00:14:39 +00001824 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001825 MemberLoc, BaseExpr));
1826 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001827
1828 // If that failed, look for an "implicit" property by seeing if the nullary
1829 // selector is implemented.
1830
1831 // FIXME: The logic for looking up nullary and unary selectors should be
1832 // shared with the code in ActOnInstanceMessage.
1833
1834 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1835 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00001836
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001837 // If this reference is in an @implementation, check for 'private' methods.
1838 if (!Getter)
1839 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1840 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001841 if (ObjCImplementationDecl *ImpDecl =
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001842 ObjCImplementations[ClassDecl->getIdentifier()])
1843 Getter = ImpDecl->getInstanceMethod(Sel);
1844
Steve Naroff04151f32008-10-22 19:16:27 +00001845 // Look through local category implementations associated with the class.
1846 if (!Getter) {
1847 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1848 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1849 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1850 }
1851 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001852 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001853 // Check if we can reference this property.
1854 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1855 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001856
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001857 // If we found a getter then this may be a valid dot-reference, we
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001858 // will look for the matching setter, in case it is needed.
1859 IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1860 &Member);
1861 Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1862 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1863 if (!Setter) {
Mike Stump9afab102009-02-19 03:04:26 +00001864 // If this reference is in an @implementation, also check for 'private'
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001865 // methods.
1866 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1867 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Mike Stump9afab102009-02-19 03:04:26 +00001868 if (ObjCImplementationDecl *ImpDecl =
Fariborz Jahanianc05da422008-11-22 20:25:50 +00001869 ObjCImplementations[ClassDecl->getIdentifier()])
1870 Setter = ImpDecl->getInstanceMethod(SetterSel);
1871 }
1872 // Look through local category implementations associated with the class.
1873 if (!Setter) {
1874 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1875 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1876 Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1877 }
1878 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001879
Douglas Gregoraa57e862009-02-18 21:56:37 +00001880 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1881 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001882
Sebastian Redl8b769972009-01-19 00:08:26 +00001883 // FIXME: we must check that the setter has property type.
Mike Stump9afab102009-02-19 03:04:26 +00001884 return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
Steve Naroff774e4152009-01-21 00:14:39 +00001885 Setter, MemberLoc, BaseExpr));
Daniel Dunbar60e8b162008-09-03 01:05:41 +00001886 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001887
1888 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1889 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00001890 }
Steve Naroffd1d44402008-10-20 22:53:06 +00001891 // Handle properties on qualified "id" protocols.
1892 const ObjCQualifiedIdType *QIdTy;
1893 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1894 // Check protocols on qualified interfaces.
1895 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001896 E = QIdTy->qual_end(); I != E; ++I) {
Chris Lattner51f6fb32009-02-16 18:35:08 +00001897 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001898 // Check the use of this declaration
1899 if (DiagnoseUseOfDecl(PD, MemberLoc))
1900 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001901
Steve Naroff774e4152009-01-21 00:14:39 +00001902 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00001903 MemberLoc, BaseExpr));
1904 }
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001905 // Also must look for a getter name which uses property syntax.
1906 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1907 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00001908 // Check the use of this method.
1909 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1910 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001911
1912 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Steve Naroff774e4152009-01-21 00:14:39 +00001913 OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00001914 }
1915 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001916
1917 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1918 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00001919 }
Chris Lattnera57cf472008-07-21 04:28:12 +00001920 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00001921 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00001922 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1923 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001924 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00001925 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00001926 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00001927 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001928
1929 return ExprError(Diag(MemberLoc,
1930 diag::err_typecheck_member_reference_struct_union)
1931 << BaseType << BaseExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001932}
1933
Douglas Gregor3257fb52008-12-22 05:46:06 +00001934/// ConvertArgumentsForCall - Converts the arguments specified in
1935/// Args/NumArgs to the parameter types of the function FDecl with
1936/// function prototype Proto. Call is the call expression itself, and
1937/// Fn is the function expression. For a C++ member function, this
1938/// routine does not attempt to convert the object argument. Returns
1939/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00001940bool
1941Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001942 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00001943 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00001944 Expr **Args, unsigned NumArgs,
1945 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00001946 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00001947 // assignment, to the types of the corresponding parameter, ...
1948 unsigned NumArgsInProto = Proto->getNumArgs();
1949 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001950 bool Invalid = false;
1951
Douglas Gregor3257fb52008-12-22 05:46:06 +00001952 // If too few arguments are available (and we don't have default
1953 // arguments for the remaining parameters), don't make the call.
1954 if (NumArgs < NumArgsInProto) {
1955 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1956 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1957 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1958 // Use default arguments for missing arguments
1959 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00001960 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00001961 }
1962
1963 // If too many are passed and not variadic, error on the extras and drop
1964 // them.
1965 if (NumArgs > NumArgsInProto) {
1966 if (!Proto->isVariadic()) {
1967 Diag(Args[NumArgsInProto]->getLocStart(),
1968 diag::err_typecheck_call_too_many_args)
1969 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1970 << SourceRange(Args[NumArgsInProto]->getLocStart(),
1971 Args[NumArgs-1]->getLocEnd());
1972 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00001973 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00001974 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00001975 }
1976 NumArgsToCheck = NumArgsInProto;
1977 }
Mike Stump9afab102009-02-19 03:04:26 +00001978
Douglas Gregor3257fb52008-12-22 05:46:06 +00001979 // Continue to check argument types (even if we have too few/many args).
1980 for (unsigned i = 0; i != NumArgsToCheck; i++) {
1981 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00001982
Douglas Gregor3257fb52008-12-22 05:46:06 +00001983 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001984 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001985 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001986
1987 // Pass the argument.
1988 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1989 return true;
Mike Stump9afab102009-02-19 03:04:26 +00001990 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001991 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00001992 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001993 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00001994
Douglas Gregor3257fb52008-12-22 05:46:06 +00001995 Call->setArg(i, Arg);
1996 }
Mike Stump9afab102009-02-19 03:04:26 +00001997
Douglas Gregor3257fb52008-12-22 05:46:06 +00001998 // If this is a variadic call, handle args passed through "...".
1999 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002000 VariadicCallType CallType = VariadicFunction;
2001 if (Fn->getType()->isBlockPointerType())
2002 CallType = VariadicBlock; // Block
2003 else if (isa<MemberExpr>(Fn))
2004 CallType = VariadicMethod;
2005
Douglas Gregor3257fb52008-12-22 05:46:06 +00002006 // Promote the arguments (C99 6.5.2.2p7).
2007 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2008 Expr *Arg = Args[i];
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002009 DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002010 Call->setArg(i, Arg);
2011 }
2012 }
2013
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002014 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002015}
2016
Steve Naroff87d58b42007-09-16 03:34:24 +00002017/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002018/// This provides the location of the left/right parens and a list of comma
2019/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002020Action::OwningExprResult
2021Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2022 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002023 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002024 unsigned NumArgs = args.size();
2025 Expr *Fn = static_cast<Expr *>(fn.release());
2026 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002027 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002028 FunctionDecl *FDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002029 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002030
Douglas Gregor3257fb52008-12-22 05:46:06 +00002031 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002032 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002033 // in which case we won't do any semantic analysis now.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002034 // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2035 bool Dependent = false;
2036 if (Fn->isTypeDependent())
2037 Dependent = true;
2038 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2039 Dependent = true;
2040
2041 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002042 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002043 Context.DependentTy, RParenLoc));
2044
2045 // Determine whether this is a call to an object (C++ [over.call.object]).
2046 if (Fn->getType()->isRecordType())
2047 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2048 CommaLocs, RParenLoc));
2049
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002050 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002051 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2052 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2053 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002054 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2055 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002056 }
2057
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002058 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002059 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002060 Expr *FnExpr = Fn;
2061 bool ADL = true;
2062 while (true) {
2063 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2064 FnExpr = IcExpr->getSubExpr();
2065 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002066 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002067 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002068 ADL = false;
2069 FnExpr = PExpr->getSubExpr();
2070 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002071 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002072 == UnaryOperator::AddrOf) {
2073 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002074 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2075 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2076 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2077 break;
Mike Stump9afab102009-02-19 03:04:26 +00002078 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002079 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2080 UnqualifiedName = DepName->getName();
2081 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002082 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002083 // Any kind of name that does not refer to a declaration (or
2084 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2085 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002086 break;
2087 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002088 }
Mike Stump9afab102009-02-19 03:04:26 +00002089
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002090 OverloadedFunctionDecl *Ovl = 0;
2091 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002092 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002093 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2094 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002095
Douglas Gregorfcb19192009-02-11 23:02:49 +00002096 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002097 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002098 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002099 ADL = false;
2100
Douglas Gregorfcb19192009-02-11 23:02:49 +00002101 // We don't perform ADL in C.
2102 if (!getLangOptions().CPlusPlus)
2103 ADL = false;
2104
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002105 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002106 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2107 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002108 NumArgs, CommaLocs, RParenLoc, ADL);
2109 if (!FDecl)
2110 return ExprError();
2111
2112 // Update Fn to refer to the actual function selected.
2113 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002114 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002115 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Mike Stump9afab102009-02-19 03:04:26 +00002116 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2117 QDRExpr->getLocation(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002118 false, false,
2119 QDRExpr->getSourceRange().getBegin());
2120 else
Mike Stump9afab102009-02-19 03:04:26 +00002121 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002122 Fn->getSourceRange().getBegin());
2123 Fn->Destroy(Context);
2124 Fn = NewFn;
2125 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002126 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002127
2128 // Promote the function operand.
2129 UsualUnaryConversions(Fn);
2130
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002131 // Make the call expr early, before semantic checks. This guarantees cleanup
2132 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002133 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2134 Args, NumArgs,
2135 Context.BoolTy,
2136 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002137
Steve Naroffd6163f32008-09-05 22:11:13 +00002138 const FunctionType *FuncT;
2139 if (!Fn->getType()->isBlockPointerType()) {
2140 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2141 // have type pointer to function".
2142 const PointerType *PT = Fn->getType()->getAsPointerType();
2143 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002144 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2145 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002146 FuncT = PT->getPointeeType()->getAsFunctionType();
2147 } else { // This is a block call.
2148 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2149 getAsFunctionType();
2150 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002151 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002152 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2153 << Fn->getType() << Fn->getSourceRange());
2154
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002155 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002156 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002157
Douglas Gregor4fa58902009-02-26 23:50:07 +00002158 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002159 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002160 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002161 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002162 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002163 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002164
Steve Naroffdb65e052007-08-28 23:30:39 +00002165 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002166 for (unsigned i = 0; i != NumArgs; i++) {
2167 Expr *Arg = Args[i];
2168 DefaultArgumentPromotion(Arg);
2169 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002170 }
Chris Lattner4b009652007-07-25 00:24:17 +00002171 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002172
Douglas Gregor3257fb52008-12-22 05:46:06 +00002173 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2174 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002175 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2176 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002177
Chris Lattner2e64c072007-08-10 20:18:51 +00002178 // Do special checking on direct calls to functions.
Eli Friedmand0e9d092008-05-14 19:38:39 +00002179 if (FDecl)
2180 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002181
Sebastian Redl8b769972009-01-19 00:08:26 +00002182 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002183}
2184
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002185Action::OwningExprResult
2186Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2187 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002188 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002189 QualType literalType = QualType::getFromOpaquePtr(Ty);
2190 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002191 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002192 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002193
Eli Friedman8c2173d2008-05-20 05:22:08 +00002194 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002195 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002196 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2197 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002198 } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2199 diag::err_typecheck_decl_incomplete_type,
2200 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002201 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002202
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002203 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002204 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002205 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002206
Chris Lattnere5cb5862008-12-04 23:50:19 +00002207 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002208 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002209 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002210 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002211 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002212 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002213 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002214 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002215}
2216
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002217Action::OwningExprResult
2218Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2219 InitListDesignations &Designators,
2220 SourceLocation RBraceLoc) {
2221 unsigned NumInit = initlist.size();
2222 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002223
Steve Naroff0acc9c92007-09-15 18:49:24 +00002224 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002225 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002226
Mike Stump9afab102009-02-19 03:04:26 +00002227 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002228 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002229 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002230 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002231}
2232
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002233/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002234bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002235 UsualUnaryConversions(castExpr);
2236
2237 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2238 // type needs to be scalar.
2239 if (castType->isVoidType()) {
2240 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002241 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2242 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002243 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002244 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2245 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2246 (castType->isStructureType() || castType->isUnionType())) {
2247 // GCC struct/union extension: allow cast to self.
2248 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2249 << castType << castExpr->getSourceRange();
2250 } else if (castType->isUnionType()) {
2251 // GCC cast to union extension
2252 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2253 RecordDecl::field_iterator Field, FieldEnd;
2254 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2255 Field != FieldEnd; ++Field) {
2256 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2257 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2258 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2259 << castExpr->getSourceRange();
2260 break;
2261 }
2262 }
2263 if (Field == FieldEnd)
2264 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2265 << castExpr->getType() << castExpr->getSourceRange();
2266 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002267 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002268 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002269 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002270 }
Mike Stump9afab102009-02-19 03:04:26 +00002271 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002272 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002273 return Diag(castExpr->getLocStart(),
2274 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002275 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002276 } else if (castExpr->getType()->isVectorType()) {
2277 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2278 return true;
2279 } else if (castType->isVectorType()) {
2280 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2281 return true;
2282 }
2283 return false;
2284}
2285
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002286bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002287 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002288
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002289 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002290 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002291 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002292 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002293 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002294 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002295 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002296 } else
2297 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002298 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002299 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002300
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002301 return false;
2302}
2303
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002304Action::OwningExprResult
2305Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2306 SourceLocation RParenLoc, ExprArg Op) {
2307 assert((Ty != 0) && (Op.get() != 0) &&
2308 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002309
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002310 Expr *castExpr = static_cast<Expr*>(Op.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002311 QualType castType = QualType::getFromOpaquePtr(Ty);
2312
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002313 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002314 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002315 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002316 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002317}
2318
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002319/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2320/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002321/// C99 6.5.15
2322QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2323 SourceLocation QuestionLoc) {
Chris Lattnere2897262009-02-18 04:28:32 +00002324 UsualUnaryConversions(Cond);
2325 UsualUnaryConversions(LHS);
2326 UsualUnaryConversions(RHS);
2327 QualType CondTy = Cond->getType();
2328 QualType LHSTy = LHS->getType();
2329 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002330
2331 // first, check the condition.
Chris Lattnere2897262009-02-18 04:28:32 +00002332 if (!Cond->isTypeDependent()) {
2333 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2334 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2335 << CondTy;
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002336 return QualType();
2337 }
Chris Lattner4b009652007-07-25 00:24:17 +00002338 }
Mike Stump9afab102009-02-19 03:04:26 +00002339
Chris Lattner992ae932008-01-06 22:42:25 +00002340 // Now check the two expressions.
Chris Lattnere2897262009-02-18 04:28:32 +00002341 if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002342 return Context.DependentTy;
2343
Chris Lattner992ae932008-01-06 22:42:25 +00002344 // If both operands have arithmetic type, do the usual arithmetic conversions
2345 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002346 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2347 UsualArithmeticConversions(LHS, RHS);
2348 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002349 }
Mike Stump9afab102009-02-19 03:04:26 +00002350
Chris Lattner992ae932008-01-06 22:42:25 +00002351 // If both operands are the same structure or union type, the result is that
2352 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002353 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2354 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002355 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002356 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002357 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002358 return LHSTy.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00002359 }
Mike Stump9afab102009-02-19 03:04:26 +00002360
Chris Lattner992ae932008-01-06 22:42:25 +00002361 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002362 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002363 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2364 if (!LHSTy->isVoidType())
2365 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2366 << RHS->getSourceRange();
2367 if (!RHSTy->isVoidType())
2368 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2369 << LHS->getSourceRange();
2370 ImpCastExprToType(LHS, Context.VoidTy);
2371 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002372 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002373 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002374 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2375 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002376 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2377 Context.isObjCObjectPointerType(LHSTy)) &&
2378 RHS->isNullPointerConstant(Context)) {
2379 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2380 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002381 }
Chris Lattnere2897262009-02-18 04:28:32 +00002382 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2383 Context.isObjCObjectPointerType(RHSTy)) &&
2384 LHS->isNullPointerConstant(Context)) {
2385 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2386 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002387 }
Mike Stump9afab102009-02-19 03:04:26 +00002388
Chris Lattner0ac51632008-01-06 22:50:31 +00002389 // Handle the case where both operands are pointers before we handle null
2390 // pointer constants in case both operands are null pointer constants.
Chris Lattnere2897262009-02-18 04:28:32 +00002391 if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2392 if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
Chris Lattner71225142007-07-31 21:27:01 +00002393 // get the "pointed to" types
2394 QualType lhptee = LHSPT->getPointeeType();
2395 QualType rhptee = RHSPT->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00002396
Chris Lattner71225142007-07-31 21:27:01 +00002397 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2398 if (lhptee->isVoidType() &&
Chris Lattner9db553e2008-04-02 06:59:01 +00002399 rhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002400 // Figure out necessary qualifiers (C99 6.5.15p6)
2401 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002402 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002403 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2404 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002405 return destType;
2406 }
Chris Lattner9db553e2008-04-02 06:59:01 +00002407 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
Chris Lattner35fef522008-02-20 20:55:12 +00002408 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
Eli Friedmanca07c902008-02-10 22:59:36 +00002409 QualType destType = Context.getPointerType(destPointee);
Chris Lattnere2897262009-02-18 04:28:32 +00002410 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2411 ImpCastExprToType(RHS, destType); // promote to void*
Eli Friedmanca07c902008-02-10 22:59:36 +00002412 return destType;
2413 }
Chris Lattner4b009652007-07-25 00:24:17 +00002414
Chris Lattner9c039b52009-02-18 04:38:20 +00002415 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
Chris Lattner676c86a2009-02-19 04:44:58 +00002416 // Two identical pointer types are always compatible.
Chris Lattner9c039b52009-02-18 04:38:20 +00002417 return LHSTy;
2418 }
Mike Stump9afab102009-02-19 03:04:26 +00002419
Chris Lattnere2897262009-02-18 04:28:32 +00002420 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002421
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002422 // If either type is an Objective-C object type then check
2423 // compatibility according to Objective-C.
Mike Stump9afab102009-02-19 03:04:26 +00002424 if (Context.isObjCObjectPointerType(LHSTy) ||
Chris Lattnere2897262009-02-18 04:28:32 +00002425 Context.isObjCObjectPointerType(RHSTy)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002426 // If both operands are interfaces and either operand can be
2427 // assigned to the other, use that type as the composite
2428 // type. This allows
2429 // xxx ? (A*) a : (B*) b
2430 // where B is a subclass of A.
2431 //
2432 // Additionally, as for assignment, if either type is 'id'
2433 // allow silent coercion. Finally, if the types are
2434 // incompatible then make sure to use 'id' as the composite
2435 // type so the result is acceptable for sending messages to.
2436
Steve Naroff9fc9cb52009-02-12 19:05:07 +00002437 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
Mike Stump9afab102009-02-19 03:04:26 +00002438 // It could return the composite type.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002439 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2440 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2441 if (LHSIface && RHSIface &&
2442 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002443 compositeType = LHSTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002444 } else if (LHSIface && RHSIface &&
Douglas Gregor5183f9e2008-11-26 06:43:45 +00002445 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
Chris Lattnere2897262009-02-18 04:28:32 +00002446 compositeType = RHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002447 } else if (Context.isObjCIdStructType(lhptee) ||
2448 Context.isObjCIdStructType(rhptee)) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002449 compositeType = Context.getObjCIdType();
2450 } else {
Chris Lattnere2897262009-02-18 04:28:32 +00002451 Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
Mike Stump9afab102009-02-19 03:04:26 +00002452 << LHSTy << RHSTy
Chris Lattnere2897262009-02-18 04:28:32 +00002453 << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002454 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002455 ImpCastExprToType(LHS, incompatTy);
2456 ImpCastExprToType(RHS, incompatTy);
Mike Stump9afab102009-02-19 03:04:26 +00002457 return incompatTy;
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002458 }
Mike Stump9afab102009-02-19 03:04:26 +00002459 } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002460 rhptee.getUnqualifiedType())) {
Chris Lattnere2897262009-02-18 04:28:32 +00002461 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2462 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002463 // In this situation, we assume void* type. No especially good
2464 // reason, but this is what gcc does, and we do have to pick
2465 // to get a consistent AST.
2466 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Chris Lattnere2897262009-02-18 04:28:32 +00002467 ImpCastExprToType(LHS, incompatTy);
2468 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002469 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002470 }
2471 // The pointer types are compatible.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00002472 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2473 // differently qualified versions of compatible types, the result type is
2474 // a pointer to an appropriately qualified version of the *composite*
2475 // type.
Eli Friedmane38150e2008-05-16 20:37:07 +00002476 // FIXME: Need to calculate the composite type.
Eli Friedmanca07c902008-02-10 22:59:36 +00002477 // FIXME: Need to add qualifiers
Chris Lattnere2897262009-02-18 04:28:32 +00002478 ImpCastExprToType(LHS, compositeType);
2479 ImpCastExprToType(RHS, compositeType);
Eli Friedmane38150e2008-05-16 20:37:07 +00002480 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00002481 }
Chris Lattner4b009652007-07-25 00:24:17 +00002482 }
Mike Stump9afab102009-02-19 03:04:26 +00002483
Chris Lattner9c039b52009-02-18 04:38:20 +00002484 // Selection between block pointer types is ok as long as they are the same.
2485 if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2486 Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2487 return LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002488
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002489 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2490 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00002491 // id with statically typed objects).
2492 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002493 // GCC allows qualified id and any Objective-C type to devolve to
2494 // id. Currently localizing to here until clear this should be
2495 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002496 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00002497 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00002498 Context.isObjCObjectPointerType(RHSTy)) ||
2499 (RHSTy->isObjCQualifiedIdType() &&
2500 Context.isObjCObjectPointerType(LHSTy))) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002501 // FIXME: This is not the correct composite type. This only
2502 // happens to work because id can more or less be used anywhere,
2503 // however this may change the type of method sends.
2504 // FIXME: gcc adds some type-checking of the arguments and emits
2505 // (confusing) incompatible comparison warnings in some
2506 // cases. Investigate.
2507 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002508 ImpCastExprToType(LHS, compositeType);
2509 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002510 return compositeType;
2511 }
2512 }
2513
Chris Lattner992ae932008-01-06 22:42:25 +00002514 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00002515 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2516 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002517 return QualType();
2518}
2519
Steve Naroff87d58b42007-09-16 03:34:24 +00002520/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00002521/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002522Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2523 SourceLocation ColonLoc,
2524 ExprArg Cond, ExprArg LHS,
2525 ExprArg RHS) {
2526 Expr *CondExpr = (Expr *) Cond.get();
2527 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00002528
2529 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2530 // was the condition.
2531 bool isLHSNull = LHSExpr == 0;
2532 if (isLHSNull)
2533 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002534
2535 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00002536 RHSExpr, QuestionLoc);
2537 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002538 return ExprError();
2539
2540 Cond.release();
2541 LHS.release();
2542 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00002543 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00002544 isLHSNull ? 0 : LHSExpr,
2545 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00002546}
2547
Chris Lattner4b009652007-07-25 00:24:17 +00002548
2549// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00002550// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00002551// routine is it effectively iqnores the qualifiers on the top level pointee.
2552// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2553// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00002554Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002555Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2556 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002557
Chris Lattner4b009652007-07-25 00:24:17 +00002558 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00002559 lhptee = lhsType->getAsPointerType()->getPointeeType();
2560 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002561
Chris Lattner4b009652007-07-25 00:24:17 +00002562 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002563 lhptee = Context.getCanonicalType(lhptee);
2564 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00002565
Chris Lattner005ed752008-01-04 18:04:52 +00002566 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002567
2568 // C99 6.5.16.1p1: This following citation is common to constraints
2569 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2570 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00002571 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002572 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00002573 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00002574
Mike Stump9afab102009-02-19 03:04:26 +00002575 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2576 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00002577 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00002578 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002579 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002580 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00002581
Chris Lattner4ca3d772008-01-03 22:56:36 +00002582 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002583 assert(rhptee->isFunctionType());
2584 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002585 }
Mike Stump9afab102009-02-19 03:04:26 +00002586
Chris Lattner4ca3d772008-01-03 22:56:36 +00002587 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00002588 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00002589 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002590
2591 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00002592 assert(lhptee->isFunctionType());
2593 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00002594 }
Mike Stump9afab102009-02-19 03:04:26 +00002595 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00002596 // unqualified versions of compatible types, ...
Mike Stump9afab102009-02-19 03:04:26 +00002597 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
Chris Lattner4ca3d772008-01-03 22:56:36 +00002598 rhptee.getUnqualifiedType()))
2599 return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
Chris Lattner005ed752008-01-04 18:04:52 +00002600 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00002601}
2602
Steve Naroff3454b6c2008-09-04 15:10:53 +00002603/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2604/// block pointer types are compatible or whether a block and normal pointer
2605/// are compatible. It is more restrict than comparing two function pointer
2606// types.
Mike Stump9afab102009-02-19 03:04:26 +00002607Sema::AssignConvertType
2608Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00002609 QualType rhsType) {
2610 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00002611
Steve Naroff3454b6c2008-09-04 15:10:53 +00002612 // get the "pointed to" type (ignoring qualifiers at the top level)
2613 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002614 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2615
Steve Naroff3454b6c2008-09-04 15:10:53 +00002616 // make sure we operate on the canonical type
2617 lhptee = Context.getCanonicalType(lhptee);
2618 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00002619
Steve Naroff3454b6c2008-09-04 15:10:53 +00002620 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00002621
Steve Naroff3454b6c2008-09-04 15:10:53 +00002622 // For blocks we enforce that qualifiers are identical.
2623 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2624 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00002625
Steve Naroff3454b6c2008-09-04 15:10:53 +00002626 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00002627 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002628 return ConvTy;
2629}
2630
Mike Stump9afab102009-02-19 03:04:26 +00002631/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2632/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00002633/// pointers. Here are some objectionable examples that GCC considers warnings:
2634///
2635/// int a, *pint;
2636/// short *pshort;
2637/// struct foo *pfoo;
2638///
2639/// pint = pshort; // warning: assignment from incompatible pointer type
2640/// a = pint; // warning: assignment makes integer from pointer without a cast
2641/// pint = a; // warning: assignment makes pointer from integer without a cast
2642/// pint = pfoo; // warning: assignment from incompatible pointer type
2643///
2644/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00002645/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00002646///
Chris Lattner005ed752008-01-04 18:04:52 +00002647Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002648Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00002649 // Get canonical types. We're not formatting these types, just comparing
2650 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002651 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2652 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00002653
2654 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00002655 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00002656
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002657 // If the left-hand side is a reference type, then we are in a
2658 // (rare!) case where we've allowed the use of references in C,
2659 // e.g., as a parameter type in a built-in function. In this case,
2660 // just make sure that the type referenced is compatible with the
2661 // right-hand side type. The caller is responsible for adjusting
2662 // lhsType so that the resulting expression does not have reference
2663 // type.
2664 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2665 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00002666 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002667 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002668 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002669
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002670 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2671 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002672 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00002673 // Relax integer conversions like we do for pointers below.
2674 if (rhsType->isIntegerType())
2675 return IntToPointer;
2676 if (lhsType->isIntegerType())
2677 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00002678 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00002679 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002680
Nate Begemanc5f0f652008-07-14 18:02:46 +00002681 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00002682 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00002683 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2684 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002685 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002686
Nate Begemanc5f0f652008-07-14 18:02:46 +00002687 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00002688 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00002689 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002690 if (getLangOptions().LaxVectorConversions &&
2691 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002692 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00002693 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002694 }
2695 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00002696 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002697
Chris Lattnerdb22bf42008-01-04 23:32:24 +00002698 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00002699 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002700
Chris Lattner390564e2008-04-07 06:49:41 +00002701 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002702 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002703 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00002704
Chris Lattner390564e2008-04-07 06:49:41 +00002705 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002706 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002707
Steve Naroffa982c712008-09-29 18:10:17 +00002708 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00002709 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002710 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00002711
2712 // Treat block pointers as objects.
2713 if (getLangOptions().ObjC1 &&
2714 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2715 return Compatible;
2716 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00002717 return Incompatible;
2718 }
2719
2720 if (isa<BlockPointerType>(lhsType)) {
2721 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00002722 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00002723
Steve Naroffa982c712008-09-29 18:10:17 +00002724 // Treat block pointers as objects.
2725 if (getLangOptions().ObjC1 &&
2726 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2727 return Compatible;
2728
Steve Naroff3454b6c2008-09-04 15:10:53 +00002729 if (rhsType->isBlockPointerType())
2730 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002731
Steve Naroff3454b6c2008-09-04 15:10:53 +00002732 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2733 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002734 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00002735 }
Chris Lattner1853da22008-01-04 23:18:45 +00002736 return Incompatible;
2737 }
2738
Chris Lattner390564e2008-04-07 06:49:41 +00002739 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002740 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00002741 if (lhsType == Context.BoolTy)
2742 return Compatible;
2743
2744 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00002745 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00002746
Mike Stump9afab102009-02-19 03:04:26 +00002747 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002748 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00002749
2750 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00002751 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00002752 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002753 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00002754 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00002755
Chris Lattner1853da22008-01-04 23:18:45 +00002756 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00002757 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00002758 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00002759 }
2760 return Incompatible;
2761}
2762
Chris Lattner005ed752008-01-04 18:04:52 +00002763Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002764Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002765 if (getLangOptions().CPlusPlus) {
2766 if (!lhsType->isRecordType()) {
2767 // C++ 5.17p3: If the left operand is not of class type, the
2768 // expression is implicitly converted (C++ 4) to the
2769 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00002770 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2771 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002772 return Incompatible;
Douglas Gregorbb461502008-10-24 04:54:22 +00002773 else
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002774 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00002775 }
2776
2777 // FIXME: Currently, we fall through and treat C++ classes like C
2778 // structures.
2779 }
2780
Steve Naroffcdee22d2007-11-27 17:58:44 +00002781 // C99 6.5.16.1p1: the left operand is a pointer and the right is
2782 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00002783 if ((lhsType->isPointerType() ||
2784 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00002785 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00002786 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002787 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00002788 return Compatible;
2789 }
Mike Stump9afab102009-02-19 03:04:26 +00002790
Chris Lattner5f505bf2007-10-16 02:55:40 +00002791 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00002792 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00002793 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00002794 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00002795 //
Mike Stump9afab102009-02-19 03:04:26 +00002796 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00002797 if (!lhsType->isReferenceType())
2798 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00002799
Chris Lattner005ed752008-01-04 18:04:52 +00002800 Sema::AssignConvertType result =
2801 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00002802
Steve Naroff0f32f432007-08-24 22:33:52 +00002803 // C99 6.5.16.1p2: The value of the right operand is converted to the
2804 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002805 // CheckAssignmentConstraints allows the left-hand side to be a reference,
2806 // so that we can use references in built-in functions even in C.
2807 // The getNonReferenceType() call makes sure that the resulting expression
2808 // does not have reference type.
Steve Naroff0f32f432007-08-24 22:33:52 +00002809 if (rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00002810 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00002811 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00002812}
2813
Chris Lattner005ed752008-01-04 18:04:52 +00002814Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00002815Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2816 return CheckAssignmentConstraints(lhsType, rhsType);
2817}
2818
Chris Lattner1eafdea2008-11-18 01:30:42 +00002819QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00002820 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00002821 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002822 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00002823 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002824}
2825
Mike Stump9afab102009-02-19 03:04:26 +00002826inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00002827 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00002828 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00002829 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002830 QualType lhsType =
2831 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2832 QualType rhsType =
2833 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00002834
Nate Begemanc5f0f652008-07-14 18:02:46 +00002835 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00002836 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00002837 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00002838
Nate Begemanc5f0f652008-07-14 18:02:46 +00002839 // Handle the case of a vector & extvector type of the same size and element
2840 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00002841 if (getLangOptions().LaxVectorConversions) {
2842 // FIXME: Should we warn here?
2843 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002844 if (const VectorType *RV = rhsType->getAsVectorType())
2845 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00002846 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002847 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00002848 }
2849 }
2850 }
Mike Stump9afab102009-02-19 03:04:26 +00002851
Nate Begemanc5f0f652008-07-14 18:02:46 +00002852 // If the lhs is an extended vector and the rhs is a scalar of the same type
2853 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002854 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002855 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002856
2857 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002858 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2859 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002860 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002861 return lhsType;
2862 }
2863 }
2864
Nate Begemanc5f0f652008-07-14 18:02:46 +00002865 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00002866 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00002867 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00002868 QualType eltType = V->getElementType();
2869
Mike Stump9afab102009-02-19 03:04:26 +00002870 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00002871 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2872 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00002873 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00002874 return rhsType;
2875 }
2876 }
2877
Chris Lattner4b009652007-07-25 00:24:17 +00002878 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00002879 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002880 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00002881 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00002882 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00002883}
2884
Chris Lattner4b009652007-07-25 00:24:17 +00002885inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002886 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002887{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00002888 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002889 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002890
Steve Naroff8f708362007-08-24 19:07:16 +00002891 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002892
Chris Lattner4b009652007-07-25 00:24:17 +00002893 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002894 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002895 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002896}
2897
2898inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00002899 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002900{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00002901 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2902 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2903 return CheckVectorOperands(Loc, lex, rex);
2904 return InvalidOperands(Loc, lex, rex);
2905 }
Chris Lattner4b009652007-07-25 00:24:17 +00002906
Steve Naroff8f708362007-08-24 19:07:16 +00002907 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002908
Chris Lattner4b009652007-07-25 00:24:17 +00002909 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00002910 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00002911 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002912}
2913
2914inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump9afab102009-02-19 03:04:26 +00002915 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00002916{
2917 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002918 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002919
Steve Naroff8f708362007-08-24 19:07:16 +00002920 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002921
Chris Lattner4b009652007-07-25 00:24:17 +00002922 // handle the common case first (both operands are arithmetic).
2923 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002924 return compType;
Chris Lattner4b009652007-07-25 00:24:17 +00002925
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002926 // Put any potential pointer into PExp
2927 Expr* PExp = lex, *IExp = rex;
2928 if (IExp->getType()->isPointerType())
2929 std::swap(PExp, IExp);
2930
2931 if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2932 if (IExp->getType()->isIntegerType()) {
2933 // Check for arithmetic on pointers to incomplete types
2934 if (!PTy->getPointeeType()->isObjectType()) {
2935 if (PTy->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002936 if (getLangOptions().CPlusPlus) {
2937 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2938 << lex->getSourceRange() << rex->getSourceRange();
2939 return QualType();
2940 }
2941
2942 // GNU extension: arithmetic on pointer to void
Chris Lattner8ba580c2008-11-19 05:08:23 +00002943 Diag(Loc, diag::ext_gnu_void_ptr)
2944 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002945 } else if (PTy->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00002946 if (getLangOptions().CPlusPlus) {
2947 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2948 << lex->getType() << lex->getSourceRange();
2949 return QualType();
2950 }
2951
2952 // GNU extension: arithmetic on pointer to function
2953 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002954 << lex->getType() << lex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002955 } else {
Mike Stump9afab102009-02-19 03:04:26 +00002956 DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002957 diag::err_typecheck_arithmetic_incomplete_type,
2958 lex->getSourceRange(), SourceRange(),
2959 lex->getType());
2960 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00002961 }
2962 }
2963 return PExp->getType();
2964 }
2965 }
2966
Chris Lattner1eafdea2008-11-18 01:30:42 +00002967 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00002968}
2969
Chris Lattnerfe1f4032008-04-07 05:30:13 +00002970// C99 6.5.6
2971QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00002972 SourceLocation Loc, bool isCompAssign) {
Chris Lattner4b009652007-07-25 00:24:17 +00002973 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00002974 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00002975
Steve Naroff8f708362007-08-24 19:07:16 +00002976 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00002977
Chris Lattnerf6da2912007-12-09 21:53:25 +00002978 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00002979
Chris Lattnerf6da2912007-12-09 21:53:25 +00002980 // Handle the common case first (both operands are arithmetic).
Chris Lattner4b009652007-07-25 00:24:17 +00002981 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00002982 return compType;
Mike Stump9afab102009-02-19 03:04:26 +00002983
Chris Lattnerf6da2912007-12-09 21:53:25 +00002984 // Either ptr - int or ptr - ptr.
2985 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00002986 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00002987
Chris Lattnerf6da2912007-12-09 21:53:25 +00002988 // The LHS must be an object type, not incomplete, function, etc.
Steve Naroff577f9722008-01-29 18:58:14 +00002989 if (!lpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00002990 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00002991 if (lpointee->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002992 Diag(Loc, diag::ext_gnu_void_ptr)
2993 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorb3193242009-01-23 00:36:41 +00002994 } else if (lpointee->isFunctionType()) {
2995 if (getLangOptions().CPlusPlus) {
2996 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2997 << lex->getType() << lex->getSourceRange();
2998 return QualType();
2999 }
3000
3001 // GNU extension: arithmetic on pointer to function
3002 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3003 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003004 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003005 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003006 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003007 return QualType();
3008 }
3009 }
3010
3011 // The result type of a pointer-int computation is the pointer type.
3012 if (rex->getType()->isIntegerType())
3013 return lex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003014
Chris Lattnerf6da2912007-12-09 21:53:25 +00003015 // Handle pointer-pointer subtractions.
3016 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003017 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003018
Chris Lattnerf6da2912007-12-09 21:53:25 +00003019 // RHS must be an object type, unless void (GNU).
Steve Naroff577f9722008-01-29 18:58:14 +00003020 if (!rpointee->isObjectType()) {
Chris Lattnerf6da2912007-12-09 21:53:25 +00003021 // Handle the GNU void* extension.
Steve Naroff577f9722008-01-29 18:58:14 +00003022 if (rpointee->isVoidType()) {
3023 if (!lpointee->isVoidType())
Chris Lattner8ba580c2008-11-19 05:08:23 +00003024 Diag(Loc, diag::ext_gnu_void_ptr)
3025 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregorf93eda12009-01-23 19:03:35 +00003026 } else if (rpointee->isFunctionType()) {
3027 if (getLangOptions().CPlusPlus) {
3028 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3029 << rex->getType() << rex->getSourceRange();
3030 return QualType();
3031 }
Mike Stump9afab102009-02-19 03:04:26 +00003032
Douglas Gregorf93eda12009-01-23 19:03:35 +00003033 // GNU extension: arithmetic on pointer to function
3034 if (!lpointee->isFunctionType())
3035 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3036 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003037 } else {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003038 Diag(Loc, diag::err_typecheck_sub_ptr_object)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003039 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003040 return QualType();
3041 }
3042 }
Mike Stump9afab102009-02-19 03:04:26 +00003043
Chris Lattnerf6da2912007-12-09 21:53:25 +00003044 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003045 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003046 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003047 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003048 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003049 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003050 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003051 return QualType();
3052 }
Mike Stump9afab102009-02-19 03:04:26 +00003053
Chris Lattnerf6da2912007-12-09 21:53:25 +00003054 return Context.getPointerDiffType();
3055 }
3056 }
Mike Stump9afab102009-02-19 03:04:26 +00003057
Chris Lattner1eafdea2008-11-18 01:30:42 +00003058 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003059}
3060
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003061// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003062QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003063 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003064 // C99 6.5.7p2: Each of the operands shall have integer type.
3065 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003066 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003067
Chris Lattner2c8bff72007-12-12 05:47:28 +00003068 // Shifts don't perform usual arithmetic conversions, they just do integer
3069 // promotions on each operand. C99 6.5.7p3
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003070 if (!isCompAssign)
3071 UsualUnaryConversions(lex);
Chris Lattner2c8bff72007-12-12 05:47:28 +00003072 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003073
Chris Lattner2c8bff72007-12-12 05:47:28 +00003074 // "The type of the result is that of the promoted left operand."
3075 return lex->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003076}
3077
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003078// C99 6.5.8
Chris Lattner1eafdea2008-11-18 01:30:42 +00003079QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003080 bool isRelational) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003081 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003082 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003083
Chris Lattner254f3bc2007-08-26 01:18:55 +00003084 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003085 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3086 UsualArithmeticConversions(lex, rex);
3087 else {
3088 UsualUnaryConversions(lex);
3089 UsualUnaryConversions(rex);
3090 }
Chris Lattner4b009652007-07-25 00:24:17 +00003091 QualType lType = lex->getType();
3092 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003093
Ted Kremenek486509e2007-10-29 17:13:39 +00003094 // For non-floating point types, check for self-comparisons of the form
3095 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3096 // often indicate logic errors in the program.
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003097 if (!lType->isFloatingType()) {
Ted Kremenek87e30c52008-01-17 16:57:34 +00003098 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3099 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003100 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003101 Diag(Loc, diag::warn_selfcomparison);
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003102 }
Mike Stump9afab102009-02-19 03:04:26 +00003103
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003104 // The result of comparisons is 'bool' in C++, 'int' in C.
3105 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3106
Chris Lattner254f3bc2007-08-26 01:18:55 +00003107 if (isRelational) {
3108 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003109 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003110 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003111 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003112 if (lType->isFloatingType()) {
3113 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003114 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003115 }
Mike Stump9afab102009-02-19 03:04:26 +00003116
Chris Lattner254f3bc2007-08-26 01:18:55 +00003117 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003118 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003119 }
Mike Stump9afab102009-02-19 03:04:26 +00003120
Chris Lattner22be8422007-08-26 01:10:14 +00003121 bool LHSIsNull = lex->isNullPointerConstant(Context);
3122 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003123
Chris Lattner254f3bc2007-08-26 01:18:55 +00003124 // All of the following pointer related warnings are GCC extensions, except
3125 // when handling null pointer constants. One day, we can consider making them
3126 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003127 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003128 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003129 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003130 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003131 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003132
Steve Naroff3b435622007-11-13 14:57:38 +00003133 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003134 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3135 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003136 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003137 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003138 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003139 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003140 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003141 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003142 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003143 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003144 // Handle block pointer types.
3145 if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3146 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3147 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003148
Steve Naroff3454b6c2008-09-04 15:10:53 +00003149 if (!LHSIsNull && !RHSIsNull &&
3150 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003151 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003152 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003153 }
3154 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003155 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003156 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003157 // Allow block pointers to be compared with null pointer constants.
3158 if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3159 (lType->isPointerType() && rType->isBlockPointerType())) {
3160 if (!LHSIsNull && !RHSIsNull) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003161 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003162 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003163 }
3164 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003165 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003166 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003167
Steve Naroff936c4362008-06-03 14:04:54 +00003168 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003169 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003170 const PointerType *LPT = lType->getAsPointerType();
3171 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003172 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003173 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003174 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003175 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003176
Steve Naroff030fcda2008-11-17 19:49:16 +00003177 if (!LPtrToVoid && !RPtrToVoid &&
3178 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003179 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003180 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003181 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003182 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003183 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003184 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003185 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003186 }
Steve Naroff936c4362008-06-03 14:04:54 +00003187 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3188 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003189 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003190 } else {
3191 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003192 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003193 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003194 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003195 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003196 }
Steve Naroff936c4362008-06-03 14:04:54 +00003197 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003198 }
Mike Stump9afab102009-02-19 03:04:26 +00003199 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003200 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00003201 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003202 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003203 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003204 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003205 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003206 }
Mike Stump9afab102009-02-19 03:04:26 +00003207 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00003208 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00003209 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003210 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003211 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00003212 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003213 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003214 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00003215 // Handle block pointers.
3216 if (lType->isBlockPointerType() && rType->isIntegerType()) {
3217 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003218 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003219 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003220 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003221 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003222 }
3223 if (lType->isIntegerType() && rType->isBlockPointerType()) {
3224 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00003225 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003226 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff4fea7b62008-09-04 16:56:14 +00003227 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003228 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00003229 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00003230 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003231}
3232
Nate Begemanc5f0f652008-07-14 18:02:46 +00003233/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00003234/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003235/// like a scalar comparison, a vector comparison produces a vector of integer
3236/// types.
3237QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00003238 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00003239 bool isRelational) {
3240 // Check to make sure we're operating on vectors of the same type and width,
3241 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003242 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003243 if (vType.isNull())
3244 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00003245
Nate Begemanc5f0f652008-07-14 18:02:46 +00003246 QualType lType = lex->getType();
3247 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003248
Nate Begemanc5f0f652008-07-14 18:02:46 +00003249 // For non-floating point types, check for self-comparisons of the form
3250 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3251 // often indicate logic errors in the program.
3252 if (!lType->isFloatingType()) {
3253 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3254 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3255 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003256 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003257 }
Mike Stump9afab102009-02-19 03:04:26 +00003258
Nate Begemanc5f0f652008-07-14 18:02:46 +00003259 // Check for comparisons of floating point operands using != and ==.
3260 if (!isRelational && lType->isFloatingType()) {
3261 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003262 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00003263 }
Mike Stump9afab102009-02-19 03:04:26 +00003264
Nate Begemanc5f0f652008-07-14 18:02:46 +00003265 // Return the type for the comparison, which is the same as vector type for
3266 // integer vectors, or an integer type of identical size and number of
3267 // elements for floating point vectors.
3268 if (lType->isIntegerType())
3269 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00003270
Nate Begemanc5f0f652008-07-14 18:02:46 +00003271 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00003272 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00003273 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00003274 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Nate Begemand6d2f772009-01-18 03:20:47 +00003275 else if (TypeSize == Context.getTypeSize(Context.LongTy))
3276 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3277
Mike Stump9afab102009-02-19 03:04:26 +00003278 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00003279 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00003280 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3281}
3282
Chris Lattner4b009652007-07-25 00:24:17 +00003283inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003284 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003285{
3286 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003287 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003288
Steve Naroff8f708362007-08-24 19:07:16 +00003289 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003290
Chris Lattner4b009652007-07-25 00:24:17 +00003291 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003292 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003293 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003294}
3295
3296inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00003297 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00003298{
3299 UsualUnaryConversions(lex);
3300 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003301
Eli Friedmanbea3f842008-05-13 20:16:47 +00003302 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00003303 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003304 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003305}
3306
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003307/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3308/// is a read-only property; return true if so. A readonly property expression
3309/// depends on various declarations and thus must be treated specially.
3310///
Mike Stump9afab102009-02-19 03:04:26 +00003311static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003312{
3313 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3314 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3315 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3316 QualType BaseType = PropExpr->getBase()->getType();
3317 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00003318 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003319 PTy->getPointeeType()->getAsObjCInterfaceType())
3320 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3321 if (S.isPropertyReadonly(PDecl, IFace))
3322 return true;
3323 }
3324 }
3325 return false;
3326}
3327
Chris Lattner4c2642c2008-11-18 01:22:49 +00003328/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
3329/// emit an error and return true. If so, return false.
3330static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00003331 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3332 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3333 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00003334 if (IsLV == Expr::MLV_Valid)
3335 return false;
Mike Stump9afab102009-02-19 03:04:26 +00003336
Chris Lattner4c2642c2008-11-18 01:22:49 +00003337 unsigned Diag = 0;
3338 bool NeedType = false;
3339 switch (IsLV) { // C99 6.5.16p2
3340 default: assert(0 && "Unknown result from isModifiableLvalue!");
3341 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00003342 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003343 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3344 NeedType = true;
3345 break;
Mike Stump9afab102009-02-19 03:04:26 +00003346 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003347 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3348 NeedType = true;
3349 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00003350 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003351 Diag = diag::err_typecheck_lvalue_casts_not_supported;
3352 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003353 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003354 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3355 break;
Chris Lattner005ed752008-01-04 18:04:52 +00003356 case Expr::MLV_IncompleteType:
3357 case Expr::MLV_IncompleteVoidType:
Mike Stump9afab102009-02-19 03:04:26 +00003358 return S.DiagnoseIncompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003359 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3360 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00003361 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003362 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3363 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00003364 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00003365 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3366 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00003367 case Expr::MLV_ReadonlyProperty:
3368 Diag = diag::error_readonly_property_assignment;
3369 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00003370 case Expr::MLV_NoSetterProperty:
3371 Diag = diag::error_nosetter_property_assignment;
3372 break;
Chris Lattner4b009652007-07-25 00:24:17 +00003373 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00003374
Chris Lattner4c2642c2008-11-18 01:22:49 +00003375 if (NeedType)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003376 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003377 else
Chris Lattner9d2cf082008-11-19 05:27:50 +00003378 S.Diag(Loc, Diag) << E->getSourceRange();
Chris Lattner4c2642c2008-11-18 01:22:49 +00003379 return true;
3380}
3381
3382
3383
3384// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00003385QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3386 SourceLocation Loc,
3387 QualType CompoundType) {
3388 // Verify that LHS is a modifiable lvalue, and emit error if not.
3389 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00003390 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00003391
3392 QualType LHSType = LHS->getType();
3393 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00003394
Chris Lattner005ed752008-01-04 18:04:52 +00003395 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003396 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00003397 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003398 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00003399 // Special case of NSObject attributes on c-style pointer types.
3400 if (ConvTy == IncompatiblePointer &&
3401 ((Context.isObjCNSObjectType(LHSType) &&
3402 Context.isObjCObjectPointerType(RHSType)) ||
3403 (Context.isObjCNSObjectType(RHSType) &&
3404 Context.isObjCObjectPointerType(LHSType))))
3405 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003406
Chris Lattner34c85082008-08-21 18:04:13 +00003407 // If the RHS is a unary plus or minus, check to see if they = and + are
3408 // right next to each other. If so, the user may have typo'd "x =+ 4"
3409 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00003410 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00003411 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3412 RHSCheck = ICE->getSubExpr();
3413 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3414 if ((UO->getOpcode() == UnaryOperator::Plus ||
3415 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00003416 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00003417 // Only if the two operators are exactly adjacent.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003418 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
Chris Lattner77d52da2008-11-20 06:06:08 +00003419 Diag(Loc, diag::warn_not_compound_assign)
3420 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3421 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner34c85082008-08-21 18:04:13 +00003422 }
3423 } else {
3424 // Compound assignment "x += y"
Chris Lattner1eafdea2008-11-18 01:30:42 +00003425 ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00003426 }
Chris Lattner005ed752008-01-04 18:04:52 +00003427
Chris Lattner1eafdea2008-11-18 01:30:42 +00003428 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3429 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00003430 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003431
Chris Lattner4b009652007-07-25 00:24:17 +00003432 // C99 6.5.16p3: The type of an assignment expression is the type of the
3433 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00003434 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00003435 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3436 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00003437 // C++ 5.17p1: the type of the assignment expression is that of its left
3438 // oprdu.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003439 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00003440}
3441
Chris Lattner1eafdea2008-11-18 01:30:42 +00003442// C99 6.5.17
3443QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3444 // FIXME: what is required for LHS?
Mike Stump9afab102009-02-19 03:04:26 +00003445
Chris Lattner03c430f2008-07-25 20:54:07 +00003446 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00003447 DefaultFunctionArrayConversion(RHS);
3448 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003449}
3450
3451/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3452/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003453QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3454 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003455 if (Op->isTypeDependent())
3456 return Context.DependentTy;
3457
Chris Lattnere65182c2008-11-21 07:05:48 +00003458 QualType ResType = Op->getType();
3459 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003460
Sebastian Redl0440c8c2008-12-20 09:35:34 +00003461 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3462 // Decrement of bool is not allowed.
3463 if (!isInc) {
3464 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3465 return QualType();
3466 }
3467 // Increment of bool sets it to true, but is deprecated.
3468 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3469 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00003470 // OK!
3471 } else if (const PointerType *PT = ResType->getAsPointerType()) {
3472 // C99 6.5.2.4p2, 6.5.6p2
3473 if (PT->getPointeeType()->isObjectType()) {
3474 // Pointer to object is ok!
3475 } else if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003476 if (getLangOptions().CPlusPlus) {
3477 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3478 << Op->getSourceRange();
3479 return QualType();
3480 }
3481
3482 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00003483 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003484 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00003485 if (getLangOptions().CPlusPlus) {
3486 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3487 << Op->getType() << Op->getSourceRange();
3488 return QualType();
3489 }
3490
3491 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003492 << ResType << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003493 return QualType();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003494 } else {
Mike Stump9afab102009-02-19 03:04:26 +00003495 DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003496 diag::err_typecheck_arithmetic_incomplete_type,
3497 Op->getSourceRange(), SourceRange(),
3498 ResType);
3499 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003500 }
Chris Lattnere65182c2008-11-21 07:05:48 +00003501 } else if (ResType->isComplexType()) {
3502 // C99 does not support ++/-- on complex types, we allow as an extension.
3503 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003504 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003505 } else {
3506 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003507 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00003508 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003509 }
Mike Stump9afab102009-02-19 03:04:26 +00003510 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00003511 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00003512 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00003513 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00003514 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00003515}
3516
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003517/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00003518/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003519/// where the declaration is needed for type checking. We only need to
3520/// handle cases when the expression references a function designator
3521/// or is an lvalue. Here are some examples:
3522/// - &(x) => x
3523/// - &*****f => f for f a function designator.
3524/// - &s.xx => s
3525/// - &s.zz[1].yy -> s, if zz is an array
3526/// - *(x + 1) -> x, if x is an array
3527/// - &"123"[2] -> 0
3528/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00003529static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00003530 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003531 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00003532 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003533 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003534 case Stmt::MemberExprClass:
Chris Lattnera3249072007-11-16 17:46:48 +00003535 // Fields cannot be declared with a 'register' storage class.
3536 // &X->f is always ok, even if X is declared register.
Chris Lattner48d7f382008-04-02 04:24:33 +00003537 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00003538 return 0;
Chris Lattner48d7f382008-04-02 04:24:33 +00003539 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003540 case Stmt::ArraySubscriptExprClass: {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003541 // &X[4] and &4[X] refers to X if X is not a pointer.
Mike Stump9afab102009-02-19 03:04:26 +00003542
Douglas Gregord2baafd2008-10-21 16:13:35 +00003543 NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
Daniel Dunbar612720d2008-10-21 21:22:32 +00003544 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
Anders Carlsson655694e2008-02-01 16:01:31 +00003545 if (!VD || VD->getType()->isPointerType())
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00003546 return 0;
3547 else
3548 return VD;
3549 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003550 case Stmt::UnaryOperatorClass: {
3551 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00003552
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003553 switch(UO->getOpcode()) {
3554 case UnaryOperator::Deref: {
3555 // *(X + 1) refers to X if X is not a pointer.
Douglas Gregord2baafd2008-10-21 16:13:35 +00003556 if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3557 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3558 if (!VD || VD->getType()->isPointerType())
3559 return 0;
3560 return VD;
3561 }
3562 return 0;
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00003563 }
3564 case UnaryOperator::Real:
3565 case UnaryOperator::Imag:
3566 case UnaryOperator::Extension:
3567 return getPrimaryDecl(UO->getSubExpr());
3568 default:
3569 return 0;
3570 }
3571 }
3572 case Stmt::BinaryOperatorClass: {
3573 BinaryOperator *BO = cast<BinaryOperator>(E);
3574
3575 // Handle cases involving pointer arithmetic. The result of an
3576 // Assign or AddAssign is not an lvalue so they can be ignored.
3577
3578 // (x + n) or (n + x) => x
3579 if (BO->getOpcode() == BinaryOperator::Add) {
3580 if (BO->getLHS()->getType()->isPointerType()) {
3581 return getPrimaryDecl(BO->getLHS());
3582 } else if (BO->getRHS()->getType()->isPointerType()) {
3583 return getPrimaryDecl(BO->getRHS());
3584 }
3585 }
3586
3587 return 0;
3588 }
Chris Lattner4b009652007-07-25 00:24:17 +00003589 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00003590 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00003591 case Stmt::ImplicitCastExprClass:
3592 // &X[4] when X is an array, has an implicit cast from array to pointer.
Chris Lattner48d7f382008-04-02 04:24:33 +00003593 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00003594 default:
3595 return 0;
3596 }
3597}
3598
3599/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00003600/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00003601/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00003602/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00003603/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00003604/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00003605/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00003606QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Douglas Gregore6be68a2008-12-17 22:52:20 +00003607 if (op->isTypeDependent())
3608 return Context.DependentTy;
3609
Steve Naroff9c6c3592008-01-13 17:10:08 +00003610 if (getLangOptions().C99) {
3611 // Implement C99-only parts of addressof rules.
3612 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3613 if (uOp->getOpcode() == UnaryOperator::Deref)
3614 // Per C99 6.5.3.2, the address of a deref always returns a valid result
3615 // (assuming the deref expression is valid).
3616 return uOp->getSubExpr()->getType();
3617 }
3618 // Technically, there should be a check for array subscript
3619 // expressions here, but the result of one is always an lvalue anyway.
3620 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00003621 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00003622 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00003623
Chris Lattner4b009652007-07-25 00:24:17 +00003624 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Chris Lattnera3249072007-11-16 17:46:48 +00003625 if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3626 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00003627 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3628 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003629 return QualType();
3630 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003631 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
Douglas Gregor82d44772008-12-20 23:49:58 +00003632 if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3633 if (Field->isBitField()) {
3634 Diag(OpLoc, diag::err_typecheck_address_of)
3635 << "bit-field" << op->getSourceRange();
3636 return QualType();
3637 }
Steve Naroff73cf87e2008-02-29 23:30:25 +00003638 }
3639 // Check for Apple extension for accessing vector components.
Nate Begemana9187ab2009-02-15 22:45:20 +00003640 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3641 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Chris Lattner77d52da2008-11-20 06:06:08 +00003642 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00003643 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00003644 return QualType();
3645 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00003646 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00003647 // with the register storage-class specifier.
3648 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3649 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00003650 Diag(OpLoc, diag::err_typecheck_address_of)
3651 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003652 return QualType();
3653 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003654 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00003655 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00003656 } else if (isa<FieldDecl>(dcl)) {
3657 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00003658 // Could be a pointer to member, though, if there is an explicit
3659 // scope qualifier for the class.
3660 if (isa<QualifiedDeclRefExpr>(op)) {
3661 DeclContext *Ctx = dcl->getDeclContext();
3662 if (Ctx && Ctx->isRecord())
3663 return Context.getMemberPointerType(op->getType(),
3664 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3665 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003666 } else if (isa<FunctionDecl>(dcl)) {
3667 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00003668 // As above.
3669 if (isa<QualifiedDeclRefExpr>(op)) {
3670 DeclContext *Ctx = dcl->getDeclContext();
3671 if (Ctx && Ctx->isRecord())
3672 return Context.getMemberPointerType(op->getType(),
3673 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3674 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00003675 }
Nuno Lopesdf239522008-12-16 22:58:26 +00003676 else
Chris Lattner4b009652007-07-25 00:24:17 +00003677 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00003678 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00003679
Chris Lattner4b009652007-07-25 00:24:17 +00003680 // If the operand has type "type", the result has type "pointer to type".
3681 return Context.getPointerType(op->getType());
3682}
3683
Chris Lattnerda5c0872008-11-23 09:13:29 +00003684QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003685 if (Op->isTypeDependent())
3686 return Context.DependentTy;
3687
Chris Lattnerda5c0872008-11-23 09:13:29 +00003688 UsualUnaryConversions(Op);
3689 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003690
Chris Lattnerda5c0872008-11-23 09:13:29 +00003691 // Note that per both C89 and C99, this is always legal, even if ptype is an
3692 // incomplete type or void. It would be possible to warn about dereferencing
3693 // a void pointer, but it's completely well-defined, and such a warning is
3694 // unlikely to catch any mistakes.
3695 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00003696 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003697
Chris Lattner77d52da2008-11-20 06:06:08 +00003698 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003699 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003700 return QualType();
3701}
3702
3703static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3704 tok::TokenKind Kind) {
3705 BinaryOperator::Opcode Opc;
3706 switch (Kind) {
3707 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00003708 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
3709 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003710 case tok::star: Opc = BinaryOperator::Mul; break;
3711 case tok::slash: Opc = BinaryOperator::Div; break;
3712 case tok::percent: Opc = BinaryOperator::Rem; break;
3713 case tok::plus: Opc = BinaryOperator::Add; break;
3714 case tok::minus: Opc = BinaryOperator::Sub; break;
3715 case tok::lessless: Opc = BinaryOperator::Shl; break;
3716 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
3717 case tok::lessequal: Opc = BinaryOperator::LE; break;
3718 case tok::less: Opc = BinaryOperator::LT; break;
3719 case tok::greaterequal: Opc = BinaryOperator::GE; break;
3720 case tok::greater: Opc = BinaryOperator::GT; break;
3721 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
3722 case tok::equalequal: Opc = BinaryOperator::EQ; break;
3723 case tok::amp: Opc = BinaryOperator::And; break;
3724 case tok::caret: Opc = BinaryOperator::Xor; break;
3725 case tok::pipe: Opc = BinaryOperator::Or; break;
3726 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
3727 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
3728 case tok::equal: Opc = BinaryOperator::Assign; break;
3729 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
3730 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
3731 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
3732 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
3733 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
3734 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
3735 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
3736 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
3737 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
3738 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
3739 case tok::comma: Opc = BinaryOperator::Comma; break;
3740 }
3741 return Opc;
3742}
3743
3744static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3745 tok::TokenKind Kind) {
3746 UnaryOperator::Opcode Opc;
3747 switch (Kind) {
3748 default: assert(0 && "Unknown unary op!");
3749 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
3750 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
3751 case tok::amp: Opc = UnaryOperator::AddrOf; break;
3752 case tok::star: Opc = UnaryOperator::Deref; break;
3753 case tok::plus: Opc = UnaryOperator::Plus; break;
3754 case tok::minus: Opc = UnaryOperator::Minus; break;
3755 case tok::tilde: Opc = UnaryOperator::Not; break;
3756 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00003757 case tok::kw___real: Opc = UnaryOperator::Real; break;
3758 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
3759 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3760 }
3761 return Opc;
3762}
3763
Douglas Gregord7f915e2008-11-06 23:29:22 +00003764/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3765/// operator @p Opc at location @c TokLoc. This routine only supports
3766/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003767Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3768 unsigned Op,
3769 Expr *lhs, Expr *rhs) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00003770 QualType ResultTy; // Result type of the binary operator.
3771 QualType CompTy; // Computation type for compound assignments (e.g. '+=')
3772 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3773
3774 switch (Opc) {
3775 default:
3776 assert(0 && "Unknown binary expr!");
3777 case BinaryOperator::Assign:
3778 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3779 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003780 case BinaryOperator::PtrMemD:
3781 case BinaryOperator::PtrMemI:
3782 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3783 Opc == BinaryOperator::PtrMemI);
3784 break;
3785 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003786 case BinaryOperator::Div:
3787 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3788 break;
3789 case BinaryOperator::Rem:
3790 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3791 break;
3792 case BinaryOperator::Add:
3793 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3794 break;
3795 case BinaryOperator::Sub:
3796 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3797 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00003798 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00003799 case BinaryOperator::Shr:
3800 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3801 break;
3802 case BinaryOperator::LE:
3803 case BinaryOperator::LT:
3804 case BinaryOperator::GE:
3805 case BinaryOperator::GT:
3806 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3807 break;
3808 case BinaryOperator::EQ:
3809 case BinaryOperator::NE:
3810 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3811 break;
3812 case BinaryOperator::And:
3813 case BinaryOperator::Xor:
3814 case BinaryOperator::Or:
3815 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3816 break;
3817 case BinaryOperator::LAnd:
3818 case BinaryOperator::LOr:
3819 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3820 break;
3821 case BinaryOperator::MulAssign:
3822 case BinaryOperator::DivAssign:
3823 CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3824 if (!CompTy.isNull())
3825 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3826 break;
3827 case BinaryOperator::RemAssign:
3828 CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3829 if (!CompTy.isNull())
3830 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3831 break;
3832 case BinaryOperator::AddAssign:
3833 CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3834 if (!CompTy.isNull())
3835 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3836 break;
3837 case BinaryOperator::SubAssign:
3838 CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3839 if (!CompTy.isNull())
3840 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3841 break;
3842 case BinaryOperator::ShlAssign:
3843 case BinaryOperator::ShrAssign:
3844 CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3845 if (!CompTy.isNull())
3846 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3847 break;
3848 case BinaryOperator::AndAssign:
3849 case BinaryOperator::XorAssign:
3850 case BinaryOperator::OrAssign:
3851 CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3852 if (!CompTy.isNull())
3853 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3854 break;
3855 case BinaryOperator::Comma:
3856 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3857 break;
3858 }
3859 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003860 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00003861 if (CompTy.isNull())
3862 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3863 else
3864 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Mike Stump9afab102009-02-19 03:04:26 +00003865 CompTy, OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00003866}
3867
Chris Lattner4b009652007-07-25 00:24:17 +00003868// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003869Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3870 tok::TokenKind Kind,
3871 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00003872 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003873 Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
Chris Lattner4b009652007-07-25 00:24:17 +00003874
Steve Naroff87d58b42007-09-16 03:34:24 +00003875 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3876 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00003877
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003878 // If either expression is type-dependent, just build the AST.
3879 // FIXME: We'll need to perform some caching of the result of name
3880 // lookup for operator+.
3881 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
Steve Naroff774e4152009-01-21 00:14:39 +00003882 if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3883 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003884 Context.DependentTy,
3885 Context.DependentTy, TokLoc));
Steve Naroff774e4152009-01-21 00:14:39 +00003886 else
Sebastian Redl95216a62009-02-07 00:15:38 +00003887 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3888 Context.DependentTy, TokLoc));
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003889 }
3890
Sebastian Redl95216a62009-02-07 00:15:38 +00003891 if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
Douglas Gregord7f915e2008-11-06 23:29:22 +00003892 (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3893 rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
Douglas Gregor70d26122008-11-12 17:17:38 +00003894 // If this is one of the assignment operators, we only perform
3895 // overload resolution if the left-hand side is a class or
3896 // enumeration type (C++ [expr.ass]p3).
3897 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3898 !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3899 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3900 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003901
Douglas Gregord7f915e2008-11-06 23:29:22 +00003902 // Determine which overloaded operator we're dealing with.
3903 static const OverloadedOperatorKind OverOps[] = {
Sebastian Redl95216a62009-02-07 00:15:38 +00003904 // Overloading .* is not possible.
3905 static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
Douglas Gregord7f915e2008-11-06 23:29:22 +00003906 OO_Star, OO_Slash, OO_Percent,
3907 OO_Plus, OO_Minus,
3908 OO_LessLess, OO_GreaterGreater,
3909 OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3910 OO_EqualEqual, OO_ExclaimEqual,
3911 OO_Amp,
3912 OO_Caret,
3913 OO_Pipe,
3914 OO_AmpAmp,
3915 OO_PipePipe,
3916 OO_Equal, OO_StarEqual,
3917 OO_SlashEqual, OO_PercentEqual,
3918 OO_PlusEqual, OO_MinusEqual,
3919 OO_LessLessEqual, OO_GreaterGreaterEqual,
3920 OO_AmpEqual, OO_CaretEqual,
3921 OO_PipeEqual,
3922 OO_Comma
3923 };
3924 OverloadedOperatorKind OverOp = OverOps[Opc];
3925
Mike Stump9afab102009-02-19 03:04:26 +00003926 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor5ed15042008-11-18 23:14:02 +00003927 // to the candidate set.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00003928 OverloadCandidateSet CandidateSet;
Douglas Gregord7f915e2008-11-06 23:29:22 +00003929 Expr *Args[2] = { lhs, rhs };
Douglas Gregor48a87322009-02-04 16:44:47 +00003930 if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3931 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003932
3933 // Perform overload resolution.
3934 OverloadCandidateSet::iterator Best;
3935 switch (BestViableFunction(CandidateSet, Best)) {
3936 case OR_Success: {
Douglas Gregor70d26122008-11-12 17:17:38 +00003937 // We found a built-in operator or an overloaded operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003938 FunctionDecl *FnDecl = Best->Function;
3939
Douglas Gregor70d26122008-11-12 17:17:38 +00003940 if (FnDecl) {
3941 // We matched an overloaded operator. Build a call to that
3942 // operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003943
Douglas Gregor70d26122008-11-12 17:17:38 +00003944 // Convert the arguments.
Douglas Gregor5ed15042008-11-18 23:14:02 +00003945 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3946 if (PerformObjectArgumentInitialization(lhs, Method) ||
3947 PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3948 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003949 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003950 } else {
3951 // Convert the arguments.
3952 if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3953 "passing") ||
3954 PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3955 "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003956 return ExprError();
Douglas Gregor5ed15042008-11-18 23:14:02 +00003957 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003958
Douglas Gregor70d26122008-11-12 17:17:38 +00003959 // Determine the result type
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003960 QualType ResultTy
Douglas Gregor70d26122008-11-12 17:17:38 +00003961 = FnDecl->getType()->getAsFunctionType()->getResultType();
3962 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003963
Douglas Gregor70d26122008-11-12 17:17:38 +00003964 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00003965 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3966 SourceLocation());
Douglas Gregor65fedaf2008-11-14 16:09:21 +00003967 UsualUnaryConversions(FnExpr);
3968
Mike Stump9afab102009-02-19 03:04:26 +00003969 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00003970 ResultTy, TokLoc));
Douglas Gregor70d26122008-11-12 17:17:38 +00003971 } else {
3972 // We matched a built-in operator. Convert the arguments, then
3973 // break out so that we will build the appropriate built-in
3974 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00003975 if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3976 Best->Conversions[0], "passing") ||
3977 PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3978 Best->Conversions[1], "passing"))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003979 return ExprError();
Douglas Gregor70d26122008-11-12 17:17:38 +00003980
3981 break;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003982 }
Douglas Gregord7f915e2008-11-06 23:29:22 +00003983 }
3984
3985 case OR_No_Viable_Function:
3986 // No viable function; fall through to handling this as a
Douglas Gregor70d26122008-11-12 17:17:38 +00003987 // built-in operator, which will produce an error message for us.
Douglas Gregord7f915e2008-11-06 23:29:22 +00003988 break;
3989
3990 case OR_Ambiguous:
Chris Lattner8ba580c2008-11-19 05:08:23 +00003991 Diag(TokLoc, diag::err_ovl_ambiguous_oper)
3992 << BinaryOperator::getOpcodeStr(Opc)
3993 << lhs->getSourceRange() << rhs->getSourceRange();
Douglas Gregord7f915e2008-11-06 23:29:22 +00003994 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003995 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00003996
3997 case OR_Deleted:
3998 Diag(TokLoc, diag::err_ovl_deleted_oper)
3999 << Best->Function->isDeleted()
4000 << BinaryOperator::getOpcodeStr(Opc)
4001 << lhs->getSourceRange() << rhs->getSourceRange();
4002 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4003 return ExprError();
Douglas Gregord7f915e2008-11-06 23:29:22 +00004004 }
4005
Douglas Gregor70d26122008-11-12 17:17:38 +00004006 // Either we found no viable overloaded operator or we matched a
4007 // built-in operator. In either case, fall through to trying to
4008 // build a built-in operation.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004009 }
4010
Douglas Gregord7f915e2008-11-06 23:29:22 +00004011 // Build a built-in binary operation.
4012 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004013}
4014
4015// Unary Operators. 'Tok' is the token for the operator.
Sebastian Redl8b769972009-01-19 00:08:26 +00004016Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4017 tok::TokenKind Op, ExprArg input) {
4018 // FIXME: Input is modified later, but smart pointer not reassigned.
4019 Expr *Input = (Expr*)input.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004020 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004021
4022 if (getLangOptions().CPlusPlus &&
Mike Stump9afab102009-02-19 03:04:26 +00004023 (Input->getType()->isRecordType()
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004024 || Input->getType()->isEnumeralType())) {
4025 // Determine which overloaded operator we're dealing with.
4026 static const OverloadedOperatorKind OverOps[] = {
4027 OO_None, OO_None,
4028 OO_PlusPlus, OO_MinusMinus,
4029 OO_Amp, OO_Star,
4030 OO_Plus, OO_Minus,
4031 OO_Tilde, OO_Exclaim,
4032 OO_None, OO_None,
Mike Stump9afab102009-02-19 03:04:26 +00004033 OO_None,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004034 OO_None
4035 };
4036 OverloadedOperatorKind OverOp = OverOps[Opc];
4037
Mike Stump9afab102009-02-19 03:04:26 +00004038 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004039 // to the candidate set.
4040 OverloadCandidateSet CandidateSet;
Douglas Gregor48a87322009-02-04 16:44:47 +00004041 if (OverOp != OO_None &&
4042 AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4043 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004044
4045 // Perform overload resolution.
4046 OverloadCandidateSet::iterator Best;
4047 switch (BestViableFunction(CandidateSet, Best)) {
4048 case OR_Success: {
4049 // We found a built-in operator or an overloaded operator.
4050 FunctionDecl *FnDecl = Best->Function;
4051
4052 if (FnDecl) {
4053 // We matched an overloaded operator. Build a call to that
4054 // operator.
4055
4056 // Convert the arguments.
4057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4058 if (PerformObjectArgumentInitialization(Input, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00004059 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004060 } else {
4061 // Convert the arguments.
Mike Stump9afab102009-02-19 03:04:26 +00004062 if (PerformCopyInitialization(Input,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004063 FnDecl->getParamDecl(0)->getType(),
4064 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004065 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004066 }
4067
4068 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00004069 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004070 = FnDecl->getType()->getAsFunctionType()->getResultType();
4071 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00004072
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004073 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00004074 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00004075 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004076 UsualUnaryConversions(FnExpr);
4077
Sebastian Redl8b769972009-01-19 00:08:26 +00004078 input.release();
Mike Stump9afab102009-02-19 03:04:26 +00004079 return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4080 1, ResultTy, OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004081 } else {
4082 // We matched a built-in operator. Convert the arguments, then
4083 // break out so that we will build the appropriate built-in
4084 // operator node.
Douglas Gregor6214d8a2009-01-14 15:45:31 +00004085 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4086 Best->Conversions[0], "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00004087 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004088
4089 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00004090 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004091 }
4092
4093 case OR_No_Viable_Function:
4094 // No viable function; fall through to handling this as a
4095 // built-in operator, which will produce an error message for us.
4096 break;
4097
4098 case OR_Ambiguous:
4099 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4100 << UnaryOperator::getOpcodeStr(Opc)
4101 << Input->getSourceRange();
4102 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00004103 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00004104
4105 case OR_Deleted:
4106 Diag(OpLoc, diag::err_ovl_deleted_oper)
4107 << Best->Function->isDeleted()
4108 << UnaryOperator::getOpcodeStr(Opc)
4109 << Input->getSourceRange();
4110 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4111 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004112 }
4113
4114 // Either we found no viable overloaded operator or we matched a
4115 // built-in operator. In either case, fall through to trying to
Sebastian Redl8b769972009-01-19 00:08:26 +00004116 // build a built-in operation.
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004117 }
4118
Chris Lattner4b009652007-07-25 00:24:17 +00004119 QualType resultType;
4120 switch (Opc) {
4121 default:
4122 assert(0 && "Unimplemented unary expr!");
4123 case UnaryOperator::PreInc:
4124 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004125 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4126 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004127 break;
Mike Stump9afab102009-02-19 03:04:26 +00004128 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004129 resultType = CheckAddressOfOperand(Input, OpLoc);
4130 break;
Mike Stump9afab102009-02-19 03:04:26 +00004131 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004132 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004133 resultType = CheckIndirectionOperand(Input, OpLoc);
4134 break;
4135 case UnaryOperator::Plus:
4136 case UnaryOperator::Minus:
4137 UsualUnaryConversions(Input);
4138 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004139 if (resultType->isDependentType())
4140 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004141 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4142 break;
4143 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4144 resultType->isEnumeralType())
4145 break;
4146 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4147 Opc == UnaryOperator::Plus &&
4148 resultType->isPointerType())
4149 break;
4150
Sebastian Redl8b769972009-01-19 00:08:26 +00004151 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4152 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004153 case UnaryOperator::Not: // bitwise complement
4154 UsualUnaryConversions(Input);
4155 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004156 if (resultType->isDependentType())
4157 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004158 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4159 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4160 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004161 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004162 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004163 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004164 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4165 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004166 break;
4167 case UnaryOperator::LNot: // logical negation
4168 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4169 DefaultFunctionArrayConversion(Input);
4170 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004171 if (resultType->isDependentType())
4172 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004173 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004174 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4175 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004176 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004177 // In C++, it's bool. C++ 5.3.1p8
4178 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004179 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004180 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004181 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004182 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004183 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004184 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004185 resultType = Input->getType();
4186 break;
4187 }
4188 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004189 return ExprError();
4190 input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004191 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004192}
4193
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004194/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Mike Stump9afab102009-02-19 03:04:26 +00004195Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
Chris Lattner4b009652007-07-25 00:24:17 +00004196 SourceLocation LabLoc,
4197 IdentifierInfo *LabelII) {
4198 // Look up the record for this label identifier.
Steve Naroff313c4162009-02-28 16:48:43 +00004199 llvm::DenseMap<IdentifierInfo*, Action::StmtTy*>::iterator I =
4200 ActiveScope->LabelMap.find(LabelII);
Mike Stump9afab102009-02-19 03:04:26 +00004201
Steve Naroff313c4162009-02-28 16:48:43 +00004202 LabelStmt *LabelDecl;
4203
Daniel Dunbar879788d2008-08-04 16:51:22 +00004204 // If we haven't seen this label yet, create a forward reference. It
4205 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff313c4162009-02-28 16:48:43 +00004206 if (I == ActiveScope->LabelMap.end()) {
Steve Naroff774e4152009-01-21 00:14:39 +00004207 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004208
Steve Naroff313c4162009-02-28 16:48:43 +00004209 ActiveScope->LabelMap.insert(std::make_pair(LabelII, LabelDecl));
4210 } else
4211 LabelDecl = static_cast<LabelStmt *>(I->second);
4212
Chris Lattner4b009652007-07-25 00:24:17 +00004213 // Create the AST node. The address of a label always has type 'void*'.
Steve Naroff774e4152009-01-21 00:14:39 +00004214 return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4215 Context.getPointerType(Context.VoidTy));
Chris Lattner4b009652007-07-25 00:24:17 +00004216}
4217
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004218Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
Chris Lattner4b009652007-07-25 00:24:17 +00004219 SourceLocation RPLoc) { // "({..})"
4220 Stmt *SubStmt = static_cast<Stmt*>(substmt);
4221 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4222 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4223
Eli Friedmanbc941e12009-01-24 23:09:00 +00004224 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4225 if (isFileScope) {
4226 return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4227 }
4228
Chris Lattner4b009652007-07-25 00:24:17 +00004229 // FIXME: there are a variety of strange constraints to enforce here, for
4230 // example, it is not possible to goto into a stmt expression apparently.
4231 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004232
Chris Lattner4b009652007-07-25 00:24:17 +00004233 // FIXME: the last statement in the compount stmt has its value used. We
4234 // should not warn about it being unused.
4235
4236 // If there are sub stmts in the compound stmt, take the type of the last one
4237 // as the type of the stmtexpr.
4238 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004239
Chris Lattner200964f2008-07-26 19:51:01 +00004240 if (!Compound->body_empty()) {
4241 Stmt *LastStmt = Compound->body_back();
4242 // If LastStmt is a label, skip down through into the body.
4243 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4244 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004245
Chris Lattner200964f2008-07-26 19:51:01 +00004246 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004247 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004248 }
Mike Stump9afab102009-02-19 03:04:26 +00004249
Steve Naroff774e4152009-01-21 00:14:39 +00004250 return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
Chris Lattner4b009652007-07-25 00:24:17 +00004251}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004252
Douglas Gregorddfd9d52008-12-23 00:26:44 +00004253Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4254 SourceLocation BuiltinLoc,
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004255 SourceLocation TypeLoc,
4256 TypeTy *argty,
4257 OffsetOfComponent *CompPtr,
4258 unsigned NumComponents,
4259 SourceLocation RPLoc) {
4260 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4261 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004262
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004263 bool Dependent = ArgTy->isDependentType();
4264
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004265 // We must have at least one component that refers to the type, and the first
4266 // one is known to be a field designator. Verify that the ArgTy represents
4267 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004268 if (!Dependent && !ArgTy->isRecordType())
Chris Lattner4bfd2232008-11-24 06:25:27 +00004269 return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
Mike Stump9afab102009-02-19 03:04:26 +00004270
Eli Friedman342d9432009-02-27 06:44:11 +00004271 // Otherwise, create a null pointer as the base, and iteratively process
4272 // the offsetof designators.
4273 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4274 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
4275 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
4276 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004277
Chris Lattnerb37522e2007-08-31 21:49:13 +00004278 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4279 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004280 // FIXME: This diagnostic isn't actually visible because the location is in
4281 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004282 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004283 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4284 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004285
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004286 if (!Dependent) {
4287 // FIXME: Dependent case loses a lot of information here. And probably
4288 // leaks like a sieve.
4289 for (unsigned i = 0; i != NumComponents; ++i) {
4290 const OffsetOfComponent &OC = CompPtr[i];
4291 if (OC.isBrackets) {
4292 // Offset of an array sub-field. TODO: Should we allow vector elements?
4293 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4294 if (!AT) {
4295 Res->Destroy(Context);
4296 return Diag(OC.LocEnd, diag::err_offsetof_array_type)
4297 << Res->getType();
4298 }
4299
4300 // FIXME: C++: Verify that operator[] isn't overloaded.
4301
Eli Friedman342d9432009-02-27 06:44:11 +00004302 // Promote the array so it looks more like a normal array subscript
4303 // expression.
4304 DefaultFunctionArrayConversion(Res);
4305
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004306 // C99 6.5.2.1p1
4307 Expr *Idx = static_cast<Expr*>(OC.U.E);
4308 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
4309 return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4310 << Idx->getSourceRange();
4311
4312 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4313 OC.LocEnd);
4314 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004315 }
Mike Stump9afab102009-02-19 03:04:26 +00004316
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004317 const RecordType *RC = Res->getType()->getAsRecordType();
4318 if (!RC) {
4319 Res->Destroy(Context);
4320 return Diag(OC.LocEnd, diag::err_offsetof_record_type)
4321 << Res->getType();
4322 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004323
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004324 // Get the decl corresponding to this.
4325 RecordDecl *RD = RC->getDecl();
4326 FieldDecl *MemberDecl
4327 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4328 LookupMemberName)
4329 .getAsDecl());
4330 if (!MemberDecl)
4331 return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4332 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004333
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004334 // FIXME: C++: Verify that MemberDecl isn't a static field.
4335 // FIXME: Verify that MemberDecl isn't a bitfield.
4336 // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4337 // matter here.
4338 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
Steve Naroff774e4152009-01-21 00:14:39 +00004339 MemberDecl->getType().getNonReferenceType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004340 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004341 }
Mike Stump9afab102009-02-19 03:04:26 +00004342
4343 return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
Steve Naroff774e4152009-01-21 00:14:39 +00004344 Context.getSizeType(), BuiltinLoc);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004345}
4346
4347
Mike Stump9afab102009-02-19 03:04:26 +00004348Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
Steve Naroff63bad2d2007-08-01 22:05:33 +00004349 TypeTy *arg1, TypeTy *arg2,
4350 SourceLocation RPLoc) {
4351 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4352 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004353
Steve Naroff63bad2d2007-08-01 22:05:33 +00004354 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004355
4356 return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
Steve Naroff774e4152009-01-21 00:14:39 +00004357 argT2, RPLoc);
Steve Naroff63bad2d2007-08-01 22:05:33 +00004358}
4359
Mike Stump9afab102009-02-19 03:04:26 +00004360Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
Steve Naroff93c53012007-08-03 21:21:27 +00004361 ExprTy *expr1, ExprTy *expr2,
4362 SourceLocation RPLoc) {
4363 Expr *CondExpr = static_cast<Expr*>(cond);
4364 Expr *LHSExpr = static_cast<Expr*>(expr1);
4365 Expr *RHSExpr = static_cast<Expr*>(expr2);
Mike Stump9afab102009-02-19 03:04:26 +00004366
Steve Naroff93c53012007-08-03 21:21:27 +00004367 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4368
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004369 QualType resType;
4370 if (CondExpr->isValueDependent()) {
4371 resType = Context.DependentTy;
4372 } else {
4373 // The conditional expression is required to be a constant expression.
4374 llvm::APSInt condEval(32);
4375 SourceLocation ExpLoc;
4376 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4377 return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4378 << CondExpr->getSourceRange();
Steve Naroff93c53012007-08-03 21:21:27 +00004379
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004380 // If the condition is > zero, then the AST type is the same as the LSHExpr.
4381 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4382 }
4383
Mike Stump9afab102009-02-19 03:04:26 +00004384 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00004385 resType, RPLoc);
Steve Naroff93c53012007-08-03 21:21:27 +00004386}
4387
Steve Naroff52a81c02008-09-03 18:15:37 +00004388//===----------------------------------------------------------------------===//
4389// Clang Extensions.
4390//===----------------------------------------------------------------------===//
4391
4392/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00004393void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00004394 // Analyze block parameters.
4395 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00004396
Steve Naroff52a81c02008-09-03 18:15:37 +00004397 // Add BSI to CurBlock.
4398 BSI->PrevBlockInfo = CurBlock;
4399 CurBlock = BSI;
Steve Naroff313c4162009-02-28 16:48:43 +00004400 ActiveScope = BlockScope;
Mike Stump9afab102009-02-19 03:04:26 +00004401
Steve Naroff52a81c02008-09-03 18:15:37 +00004402 BSI->ReturnType = 0;
4403 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00004404 BSI->hasBlockDeclRefExprs = false;
Mike Stump9afab102009-02-19 03:04:26 +00004405
Steve Naroff52059382008-10-10 01:28:17 +00004406 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00004407 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00004408}
4409
Mike Stumpc1fddff2009-02-04 22:31:32 +00004410void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4411 assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4412
4413 if (ParamInfo.getNumTypeObjects() == 0
4414 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4415 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4416
4417 // The type is entirely optional as well, if none, use DependentTy.
4418 if (T.isNull())
4419 T = Context.DependentTy;
4420
4421 // The parameter list is optional, if there was none, assume ().
4422 if (!T->isFunctionType())
4423 T = Context.getFunctionType(T, NULL, 0, 0, 0);
4424
4425 CurBlock->hasPrototype = true;
4426 CurBlock->isVariadic = false;
4427 Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4428 .getTypePtr();
4429
4430 if (!RetTy->isDependentType())
4431 CurBlock->ReturnType = RetTy;
4432 return;
4433 }
4434
Steve Naroff52a81c02008-09-03 18:15:37 +00004435 // Analyze arguments to block.
4436 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4437 "Not a function declarator!");
4438 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00004439
Steve Naroff52059382008-10-10 01:28:17 +00004440 CurBlock->hasPrototype = FTI.hasPrototype;
4441 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00004442
Steve Naroff52a81c02008-09-03 18:15:37 +00004443 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4444 // no arguments, not a function that takes a single void argument.
4445 if (FTI.hasPrototype &&
4446 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4447 (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4448 ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4449 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00004450 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00004451 } else if (FTI.hasPrototype) {
4452 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Steve Naroff52059382008-10-10 01:28:17 +00004453 CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4454 CurBlock->isVariadic = FTI.isVariadic;
Mike Stumpc1fddff2009-02-04 22:31:32 +00004455 QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4456
4457 Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4458 .getTypePtr();
4459
4460 if (!RetTy->isDependentType())
4461 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00004462 }
Steve Naroff52059382008-10-10 01:28:17 +00004463 CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00004464
Steve Naroff52059382008-10-10 01:28:17 +00004465 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4466 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4467 // If this has an identifier, add it to the scope stack.
4468 if ((*AI)->getIdentifier())
4469 PushOnScopeChains(*AI, CurBlock->TheScope);
Steve Naroff52a81c02008-09-03 18:15:37 +00004470}
4471
4472/// ActOnBlockError - If there is an error parsing a block, this callback
4473/// is invoked to pop the information about the block from the action impl.
4474void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4475 // Ensure that CurBlock is deleted.
4476 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00004477
Steve Naroff52a81c02008-09-03 18:15:37 +00004478 // Pop off CurBlock, handle nested blocks.
4479 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004480
Steve Naroff52a81c02008-09-03 18:15:37 +00004481 // FIXME: Delete the ParmVarDecl objects as well???
Mike Stump9afab102009-02-19 03:04:26 +00004482
Steve Naroff52a81c02008-09-03 18:15:37 +00004483}
4484
4485/// ActOnBlockStmtExpr - This is called when the body of a block statement
4486/// literal was successfully completed. ^(int x){...}
4487Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4488 Scope *CurScope) {
4489 // Ensure that CurBlock is deleted.
4490 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Ted Kremenek0c97e042009-02-07 01:47:29 +00004491 ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
Steve Naroff52a81c02008-09-03 18:15:37 +00004492
Steve Naroff52059382008-10-10 01:28:17 +00004493 PopDeclContext();
4494
Steve Naroff5cd38432009-02-28 21:01:15 +00004495 // Before poping CurBlock, set ActiveScope to this scopes parent.
4496 ActiveScope = CurBlock->TheScope->getParent();
4497
Steve Naroff52a81c02008-09-03 18:15:37 +00004498 // Pop off CurBlock, handle nested blocks.
4499 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00004500
Steve Naroff52a81c02008-09-03 18:15:37 +00004501 QualType RetTy = Context.VoidTy;
4502 if (BSI->ReturnType)
4503 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004504
Steve Naroff52a81c02008-09-03 18:15:37 +00004505 llvm::SmallVector<QualType, 8> ArgTypes;
4506 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4507 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00004508
Steve Naroff52a81c02008-09-03 18:15:37 +00004509 QualType BlockTy;
4510 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00004511 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00004512 else
4513 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00004514 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004515
Steve Naroff52a81c02008-09-03 18:15:37 +00004516 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00004517
Steve Naroff95029d92008-10-08 18:44:00 +00004518 BSI->TheDecl->setBody(Body.take());
Mike Stumpae93d652009-02-19 22:01:56 +00004519 return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
Steve Naroff52a81c02008-09-03 18:15:37 +00004520}
4521
Anders Carlsson36760332007-10-15 20:28:48 +00004522Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4523 ExprTy *expr, TypeTy *type,
Chris Lattner005ed752008-01-04 18:04:52 +00004524 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00004525 Expr *E = static_cast<Expr*>(expr);
4526 QualType T = QualType::getFromOpaquePtr(type);
4527
4528 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004529
4530 // Get the va_list type
4531 QualType VaListType = Context.getBuiltinVaListType();
4532 // Deal with implicit array decay; for example, on x86-64,
4533 // va_list is an array, but it's supposed to decay to
4534 // a pointer for va_arg.
4535 if (VaListType->isArrayType())
4536 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00004537 // Make sure the input expression also decays appropriately.
4538 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00004539
4540 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
Anders Carlsson36760332007-10-15 20:28:48 +00004541 return Diag(E->getLocStart(),
Chris Lattner77d52da2008-11-20 06:06:08 +00004542 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004543 << E->getType() << E->getSourceRange();
Mike Stump9afab102009-02-19 03:04:26 +00004544
Anders Carlsson36760332007-10-15 20:28:48 +00004545 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00004546
Steve Naroff774e4152009-01-21 00:14:39 +00004547 return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
Anders Carlsson36760332007-10-15 20:28:48 +00004548}
4549
Douglas Gregorad4b3792008-11-29 04:51:27 +00004550Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4551 // The type of __null will be int or long, depending on the size of
4552 // pointers on the target.
4553 QualType Ty;
4554 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4555 Ty = Context.IntTy;
4556 else
4557 Ty = Context.LongTy;
4558
Steve Naroff774e4152009-01-21 00:14:39 +00004559 return new (Context) GNUNullExpr(Ty, TokenLoc);
Douglas Gregorad4b3792008-11-29 04:51:27 +00004560}
4561
Chris Lattner005ed752008-01-04 18:04:52 +00004562bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4563 SourceLocation Loc,
4564 QualType DstType, QualType SrcType,
4565 Expr *SrcExpr, const char *Flavor) {
4566 // Decode the result (notice that AST's are still created for extensions).
4567 bool isInvalid = false;
4568 unsigned DiagKind;
4569 switch (ConvTy) {
4570 default: assert(0 && "Unknown conversion type");
4571 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004572 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00004573 DiagKind = diag::ext_typecheck_convert_pointer_int;
4574 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00004575 case IntToPointer:
4576 DiagKind = diag::ext_typecheck_convert_int_pointer;
4577 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004578 case IncompatiblePointer:
4579 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4580 break;
4581 case FunctionVoidPointer:
4582 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4583 break;
4584 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00004585 // If the qualifiers lost were because we were applying the
4586 // (deprecated) C++ conversion from a string literal to a char*
4587 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
4588 // Ideally, this check would be performed in
4589 // CheckPointerTypesForAssignment. However, that would require a
4590 // bit of refactoring (so that the second argument is an
4591 // expression, rather than a type), which should be done as part
4592 // of a larger effort to fix CheckPointerTypesForAssignment for
4593 // C++ semantics.
4594 if (getLangOptions().CPlusPlus &&
4595 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4596 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00004597 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4598 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004599 case IntToBlockPointer:
4600 DiagKind = diag::err_int_to_block_pointer;
4601 break;
4602 case IncompatibleBlockPointer:
Steve Naroff82324d62008-09-24 23:31:10 +00004603 DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004604 break;
Steve Naroff19608432008-10-14 22:18:38 +00004605 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00004606 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00004607 // it can give a more specific diagnostic.
4608 DiagKind = diag::warn_incompatible_qualified_id;
4609 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00004610 case IncompatibleVectors:
4611 DiagKind = diag::warn_incompatible_vectors;
4612 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004613 case Incompatible:
4614 DiagKind = diag::err_typecheck_convert_incompatible;
4615 isInvalid = true;
4616 break;
4617 }
Mike Stump9afab102009-02-19 03:04:26 +00004618
Chris Lattner271d4c22008-11-24 05:29:24 +00004619 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4620 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00004621 return isInvalid;
4622}
Anders Carlssond5201b92008-11-30 19:50:32 +00004623
4624bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4625{
4626 Expr::EvalResult EvalResult;
4627
Mike Stump9afab102009-02-19 03:04:26 +00004628 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00004629 EvalResult.HasSideEffects) {
4630 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4631
4632 if (EvalResult.Diag) {
4633 // We only show the note if it's not the usual "invalid subexpression"
4634 // or if it's actually in a subexpression.
4635 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4636 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4637 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4638 }
Mike Stump9afab102009-02-19 03:04:26 +00004639
Anders Carlssond5201b92008-11-30 19:50:32 +00004640 return true;
4641 }
4642
4643 if (EvalResult.Diag) {
Mike Stump9afab102009-02-19 03:04:26 +00004644 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
Anders Carlssond5201b92008-11-30 19:50:32 +00004645 E->getSourceRange();
4646
4647 // Print the reason it's not a constant.
4648 if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4649 Diag(EvalResult.DiagLoc, EvalResult.Diag);
4650 }
Mike Stump9afab102009-02-19 03:04:26 +00004651
Anders Carlssond5201b92008-11-30 19:50:32 +00004652 if (Result)
4653 *Result = EvalResult.Val.getInt();
4654 return false;
4655}