blob: cfb9eb658deee2294555df58d5566e927d13ec22 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000020#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000028using namespace clang;
29
David Chisnall0f436562009-08-17 16:35:33 +000030
Douglas Gregor48f3bb92009-02-18 21:56:37 +000031/// \brief Determine whether the use of this declaration is valid, and
32/// emit any corresponding diagnostics.
33///
34/// This routine diagnoses various problems with referencing
35/// declarations that can occur when using a declaration. For example,
36/// it might warn if a deprecated or unavailable declaration is being
37/// used, or produce an error (and return true) if a C++0x deleted
38/// function is being used.
39///
40/// \returns true if there was an error (this declaration cannot be
41/// referenced), false otherwise.
42bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000043 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000044 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000045 // Implementing deprecated stuff requires referencing deprecated
46 // stuff. Don't warn if we are implementing a deprecated
47 // construct.
Chris Lattnerf15970c2009-02-16 19:35:30 +000048 bool isSilenced = false;
49
50 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
51 // If this reference happens *in* a deprecated function or method, don't
52 // warn.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000053 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerf15970c2009-02-16 19:35:30 +000054
55 // If this is an Objective-C method implementation, check to see if the
56 // method was deprecated on the declaration, not the definition.
57 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
58 // The semantic decl context of a ObjCMethodDecl is the
59 // ObjCImplementationDecl.
60 if (ObjCImplementationDecl *Impl
61 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
62
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +000063 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerf15970c2009-02-16 19:35:30 +000064 MD->isInstanceMethod());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000065 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerf15970c2009-02-16 19:35:30 +000066 }
67 }
68 }
69
70 if (!isSilenced)
Chris Lattner76a642f2009-02-15 22:43:40 +000071 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
72 }
73
Douglas Gregor48f3bb92009-02-18 21:56:37 +000074 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000075 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000076 if (FD->isDeleted()) {
77 Diag(Loc, diag::err_deleted_function_use);
78 Diag(D->getLocation(), diag::note_unavailable_here) << true;
79 return true;
80 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000081 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000082
83 // See if the decl is unavailable
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000084 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner76a642f2009-02-15 22:43:40 +000085 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000086 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
87 }
88
Douglas Gregor48f3bb92009-02-18 21:56:37 +000089 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000090}
91
Fariborz Jahanian5b530052009-05-13 18:09:35 +000092/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
93/// (and other functions in future), which have been declared with sentinel
94/// attribute. It warns if call does not have the sentinel argument.
95///
96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
97 Expr **Args, unsigned NumArgs)
98{
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000099 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000100 if (!attr)
101 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000102 int sentinelPos = attr->getSentinel();
103 int nullPos = attr->getNullPos();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000104
Mike Stump390b4cc2009-05-16 07:39:55 +0000105 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
106 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000107 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000108 bool warnNotEnoughArgs = false;
109 int isMethod = 0;
110 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
111 // skip over named parameters.
112 ObjCMethodDecl::param_iterator P, E = MD->param_end();
113 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
114 if (nullPos)
115 --nullPos;
116 else
117 ++i;
118 }
119 warnNotEnoughArgs = (P != E || i >= NumArgs);
120 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000121 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000122 // skip over named parameters.
123 ObjCMethodDecl::param_iterator P, E = FD->param_end();
124 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
125 if (nullPos)
126 --nullPos;
127 else
128 ++i;
129 }
130 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000131 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000132 // block or function pointer call.
133 QualType Ty = V->getType();
134 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
135 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenek6217b802009-07-29 21:53:49 +0000136 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
137 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000138 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
139 unsigned NumArgsInProto = Proto->getNumArgs();
140 unsigned k;
141 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
142 if (nullPos)
143 --nullPos;
144 else
145 ++i;
146 }
147 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
148 }
149 if (Ty->isBlockPointerType())
150 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000151 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000152 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000153 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000154 return;
155
156 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000157 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000158 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000159 return;
160 }
161 int sentinel = i;
162 while (sentinelPos > 0 && i < NumArgs-1) {
163 --sentinelPos;
164 ++i;
165 }
166 if (sentinelPos > 0) {
167 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000168 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000169 return;
170 }
171 while (i < NumArgs-1) {
172 ++i;
173 ++sentinel;
174 }
175 Expr *sentinelExpr = Args[sentinel];
176 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
177 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000178 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000179 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000180 }
181 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000182}
183
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000184SourceRange Sema::getExprRange(ExprTy *E) const {
185 Expr *Ex = (Expr *)E;
186 return Ex? Ex->getSourceRange() : SourceRange();
187}
188
Chris Lattnere7a2e912008-07-25 21:10:04 +0000189//===----------------------------------------------------------------------===//
190// Standard Promotions and Conversions
191//===----------------------------------------------------------------------===//
192
Chris Lattnere7a2e912008-07-25 21:10:04 +0000193/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
194void Sema::DefaultFunctionArrayConversion(Expr *&E) {
195 QualType Ty = E->getType();
196 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
197
Chris Lattnere7a2e912008-07-25 21:10:04 +0000198 if (Ty->isFunctionType())
199 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner67d33d82008-07-25 21:33:13 +0000200 else if (Ty->isArrayType()) {
201 // In C90 mode, arrays only promote to pointers if the array expression is
202 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
203 // type 'array of type' is converted to an expression that has type 'pointer
204 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
205 // that has type 'array of type' ...". The relevant change is "an lvalue"
206 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000207 //
208 // C++ 4.2p1:
209 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
210 // T" can be converted to an rvalue of type "pointer to T".
211 //
212 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
213 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000214 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
215 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000216 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000217}
218
219/// UsualUnaryConversions - Performs various conversions that are common to most
220/// operators (C99 6.3). The conversions of array and function types are
221/// sometimes surpressed. For example, the array->pointer conversion doesn't
222/// apply if the array is an argument to the sizeof or address (&) operators.
223/// In these instances, this routine should *not* be called.
224Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
225 QualType Ty = Expr->getType();
226 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
227
Douglas Gregorfc24e442009-05-01 20:41:21 +0000228 // C99 6.3.1.1p2:
229 //
230 // The following may be used in an expression wherever an int or
231 // unsigned int may be used:
232 // - an object or expression with an integer type whose integer
233 // conversion rank is less than or equal to the rank of int
234 // and unsigned int.
235 // - A bit-field of type _Bool, int, signed int, or unsigned int.
236 //
237 // If an int can represent all values of the original type, the
238 // value is converted to an int; otherwise, it is converted to an
239 // unsigned int. These are called the integer promotions. All
240 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000241 QualType PTy = Context.isPromotableBitField(Expr);
242 if (!PTy.isNull()) {
243 ImpCastExprToType(Expr, PTy);
244 return Expr;
245 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000246 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000247 QualType PT = Context.getPromotedIntegerType(Ty);
248 ImpCastExprToType(Expr, PT);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000249 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000250 }
251
Douglas Gregorfc24e442009-05-01 20:41:21 +0000252 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000253 return Expr;
254}
255
Chris Lattner05faf172008-07-25 22:25:12 +0000256/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
257/// do not have a prototype. Arguments that have type float are promoted to
258/// double. All other argument types are converted by UsualUnaryConversions().
259void Sema::DefaultArgumentPromotion(Expr *&Expr) {
260 QualType Ty = Expr->getType();
261 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
262
263 // If this is a 'float' (CVR qualified or typedef) promote to double.
264 if (const BuiltinType *BT = Ty->getAsBuiltinType())
265 if (BT->getKind() == BuiltinType::Float)
266 return ImpCastExprToType(Expr, Context.DoubleTy);
267
268 UsualUnaryConversions(Expr);
269}
270
Chris Lattner312531a2009-04-12 08:11:20 +0000271/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
272/// will warn if the resulting type is not a POD type, and rejects ObjC
273/// interfaces passed by value. This returns true if the argument type is
274/// completely illegal.
275bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000276 DefaultArgumentPromotion(Expr);
277
Chris Lattner312531a2009-04-12 08:11:20 +0000278 if (Expr->getType()->isObjCInterfaceType()) {
279 Diag(Expr->getLocStart(),
280 diag::err_cannot_pass_objc_interface_to_vararg)
281 << Expr->getType() << CT;
282 return true;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000283 }
Chris Lattner312531a2009-04-12 08:11:20 +0000284
285 if (!Expr->getType()->isPODType())
286 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
287 << Expr->getType() << CT;
288
289 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000290}
291
292
Chris Lattnere7a2e912008-07-25 21:10:04 +0000293/// UsualArithmeticConversions - Performs various conversions that are common to
294/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
295/// routine returns the first non-arithmetic type found. The client is
296/// responsible for emitting appropriate error diagnostics.
297/// FIXME: verify the conversion rules for "complex int" are consistent with
298/// GCC.
299QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
300 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000301 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000302 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000303
304 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000305
Chris Lattnere7a2e912008-07-25 21:10:04 +0000306 // For conversion purposes, we ignore any qualifiers.
307 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000308 QualType lhs =
309 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
310 QualType rhs =
311 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000312
313 // If both types are identical, no conversion is needed.
314 if (lhs == rhs)
315 return lhs;
316
317 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
318 // The caller can deal with this (e.g. pointer + int).
319 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
320 return lhs;
321
Douglas Gregor2d833e32009-05-02 00:36:19 +0000322 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000323 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000324 if (!LHSBitfieldPromoteTy.isNull())
325 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000326 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000327 if (!RHSBitfieldPromoteTy.isNull())
328 rhs = RHSBitfieldPromoteTy;
329
Eli Friedmana95d7572009-08-19 07:44:53 +0000330 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000331 if (!isCompAssign)
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000332 ImpCastExprToType(lhsExpr, destType);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000333 ImpCastExprToType(rhsExpr, destType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000334 return destType;
335}
336
Chris Lattnere7a2e912008-07-25 21:10:04 +0000337//===----------------------------------------------------------------------===//
338// Semantic Analysis for various Expression Types
339//===----------------------------------------------------------------------===//
340
341
Steve Narofff69936d2007-09-16 03:34:24 +0000342/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000343/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
344/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
345/// multiple tokens. However, the common case is that StringToks points to one
346/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000347///
348Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000349Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000350 assert(NumStringToks && "Must have at least one string!");
351
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000352 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000354 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000355
356 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
357 for (unsigned i = 0; i != NumStringToks; ++i)
358 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000359
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000360 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000361 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000362 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000363
364 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
365 if (getLangOptions().CPlusPlus)
366 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000367
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000368 // Get an array type for the string, according to C99 6.4.5. This includes
369 // the nul terminator character as well as the string length for pascal
370 // strings.
371 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000372 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000373 ArrayType::Normal, 0);
Chris Lattner726e1682009-02-18 05:49:11 +0000374
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattner2085fd62009-02-18 06:40:38 +0000376 return Owned(StringLiteral::Create(Context, Literal.GetString(),
377 Literal.GetStringLength(),
378 Literal.AnyWide, StrTy,
379 &StringTokLocs[0],
380 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000381}
382
Chris Lattner639e2d32008-10-20 05:16:36 +0000383/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
384/// CurBlock to VD should cause it to be snapshotted (as we do for auto
385/// variables defined outside the block) or false if this is not needed (e.g.
386/// for values inside the block or for globals).
387///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000388/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
389/// up-to-date.
390///
Chris Lattner639e2d32008-10-20 05:16:36 +0000391static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
392 ValueDecl *VD) {
393 // If the value is defined inside the block, we couldn't snapshot it even if
394 // we wanted to.
395 if (CurBlock->TheDecl == VD->getDeclContext())
396 return false;
397
398 // If this is an enum constant or function, it is constant, don't snapshot.
399 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
400 return false;
401
402 // If this is a reference to an extern, static, or global variable, no need to
403 // snapshot it.
404 // FIXME: What about 'const' variables in C++?
405 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000406 if (!Var->hasLocalStorage())
407 return false;
408
409 // Blocks that have these can't be constant.
410 CurBlock->hasBlockDeclRefExprs = true;
411
412 // If we have nested blocks, the decl may be declared in an outer block (in
413 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
414 // be defined outside all of the current blocks (in which case the blocks do
415 // all get the bit). Walk the nesting chain.
416 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
417 NextBlock = NextBlock->PrevBlockInfo) {
418 // If we found the defining block for the variable, don't mark the block as
419 // having a reference outside it.
420 if (NextBlock->TheDecl == VD->getDeclContext())
421 break;
422
423 // Otherwise, the DeclRef from the inner block causes the outer one to need
424 // a snapshot as well.
425 NextBlock->hasBlockDeclRefExprs = true;
426 }
Chris Lattner639e2d32008-10-20 05:16:36 +0000427
428 return true;
429}
430
431
432
Steve Naroff08d92e42007-09-15 18:49:24 +0000433/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Reid Spencer5f016e22007-07-11 17:01:13 +0000434/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff0d755ad2008-03-19 23:46:26 +0000435/// identifier is used in a function call context.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000436/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000437/// class or namespace that the identifier must be a member of.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000438Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
439 IdentifierInfo &II,
440 bool HasTrailingLParen,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000441 const CXXScopeSpec *SS,
442 bool isAddressOfOperand) {
443 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor17330012009-02-04 15:01:18 +0000444 isAddressOfOperand);
Douglas Gregor10c42622008-11-18 15:03:34 +0000445}
446
Douglas Gregor1a49af92009-01-06 05:10:23 +0000447/// BuildDeclRefExpr - Build either a DeclRefExpr or a
448/// QualifiedDeclRefExpr based on whether or not SS is a
449/// nested-name-specifier.
Anders Carlssone41590d2009-06-24 00:10:43 +0000450Sema::OwningExprResult
Sebastian Redlebc07d52009-02-03 20:19:35 +0000451Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
452 bool TypeDependent, bool ValueDependent,
453 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000454 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
455 Diag(Loc,
456 diag::err_auto_variable_cannot_appear_in_own_initializer)
457 << D->getDeclName();
458 return ExprError();
459 }
Anders Carlssone41590d2009-06-24 00:10:43 +0000460
461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
462 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
463 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
464 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
465 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
466 << D->getIdentifier() << FD->getDeclName();
467 Diag(D->getLocation(), diag::note_local_variable_declared_here)
468 << D->getIdentifier();
469 return ExprError();
470 }
471 }
472 }
473 }
474
Douglas Gregore0762c92009-06-19 23:52:42 +0000475 MarkDeclarationReferenced(Loc, D);
Anders Carlssone41590d2009-06-24 00:10:43 +0000476
477 Expr *E;
Douglas Gregorbad35182009-03-19 03:51:16 +0000478 if (SS && !SS->isEmpty()) {
Anders Carlssone41590d2009-06-24 00:10:43 +0000479 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
480 ValueDependent, SS->getRange(),
Douglas Gregor35073692009-03-26 23:56:24 +0000481 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregorbad35182009-03-19 03:51:16 +0000482 } else
Anders Carlssone41590d2009-06-24 00:10:43 +0000483 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
484
485 return Owned(E);
Douglas Gregor1a49af92009-01-06 05:10:23 +0000486}
487
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000488/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
489/// variable corresponding to the anonymous union or struct whose type
490/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000491static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
492 RecordDecl *Record) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000493 assert(Record->isAnonymousStructOrUnion() &&
494 "Record must be an anonymous struct or union!");
495
Mike Stump390b4cc2009-05-16 07:39:55 +0000496 // FIXME: Once Decls are directly linked together, this will be an O(1)
497 // operation rather than a slow walk through DeclContext's vector (which
498 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000499 DeclContext *Ctx = Record->getDeclContext();
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000500 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
501 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000502 D != DEnd; ++D) {
503 if (*D == Record) {
504 // The object for the anonymous struct/union directly
505 // follows its type in the list of declarations.
506 ++D;
507 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000508 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000509 return *D;
510 }
511 }
512
513 assert(false && "Missing object for anonymous record");
514 return 0;
515}
516
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000517/// \brief Given a field that represents a member of an anonymous
518/// struct/union, build the path from that field's context to the
519/// actual member.
520///
521/// Construct the sequence of field member references we'll have to
522/// perform to get to the field in the anonymous union/struct. The
523/// list of members is built from the field outward, so traverse it
524/// backwards to go from an object in the current context to the field
525/// we found.
526///
527/// \returns The variable from which the field access should begin,
528/// for an anonymous struct/union that is not a member of another
529/// class. Otherwise, returns NULL.
530VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
531 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000532 assert(Field->getDeclContext()->isRecord() &&
533 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
534 && "Field must be stored inside an anonymous struct or union");
535
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000536 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000537 VarDecl *BaseObject = 0;
538 DeclContext *Ctx = Field->getDeclContext();
539 do {
540 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000541 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000542 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000543 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000544 else {
545 BaseObject = cast<VarDecl>(AnonObject);
546 break;
547 }
548 Ctx = Ctx->getParent();
549 } while (Ctx->isRecord() &&
550 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000551
552 return BaseObject;
553}
554
555Sema::OwningExprResult
556Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
557 FieldDecl *Field,
558 Expr *BaseObjectExpr,
559 SourceLocation OpLoc) {
560 llvm::SmallVector<FieldDecl *, 4> AnonFields;
561 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
562 AnonFields);
563
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000564 // Build the expression that refers to the base object, from
565 // which we will build a sequence of member references to each
566 // of the anonymous union objects and, eventually, the field we
567 // found via name lookup.
568 bool BaseObjectIsPointer = false;
569 unsigned ExtraQuals = 0;
570 if (BaseObject) {
571 // BaseObject is an anonymous struct/union variable (and is,
572 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000573 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000574 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000575 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000576 SourceLocation());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000577 ExtraQuals
578 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
579 } else if (BaseObjectExpr) {
580 // The caller provided the base object expression. Determine
581 // whether its a pointer and whether it adds any qualifiers to the
582 // anonymous struct/union fields we're looking into.
583 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000584 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000585 BaseObjectIsPointer = true;
586 ObjectType = ObjectPtr->getPointeeType();
587 }
588 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
589 } else {
590 // We've found a member of an anonymous struct/union that is
591 // inside a non-anonymous struct/union, so in a well-formed
592 // program our base object expression is "this".
593 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
594 if (!MD->isStatic()) {
595 QualType AnonFieldType
596 = Context.getTagDeclType(
597 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
598 QualType ThisType = Context.getTagDeclType(MD->getParent());
599 if ((Context.getCanonicalType(AnonFieldType)
600 == Context.getCanonicalType(ThisType)) ||
601 IsDerivedFrom(ThisType, AnonFieldType)) {
602 // Our base object expression is "this".
Steve Naroff6ece14c2009-01-21 00:14:39 +0000603 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000604 MD->getThisType(Context));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000605 BaseObjectIsPointer = true;
606 }
607 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000608 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
609 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000610 }
611 ExtraQuals = MD->getTypeQualifiers();
612 }
613
614 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000615 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
616 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000617 }
618
619 // Build the implicit member references to the field of the
620 // anonymous struct/union.
621 Expr *Result = BaseObjectExpr;
Mon P Wangc6a38a42009-07-22 03:08:17 +0000622 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000623 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
624 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
625 FI != FIEnd; ++FI) {
626 QualType MemberType = (*FI)->getType();
627 if (!(*FI)->isMutable()) {
628 unsigned combinedQualifiers
629 = MemberType.getCVRQualifiers() | ExtraQuals;
630 MemberType = MemberType.getQualifiedType(combinedQualifiers);
631 }
Mon P Wangc6a38a42009-07-22 03:08:17 +0000632 if (BaseAddrSpace != MemberType.getAddressSpace())
633 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregore0762c92009-06-19 23:52:42 +0000634 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000635 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000636 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
637 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000638 BaseObjectIsPointer = false;
639 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000640 }
641
Sebastian Redlcd965b92009-01-18 18:53:16 +0000642 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000643}
644
Douglas Gregor10c42622008-11-18 15:03:34 +0000645/// ActOnDeclarationNameExpr - The parser has read some kind of name
646/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
647/// performs lookup on that name and returns an expression that refers
648/// to that name. This routine isn't directly called from the parser,
649/// because the parser doesn't know about DeclarationName. Rather,
650/// this routine is called by ActOnIdentifierExpr,
651/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
652/// which form the DeclarationName from the corresponding syntactic
653/// forms.
654///
655/// HasTrailingLParen indicates whether this identifier is used in a
656/// function call context. LookupCtx is only used for a C++
657/// qualified-id (foo::bar) to indicate the class or namespace that
658/// the identifier must be a member of.
Douglas Gregor5c37de72008-12-06 00:22:45 +0000659///
Sebastian Redlebc07d52009-02-03 20:19:35 +0000660/// isAddressOfOperand means that this expression is the direct operand
661/// of an address-of operator. This matters because this is the only
662/// situation where a qualified name referencing a non-static member may
663/// appear outside a member function of this class.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000664Sema::OwningExprResult
665Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
666 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor17330012009-02-04 15:01:18 +0000667 const CXXScopeSpec *SS,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000668 bool isAddressOfOperand) {
Chris Lattner8a934232008-03-31 00:36:02 +0000669 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000670 if (SS && SS->isInvalid())
671 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000672
673 // C++ [temp.dep.expr]p3:
674 // An id-expression is type-dependent if it contains:
675 // -- a nested-name-specifier that contains a class-name that
676 // names a dependent type.
Douglas Gregor00c44862009-05-29 14:49:33 +0000677 // FIXME: Member of the current instantiation.
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000678 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregorab452ba2009-03-26 23:50:42 +0000679 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
680 Loc, SS->getRange(),
Anders Carlsson9b31df42009-07-09 00:05:08 +0000681 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
682 isAddressOfOperand));
Douglas Gregor5953d8b2009-03-19 17:26:29 +0000683 }
684
Douglas Gregor3e41d602009-02-13 23:20:09 +0000685 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
686 false, true, Loc);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000687
Sebastian Redlcd965b92009-01-18 18:53:16 +0000688 if (Lookup.isAmbiguous()) {
689 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
690 SS && SS->isSet() ? SS->getRange()
691 : SourceRange());
692 return ExprError();
Chris Lattner5cb10d32009-04-24 22:30:50 +0000693 }
694
695 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregor5c37de72008-12-06 00:22:45 +0000696
Chris Lattner8a934232008-03-31 00:36:02 +0000697 // If this reference is in an Objective-C method, then ivar lookup happens as
698 // well.
Douglas Gregor10c42622008-11-18 15:03:34 +0000699 IdentifierInfo *II = Name.getAsIdentifierInfo();
700 if (II && getCurMethodDecl()) {
Chris Lattner8a934232008-03-31 00:36:02 +0000701 // There are two cases to handle here. 1) scoped lookup could have failed,
702 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000703 // found a decl, but that decl is outside the current instance method (i.e.
704 // a global variable). In these two cases, we do a lookup for an ivar with
705 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000706 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000707 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000708 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000709 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner553905d2009-02-16 17:19:12 +0000710 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000711 if (DiagnoseUseOfDecl(IV, Loc))
712 return ExprError();
Chris Lattner5cb10d32009-04-24 22:30:50 +0000713
714 // If we're referencing an invalid decl, just return this as a silent
715 // error node. The error diagnostic was already emitted on the decl.
716 if (IV->isInvalidDecl())
717 return ExprError();
718
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000719 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
720 // If a class method attemps to use a free standing ivar, this is
721 // an error.
722 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
723 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
724 << IV->getDeclName());
725 // If a class method uses a global variable, even if an ivar with
726 // same name exists, use the global.
727 if (!IsClsMethod) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000728 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
729 ClassDeclared != IFace)
730 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stump390b4cc2009-05-16 07:39:55 +0000731 // FIXME: This should use a new expr for a direct reference, don't
732 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000733 IdentifierInfo &II = Context.Idents.get("self");
Argyrios Kyrtzidisecd1bae2009-07-18 08:49:37 +0000734 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
735 II, false);
Douglas Gregore0762c92009-06-19 23:52:42 +0000736 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbar525c9b72009-04-21 01:19:28 +0000737 return Owned(new (Context)
738 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlssone9146f22009-05-01 19:49:17 +0000739 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000740 }
Chris Lattner8a934232008-03-31 00:36:02 +0000741 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000742 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000743 // We should warn if a local variable hides an ivar.
744 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000745 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000746 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000747 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
748 IFace == ClassDeclared)
Chris Lattner5cb10d32009-04-24 22:30:50 +0000749 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahanian935fd762009-03-03 01:21:12 +0000750 }
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000751 }
Steve Naroff76de9d72008-08-10 19:10:41 +0000752 // Needed to implement property "super.method" notation.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000753 if (D == 0 && II->isStr("super")) {
Steve Naroffdd53eb52009-03-05 20:12:00 +0000754 QualType T;
755
756 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff14108da2009-07-10 23:34:53 +0000757 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
758 getCurMethodDecl()->getClassInterface()));
Steve Naroffdd53eb52009-03-05 20:12:00 +0000759 else
760 T = Context.getObjCClassType();
Steve Naroff6ece14c2009-01-21 00:14:39 +0000761 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffe3e9add2008-06-02 23:03:37 +0000762 }
Chris Lattner8a934232008-03-31 00:36:02 +0000763 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000764
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000765 // Determine whether this name might be a candidate for
766 // argument-dependent lookup.
767 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
768 HasTrailingLParen;
769
770 if (ADL && D == 0) {
Douglas Gregorc71e28c2009-02-16 19:28:42 +0000771 // We've seen something of the form
772 //
773 // identifier(
774 //
775 // and we did not find any entity by the name
776 // "identifier". However, this identifier is still subject to
777 // argument-dependent lookup, so keep track of the name.
778 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
779 Context.OverloadTy,
780 Loc));
781 }
782
Reid Spencer5f016e22007-07-11 17:01:13 +0000783 if (D == 0) {
784 // Otherwise, this could be an implicitly declared function reference (legal
785 // in C90, extension in C99).
Douglas Gregor10c42622008-11-18 15:03:34 +0000786 if (HasTrailingLParen && II &&
Chris Lattner8a934232008-03-31 00:36:02 +0000787 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor10c42622008-11-18 15:03:34 +0000788 D = ImplicitlyDefineFunction(Loc, *II, S);
Reid Spencer5f016e22007-07-11 17:01:13 +0000789 else {
790 // If this name wasn't predeclared and if this is not a function call,
791 // diagnose the problem.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000792 if (SS && !SS->isEmpty())
Sebastian Redlcd965b92009-01-18 18:53:16 +0000793 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
794 << Name << SS->getRange());
Douglas Gregor10c42622008-11-18 15:03:34 +0000795 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
796 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000797 return ExprError(Diag(Loc, diag::err_undeclared_use)
798 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000799 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000800 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 }
802 }
Douglas Gregor751f9a42009-06-30 15:47:41 +0000803
804 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
805 // Warn about constructs like:
806 // if (void *X = foo()) { ... } else { X }.
807 // In the else block, the pointer is always false.
808
809 // FIXME: In a template instantiation, we don't have scope
810 // information to check this property.
811 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
812 Scope *CheckS = S;
813 while (CheckS) {
814 if (CheckS->isWithinElse() &&
815 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
816 if (Var->getType()->isBooleanType())
817 ExprError(Diag(Loc, diag::warn_value_always_false)
818 << Var->getDeclName());
819 else
820 ExprError(Diag(Loc, diag::warn_value_always_zero)
821 << Var->getDeclName());
822 break;
823 }
824
825 // Move up one more control parent to check again.
826 CheckS = CheckS->getControlParent();
827 if (CheckS)
828 CheckS = CheckS->getParent();
829 }
830 }
831 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
832 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
833 // C99 DR 316 says that, if a function type comes from a
834 // function definition (without a prototype), that type is only
835 // used for checking compatibility. Therefore, when referencing
836 // the function, we pretend that we don't have the full function
837 // type.
838 if (DiagnoseUseOfDecl(Func, Loc))
839 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000840
Douglas Gregor751f9a42009-06-30 15:47:41 +0000841 QualType T = Func->getType();
842 QualType NoProtoType = T;
843 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
844 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
845 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
846 }
847 }
848
849 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
850}
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000851/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000852bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000853Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
854 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
855 if (CXXRecordDecl *RD =
856 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
857 QualType DestType =
858 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000859 if (DestType->isDependentType() || From->getType()->isDependentType())
860 return false;
861 QualType FromRecordType = From->getType();
862 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +0000863 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000864 DestType = Context.getPointerType(DestType);
865 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000866 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000867 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
868 CheckDerivedToBaseConversion(FromRecordType,
869 DestRecordType,
870 From->getSourceRange().getBegin(),
871 From->getSourceRange()))
872 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +0000873 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
874 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000875 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000876 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000877}
Douglas Gregor751f9a42009-06-30 15:47:41 +0000878
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000879/// \brief Build a MemberExpr or CXXQualifiedMemberExpr, as appropriate.
880static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
881 const CXXScopeSpec *SS, NamedDecl *Member,
882 SourceLocation Loc, QualType Ty) {
883 if (SS && SS->isSet())
884 return new (C) CXXQualifiedMemberExpr(Base, isArrow,
885 (NestedNameSpecifier *)SS->getScopeRep(),
886 SS->getRange(),
887 Member, Loc, Ty);
888
889 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
890}
891
Douglas Gregor751f9a42009-06-30 15:47:41 +0000892/// \brief Complete semantic analysis for a reference to the given declaration.
893Sema::OwningExprResult
894Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
895 bool HasTrailingLParen,
896 const CXXScopeSpec *SS,
897 bool isAddressOfOperand) {
898 assert(D && "Cannot refer to a NULL declaration");
899 DeclarationName Name = D->getDeclName();
900
Sebastian Redlebc07d52009-02-03 20:19:35 +0000901 // If this is an expression of the form &Class::member, don't build an
902 // implicit member ref, because we want a pointer to the member in general,
903 // not any specific instance's member.
904 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000905 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000906 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000907 QualType DType;
908 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
909 DType = FD->getType().getNonReferenceType();
910 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
911 DType = Method->getType();
912 } else if (isa<OverloadedFunctionDecl>(D)) {
913 DType = Context.OverloadTy;
914 }
915 // Could be an inner type. That's diagnosed below, so ignore it here.
916 if (!DType.isNull()) {
917 // The pointer is type- and value-dependent if it points into something
918 // dependent.
Douglas Gregor00c44862009-05-29 14:49:33 +0000919 bool Dependent = DC->isDependentContext();
Anders Carlssone41590d2009-06-24 00:10:43 +0000920 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redlebc07d52009-02-03 20:19:35 +0000921 }
922 }
923 }
924
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000925 // We may have found a field within an anonymous union or struct
926 // (C++ [class.union]).
927 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
928 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
929 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000930
Douglas Gregor88a35142008-12-22 05:46:06 +0000931 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
932 if (!MD->isStatic()) {
933 // C++ [class.mfct.nonstatic]p2:
934 // [...] if name lookup (3.4.1) resolves the name in the
935 // id-expression to a nonstatic nontype member of class X or of
936 // a base class of X, the id-expression is transformed into a
937 // class member access expression (5.2.5) using (*this) (9.3.2)
938 // as the postfix-expression to the left of the '.' operator.
939 DeclContext *Ctx = 0;
940 QualType MemberType;
941 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
942 Ctx = FD->getDeclContext();
943 MemberType = FD->getType();
944
Ted Kremenek6217b802009-07-29 21:53:49 +0000945 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor88a35142008-12-22 05:46:06 +0000946 MemberType = RefType->getPointeeType();
947 else if (!FD->isMutable()) {
948 unsigned combinedQualifiers
949 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
950 MemberType = MemberType.getQualifiedType(combinedQualifiers);
951 }
952 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
953 if (!Method->isStatic()) {
954 Ctx = Method->getParent();
955 MemberType = Method->getType();
956 }
Douglas Gregor6b906862009-08-21 00:16:32 +0000957 } else if (FunctionTemplateDecl *FunTmpl
958 = dyn_cast<FunctionTemplateDecl>(D)) {
959 if (CXXMethodDecl *Method
960 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
961 if (!Method->isStatic()) {
962 Ctx = Method->getParent();
963 MemberType = Context.OverloadTy;
964 }
965 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000966 } else if (OverloadedFunctionDecl *Ovl
967 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000968 // FIXME: We need an abstraction for iterating over one or more function
969 // templates or functions. This code is far too repetitive!
Douglas Gregor88a35142008-12-22 05:46:06 +0000970 for (OverloadedFunctionDecl::function_iterator
971 Func = Ovl->function_begin(),
972 FuncEnd = Ovl->function_end();
973 Func != FuncEnd; ++Func) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000974 CXXMethodDecl *DMethod = 0;
975 if (FunctionTemplateDecl *FunTmpl
976 = dyn_cast<FunctionTemplateDecl>(*Func))
977 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
978 else
979 DMethod = dyn_cast<CXXMethodDecl>(*Func);
980
981 if (DMethod && !DMethod->isStatic()) {
982 Ctx = DMethod->getDeclContext();
983 MemberType = Context.OverloadTy;
984 break;
985 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000986 }
987 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000988
989 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000990 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
991 QualType ThisType = Context.getTagDeclType(MD->getParent());
992 if ((Context.getCanonicalType(CtxType)
993 == Context.getCanonicalType(ThisType)) ||
994 IsDerivedFrom(ThisType, CtxType)) {
995 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +0000996 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000997 MD->getThisType(Context));
Douglas Gregore0762c92009-06-19 23:52:42 +0000998 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000999 if (PerformObjectMemberConversion(This, D))
1000 return ExprError();
Anders Carlsson0f44b5a2009-08-08 16:55:18 +00001001 if (DiagnoseUseOfDecl(D, Loc))
1002 return ExprError();
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001003 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1004 Loc, MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +00001005 }
1006 }
1007 }
1008 }
1009
Douglas Gregor44b43212008-12-11 16:49:14 +00001010 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001011 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1012 if (MD->isStatic())
1013 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +00001014 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1015 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001016 }
1017
Douglas Gregor88a35142008-12-22 05:46:06 +00001018 // Any other ways we could have found the field in a well-formed
1019 // program would have been turned into implicit member expressions
1020 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001021 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1022 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001023 }
Douglas Gregor88a35142008-12-22 05:46:06 +00001024
Reid Spencer5f016e22007-07-11 17:01:13 +00001025 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001026 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001027 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001028 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001029 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001030 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00001031
Steve Naroffdd972f22008-09-05 22:11:13 +00001032 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001033 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlssone41590d2009-06-24 00:10:43 +00001034 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1035 false, false, SS);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001036 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlssone41590d2009-06-24 00:10:43 +00001037 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1038 false, false, SS);
Anders Carlsson598da5b2009-08-29 01:06:32 +00001039 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
1040 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1041 /*TypeDependent=*/true,
1042 /*ValueDependent=*/true, SS);
1043
Steve Naroffdd972f22008-09-05 22:11:13 +00001044 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001045
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001046 // Check whether this declaration can be used. Note that we suppress
1047 // this check when we're going to perform argument-dependent lookup
1048 // on this function name, because this might not be the function
1049 // that overload resolution actually selects.
Douglas Gregor751f9a42009-06-30 15:47:41 +00001050 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1051 HasTrailingLParen;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001052 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1053 return ExprError();
1054
Steve Naroffdd972f22008-09-05 22:11:13 +00001055 // Only create DeclRefExpr's for valid Decl's.
1056 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001057 return ExprError();
1058
Chris Lattner639e2d32008-10-20 05:16:36 +00001059 // If the identifier reference is inside a block, and it refers to a value
1060 // that is outside the block, create a BlockDeclRefExpr instead of a
1061 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1062 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001063 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001064 // We do not do this for things like enum constants, global variables, etc,
1065 // as they do not get snapshotted.
1066 //
1067 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001068 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001069 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001070 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001071 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001072 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001073 // This is to record that a 'const' was actually synthesize and added.
1074 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001075 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001076
Eli Friedman5fdeae12009-03-22 23:00:19 +00001077 ExprTy.addConst();
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001078 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1079 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001080 }
1081 // If this reference is not in a block or if the referenced variable is
1082 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001083
Douglas Gregor898574e2008-12-05 23:32:09 +00001084 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +00001085 bool ValueDependent = false;
1086 if (getLangOptions().CPlusPlus) {
1087 // C++ [temp.dep.expr]p3:
1088 // An id-expression is type-dependent if it contains:
1089 // - an identifier that was declared with a dependent type,
1090 if (VD->getType()->isDependentType())
1091 TypeDependent = true;
1092 // - FIXME: a template-id that is dependent,
1093 // - a conversion-function-id that specifies a dependent type,
1094 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1095 Name.getCXXNameType()->isDependentType())
1096 TypeDependent = true;
1097 // - a nested-name-specifier that contains a class-name that
1098 // names a dependent type.
1099 else if (SS && !SS->isEmpty()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001100 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor83f96f62008-12-10 20:57:37 +00001101 DC; DC = DC->getParent()) {
1102 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001103 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +00001104 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1105 if (Context.getTypeDeclType(Record)->isDependentType()) {
1106 TypeDependent = true;
1107 break;
1108 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001109 }
1110 }
1111 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001112
Douglas Gregor83f96f62008-12-10 20:57:37 +00001113 // C++ [temp.dep.constexpr]p2:
1114 //
1115 // An identifier is value-dependent if it is:
1116 // - a name declared with a dependent type,
1117 if (TypeDependent)
1118 ValueDependent = true;
1119 // - the name of a non-type template parameter,
1120 else if (isa<NonTypeTemplateParmDecl>(VD))
1121 ValueDependent = true;
1122 // - a constant with integral or enumeration type and is
1123 // initialized with an expression that is value-dependent
Eli Friedmanc1494122009-06-11 01:11:20 +00001124 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1125 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1126 Dcl->getInit()) {
1127 ValueDependent = Dcl->getInit()->isValueDependent();
1128 }
1129 }
Douglas Gregor83f96f62008-12-10 20:57:37 +00001130 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001131
Anders Carlssone41590d2009-06-24 00:10:43 +00001132 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1133 TypeDependent, ValueDependent, SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001134}
1135
Sebastian Redlcd965b92009-01-18 18:53:16 +00001136Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1137 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001138 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001139
Reid Spencer5f016e22007-07-11 17:01:13 +00001140 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001141 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001142 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1143 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1144 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001145 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001146
Chris Lattnerfa28b302008-01-12 08:14:25 +00001147 // Pre-defined identifiers are of type char[x], where x is the length of the
1148 // string.
Chris Lattner8f978d52008-01-12 19:32:28 +00001149 unsigned Length;
Chris Lattner371f2582008-12-04 23:50:19 +00001150 if (FunctionDecl *FD = getCurFunctionDecl())
1151 Length = FD->getIdentifier()->getLength();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001152 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1153 Length = MD->getSynthesizedMethodSize();
1154 else {
1155 Diag(Loc, diag::ext_predef_outside_function);
1156 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1157 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1158 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001159
1160
Chris Lattner8f978d52008-01-12 19:32:28 +00001161 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +00001162 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +00001163 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +00001164 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001165}
1166
Sebastian Redlcd965b92009-01-18 18:53:16 +00001167Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001168 llvm::SmallString<16> CharBuffer;
1169 CharBuffer.resize(Tok.getLength());
1170 const char *ThisTokBegin = &CharBuffer[0];
1171 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001172
Reid Spencer5f016e22007-07-11 17:01:13 +00001173 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1174 Tok.getLocation(), PP);
1175 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001176 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001177
1178 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1179
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001180 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1181 Literal.isWide(),
1182 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001183}
1184
Sebastian Redlcd965b92009-01-18 18:53:16 +00001185Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1186 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001187 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1188 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001189 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001190 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001191 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001192 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001193 }
Ted Kremenek28396602009-01-13 23:19:12 +00001194
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001196 // Add padding so that NumericLiteralParser can overread by one character.
1197 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001198 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001199
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 // Get the spelling of the token, which eliminates trigraphs, etc.
1201 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001202
Reid Spencer5f016e22007-07-11 17:01:13 +00001203 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1204 Tok.getLocation(), PP);
1205 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001206 return ExprError();
1207
Chris Lattner5d661452007-08-26 03:42:43 +00001208 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001209
Chris Lattner5d661452007-08-26 03:42:43 +00001210 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001211 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001212 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001213 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001214 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001215 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001216 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001217 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001218
1219 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1220
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001221 // isExact will be set by GetFloatValue().
1222 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001223 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1224 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001225
Chris Lattner5d661452007-08-26 03:42:43 +00001226 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001227 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001228 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001229 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001230
Neil Boothb9449512007-08-29 22:00:19 +00001231 // long long is a C99 feature.
1232 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001233 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001234 Diag(Tok.getLocation(), diag::ext_longlong);
1235
Reid Spencer5f016e22007-07-11 17:01:13 +00001236 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001237 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001238
Reid Spencer5f016e22007-07-11 17:01:13 +00001239 if (Literal.GetIntegerValue(ResultVal)) {
1240 // If this value didn't fit into uintmax_t, warn and force to ull.
1241 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001242 Ty = Context.UnsignedLongLongTy;
1243 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001244 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001245 } else {
1246 // If this value fits into a ULL, try to figure out what else it fits into
1247 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001248
Reid Spencer5f016e22007-07-11 17:01:13 +00001249 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1250 // be an unsigned int.
1251 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1252
1253 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001254 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001255 if (!Literal.isLong && !Literal.isLongLong) {
1256 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001257 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001258
Reid Spencer5f016e22007-07-11 17:01:13 +00001259 // Does it fit in a unsigned int?
1260 if (ResultVal.isIntN(IntSize)) {
1261 // Does it fit in a signed int?
1262 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001263 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001264 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001265 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001266 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001267 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001268 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001269
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001271 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001272 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001273
Reid Spencer5f016e22007-07-11 17:01:13 +00001274 // Does it fit in a unsigned long?
1275 if (ResultVal.isIntN(LongSize)) {
1276 // Does it fit in a signed long?
1277 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001278 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001279 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001280 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001281 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001282 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001283 }
1284
Reid Spencer5f016e22007-07-11 17:01:13 +00001285 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001286 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001287 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001288
Reid Spencer5f016e22007-07-11 17:01:13 +00001289 // Does it fit in a unsigned long long?
1290 if (ResultVal.isIntN(LongLongSize)) {
1291 // Does it fit in a signed long long?
1292 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001293 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001294 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001295 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001296 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001297 }
1298 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001299
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 // If we still couldn't decide a type, we probably have something that
1301 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001302 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001303 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001304 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001305 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001306 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001307
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001308 if (ResultVal.getBitWidth() != Width)
1309 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001310 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001311 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001313
Chris Lattner5d661452007-08-26 03:42:43 +00001314 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1315 if (Literal.isImaginary)
Steve Naroff6ece14c2009-01-21 00:14:39 +00001316 Res = new (Context) ImaginaryLiteral(Res,
1317 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001318
1319 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001320}
1321
Sebastian Redlcd965b92009-01-18 18:53:16 +00001322Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1323 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001324 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001325 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001326 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001327}
1328
1329/// The UsualUnaryConversions() function is *not* called by this routine.
1330/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001331bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001332 SourceLocation OpLoc,
1333 const SourceRange &ExprRange,
1334 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001335 if (exprType->isDependentType())
1336 return false;
1337
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001339 if (isa<FunctionType>(exprType)) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001340 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001341 if (isSizeof)
1342 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1343 return false;
1344 }
1345
Chris Lattner1efaa952009-04-24 00:30:45 +00001346 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001347 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001348 Diag(OpLoc, diag::ext_sizeof_void_type)
1349 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001350 return false;
1351 }
Chris Lattnerca790922009-04-21 19:55:16 +00001352
Chris Lattner1efaa952009-04-24 00:30:45 +00001353 if (RequireCompleteType(OpLoc, exprType,
1354 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001355 PDiag(diag::err_alignof_incomplete_type)
1356 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001357 return true;
1358
1359 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001360 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001361 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001362 << exprType << isSizeof << ExprRange;
1363 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001364 }
1365
Chris Lattner1efaa952009-04-24 00:30:45 +00001366 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001367}
1368
Chris Lattner31e21e02009-01-24 20:17:12 +00001369bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1370 const SourceRange &ExprRange) {
1371 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001372
Chris Lattner31e21e02009-01-24 20:17:12 +00001373 // alignof decl is always ok.
1374 if (isa<DeclRefExpr>(E))
1375 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001376
1377 // Cannot know anything else if the expression is dependent.
1378 if (E->isTypeDependent())
1379 return false;
1380
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001381 if (E->getBitField()) {
1382 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1383 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001384 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001385
1386 // Alignment of a field access is always okay, so long as it isn't a
1387 // bit-field.
1388 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001389 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001390 return false;
1391
Chris Lattner31e21e02009-01-24 20:17:12 +00001392 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1393}
1394
Douglas Gregorba498172009-03-13 21:01:28 +00001395/// \brief Build a sizeof or alignof expression given a type operand.
1396Action::OwningExprResult
1397Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1398 bool isSizeOf, SourceRange R) {
1399 if (T.isNull())
1400 return ExprError();
1401
1402 if (!T->isDependentType() &&
1403 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1404 return ExprError();
1405
1406 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1407 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1408 Context.getSizeType(), OpLoc,
1409 R.getEnd()));
1410}
1411
1412/// \brief Build a sizeof or alignof expression given an expression
1413/// operand.
1414Action::OwningExprResult
1415Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1416 bool isSizeOf, SourceRange R) {
1417 // Verify that the operand is valid.
1418 bool isInvalid = false;
1419 if (E->isTypeDependent()) {
1420 // Delay type-checking for type-dependent expressions.
1421 } else if (!isSizeOf) {
1422 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001423 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001424 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1425 isInvalid = true;
1426 } else {
1427 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1428 }
1429
1430 if (isInvalid)
1431 return ExprError();
1432
1433 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1434 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1435 Context.getSizeType(), OpLoc,
1436 R.getEnd()));
1437}
1438
Sebastian Redl05189992008-11-11 17:56:53 +00001439/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1440/// the same for @c alignof and @c __alignof
1441/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001442Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001443Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1444 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001445 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001446 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001447
Sebastian Redl05189992008-11-11 17:56:53 +00001448 if (isType) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001449 // FIXME: Preserve type source info.
1450 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregorba498172009-03-13 21:01:28 +00001451 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1452 }
Sebastian Redl05189992008-11-11 17:56:53 +00001453
Douglas Gregorba498172009-03-13 21:01:28 +00001454 // Get the end location.
1455 Expr *ArgEx = (Expr *)TyOrEx;
1456 Action::OwningExprResult Result
1457 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1458
1459 if (Result.isInvalid())
1460 DeleteExpr(ArgEx);
1461
1462 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001463}
1464
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001465QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001466 if (V->isTypeDependent())
1467 return Context.DependentTy;
Chris Lattnerdbb36972007-08-24 21:16:53 +00001468
Chris Lattnercc26ed72007-08-26 05:39:26 +00001469 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001470 if (const ComplexType *CT = V->getType()->getAsComplexType())
1471 return CT->getElementType();
Chris Lattnercc26ed72007-08-26 05:39:26 +00001472
1473 // Otherwise they pass through real integer and floating point types here.
1474 if (V->getType()->isArithmeticType())
1475 return V->getType();
1476
1477 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001478 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1479 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001480 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001481}
1482
1483
Reid Spencer5f016e22007-07-11 17:01:13 +00001484
Sebastian Redl0eb23302009-01-19 00:08:26 +00001485Action::OwningExprResult
1486Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1487 tok::TokenKind Kind, ExprArg Input) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001488 // Since this might be a postfix expression, get rid of ParenListExprs.
1489 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001490 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001491
Reid Spencer5f016e22007-07-11 17:01:13 +00001492 UnaryOperator::Opcode Opc;
1493 switch (Kind) {
1494 default: assert(0 && "Unknown unary op!");
1495 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1496 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1497 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001498
Douglas Gregor74253732008-11-19 15:42:04 +00001499 if (getLangOptions().CPlusPlus &&
1500 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1501 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001502 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001503 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1504
1505 // C++ [over.inc]p1:
1506 //
1507 // [...] If the function is a member function with one
1508 // parameter (which shall be of type int) or a non-member
1509 // function with two parameters (the second of which shall be
1510 // of type int), it defines the postfix increment operator ++
1511 // for objects of that type. When the postfix increment is
1512 // called as a result of using the ++ operator, the int
1513 // argument will have value zero.
1514 Expr *Args[2] = {
1515 Arg,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001516 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1517 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001518 };
1519
1520 // Build the candidate set for overloading
1521 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00001522 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor74253732008-11-19 15:42:04 +00001523
1524 // Perform overload resolution.
1525 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001526 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor74253732008-11-19 15:42:04 +00001527 case OR_Success: {
1528 // We found a built-in operator or an overloaded operator.
1529 FunctionDecl *FnDecl = Best->Function;
1530
1531 if (FnDecl) {
1532 // We matched an overloaded operator. Build a call to that
1533 // operator.
1534
1535 // Convert the arguments.
1536 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1537 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001538 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001539 } else {
1540 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001541 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001542 FnDecl->getParamDecl(0)->getType(),
1543 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001544 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001545 }
1546
1547 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001548 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001549 = FnDecl->getType()->getAsFunctionType()->getResultType();
1550 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001551
Douglas Gregor74253732008-11-19 15:42:04 +00001552 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001553 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump488e25b2009-02-19 02:54:59 +00001554 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00001555 UsualUnaryConversions(FnExpr);
1556
Sebastian Redl0eb23302009-01-19 00:08:26 +00001557 Input.release();
Douglas Gregor7ff69262009-05-27 05:00:47 +00001558 Args[0] = Arg;
Douglas Gregor063daf62009-03-13 18:40:31 +00001559 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1560 Args, 2, ResultTy,
1561 OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001562 } else {
1563 // We matched a built-in operator. Convert the arguments, then
1564 // break out so that we will build the appropriate built-in
1565 // operator node.
1566 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1567 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001568 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001569
1570 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001571 }
Douglas Gregor74253732008-11-19 15:42:04 +00001572 }
1573
1574 case OR_No_Viable_Function:
1575 // No viable function; fall through to handling this as a
1576 // built-in operator, which will produce an error message for us.
1577 break;
1578
1579 case OR_Ambiguous:
1580 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1581 << UnaryOperator::getOpcodeStr(Opc)
1582 << Arg->getSourceRange();
1583 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001584 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001585
1586 case OR_Deleted:
1587 Diag(OpLoc, diag::err_ovl_deleted_oper)
1588 << Best->Function->isDeleted()
1589 << UnaryOperator::getOpcodeStr(Opc)
1590 << Arg->getSourceRange();
1591 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1592 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001593 }
1594
1595 // Either we found no viable overloaded operator or we matched a
1596 // built-in operator. In either case, fall through to trying to
1597 // build a built-in operation.
1598 }
1599
Eli Friedman6016cb22009-07-22 23:24:42 +00001600 Input.release();
1601 Input = Arg;
Eli Friedmande99a452009-07-22 22:25:00 +00001602 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001603}
1604
Sebastian Redl0eb23302009-01-19 00:08:26 +00001605Action::OwningExprResult
1606Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1607 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001608 // Since this might be a postfix expression, get rid of ParenListExprs.
1609 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1610
Sebastian Redl0eb23302009-01-19 00:08:26 +00001611 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1612 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begeman2ef13e52009-08-10 23:49:36 +00001613
Douglas Gregor337c6b92008-11-19 17:17:41 +00001614 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001615 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1616 Base.release();
1617 Idx.release();
1618 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1619 Context.DependentTy, RLoc));
1620 }
1621
1622 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001623 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001624 LHSExp->getType()->isEnumeralType() ||
1625 RHSExp->getType()->isRecordType() ||
1626 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001627 // Add the appropriate overloaded operators (C++ [over.match.oper])
1628 // to the candidate set.
1629 OverloadCandidateSet CandidateSet;
1630 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor063daf62009-03-13 18:40:31 +00001631 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1632 SourceRange(LLoc, RLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001633
Douglas Gregor337c6b92008-11-19 17:17:41 +00001634 // Perform overload resolution.
1635 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001636 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001637 case OR_Success: {
1638 // We found a built-in operator or an overloaded operator.
1639 FunctionDecl *FnDecl = Best->Function;
1640
1641 if (FnDecl) {
1642 // We matched an overloaded operator. Build a call to that
1643 // operator.
1644
1645 // Convert the arguments.
1646 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1647 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1648 PerformCopyInitialization(RHSExp,
1649 FnDecl->getParamDecl(0)->getType(),
1650 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001651 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001652 } else {
1653 // Convert the arguments.
1654 if (PerformCopyInitialization(LHSExp,
1655 FnDecl->getParamDecl(0)->getType(),
1656 "passing") ||
1657 PerformCopyInitialization(RHSExp,
1658 FnDecl->getParamDecl(1)->getType(),
1659 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001660 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001661 }
1662
1663 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001664 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001665 = FnDecl->getType()->getAsFunctionType()->getResultType();
1666 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001667
Douglas Gregor337c6b92008-11-19 17:17:41 +00001668 // Build the actual expression node.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001669 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1670 SourceLocation());
Douglas Gregor337c6b92008-11-19 17:17:41 +00001671 UsualUnaryConversions(FnExpr);
1672
Sebastian Redl0eb23302009-01-19 00:08:26 +00001673 Base.release();
1674 Idx.release();
Douglas Gregor7ff69262009-05-27 05:00:47 +00001675 Args[0] = LHSExp;
1676 Args[1] = RHSExp;
Douglas Gregor063daf62009-03-13 18:40:31 +00001677 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1678 FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001679 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001680 } else {
1681 // We matched a built-in operator. Convert the arguments, then
1682 // break out so that we will build the appropriate built-in
1683 // operator node.
1684 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1685 "passing") ||
1686 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1687 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001688 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001689
1690 break;
1691 }
1692 }
1693
1694 case OR_No_Viable_Function:
1695 // No viable function; fall through to handling this as a
1696 // built-in operator, which will produce an error message for us.
1697 break;
1698
1699 case OR_Ambiguous:
1700 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1701 << "[]"
1702 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1703 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001704 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001705
1706 case OR_Deleted:
1707 Diag(LLoc, diag::err_ovl_deleted_oper)
1708 << Best->Function->isDeleted()
1709 << "[]"
1710 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1711 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1712 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001713 }
1714
1715 // Either we found no viable overloaded operator or we matched a
1716 // built-in operator. In either case, fall through to trying to
1717 // build a built-in operation.
1718 }
1719
Chris Lattner12d9ff62007-07-16 00:14:47 +00001720 // Perform default conversions.
1721 DefaultFunctionArrayConversion(LHSExp);
1722 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001723
Chris Lattner12d9ff62007-07-16 00:14:47 +00001724 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001725
Reid Spencer5f016e22007-07-11 17:01:13 +00001726 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001727 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001728 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001730 Expr *BaseExpr, *IndexExpr;
1731 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001732 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1733 BaseExpr = LHSExp;
1734 IndexExpr = RHSExp;
1735 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001736 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001737 BaseExpr = LHSExp;
1738 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001739 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001740 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001741 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001742 BaseExpr = RHSExp;
1743 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001744 ResultType = PTy->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00001745 } else if (const ObjCObjectPointerType *PTy =
1746 LHSTy->getAsObjCObjectPointerType()) {
1747 BaseExpr = LHSExp;
1748 IndexExpr = RHSExp;
1749 ResultType = PTy->getPointeeType();
1750 } else if (const ObjCObjectPointerType *PTy =
1751 RHSTy->getAsObjCObjectPointerType()) {
1752 // Handle the uncommon case of "123[Ptr]".
1753 BaseExpr = RHSExp;
1754 IndexExpr = LHSExp;
1755 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001756 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1757 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001758 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001759
Chris Lattner12d9ff62007-07-16 00:14:47 +00001760 // FIXME: need to deal with const...
1761 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001762 } else if (LHSTy->isArrayType()) {
1763 // If we see an array that wasn't promoted by
1764 // DefaultFunctionArrayConversion, it must be an array that
1765 // wasn't promoted because of the C90 rule that doesn't
1766 // allow promoting non-lvalue arrays. Warn, then
1767 // force the promotion here.
1768 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1769 LHSExp->getSourceRange();
1770 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1771 LHSTy = LHSExp->getType();
1772
1773 BaseExpr = LHSExp;
1774 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001775 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001776 } else if (RHSTy->isArrayType()) {
1777 // Same as previous, except for 123[f().a] case
1778 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1779 RHSExp->getSourceRange();
1780 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1781 RHSTy = RHSExp->getType();
1782
1783 BaseExpr = RHSExp;
1784 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001785 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001786 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001787 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1788 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001789 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001790 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001791 if (!(IndexExpr->getType()->isIntegerType() &&
1792 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001793 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1794 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001795
Douglas Gregore7450f52009-03-24 19:52:54 +00001796 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1797 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1798 // type. Note that Functions are not objects, and that (in C99 parlance)
1799 // incomplete types are not object types.
1800 if (ResultType->isFunctionType()) {
1801 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1802 << ResultType << BaseExpr->getSourceRange();
1803 return ExprError();
1804 }
Chris Lattner1efaa952009-04-24 00:30:45 +00001805
Douglas Gregore7450f52009-03-24 19:52:54 +00001806 if (!ResultType->isDependentType() &&
Anders Carlssonb7906612009-08-26 23:45:07 +00001807 RequireCompleteType(LLoc, ResultType,
1808 PDiag(diag::err_subscript_incomplete_type)
1809 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001810 return ExprError();
Chris Lattner1efaa952009-04-24 00:30:45 +00001811
1812 // Diagnose bad cases where we step over interface counts.
1813 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1814 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1815 << ResultType << BaseExpr->getSourceRange();
1816 return ExprError();
1817 }
1818
Sebastian Redl0eb23302009-01-19 00:08:26 +00001819 Base.release();
1820 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001821 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001822 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001823}
1824
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001825QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001826CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001827 const IdentifierInfo *CompName,
1828 SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001829 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001830
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001831 // The vector accessor can't exceed the number of elements.
Anders Carlsson8f28f992009-08-26 18:25:21 +00001832 const char *compStr = CompName->getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001833
Mike Stumpeed9cac2009-02-19 03:04:26 +00001834 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001835 // special names that indicate a subset of exactly half the elements are
1836 // to be selected.
1837 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001838
Nate Begeman353417a2009-01-18 01:47:54 +00001839 // This flag determines whether or not CompName has an 's' char prefix,
1840 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001841 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001842
1843 // Check that we've found one of the special components, or that the component
1844 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001845 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001846 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1847 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001848 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001849 do
1850 compStr++;
1851 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001852 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001853 do
1854 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001855 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001856 }
Nate Begeman353417a2009-01-18 01:47:54 +00001857
Mike Stumpeed9cac2009-02-19 03:04:26 +00001858 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001859 // We didn't get to the end of the string. This means the component names
1860 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001861 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1862 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001863 return QualType();
1864 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001865
Nate Begeman353417a2009-01-18 01:47:54 +00001866 // Ensure no component accessor exceeds the width of the vector type it
1867 // operates on.
1868 if (!HalvingSwizzle) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001869 compStr = CompName->getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001870
1871 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001872 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001873
1874 while (*compStr) {
1875 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1876 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1877 << baseType << SourceRange(CompLoc);
1878 return QualType();
1879 }
1880 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001881 }
Nate Begeman8a997642008-05-09 06:41:27 +00001882
Nate Begeman353417a2009-01-18 01:47:54 +00001883 // If this is a halving swizzle, verify that the base type has an even
1884 // number of elements.
1885 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001886 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001887 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001888 return QualType();
1889 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001890
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001891 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001892 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001893 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001894 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001895 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001896 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00001897 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00001898 if (HexSwizzle)
1899 CompSize--;
1900
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001901 if (CompSize == 1)
1902 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001903
Nate Begeman213541a2008-04-18 23:10:10 +00001904 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001905 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001906 // diagostics look bad. We want extended vector types to appear built-in.
1907 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1908 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1909 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001910 }
1911 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001912}
1913
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001914static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001915 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001916 const Selector &Sel,
1917 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001918
Anders Carlsson8f28f992009-08-26 18:25:21 +00001919 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001920 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001921 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001922 return OMD;
1923
1924 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1925 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregor6ab35242009-04-09 21:40:53 +00001926 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1927 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001928 return D;
1929 }
1930 return 0;
1931}
1932
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001933static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001934 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001935 const Selector &Sel,
1936 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001937 // Check protocols on qualified interfaces.
1938 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001939 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001940 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001941 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001942 GDecl = PD;
1943 break;
1944 }
1945 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001946 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001947 GDecl = OMD;
1948 break;
1949 }
1950 }
1951 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001952 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001953 E = QIdTy->qual_end(); I != E; ++I) {
1954 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001955 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001956 if (GDecl)
1957 return GDecl;
1958 }
1959 }
1960 return GDecl;
1961}
Chris Lattner76a642f2009-02-15 22:43:40 +00001962
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00001963/// FindMethodInNestedImplementations - Look up a method in current and
1964/// all base class implementations.
1965///
1966ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1967 const ObjCInterfaceDecl *IFace,
1968 const Selector &Sel) {
1969 ObjCMethodDecl *Method = 0;
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001970 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001971 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00001972
1973 if (!Method && IFace->getSuperClass())
1974 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1975 return Method;
1976}
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001977
Anders Carlsson8f28f992009-08-26 18:25:21 +00001978Action::OwningExprResult
1979Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001980 tok::TokenKind OpKind, SourceLocation MemberLoc,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001981 DeclarationName MemberName,
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001982 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001983 if (SS && SS->isInvalid())
1984 return ExprError();
1985
Nate Begeman2ef13e52009-08-10 23:49:36 +00001986 // Since this might be a postfix expression, get rid of ParenListExprs.
1987 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1988
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001989 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001990 assert(BaseExpr && "no record expression");
Nate Begeman2ef13e52009-08-10 23:49:36 +00001991
Steve Naroff3cc4af82007-12-16 21:42:28 +00001992 // Perform default conversions.
1993 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001994
Steve Naroffdfa6aae2007-07-26 03:11:44 +00001995 QualType BaseType = BaseExpr->getType();
David Chisnall0f436562009-08-17 16:35:33 +00001996 // If this is an Objective-C pseudo-builtin and a definition is provided then
1997 // use that.
1998 if (BaseType->isObjCIdType()) {
1999 // We have an 'id' type. Rather than fall through, we check if this
2000 // is a reference to 'isa'.
2001 if (BaseType != Context.ObjCIdRedefinitionType) {
2002 BaseType = Context.ObjCIdRedefinitionType;
2003 ImpCastExprToType(BaseExpr, BaseType);
2004 }
2005 } else if (BaseType->isObjCClassType() &&
2006 BaseType != Context.ObjCClassRedefinitionType) {
2007 BaseType = Context.ObjCClassRedefinitionType;
2008 ImpCastExprToType(BaseExpr, BaseType);
2009 }
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002010 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002011
Chris Lattner68a057b2008-07-21 04:36:39 +00002012 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2013 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00002014 if (OpKind == tok::arrow) {
Anders Carlssonffce2df2009-05-15 23:10:19 +00002015 if (BaseType->isDependentType())
Douglas Gregor1c0ca592009-05-22 21:13:27 +00002016 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2017 BaseExpr, true,
2018 OpLoc,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002019 MemberName,
Douglas Gregor1c0ca592009-05-22 21:13:27 +00002020 MemberLoc));
Ted Kremenek6217b802009-07-29 21:53:49 +00002021 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002022 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002023 else if (BaseType->isObjCObjectPointerType())
2024 ;
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002025 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00002026 return ExprError(Diag(MemberLoc,
2027 diag::err_typecheck_member_reference_arrow)
2028 << BaseType << BaseExpr->getSourceRange());
Anders Carlssonffce2df2009-05-15 23:10:19 +00002029 } else {
Anders Carlsson4ef27702009-05-16 20:31:20 +00002030 if (BaseType->isDependentType()) {
2031 // Require that the base type isn't a pointer type
2032 // (so we'll report an error for)
2033 // T* t;
2034 // t.f;
2035 //
2036 // In Obj-C++, however, the above expression is valid, since it could be
2037 // accessing the 'f' property if T is an Obj-C interface. The extra check
2038 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenek6217b802009-07-29 21:53:49 +00002039 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002040
2041 if (!PT || (getLangOptions().ObjC1 &&
2042 !PT->getPointeeType()->isRecordType()))
Douglas Gregor1c0ca592009-05-22 21:13:27 +00002043 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2044 BaseExpr, false,
2045 OpLoc,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002046 MemberName,
Douglas Gregor1c0ca592009-05-22 21:13:27 +00002047 MemberLoc));
Anders Carlsson4ef27702009-05-16 20:31:20 +00002048 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002049 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002050
Chris Lattner68a057b2008-07-21 04:36:39 +00002051 // Handle field access to simple records. This also handles access to fields
2052 // of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002053 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002054 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00002055 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002056 PDiag(diag::err_typecheck_incomplete_tag)
2057 << BaseExpr->getSourceRange()))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002058 return ExprError();
2059
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002060 DeclContext *DC = RDecl;
2061 if (SS && SS->isSet()) {
2062 // If the member name was a qualified-id, look into the
2063 // nested-name-specifier.
2064 DC = computeDeclContext(*SS, false);
2065
2066 // FIXME: If DC is not computable, we should build a
2067 // CXXUnresolvedMemberExpr.
2068 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2069 }
2070
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002071 // The record definition is complete, now make sure the member is valid.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002072 LookupResult Result
Anders Carlsson8f28f992009-08-26 18:25:21 +00002073 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00002074
Douglas Gregordcee1a12009-08-06 05:28:30 +00002075 if (SS && SS->isSet()) {
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002076 QualType BaseTypeCanon
2077 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2078 QualType MemberTypeCanon
2079 = Context.getCanonicalType(
2080 Context.getTypeDeclType(
2081 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2082
2083 if (BaseTypeCanon != MemberTypeCanon &&
2084 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2085 return ExprError(Diag(SS->getBeginLoc(),
2086 diag::err_not_direct_base_or_virtual)
2087 << MemberTypeCanon << BaseTypeCanon);
2088 }
2089
Douglas Gregor7176fff2009-01-15 00:26:24 +00002090 if (!Result)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002091 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002092 << MemberName << BaseExpr->getSourceRange());
Chris Lattnera3d25242009-03-31 08:18:48 +00002093 if (Result.isAmbiguous()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002094 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2095 BaseExpr->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002096 return ExprError();
Chris Lattnera3d25242009-03-31 08:18:48 +00002097 }
2098
2099 NamedDecl *MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00002100
Chris Lattner56cd21b2009-02-13 22:08:30 +00002101 // If the decl being referenced had an error, return an error for this
2102 // sub-expr without emitting another error, in order to avoid cascading
2103 // error cases.
2104 if (MemberDecl->isInvalidDecl())
2105 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002106
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002107 // Check the use of this field
2108 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2109 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00002110
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002111 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002112 // We may have found a field within an anonymous union or struct
2113 // (C++ [class.union]).
2114 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002115 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00002116 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002117
Douglas Gregor86f19402008-12-20 23:49:58 +00002118 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002119 QualType MemberType = FD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002120 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor86f19402008-12-20 23:49:58 +00002121 MemberType = Ref->getPointeeType();
2122 else {
Mon P Wangc6a38a42009-07-22 03:08:17 +00002123 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor86f19402008-12-20 23:49:58 +00002124 unsigned combinedQualifiers =
2125 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002126 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00002127 combinedQualifiers &= ~QualType::Const;
2128 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wangc6a38a42009-07-22 03:08:17 +00002129 if (BaseAddrSpace != MemberType.getAddressSpace())
2130 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor86f19402008-12-20 23:49:58 +00002131 }
Eli Friedman51019072008-02-06 22:48:16 +00002132
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002133 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002134 if (PerformObjectMemberConversion(BaseExpr, FD))
2135 return ExprError();
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002136 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2137 FD, MemberLoc, MemberType));
Chris Lattnera3d25242009-03-31 08:18:48 +00002138 }
2139
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002140 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2141 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002142 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2143 Var, MemberLoc,
2144 Var->getType().getNonReferenceType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002145 }
2146 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2147 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002148 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2149 MemberFn, MemberLoc,
2150 MemberFn->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002151 }
Douglas Gregor6b906862009-08-21 00:16:32 +00002152 if (FunctionTemplateDecl *FunTmpl
2153 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2154 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002155 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2156 FunTmpl, MemberLoc,
2157 Context.OverloadTy));
Douglas Gregor6b906862009-08-21 00:16:32 +00002158 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002159 if (OverloadedFunctionDecl *Ovl
2160 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002161 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2162 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002163 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2164 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002165 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2166 Enum, MemberLoc, Enum->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002167 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002168 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002169 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002170 << MemberName << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00002171
Douglas Gregor86f19402008-12-20 23:49:58 +00002172 // We found a declaration kind that we didn't expect. This is a
2173 // generic error message that tells the user that she can't refer
2174 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002175 return ExprError(Diag(MemberLoc,
2176 diag::err_typecheck_member_reference_unknown)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002177 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002178 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002179
Steve Naroff14108da2009-07-10 23:34:53 +00002180 // Handle properties on ObjC 'Class' types.
Steve Naroff430ee5a2009-07-13 17:19:15 +00002181 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002182 // Also must look for a getter name which uses property syntax.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002183 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2184 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002185 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2186 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2187 ObjCMethodDecl *Getter;
2188 // FIXME: need to also look locally in the implementation.
2189 if ((Getter = IFace->lookupClassMethod(Sel))) {
2190 // Check the use of this method.
2191 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2192 return ExprError();
2193 }
2194 // If we found a getter then this may be a valid dot-reference, we
2195 // will look for the matching setter, in case it is needed.
2196 Selector SetterSel =
2197 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002198 PP.getSelectorTable(), Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002199 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2200 if (!Setter) {
2201 // If this reference is in an @implementation, also check for 'private'
2202 // methods.
2203 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2204 }
2205 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002206 if (!Setter)
2207 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff14108da2009-07-10 23:34:53 +00002208
2209 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2210 return ExprError();
2211
2212 if (Getter || Setter) {
2213 QualType PType;
2214
2215 if (Getter)
2216 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002217 else
2218 // Get the expression type from Setter's incoming parameter.
2219 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00002220 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002221 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff14108da2009-07-10 23:34:53 +00002222 Setter, MemberLoc, BaseExpr));
2223 }
2224 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002225 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002226 }
2227 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002228 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2229 // (*Obj).ivar.
Steve Naroff14108da2009-07-10 23:34:53 +00002230 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2231 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2232 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2233 const ObjCInterfaceType *IFaceT =
2234 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002235 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002236 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2237
Steve Naroffc70e8d92009-07-16 00:25:06 +00002238 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2239 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002240 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Steve Naroffc70e8d92009-07-16 00:25:06 +00002241
2242 if (IV) {
2243 // If the decl being referenced had an error, return an error for this
2244 // sub-expr without emitting another error, in order to avoid cascading
2245 // error cases.
2246 if (IV->isInvalidDecl())
2247 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002248
Steve Naroffc70e8d92009-07-16 00:25:06 +00002249 // Check whether we can reference this field.
2250 if (DiagnoseUseOfDecl(IV, MemberLoc))
2251 return ExprError();
2252 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2253 IV->getAccessControl() != ObjCIvarDecl::Package) {
2254 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2255 if (ObjCMethodDecl *MD = getCurMethodDecl())
2256 ClassOfMethodDecl = MD->getClassInterface();
2257 else if (ObjCImpDecl && getCurFunctionDecl()) {
2258 // Case of a c-function declared inside an objc implementation.
2259 // FIXME: For a c-style function nested inside an objc implementation
2260 // class, there is no implementation context available, so we pass
2261 // down the context as argument to this routine. Ideally, this context
2262 // need be passed down in the AST node and somehow calculated from the
2263 // AST for a function decl.
2264 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2265 if (ObjCImplementationDecl *IMPD =
2266 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2267 ClassOfMethodDecl = IMPD->getClassInterface();
2268 else if (ObjCCategoryImplDecl* CatImplClass =
2269 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2270 ClassOfMethodDecl = CatImplClass->getClassInterface();
2271 }
2272
2273 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2274 if (ClassDeclared != IDecl ||
2275 ClassOfMethodDecl != ClassDeclared)
2276 Diag(MemberLoc, diag::error_private_ivar_access)
2277 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002278 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2279 // @protected
Steve Naroffc70e8d92009-07-16 00:25:06 +00002280 Diag(MemberLoc, diag::error_protected_ivar_access)
2281 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002282 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002283
2284 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2285 MemberLoc, BaseExpr,
2286 OpKind == tok::arrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002287 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002288 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002289 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002290 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002291 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002292 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002293 // Handle properties on 'id' and qualified "id".
2294 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2295 BaseType->isObjCQualifiedIdType())) {
2296 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002297 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroffde2e22d2009-07-15 18:40:39 +00002298
Steve Naroff14108da2009-07-10 23:34:53 +00002299 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002300 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002301 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2302 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2303 // Check the use of this declaration
2304 if (DiagnoseUseOfDecl(PD, MemberLoc))
2305 return ExprError();
2306
2307 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2308 MemberLoc, BaseExpr));
2309 }
2310 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2311 // Check the use of this method.
2312 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2313 return ExprError();
2314
2315 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2316 OMD->getResultType(),
2317 OMD, OpLoc, MemberLoc,
2318 NULL, 0));
2319 }
2320 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002321
Steve Naroff14108da2009-07-10 23:34:53 +00002322 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002323 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002324 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002325 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2326 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002327 const ObjCObjectPointerType *OPT;
2328 if (OpKind == tok::period &&
2329 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2330 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2331 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002332 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Steve Naroff14108da2009-07-10 23:34:53 +00002333
Daniel Dunbar2307d312008-09-03 01:05:41 +00002334 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002335 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002336 // Check whether we can reference this property.
2337 if (DiagnoseUseOfDecl(PD, MemberLoc))
2338 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002339 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002340 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002341 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002342 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2343 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002344 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002345 MemberLoc, BaseExpr));
2346 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002347 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002348 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2349 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002350 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002351 // Check whether we can reference this property.
2352 if (DiagnoseUseOfDecl(PD, MemberLoc))
2353 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002354
Steve Naroff6ece14c2009-01-21 00:14:39 +00002355 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002356 MemberLoc, BaseExpr));
2357 }
Steve Naroff14108da2009-07-10 23:34:53 +00002358 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2359 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002360 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff14108da2009-07-10 23:34:53 +00002361 // Check whether we can reference this property.
2362 if (DiagnoseUseOfDecl(PD, MemberLoc))
2363 return ExprError();
Daniel Dunbar2307d312008-09-03 01:05:41 +00002364
Steve Naroff14108da2009-07-10 23:34:53 +00002365 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2366 MemberLoc, BaseExpr));
2367 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002368 // If that failed, look for an "implicit" property by seeing if the nullary
2369 // selector is implemented.
2370
2371 // FIXME: The logic for looking up nullary and unary selectors should be
2372 // shared with the code in ActOnInstanceMessage.
2373
Anders Carlsson8f28f992009-08-26 18:25:21 +00002374 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002375 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002376
Daniel Dunbar2307d312008-09-03 01:05:41 +00002377 // If this reference is in an @implementation, check for 'private' methods.
2378 if (!Getter)
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00002379 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002380
Steve Naroff7692ed62008-10-22 19:16:27 +00002381 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002382 if (!Getter)
2383 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002384 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002385 // Check if we can reference this property.
2386 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2387 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002388 }
2389 // If we found a getter then this may be a valid dot-reference, we
2390 // will look for the matching setter, in case it is needed.
2391 Selector SetterSel =
2392 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002393 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002394 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002395 if (!Setter) {
2396 // If this reference is in an @implementation, also check for 'private'
2397 // methods.
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00002398 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002399 }
2400 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002401 if (!Setter)
2402 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002403
Steve Naroff1ca66942009-03-11 13:48:17 +00002404 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2405 return ExprError();
2406
2407 if (Getter || Setter) {
2408 QualType PType;
2409
2410 if (Getter)
2411 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002412 else
2413 // Get the expression type from Setter's incoming parameter.
2414 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002415 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002416 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002417 Setter, MemberLoc, BaseExpr));
2418 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002419 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002420 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002421 }
Steve Naroffdd53eb52009-03-05 20:12:00 +00002422
Steve Narofff242b1b2009-07-24 17:54:45 +00002423 // Handle the following exceptional case (*Obj).isa.
2424 if (OpKind == tok::period &&
2425 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002426 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002427 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2428 Context.getObjCIdType()));
2429
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002430 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002431 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002432 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002433 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2434 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002435 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002436 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002437 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002438 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002439
Douglas Gregor214f31a2009-03-27 06:00:30 +00002440 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2441 << BaseType << BaseExpr->getSourceRange();
2442
2443 // If the user is trying to apply -> or . to a function or function
2444 // pointer, it's probably because they forgot parentheses to call
2445 // the function. Suggest the addition of those parentheses.
2446 if (BaseType == Context.OverloadTy ||
2447 BaseType->isFunctionType() ||
2448 (BaseType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002449 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor214f31a2009-03-27 06:00:30 +00002450 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2451 Diag(Loc, diag::note_member_reference_needs_call)
2452 << CodeModificationHint::CreateInsertion(Loc, "()");
2453 }
2454
2455 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002456}
2457
Anders Carlsson8f28f992009-08-26 18:25:21 +00002458Action::OwningExprResult
2459Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2460 tok::TokenKind OpKind, SourceLocation MemberLoc,
2461 IdentifierInfo &Member,
2462 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2463 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2464 DeclarationName(&Member), ObjCImpDecl, SS);
2465}
2466
Anders Carlsson56c5e332009-08-25 03:49:14 +00002467Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2468 FunctionDecl *FD,
2469 ParmVarDecl *Param) {
2470 if (Param->hasUnparsedDefaultArg()) {
2471 Diag (CallLoc,
2472 diag::err_use_of_default_argument_to_function_declared_later) <<
2473 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2474 Diag(UnparsedDefaultArgLocs[Param],
2475 diag::note_default_argument_declared_here);
2476 } else {
2477 if (Param->hasUninstantiatedDefaultArg()) {
2478 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2479
2480 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002481 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson56c5e332009-08-25 03:49:14 +00002482
2483 // FIXME: We should really make a new InstantiatingTemplate ctor
2484 // that has a better message - right now we're just piggy-backing
2485 // off the "default template argument" error message.
2486 InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002487 ArgList.getInnermost().getFlatArgumentList(),
2488 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002489
John McCallce3ff2b2009-08-25 22:02:44 +00002490 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Anders Carlsson56c5e332009-08-25 03:49:14 +00002491 if (Result.isInvalid())
2492 return ExprError();
2493
2494 if (SetParamDefaultArgument(Param, move(Result),
2495 /*FIXME:EqualLoc*/
2496 UninstExpr->getSourceRange().getBegin()))
2497 return ExprError();
2498 }
2499
2500 Expr *DefaultExpr = Param->getDefaultArg();
2501
2502 // If the default expression creates temporaries, we need to
2503 // push them to the current stack of expression temporaries so they'll
2504 // be properly destroyed.
2505 if (CXXExprWithTemporaries *E
2506 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2507 assert(!E->shouldDestroyTemporaries() &&
2508 "Can't destroy temporaries in a default argument expr!");
2509 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2510 ExprTemporaries.push_back(E->getTemporary(I));
2511 }
2512 }
2513
2514 // We already type-checked the argument, so we know it works.
2515 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2516}
2517
Douglas Gregor88a35142008-12-22 05:46:06 +00002518/// ConvertArgumentsForCall - Converts the arguments specified in
2519/// Args/NumArgs to the parameter types of the function FDecl with
2520/// function prototype Proto. Call is the call expression itself, and
2521/// Fn is the function expression. For a C++ member function, this
2522/// routine does not attempt to convert the object argument. Returns
2523/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002524bool
2525Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002526 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002527 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002528 Expr **Args, unsigned NumArgs,
2529 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002530 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002531 // assignment, to the types of the corresponding parameter, ...
2532 unsigned NumArgsInProto = Proto->getNumArgs();
2533 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002534 bool Invalid = false;
2535
Douglas Gregor88a35142008-12-22 05:46:06 +00002536 // If too few arguments are available (and we don't have default
2537 // arguments for the remaining parameters), don't make the call.
2538 if (NumArgs < NumArgsInProto) {
2539 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2540 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2541 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2542 // Use default arguments for missing arguments
2543 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002544 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002545 }
2546
2547 // If too many are passed and not variadic, error on the extras and drop
2548 // them.
2549 if (NumArgs > NumArgsInProto) {
2550 if (!Proto->isVariadic()) {
2551 Diag(Args[NumArgsInProto]->getLocStart(),
2552 diag::err_typecheck_call_too_many_args)
2553 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2554 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2555 Args[NumArgs-1]->getLocEnd());
2556 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002557 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002558 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002559 }
2560 NumArgsToCheck = NumArgsInProto;
2561 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002562
Douglas Gregor88a35142008-12-22 05:46:06 +00002563 // Continue to check argument types (even if we have too few/many args).
2564 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2565 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002566
Douglas Gregor88a35142008-12-22 05:46:06 +00002567 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002568 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002569 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002570
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002571 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2572 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002573 PDiag(diag::err_call_incomplete_argument)
2574 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002575 return true;
2576
Douglas Gregor61366e92008-12-24 00:01:03 +00002577 // Pass the argument.
2578 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2579 return true;
Anders Carlsson5e300d12009-06-12 16:51:40 +00002580 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00002581 ParmVarDecl *Param = FDecl->getParamDecl(i);
Anders Carlsson56c5e332009-08-25 03:49:14 +00002582
2583 OwningExprResult ArgExpr =
2584 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2585 FDecl, Param);
2586 if (ArgExpr.isInvalid())
2587 return true;
2588
2589 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002590 }
2591
Douglas Gregor88a35142008-12-22 05:46:06 +00002592 Call->setArg(i, Arg);
2593 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002594
Douglas Gregor88a35142008-12-22 05:46:06 +00002595 // If this is a variadic call, handle args passed through "...".
2596 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002597 VariadicCallType CallType = VariadicFunction;
2598 if (Fn->getType()->isBlockPointerType())
2599 CallType = VariadicBlock; // Block
2600 else if (isa<MemberExpr>(Fn))
2601 CallType = VariadicMethod;
2602
Douglas Gregor88a35142008-12-22 05:46:06 +00002603 // Promote the arguments (C99 6.5.2.2p7).
2604 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2605 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00002606 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002607 Call->setArg(i, Arg);
2608 }
2609 }
2610
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002611 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002612}
2613
Steve Narofff69936d2007-09-16 03:34:24 +00002614/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002615/// This provides the location of the left/right parens and a list of comma
2616/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002617Action::OwningExprResult
2618Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2619 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002620 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002621 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002622
2623 // Since this might be a postfix expression, get rid of ParenListExprs.
2624 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2625
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002626 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002627 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002628 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00002629 FunctionDecl *FDecl = NULL;
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002630 NamedDecl *NDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00002631 DeclarationName UnqualifiedName;
Nate Begeman2ef13e52009-08-10 23:49:36 +00002632
Douglas Gregor88a35142008-12-22 05:46:06 +00002633 if (getLangOptions().CPlusPlus) {
Douglas Gregor17330012009-02-04 15:01:18 +00002634 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002635 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00002636 // FIXME: Will need to cache the results of name lookup (including ADL) in
2637 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00002638 bool Dependent = false;
2639 if (Fn->isTypeDependent())
2640 Dependent = true;
2641 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2642 Dependent = true;
2643
2644 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002645 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002646 Context.DependentTy, RParenLoc));
2647
2648 // Determine whether this is a call to an object (C++ [over.call.object]).
2649 if (Fn->getType()->isRecordType())
2650 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2651 CommaLocs, RParenLoc));
2652
Douglas Gregorfa047642009-02-04 00:32:51 +00002653 // Determine whether this is a call to a member function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002654 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2655 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2656 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2657 isa<CXXMethodDecl>(MemDecl) ||
2658 (isa<FunctionTemplateDecl>(MemDecl) &&
2659 isa<CXXMethodDecl>(
2660 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002661 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2662 CommaLocs, RParenLoc));
Douglas Gregore53060f2009-06-25 22:08:12 +00002663 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002664 }
2665
Douglas Gregorfa047642009-02-04 00:32:51 +00002666 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002667 // Also, in C++, keep track of whether we should perform argument-dependent
2668 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregorfa047642009-02-04 00:32:51 +00002669 Expr *FnExpr = Fn;
2670 bool ADL = true;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002671 bool HasExplicitTemplateArgs = 0;
2672 const TemplateArgument *ExplicitTemplateArgs = 0;
2673 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregorfa047642009-02-04 00:32:51 +00002674 while (true) {
2675 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2676 FnExpr = IcExpr->getSubExpr();
2677 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002678 // Parentheses around a function disable ADL
Douglas Gregor17330012009-02-04 15:01:18 +00002679 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregorfa047642009-02-04 00:32:51 +00002680 ADL = false;
2681 FnExpr = PExpr->getSubExpr();
2682 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stumpeed9cac2009-02-19 03:04:26 +00002683 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregorfa047642009-02-04 00:32:51 +00002684 == UnaryOperator::AddrOf) {
2685 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002686 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattner90e150d2009-02-14 07:22:29 +00002687 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2688 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002689 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattner90e150d2009-02-14 07:22:29 +00002690 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002691 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattner90e150d2009-02-14 07:22:29 +00002692 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2693 UnqualifiedName = DepName->getName();
2694 break;
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002695 } else if (TemplateIdRefExpr *TemplateIdRef
2696 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2697 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregord99cbe62009-07-29 18:26:50 +00002698 if (!NDecl)
2699 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002700 HasExplicitTemplateArgs = true;
2701 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2702 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2703
2704 // C++ [temp.arg.explicit]p6:
2705 // [Note: For simple function names, argument dependent lookup (3.4.2)
2706 // applies even when the function name is not visible within the
2707 // scope of the call. This is because the call still has the syntactic
2708 // form of a function call (3.4.1). But when a function template with
2709 // explicit template arguments is used, the call does not have the
2710 // correct syntactic form unless there is a function template with
2711 // that name visible at the point of the call. If no such name is
2712 // visible, the call is not syntactically well-formed and
2713 // argument-dependent lookup does not apply. If some such name is
2714 // visible, argument dependent lookup applies and additional function
2715 // templates may be found in other namespaces.
2716 //
2717 // The summary of this paragraph is that, if we get to this point and the
2718 // template-id was not a qualified name, then argument-dependent lookup
2719 // is still possible.
2720 if (TemplateIdRef->getQualifier())
2721 ADL = false;
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002722 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002723 } else {
Chris Lattner90e150d2009-02-14 07:22:29 +00002724 // Any kind of name that does not refer to a declaration (or
2725 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2726 ADL = false;
Douglas Gregorfa047642009-02-04 00:32:51 +00002727 break;
2728 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002729 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002730
Douglas Gregor17330012009-02-04 15:01:18 +00002731 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregore53060f2009-06-25 22:08:12 +00002732 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002733 if (NDecl) {
2734 FDecl = dyn_cast<FunctionDecl>(NDecl);
2735 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregore53060f2009-06-25 22:08:12 +00002736 FDecl = FunctionTemplate->getTemplatedDecl();
2737 else
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002738 FDecl = dyn_cast<FunctionDecl>(NDecl);
2739 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor17330012009-02-04 15:01:18 +00002740 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002741
Douglas Gregore53060f2009-06-25 22:08:12 +00002742 if (Ovl || FunctionTemplate ||
2743 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00002744 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor3c385e52009-02-14 18:57:46 +00002745 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00002746 ADL = false;
2747
Douglas Gregorf9201e02009-02-11 23:02:49 +00002748 // We don't perform ADL in C.
2749 if (!getLangOptions().CPlusPlus)
2750 ADL = false;
2751
Douglas Gregore53060f2009-06-25 22:08:12 +00002752 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002753 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2754 HasExplicitTemplateArgs,
2755 ExplicitTemplateArgs,
2756 NumExplicitTemplateArgs,
2757 LParenLoc, Args, NumArgs, CommaLocs,
2758 RParenLoc, ADL);
Douglas Gregorfa047642009-02-04 00:32:51 +00002759 if (!FDecl)
2760 return ExprError();
2761
2762 // Update Fn to refer to the actual function selected.
2763 Expr *NewFn = 0;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002764 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002765 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregorab452ba2009-03-26 23:50:42 +00002766 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2767 QDRExpr->getLocation(),
2768 false, false,
2769 QDRExpr->getQualifierRange(),
2770 QDRExpr->getQualifier());
Douglas Gregorfa047642009-02-04 00:32:51 +00002771 else
Mike Stumpeed9cac2009-02-19 03:04:26 +00002772 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00002773 Fn->getSourceRange().getBegin());
2774 Fn->Destroy(Context);
2775 Fn = NewFn;
2776 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002777 }
Chris Lattner04421082008-04-08 04:40:51 +00002778
2779 // Promote the function operand.
2780 UsualUnaryConversions(Fn);
2781
Chris Lattner925e60d2007-12-28 05:29:59 +00002782 // Make the call expr early, before semantic checks. This guarantees cleanup
2783 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002784 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2785 Args, NumArgs,
2786 Context.BoolTy,
2787 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002788
Steve Naroffdd972f22008-09-05 22:11:13 +00002789 const FunctionType *FuncT;
2790 if (!Fn->getType()->isBlockPointerType()) {
2791 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2792 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00002793 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002794 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002795 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2796 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00002797 FuncT = PT->getPointeeType()->getAsFunctionType();
2798 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00002799 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffdd972f22008-09-05 22:11:13 +00002800 getAsFunctionType();
2801 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002802 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002803 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2804 << Fn->getType() << Fn->getSourceRange());
2805
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002806 // Check for a valid return type
2807 if (!FuncT->getResultType()->isVoidType() &&
2808 RequireCompleteType(Fn->getSourceRange().getBegin(),
2809 FuncT->getResultType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00002810 PDiag(diag::err_call_incomplete_return)
2811 << TheCall->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002812 return ExprError();
2813
Chris Lattner925e60d2007-12-28 05:29:59 +00002814 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002815 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002816
Douglas Gregor72564e72009-02-26 23:50:07 +00002817 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002818 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002819 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002820 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002821 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002822 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002823
Douglas Gregor74734d52009-04-02 15:37:10 +00002824 if (FDecl) {
2825 // Check if we have too few/too many template arguments, based
2826 // on our knowledge of the function definition.
2827 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002828 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002829 const FunctionProtoType *Proto =
2830 Def->getType()->getAsFunctionProtoType();
2831 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2832 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2833 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2834 }
2835 }
Douglas Gregor74734d52009-04-02 15:37:10 +00002836 }
2837
Steve Naroffb291ab62007-08-28 23:30:39 +00002838 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002839 for (unsigned i = 0; i != NumArgs; i++) {
2840 Expr *Arg = Args[i];
2841 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002842 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2843 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00002844 PDiag(diag::err_call_incomplete_argument)
2845 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002846 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002847 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002848 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002849 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002850
Douglas Gregor88a35142008-12-22 05:46:06 +00002851 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2852 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002853 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2854 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002855
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002856 // Check for sentinels
2857 if (NDecl)
2858 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlssond406bf02009-08-16 01:56:34 +00002859
Chris Lattner59907c42007-08-10 20:18:51 +00002860 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00002861 if (FDecl) {
2862 if (CheckFunctionCall(FDecl, TheCall.get()))
2863 return ExprError();
2864
2865 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2866 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2867 } else if (NDecl) {
2868 if (CheckBlockCall(NDecl, TheCall.get()))
2869 return ExprError();
2870 }
Chris Lattner59907c42007-08-10 20:18:51 +00002871
Anders Carlssonec74c592009-08-16 03:06:32 +00002872 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00002873}
2874
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002875Action::OwningExprResult
2876Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2877 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00002878 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002879 //FIXME: Preserve type source info.
2880 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002881 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002882 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002883 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002884
Eli Friedman6223c222008-05-20 05:22:08 +00002885 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00002886 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002887 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2888 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00002889 } else if (!literalType->isDependentType() &&
2890 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002891 PDiag(diag::err_typecheck_decl_incomplete_type)
2892 << SourceRange(LParenLoc,
2893 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002894 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00002895
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002896 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002897 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002898 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00002899
Chris Lattner371f2582008-12-04 23:50:19 +00002900 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00002901 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00002902 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002903 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002904 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002905 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002906 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002907 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00002908}
2909
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002910Action::OwningExprResult
2911Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002912 SourceLocation RBraceLoc) {
2913 unsigned NumInit = initlist.size();
2914 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00002915
Steve Naroff08d92e42007-09-15 18:49:24 +00002916 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00002917 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002918
Mike Stumpeed9cac2009-02-19 03:04:26 +00002919 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00002920 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00002921 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002922 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00002923}
2924
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002925/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00002926bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00002927 CastExpr::CastKind& Kind,
2928 CXXMethodDecl *& ConversionDecl,
2929 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002930 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00002931 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2932 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002933
Eli Friedman199ea952009-08-15 19:02:19 +00002934 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002935
2936 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2937 // type needs to be scalar.
2938 if (castType->isVoidType()) {
2939 // Cast to void allows any expr type.
2940 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002941 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2942 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2943 (castType->isStructureType() || castType->isUnionType())) {
2944 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00002945 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002946 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2947 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00002948 Kind = CastExpr::CK_NoOp;
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002949 } else if (castType->isUnionType()) {
2950 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00002951 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002952 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002953 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002954 Field != FieldEnd; ++Field) {
2955 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2956 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2957 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2958 << castExpr->getSourceRange();
2959 break;
2960 }
2961 }
2962 if (Field == FieldEnd)
2963 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2964 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00002965 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00002966 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002967 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002968 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00002969 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002970 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002971 } else if (!castExpr->getType()->isScalarType() &&
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002972 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002973 return Diag(castExpr->getLocStart(),
2974 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00002975 << castExpr->getType() << castExpr->getSourceRange();
Nate Begeman58d29a42009-06-26 00:50:28 +00002976 } else if (castType->isExtVectorType()) {
2977 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002978 return true;
2979 } else if (castType->isVectorType()) {
2980 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2981 return true;
Nate Begeman58d29a42009-06-26 00:50:28 +00002982 } else if (castExpr->getType()->isVectorType()) {
2983 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2984 return true;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002985 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00002986 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman41826bb2009-05-01 02:23:58 +00002987 } else if (!castType->isArithmeticType()) {
2988 QualType castExprType = castExpr->getType();
2989 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2990 return Diag(castExpr->getLocStart(),
2991 diag::err_cast_pointer_from_non_pointer_int)
2992 << castExprType << castExpr->getSourceRange();
2993 } else if (!castExpr->getType()->isArithmeticType()) {
2994 if (!castType->isIntegralType() && castType->isArithmeticType())
2995 return Diag(castExpr->getLocStart(),
2996 diag::err_cast_pointer_to_non_pointer_int)
2997 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00002998 }
Fariborz Jahanianb5ff6bf2009-05-22 21:42:52 +00002999 if (isa<ObjCSelectorExpr>(castExpr))
3000 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003001 return false;
3002}
3003
Chris Lattnerfe23e212007-12-20 00:44:32 +00003004bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003005 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003006
Anders Carlssona64db8f2007-11-27 05:51:55 +00003007 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003008 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003009 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003010 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003011 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003012 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003013 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003014 } else
3015 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003016 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003017 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003018
Anders Carlssona64db8f2007-11-27 05:51:55 +00003019 return false;
3020}
3021
Nate Begeman58d29a42009-06-26 00:50:28 +00003022bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3023 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3024
Nate Begeman9b10da62009-06-27 22:05:55 +00003025 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3026 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003027 if (SrcTy->isVectorType()) {
3028 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3029 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3030 << DestTy << SrcTy << R;
3031 return false;
3032 }
3033
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003034 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003035 // conversion will take place first from scalar to elt type, and then
3036 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003037 if (SrcTy->isPointerType())
3038 return Diag(R.getBegin(),
3039 diag::err_invalid_conversion_between_vector_and_scalar)
3040 << DestTy << SrcTy << R;
Nate Begeman58d29a42009-06-26 00:50:28 +00003041 return false;
3042}
3043
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003044Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003045Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003046 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003047 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3048
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003049 assert((Ty != 0) && (Op.get() != 0) &&
3050 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003051
Nate Begeman2ef13e52009-08-10 23:49:36 +00003052 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003053 //FIXME: Preserve type source info.
3054 QualType castType = GetTypeFromParser(Ty);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003055
3056 // If the Expr being casted is a ParenListExpr, handle it specially.
3057 if (isa<ParenListExpr>(castExpr))
3058 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003059 CXXMethodDecl *ConversionDecl = 0;
Anders Carlssoncdb61972009-08-07 22:21:05 +00003060 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003061 Kind, ConversionDecl))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003062 return ExprError();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003063 if (ConversionDecl) {
3064 // encounterred a c-style cast requiring a conversion function.
3065 if (CXXConversionDecl *CD = dyn_cast<CXXConversionDecl>(ConversionDecl)) {
3066 castExpr =
3067 new (Context) CXXFunctionalCastExpr(castType.getNonReferenceType(),
3068 castType, LParenLoc,
3069 CastExpr::CK_UserDefinedConversion,
3070 castExpr, CD,
3071 RParenLoc);
3072 Kind = CastExpr::CK_UserDefinedConversion;
3073 }
3074 // FIXME. AST for when dealing with conversion functions (FunctionDecl).
3075 }
Nate Begeman2ef13e52009-08-10 23:49:36 +00003076
3077 Op.release();
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003078 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlssoncdb61972009-08-07 22:21:05 +00003079 Kind, castExpr, castType,
3080 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003081}
3082
Nate Begeman2ef13e52009-08-10 23:49:36 +00003083/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3084/// of comma binary operators.
3085Action::OwningExprResult
3086Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3087 Expr *expr = EA.takeAs<Expr>();
3088 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3089 if (!E)
3090 return Owned(expr);
3091
3092 OwningExprResult Result(*this, E->getExpr(0));
3093
3094 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3095 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3096 Owned(E->getExpr(i)));
3097
3098 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3099}
3100
3101Action::OwningExprResult
3102Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3103 SourceLocation RParenLoc, ExprArg Op,
3104 QualType Ty) {
3105 ParenListExpr *PE = (ParenListExpr *)Op.get();
3106
3107 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3108 // then handle it as such.
3109 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3110 if (PE->getNumExprs() == 0) {
3111 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3112 return ExprError();
3113 }
3114
3115 llvm::SmallVector<Expr *, 8> initExprs;
3116 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3117 initExprs.push_back(PE->getExpr(i));
3118
3119 // FIXME: This means that pretty-printing the final AST will produce curly
3120 // braces instead of the original commas.
3121 Op.release();
3122 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3123 initExprs.size(), RParenLoc);
3124 E->setType(Ty);
3125 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3126 Owned(E));
3127 } else {
3128 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3129 // sequence of BinOp comma operators.
3130 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3131 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3132 }
3133}
3134
3135Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3136 SourceLocation R,
3137 MultiExprArg Val) {
3138 unsigned nexprs = Val.size();
3139 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3140 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3141 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3142 return Owned(expr);
3143}
3144
Sebastian Redl28507842009-02-26 14:39:58 +00003145/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3146/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003147/// C99 6.5.15
3148QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3149 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003150 // C++ is sufficiently different to merit its own checker.
3151 if (getLangOptions().CPlusPlus)
3152 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3153
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003154 UsualUnaryConversions(Cond);
3155 UsualUnaryConversions(LHS);
3156 UsualUnaryConversions(RHS);
3157 QualType CondTy = Cond->getType();
3158 QualType LHSTy = LHS->getType();
3159 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003160
Reid Spencer5f016e22007-07-11 17:01:13 +00003161 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003162 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3163 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3164 << CondTy;
3165 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003166 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003167
Chris Lattner70d67a92008-01-06 22:42:25 +00003168 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003169 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3170 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003171
Chris Lattner70d67a92008-01-06 22:42:25 +00003172 // If both operands have arithmetic type, do the usual arithmetic conversions
3173 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003174 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3175 UsualArithmeticConversions(LHS, RHS);
3176 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003177 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003178
Chris Lattner70d67a92008-01-06 22:42:25 +00003179 // If both operands are the same structure or union type, the result is that
3180 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003181 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3182 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003183 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003184 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003185 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003186 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003187 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003188 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003189
Chris Lattner70d67a92008-01-06 22:42:25 +00003190 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003191 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003192 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3193 if (!LHSTy->isVoidType())
3194 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3195 << RHS->getSourceRange();
3196 if (!RHSTy->isVoidType())
3197 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3198 << LHS->getSourceRange();
3199 ImpCastExprToType(LHS, Context.VoidTy);
3200 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedman0e724012008-06-04 19:47:51 +00003201 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003202 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003203 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3204 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003205 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003206 RHS->isNullPointerConstant(Context)) {
3207 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3208 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003209 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003210 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003211 LHS->isNullPointerConstant(Context)) {
3212 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3213 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003214 }
David Chisnall0f436562009-08-17 16:35:33 +00003215 // Handle things like Class and struct objc_class*. Here we case the result
3216 // to the pseudo-builtin, because that will be implicitly cast back to the
3217 // redefinition type if an attempt is made to access its fields.
3218 if (LHSTy->isObjCClassType() &&
3219 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3220 ImpCastExprToType(RHS, LHSTy);
3221 return LHSTy;
3222 }
3223 if (RHSTy->isObjCClassType() &&
3224 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3225 ImpCastExprToType(LHS, RHSTy);
3226 return RHSTy;
3227 }
3228 // And the same for struct objc_object* / id
3229 if (LHSTy->isObjCIdType() &&
3230 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3231 ImpCastExprToType(RHS, LHSTy);
3232 return LHSTy;
3233 }
3234 if (RHSTy->isObjCIdType() &&
3235 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3236 ImpCastExprToType(LHS, RHSTy);
3237 return RHSTy;
3238 }
Steve Naroff7154a772009-07-01 14:36:47 +00003239 // Handle block pointer types.
3240 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3241 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3242 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3243 QualType destType = Context.getPointerType(Context.VoidTy);
3244 ImpCastExprToType(LHS, destType);
3245 ImpCastExprToType(RHS, destType);
3246 return destType;
3247 }
3248 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3249 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3250 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003251 }
Steve Naroff7154a772009-07-01 14:36:47 +00003252 // We have 2 block pointer types.
3253 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3254 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003255 return LHSTy;
3256 }
Steve Naroff7154a772009-07-01 14:36:47 +00003257 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003258 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3259 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003260
Steve Naroff7154a772009-07-01 14:36:47 +00003261 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3262 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003263 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3264 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3265 // In this situation, we assume void* type. No especially good
3266 // reason, but this is what gcc does, and we do have to pick
3267 // to get a consistent AST.
3268 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3269 ImpCastExprToType(LHS, incompatTy);
3270 ImpCastExprToType(RHS, incompatTy);
3271 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003272 }
Steve Naroff7154a772009-07-01 14:36:47 +00003273 // The block pointer types are compatible.
3274 ImpCastExprToType(LHS, LHSTy);
3275 ImpCastExprToType(RHS, LHSTy);
Steve Naroff91588042009-04-08 17:05:15 +00003276 return LHSTy;
3277 }
Steve Naroff7154a772009-07-01 14:36:47 +00003278 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003279 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003280
3281 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3282 // Two identical object pointer types are always compatible.
3283 return LHSTy;
3284 }
Steve Naroff14108da2009-07-10 23:34:53 +00003285 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3286 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff7154a772009-07-01 14:36:47 +00003287 QualType compositeType = LHSTy;
3288
3289 // If both operands are interfaces and either operand can be
3290 // assigned to the other, use that type as the composite
3291 // type. This allows
3292 // xxx ? (A*) a : (B*) b
3293 // where B is a subclass of A.
3294 //
3295 // Additionally, as for assignment, if either type is 'id'
3296 // allow silent coercion. Finally, if the types are
3297 // incompatible then make sure to use 'id' as the composite
3298 // type so the result is acceptable for sending messages to.
3299
3300 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3301 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003302 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003303 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003304 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003305 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003306 } else if ((LHSTy->isObjCQualifiedIdType() ||
3307 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003308 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff14108da2009-07-10 23:34:53 +00003309 // Need to handle "id<xx>" explicitly.
3310 // GCC allows qualified id and any Objective-C type to devolve to
3311 // id. Currently localizing to here until clear this should be
3312 // part of ObjCQualifiedIdTypesAreCompatible.
3313 compositeType = Context.getObjCIdType();
3314 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003315 compositeType = Context.getObjCIdType();
3316 } else {
3317 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3318 << LHSTy << RHSTy
3319 << LHS->getSourceRange() << RHS->getSourceRange();
3320 QualType incompatTy = Context.getObjCIdType();
3321 ImpCastExprToType(LHS, incompatTy);
3322 ImpCastExprToType(RHS, incompatTy);
3323 return incompatTy;
3324 }
3325 // The object pointer types are compatible.
3326 ImpCastExprToType(LHS, compositeType);
3327 ImpCastExprToType(RHS, compositeType);
3328 return compositeType;
3329 }
Steve Naroffc715e782009-07-29 15:09:39 +00003330 // Check Objective-C object pointer types and 'void *'
3331 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003332 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffc715e782009-07-29 15:09:39 +00003333 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3334 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3335 QualType destType = Context.getPointerType(destPointee);
3336 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3337 ImpCastExprToType(RHS, destType); // promote to void*
3338 return destType;
3339 }
3340 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3341 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003342 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffc715e782009-07-29 15:09:39 +00003343 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3344 QualType destType = Context.getPointerType(destPointee);
3345 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3346 ImpCastExprToType(LHS, destType); // promote to void*
3347 return destType;
3348 }
Steve Naroff7154a772009-07-01 14:36:47 +00003349 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3350 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3351 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003352 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3353 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003354
3355 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3356 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3357 // Figure out necessary qualifiers (C99 6.5.15p6)
3358 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3359 QualType destType = Context.getPointerType(destPointee);
3360 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3361 ImpCastExprToType(RHS, destType); // promote to void*
3362 return destType;
3363 }
3364 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3365 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3366 QualType destType = Context.getPointerType(destPointee);
3367 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3368 ImpCastExprToType(RHS, destType); // promote to void*
3369 return destType;
3370 }
3371
3372 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3373 // Two identical pointer types are always compatible.
3374 return LHSTy;
3375 }
3376 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3377 rhptee.getUnqualifiedType())) {
3378 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3379 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3380 // In this situation, we assume void* type. No especially good
3381 // reason, but this is what gcc does, and we do have to pick
3382 // to get a consistent AST.
3383 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3384 ImpCastExprToType(LHS, incompatTy);
3385 ImpCastExprToType(RHS, incompatTy);
3386 return incompatTy;
3387 }
3388 // The pointer types are compatible.
3389 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3390 // differently qualified versions of compatible types, the result type is
3391 // a pointer to an appropriately qualified version of the *composite*
3392 // type.
3393 // FIXME: Need to calculate the composite type.
3394 // FIXME: Need to add qualifiers
3395 ImpCastExprToType(LHS, LHSTy);
3396 ImpCastExprToType(RHS, LHSTy);
3397 return LHSTy;
3398 }
3399
3400 // GCC compatibility: soften pointer/integer mismatch.
3401 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3402 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3403 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3404 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3405 return RHSTy;
3406 }
3407 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3408 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3409 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3410 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3411 return LHSTy;
3412 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003413
Chris Lattner70d67a92008-01-06 22:42:25 +00003414 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003415 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3416 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003417 return QualType();
3418}
3419
Steve Narofff69936d2007-09-16 03:34:24 +00003420/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00003421/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003422Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3423 SourceLocation ColonLoc,
3424 ExprArg Cond, ExprArg LHS,
3425 ExprArg RHS) {
3426 Expr *CondExpr = (Expr *) Cond.get();
3427 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00003428
3429 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3430 // was the condition.
3431 bool isLHSNull = LHSExpr == 0;
3432 if (isLHSNull)
3433 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003434
3435 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00003436 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003437 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003438 return ExprError();
3439
3440 Cond.release();
3441 LHS.release();
3442 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003443 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003444 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003445 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00003446}
3447
Reid Spencer5f016e22007-07-11 17:01:13 +00003448// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00003449// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00003450// routine is it effectively iqnores the qualifiers on the top level pointee.
3451// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3452// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003453Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003454Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3455 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003456
David Chisnall0f436562009-08-17 16:35:33 +00003457 if ((lhsType->isObjCClassType() &&
3458 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3459 (rhsType->isObjCClassType() &&
3460 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3461 return Compatible;
3462 }
3463
Reid Spencer5f016e22007-07-11 17:01:13 +00003464 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003465 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3466 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003467
Reid Spencer5f016e22007-07-11 17:01:13 +00003468 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00003469 lhptee = Context.getCanonicalType(lhptee);
3470 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00003471
Chris Lattner5cf216b2008-01-04 18:04:52 +00003472 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003473
3474 // C99 6.5.16.1p1: This following citation is common to constraints
3475 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3476 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003477 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00003478 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003479 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003480
Mike Stumpeed9cac2009-02-19 03:04:26 +00003481 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3482 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00003483 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003484 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003485 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003486 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003487
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003488 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003489 assert(rhptee->isFunctionType());
3490 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003491 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003492
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003493 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003494 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003495 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003496
3497 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003498 assert(lhptee->isFunctionType());
3499 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003500 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003501 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00003502 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003503 lhptee = lhptee.getUnqualifiedType();
3504 rhptee = rhptee.getUnqualifiedType();
3505 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3506 // Check if the pointee types are compatible ignoring the sign.
3507 // We explicitly check for char so that we catch "char" vs
3508 // "unsigned char" on systems where "char" is unsigned.
3509 if (lhptee->isCharType()) {
3510 lhptee = Context.UnsignedCharTy;
3511 } else if (lhptee->isSignedIntegerType()) {
3512 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3513 }
3514 if (rhptee->isCharType()) {
3515 rhptee = Context.UnsignedCharTy;
3516 } else if (rhptee->isSignedIntegerType()) {
3517 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3518 }
3519 if (lhptee == rhptee) {
3520 // Types are compatible ignoring the sign. Qualifier incompatibility
3521 // takes priority over sign incompatibility because the sign
3522 // warning can be disabled.
3523 if (ConvTy != Compatible)
3524 return ConvTy;
3525 return IncompatiblePointerSign;
3526 }
3527 // General pointer incompatibility takes priority over qualifiers.
3528 return IncompatiblePointer;
3529 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003530 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003531}
3532
Steve Naroff1c7d0672008-09-04 15:10:53 +00003533/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3534/// block pointer types are compatible or whether a block and normal pointer
3535/// are compatible. It is more restrict than comparing two function pointer
3536// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003537Sema::AssignConvertType
3538Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00003539 QualType rhsType) {
3540 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003541
Steve Naroff1c7d0672008-09-04 15:10:53 +00003542 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003543 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3544 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003545
Steve Naroff1c7d0672008-09-04 15:10:53 +00003546 // make sure we operate on the canonical type
3547 lhptee = Context.getCanonicalType(lhptee);
3548 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003549
Steve Naroff1c7d0672008-09-04 15:10:53 +00003550 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003551
Steve Naroff1c7d0672008-09-04 15:10:53 +00003552 // For blocks we enforce that qualifiers are identical.
3553 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3554 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003555
Eli Friedman26784c12009-06-08 05:08:54 +00003556 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003557 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003558 return ConvTy;
3559}
3560
Mike Stumpeed9cac2009-02-19 03:04:26 +00003561/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3562/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00003563/// pointers. Here are some objectionable examples that GCC considers warnings:
3564///
3565/// int a, *pint;
3566/// short *pshort;
3567/// struct foo *pfoo;
3568///
3569/// pint = pshort; // warning: assignment from incompatible pointer type
3570/// a = pint; // warning: assignment makes integer from pointer without a cast
3571/// pint = a; // warning: assignment makes pointer from integer without a cast
3572/// pint = pfoo; // warning: assignment from incompatible pointer type
3573///
3574/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00003575/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00003576///
Chris Lattner5cf216b2008-01-04 18:04:52 +00003577Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003578Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00003579 // Get canonical types. We're not formatting these types, just comparing
3580 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003581 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3582 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003583
3584 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00003585 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00003586
David Chisnall0f436562009-08-17 16:35:33 +00003587 if ((lhsType->isObjCClassType() &&
3588 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3589 (rhsType->isObjCClassType() &&
3590 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3591 return Compatible;
3592 }
3593
Douglas Gregor9d293df2008-10-28 00:22:11 +00003594 // If the left-hand side is a reference type, then we are in a
3595 // (rare!) case where we've allowed the use of references in C,
3596 // e.g., as a parameter type in a built-in function. In this case,
3597 // just make sure that the type referenced is compatible with the
3598 // right-hand side type. The caller is responsible for adjusting
3599 // lhsType so that the resulting expression does not have reference
3600 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003601 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00003602 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00003603 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003604 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003605 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003606 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3607 // to the same ExtVector type.
3608 if (lhsType->isExtVectorType()) {
3609 if (rhsType->isExtVectorType())
3610 return lhsType == rhsType ? Compatible : Incompatible;
3611 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3612 return Compatible;
3613 }
3614
Nate Begemanbe2341d2008-07-14 18:02:46 +00003615 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003616 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00003617 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00003618 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00003619 if (getLangOptions().LaxVectorConversions &&
3620 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003621 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003622 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00003623 }
3624 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003625 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003626
Chris Lattnere8b3e962008-01-04 23:32:24 +00003627 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003628 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003629
Chris Lattner78eca282008-04-07 06:49:41 +00003630 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003631 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003632 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003633
Chris Lattner78eca282008-04-07 06:49:41 +00003634 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003635 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003636
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003637 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003638 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003639 if (lhsType->isVoidPointerType()) // an exception to the rule.
3640 return Compatible;
3641 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003642 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003643 if (rhsType->getAs<BlockPointerType>()) {
3644 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003645 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00003646
3647 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003648 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003649 return Compatible;
3650 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003651 return Incompatible;
3652 }
3653
3654 if (isa<BlockPointerType>(lhsType)) {
3655 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00003656 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003657
Steve Naroffb4406862008-09-29 18:10:17 +00003658 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003659 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003660 return Compatible;
3661
Steve Naroff1c7d0672008-09-04 15:10:53 +00003662 if (rhsType->isBlockPointerType())
3663 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003664
Ted Kremenek6217b802009-07-29 21:53:49 +00003665 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00003666 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003667 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003668 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00003669 return Incompatible;
3670 }
3671
Steve Naroff14108da2009-07-10 23:34:53 +00003672 if (isa<ObjCObjectPointerType>(lhsType)) {
3673 if (rhsType->isIntegerType())
3674 return IntToPointer;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003675
3676 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003677 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003678 if (rhsType->isVoidPointerType()) // an exception to the rule.
3679 return Compatible;
3680 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003681 }
3682 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003683 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3684 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003685 if (Context.typesAreCompatible(lhsType, rhsType))
3686 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00003687 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3688 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003689 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003690 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003691 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003692 if (RHSPT->getPointeeType()->isVoidType())
3693 return Compatible;
3694 }
3695 // Treat block pointers as objects.
3696 if (rhsType->isBlockPointerType())
3697 return Compatible;
3698 return Incompatible;
3699 }
Chris Lattner78eca282008-04-07 06:49:41 +00003700 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003701 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003702 if (lhsType == Context.BoolTy)
3703 return Compatible;
3704
3705 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003706 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00003707
Mike Stumpeed9cac2009-02-19 03:04:26 +00003708 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003709 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003710
3711 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003712 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003713 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003714 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003715 }
Steve Naroff14108da2009-07-10 23:34:53 +00003716 if (isa<ObjCObjectPointerType>(rhsType)) {
3717 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3718 if (lhsType == Context.BoolTy)
3719 return Compatible;
3720
3721 if (lhsType->isIntegerType())
3722 return PointerToInt;
3723
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003724 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003725 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003726 if (lhsType->isVoidPointerType()) // an exception to the rule.
3727 return Compatible;
3728 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003729 }
3730 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003731 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00003732 return Compatible;
3733 return Incompatible;
3734 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003735
Chris Lattnerfc144e22008-01-04 23:18:45 +00003736 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00003737 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003738 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00003739 }
3740 return Incompatible;
3741}
3742
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003743/// \brief Constructs a transparent union from an expression that is
3744/// used to initialize the transparent union.
3745static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3746 QualType UnionType, FieldDecl *Field) {
3747 // Build an initializer list that designates the appropriate member
3748 // of the transparent union.
3749 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3750 &E, 1,
3751 SourceLocation());
3752 Initializer->setType(UnionType);
3753 Initializer->setInitializedFieldInUnion(Field);
3754
3755 // Build a compound literal constructing a value of the transparent
3756 // union type from this initializer list.
3757 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3758 false);
3759}
3760
3761Sema::AssignConvertType
3762Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3763 QualType FromType = rExpr->getType();
3764
3765 // If the ArgType is a Union type, we want to handle a potential
3766 // transparent_union GCC extension.
3767 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003768 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003769 return Incompatible;
3770
3771 // The field to initialize within the transparent union.
3772 RecordDecl *UD = UT->getDecl();
3773 FieldDecl *InitField = 0;
3774 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003775 for (RecordDecl::field_iterator it = UD->field_begin(),
3776 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003777 it != itend; ++it) {
3778 if (it->getType()->isPointerType()) {
3779 // If the transparent union contains a pointer type, we allow:
3780 // 1) void pointer
3781 // 2) null pointer constant
3782 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003783 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003784 ImpCastExprToType(rExpr, it->getType());
3785 InitField = *it;
3786 break;
3787 }
3788
3789 if (rExpr->isNullPointerConstant(Context)) {
3790 ImpCastExprToType(rExpr, it->getType());
3791 InitField = *it;
3792 break;
3793 }
3794 }
3795
3796 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3797 == Compatible) {
3798 InitField = *it;
3799 break;
3800 }
3801 }
3802
3803 if (!InitField)
3804 return Incompatible;
3805
3806 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3807 return Compatible;
3808}
3809
Chris Lattner5cf216b2008-01-04 18:04:52 +00003810Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00003811Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00003812 if (getLangOptions().CPlusPlus) {
3813 if (!lhsType->isRecordType()) {
3814 // C++ 5.17p3: If the left operand is not of class type, the
3815 // expression is implicitly converted (C++ 4) to the
3816 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00003817 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3818 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00003819 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00003820 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00003821 }
3822
3823 // FIXME: Currently, we fall through and treat C++ classes like C
3824 // structures.
3825 }
3826
Steve Naroff529a4ad2007-11-27 17:58:44 +00003827 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3828 // a null pointer constant.
Steve Narofff7f52e72009-02-21 21:17:01 +00003829 if ((lhsType->isPointerType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003830 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00003831 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00003832 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00003833 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00003834 return Compatible;
3835 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003836
Chris Lattner943140e2007-10-16 02:55:40 +00003837 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00003838 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00003839 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00003840 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00003841 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00003842 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00003843 if (!lhsType->isReferenceType())
3844 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00003845
Chris Lattner5cf216b2008-01-04 18:04:52 +00003846 Sema::AssignConvertType result =
3847 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00003848
Steve Narofff1120de2007-08-24 22:33:52 +00003849 // C99 6.5.16.1p2: The value of the right operand is converted to the
3850 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003851 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3852 // so that we can use references in built-in functions even in C.
3853 // The getNonReferenceType() call makes sure that the resulting expression
3854 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003855 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00003856 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00003857 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00003858}
3859
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003860QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003861 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00003862 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003863 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00003864 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003865}
3866
Mike Stumpeed9cac2009-02-19 03:04:26 +00003867inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00003868 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003869 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003870 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003871 QualType lhsType =
3872 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3873 QualType rhsType =
3874 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003875
Nate Begemanbe2341d2008-07-14 18:02:46 +00003876 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003877 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00003878 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00003879
Nate Begemanbe2341d2008-07-14 18:02:46 +00003880 // Handle the case of a vector & extvector type of the same size and element
3881 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003882 if (getLangOptions().LaxVectorConversions) {
3883 // FIXME: Should we warn here?
3884 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003885 if (const VectorType *RV = rhsType->getAsVectorType())
3886 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003887 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003888 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003889 }
3890 }
3891 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003892
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003893 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3894 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3895 bool swapped = false;
3896 if (rhsType->isExtVectorType()) {
3897 swapped = true;
3898 std::swap(rex, lex);
3899 std::swap(rhsType, lhsType);
3900 }
3901
Nate Begemandde25982009-06-28 19:12:57 +00003902 // Handle the case of an ext vector and scalar.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003903 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3904 QualType EltTy = LV->getElementType();
3905 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3906 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemandde25982009-06-28 19:12:57 +00003907 ImpCastExprToType(rex, lhsType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003908 if (swapped) std::swap(rex, lex);
3909 return lhsType;
3910 }
3911 }
3912 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3913 rhsType->isRealFloatingType()) {
3914 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemandde25982009-06-28 19:12:57 +00003915 ImpCastExprToType(rex, lhsType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003916 if (swapped) std::swap(rex, lex);
3917 return lhsType;
3918 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00003919 }
3920 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003921
Nate Begemandde25982009-06-28 19:12:57 +00003922 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003923 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00003924 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003925 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003926 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00003927}
3928
Reid Spencer5f016e22007-07-11 17:01:13 +00003929inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003930 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003931{
Daniel Dunbar69d1d002009-01-05 22:42:10 +00003932 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003933 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003934
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003935 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003936
Steve Naroffa4332e22007-07-17 00:58:39 +00003937 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003938 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003939 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003940}
3941
3942inline QualType Sema::CheckRemainderOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00003943 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00003944{
Daniel Dunbar523aa602009-01-05 22:55:36 +00003945 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3946 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3947 return CheckVectorOperands(Loc, lex, rex);
3948 return InvalidOperands(Loc, lex, rex);
3949 }
Steve Naroff90045e82007-07-13 23:32:42 +00003950
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003951 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003952
Steve Naroffa4332e22007-07-17 00:58:39 +00003953 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003954 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003955 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00003956}
3957
3958inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedmanab3a8522009-03-28 01:22:36 +00003959 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Reid Spencer5f016e22007-07-11 17:01:13 +00003960{
Eli Friedmanab3a8522009-03-28 01:22:36 +00003961 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3962 QualType compType = CheckVectorOperands(Loc, lex, rex);
3963 if (CompLHSTy) *CompLHSTy = compType;
3964 return compType;
3965 }
Steve Naroff49b45262007-07-13 16:58:59 +00003966
Eli Friedmanab3a8522009-03-28 01:22:36 +00003967 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00003968
Reid Spencer5f016e22007-07-11 17:01:13 +00003969 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00003970 if (lex->getType()->isArithmeticType() &&
3971 rex->getType()->isArithmeticType()) {
3972 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00003973 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00003974 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003975
Eli Friedmand72d16e2008-05-18 18:08:51 +00003976 // Put any potential pointer into PExp
3977 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003978 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00003979 std::swap(PExp, IExp);
3980
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003981 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003982
Eli Friedmand72d16e2008-05-18 18:08:51 +00003983 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00003984 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00003985
Chris Lattnerb5f15622009-04-24 23:50:08 +00003986 // Check for arithmetic on pointers to incomplete types.
3987 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00003988 if (getLangOptions().CPlusPlus) {
3989 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003990 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003991 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00003992 }
Douglas Gregore7450f52009-03-24 19:52:54 +00003993
3994 // GNU extension: arithmetic on pointer to void
3995 Diag(Loc, diag::ext_gnu_void_ptr)
3996 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00003997 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00003998 if (getLangOptions().CPlusPlus) {
3999 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4000 << lex->getType() << lex->getSourceRange();
4001 return QualType();
4002 }
4003
4004 // GNU extension: arithmetic on pointer to function
4005 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4006 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004007 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004008 // Check if we require a complete type.
4009 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004010 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004011 PExp->getType()->isObjCObjectPointerType()) &&
4012 RequireCompleteType(Loc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00004013 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4014 << PExp->getSourceRange()
4015 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004016 return QualType();
4017 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004018 // Diagnose bad cases where we step over interface counts.
4019 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4020 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4021 << PointeeTy << PExp->getSourceRange();
4022 return QualType();
4023 }
4024
Eli Friedmanab3a8522009-03-28 01:22:36 +00004025 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004026 QualType LHSTy = Context.isPromotableBitField(lex);
4027 if (LHSTy.isNull()) {
4028 LHSTy = lex->getType();
4029 if (LHSTy->isPromotableIntegerType())
4030 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004031 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004032 *CompLHSTy = LHSTy;
4033 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004034 return PExp->getType();
4035 }
4036 }
4037
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004038 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004039}
4040
Chris Lattnereca7be62008-04-07 05:30:13 +00004041// C99 6.5.6
4042QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004043 SourceLocation Loc, QualType* CompLHSTy) {
4044 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4045 QualType compType = CheckVectorOperands(Loc, lex, rex);
4046 if (CompLHSTy) *CompLHSTy = compType;
4047 return compType;
4048 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004049
Eli Friedmanab3a8522009-03-28 01:22:36 +00004050 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004051
Chris Lattner6e4ab612007-12-09 21:53:25 +00004052 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004053
Chris Lattner6e4ab612007-12-09 21:53:25 +00004054 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004055 if (lex->getType()->isArithmeticType()
4056 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004057 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004058 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004059 }
Steve Naroff14108da2009-07-10 23:34:53 +00004060
Chris Lattner6e4ab612007-12-09 21:53:25 +00004061 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004062 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004063 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004064
Douglas Gregore7450f52009-03-24 19:52:54 +00004065 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004066
Douglas Gregore7450f52009-03-24 19:52:54 +00004067 bool ComplainAboutVoid = false;
4068 Expr *ComplainAboutFunc = 0;
4069 if (lpointee->isVoidType()) {
4070 if (getLangOptions().CPlusPlus) {
4071 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4072 << lex->getSourceRange() << rex->getSourceRange();
4073 return QualType();
4074 }
4075
4076 // GNU C extension: arithmetic on pointer to void
4077 ComplainAboutVoid = true;
4078 } else if (lpointee->isFunctionType()) {
4079 if (getLangOptions().CPlusPlus) {
4080 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004081 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004082 return QualType();
4083 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004084
4085 // GNU C extension: arithmetic on pointer to function
4086 ComplainAboutFunc = lex;
4087 } else if (!lpointee->isDependentType() &&
4088 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004089 PDiag(diag::err_typecheck_sub_ptr_object)
4090 << lex->getSourceRange()
4091 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004092 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004093
Chris Lattnerb5f15622009-04-24 23:50:08 +00004094 // Diagnose bad cases where we step over interface counts.
4095 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4096 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4097 << lpointee << lex->getSourceRange();
4098 return QualType();
4099 }
4100
Chris Lattner6e4ab612007-12-09 21:53:25 +00004101 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004102 if (rex->getType()->isIntegerType()) {
4103 if (ComplainAboutVoid)
4104 Diag(Loc, diag::ext_gnu_void_ptr)
4105 << lex->getSourceRange() << rex->getSourceRange();
4106 if (ComplainAboutFunc)
4107 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4108 << ComplainAboutFunc->getType()
4109 << ComplainAboutFunc->getSourceRange();
4110
Eli Friedmanab3a8522009-03-28 01:22:36 +00004111 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004112 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004113 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004114
Chris Lattner6e4ab612007-12-09 21:53:25 +00004115 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004116 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004117 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004118
Douglas Gregore7450f52009-03-24 19:52:54 +00004119 // RHS must be a completely-type object type.
4120 // Handle the GNU void* extension.
4121 if (rpointee->isVoidType()) {
4122 if (getLangOptions().CPlusPlus) {
4123 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4124 << lex->getSourceRange() << rex->getSourceRange();
4125 return QualType();
4126 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004127
Douglas Gregore7450f52009-03-24 19:52:54 +00004128 ComplainAboutVoid = true;
4129 } else if (rpointee->isFunctionType()) {
4130 if (getLangOptions().CPlusPlus) {
4131 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004132 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004133 return QualType();
4134 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004135
4136 // GNU extension: arithmetic on pointer to function
4137 if (!ComplainAboutFunc)
4138 ComplainAboutFunc = rex;
4139 } else if (!rpointee->isDependentType() &&
4140 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004141 PDiag(diag::err_typecheck_sub_ptr_object)
4142 << rex->getSourceRange()
4143 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004144 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004145
Eli Friedman88d936b2009-05-16 13:54:38 +00004146 if (getLangOptions().CPlusPlus) {
4147 // Pointee types must be the same: C++ [expr.add]
4148 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4149 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4150 << lex->getType() << rex->getType()
4151 << lex->getSourceRange() << rex->getSourceRange();
4152 return QualType();
4153 }
4154 } else {
4155 // Pointee types must be compatible C99 6.5.6p3
4156 if (!Context.typesAreCompatible(
4157 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4158 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4159 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4160 << lex->getType() << rex->getType()
4161 << lex->getSourceRange() << rex->getSourceRange();
4162 return QualType();
4163 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004164 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004165
Douglas Gregore7450f52009-03-24 19:52:54 +00004166 if (ComplainAboutVoid)
4167 Diag(Loc, diag::ext_gnu_void_ptr)
4168 << lex->getSourceRange() << rex->getSourceRange();
4169 if (ComplainAboutFunc)
4170 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4171 << ComplainAboutFunc->getType()
4172 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004173
4174 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004175 return Context.getPointerDiffType();
4176 }
4177 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004178
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004179 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004180}
4181
Chris Lattnereca7be62008-04-07 05:30:13 +00004182// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004183QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004184 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004185 // C99 6.5.7p2: Each of the operands shall have integer type.
4186 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004187 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004188
Chris Lattnerca5eede2007-12-12 05:47:28 +00004189 // Shifts don't perform usual arithmetic conversions, they just do integer
4190 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004191 QualType LHSTy = Context.isPromotableBitField(lex);
4192 if (LHSTy.isNull()) {
4193 LHSTy = lex->getType();
4194 if (LHSTy->isPromotableIntegerType())
4195 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004196 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004197 if (!isCompAssign)
Eli Friedmanab3a8522009-03-28 01:22:36 +00004198 ImpCastExprToType(lex, LHSTy);
4199
Chris Lattnerca5eede2007-12-12 05:47:28 +00004200 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004201
Ryan Flynnd0439682009-08-07 16:20:20 +00004202 // Sanity-check shift operands
4203 llvm::APSInt Right;
4204 // Check right/shifter operand
4205 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004206 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004207 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4208 else {
4209 llvm::APInt LeftBits(Right.getBitWidth(),
4210 Context.getTypeSize(lex->getType()));
4211 if (Right.uge(LeftBits))
4212 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4213 }
4214 }
4215
Chris Lattnerca5eede2007-12-12 05:47:28 +00004216 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004217 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004218}
4219
Douglas Gregor0c6db942009-05-04 06:07:12 +00004220// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004221QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00004222 unsigned OpaqueOpc, bool isRelational) {
4223 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4224
Nate Begemanbe2341d2008-07-14 18:02:46 +00004225 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004226 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004227
Chris Lattnera5937dd2007-08-26 01:18:55 +00004228 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00004229 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4230 UsualArithmeticConversions(lex, rex);
4231 else {
4232 UsualUnaryConversions(lex);
4233 UsualUnaryConversions(rex);
4234 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004235 QualType lType = lex->getType();
4236 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004237
Mike Stumpaf199f32009-05-07 18:43:07 +00004238 if (!lType->isFloatingType()
4239 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00004240 // For non-floating point types, check for self-comparisons of the form
4241 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4242 // often indicate logic errors in the program.
Ted Kremenek9ecede72009-03-20 19:57:37 +00004243 // NOTE: Don't warn about comparisons of enum constants. These can arise
4244 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00004245 Expr *LHSStripped = lex->IgnoreParens();
4246 Expr *RHSStripped = rex->IgnoreParens();
4247 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4248 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00004249 if (DRL->getDecl() == DRR->getDecl() &&
4250 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004251 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner55660a72009-03-08 19:39:53 +00004252
4253 if (isa<CastExpr>(LHSStripped))
4254 LHSStripped = LHSStripped->IgnoreParenCasts();
4255 if (isa<CastExpr>(RHSStripped))
4256 RHSStripped = RHSStripped->IgnoreParenCasts();
4257
4258 // Warn about comparisons against a string constant (unless the other
4259 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00004260 Expr *literalString = 0;
4261 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00004262 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregora86b8322009-04-06 18:45:53 +00004263 !RHSStripped->isNullPointerConstant(Context)) {
4264 literalString = lex;
4265 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004266 } else if ((isa<StringLiteral>(RHSStripped) ||
4267 isa<ObjCEncodeExpr>(RHSStripped)) &&
4268 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004269 literalString = rex;
4270 literalStringStripped = RHSStripped;
4271 }
4272
4273 if (literalString) {
4274 std::string resultComparison;
4275 switch (Opc) {
4276 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4277 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4278 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4279 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4280 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4281 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4282 default: assert(false && "Invalid comparison operator");
4283 }
4284 Diag(Loc, diag::warn_stringcompare)
4285 << isa<ObjCEncodeExpr>(literalStringStripped)
4286 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00004287 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4288 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4289 "strcmp(")
4290 << CodeModificationHint::CreateInsertion(
4291 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00004292 resultComparison);
4293 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00004294 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004295
Douglas Gregor447b69e2008-11-19 03:25:36 +00004296 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00004297 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00004298
Chris Lattnera5937dd2007-08-26 01:18:55 +00004299 if (isRelational) {
4300 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004301 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004302 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004303 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004304 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00004305 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004306 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00004307 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004308
Chris Lattnera5937dd2007-08-26 01:18:55 +00004309 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004310 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004311 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004312
Chris Lattnerd28f8152007-08-26 01:10:14 +00004313 bool LHSIsNull = lex->isNullPointerConstant(Context);
4314 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004315
Chris Lattnera5937dd2007-08-26 01:18:55 +00004316 // All of the following pointer related warnings are GCC extensions, except
4317 // when handling null pointer constants. One day, we can consider making them
4318 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00004319 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00004320 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004321 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00004322 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004323 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004324
Douglas Gregor0c6db942009-05-04 06:07:12 +00004325 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00004326 if (LCanPointeeTy == RCanPointeeTy)
4327 return ResultTy;
4328
Douglas Gregor0c6db942009-05-04 06:07:12 +00004329 // C++ [expr.rel]p2:
4330 // [...] Pointer conversions (4.10) and qualification
4331 // conversions (4.4) are performed on pointer operands (or on
4332 // a pointer operand and a null pointer constant) to bring
4333 // them to their composite pointer type. [...]
4334 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00004335 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00004336 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00004337 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004338 if (T.isNull()) {
4339 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4340 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4341 return QualType();
4342 }
4343
4344 ImpCastExprToType(lex, T);
4345 ImpCastExprToType(rex, T);
4346 return ResultTy;
4347 }
Eli Friedman3075e762009-08-23 00:27:47 +00004348 // C99 6.5.9p2 and C99 6.5.8p2
4349 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4350 RCanPointeeTy.getUnqualifiedType())) {
4351 // Valid unless a relational comparison of function pointers
4352 if (isRelational && LCanPointeeTy->isFunctionType()) {
4353 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4354 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4355 }
4356 } else if (!isRelational &&
4357 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4358 // Valid unless comparison between non-null pointer and function pointer
4359 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4360 && !LHSIsNull && !RHSIsNull) {
4361 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4362 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4363 }
4364 } else {
4365 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004366 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004367 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004368 }
Eli Friedman3075e762009-08-23 00:27:47 +00004369 if (LCanPointeeTy != RCanPointeeTy)
4370 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004371 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004372 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004373
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004374 if (getLangOptions().CPlusPlus) {
Douglas Gregor20b3e992009-08-24 17:42:35 +00004375 // Comparison of pointers with null pointer constants and equality
4376 // comparisons of member pointers to null pointer constants.
4377 if (RHSIsNull &&
4378 (lType->isPointerType() ||
4379 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004380 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004381 return ResultTy;
4382 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004383 if (LHSIsNull &&
4384 (rType->isPointerType() ||
4385 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004386 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004387 return ResultTy;
4388 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004389
4390 // Comparison of member pointers.
4391 if (!isRelational &&
4392 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4393 // C++ [expr.eq]p2:
4394 // In addition, pointers to members can be compared, or a pointer to
4395 // member and a null pointer constant. Pointer to member conversions
4396 // (4.11) and qualification conversions (4.4) are performed to bring
4397 // them to a common type. If one operand is a null pointer constant,
4398 // the common type is the type of the other operand. Otherwise, the
4399 // common type is a pointer to member type similar (4.4) to the type
4400 // of one of the operands, with a cv-qualification signature (4.4)
4401 // that is the union of the cv-qualification signatures of the operand
4402 // types.
4403 QualType T = FindCompositePointerType(lex, rex);
4404 if (T.isNull()) {
4405 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4406 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4407 return QualType();
4408 }
4409
4410 ImpCastExprToType(lex, T);
4411 ImpCastExprToType(rex, T);
4412 return ResultTy;
4413 }
4414
4415 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004416 if (lType->isNullPtrType() && rType->isNullPtrType())
4417 return ResultTy;
4418 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004419
Steve Naroff1c7d0672008-09-04 15:10:53 +00004420 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004421 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004422 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4423 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004424
Steve Naroff1c7d0672008-09-04 15:10:53 +00004425 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00004426 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004427 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00004428 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00004429 }
4430 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004431 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004432 }
Steve Naroff59f53942008-09-28 01:11:11 +00004433 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004434 if (!isRelational
4435 && ((lType->isBlockPointerType() && rType->isPointerType())
4436 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00004437 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004438 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004439 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004440 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004441 ->getPointeeType()->isVoidType())))
4442 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4443 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00004444 }
4445 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004446 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00004447 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004448
Steve Naroff14108da2009-07-10 23:34:53 +00004449 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00004450 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004451 const PointerType *LPT = lType->getAs<PointerType>();
4452 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004453 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004454 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004455 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004456 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004457
Steve Naroffa8069f12008-11-17 19:49:16 +00004458 if (!LPtrToVoid && !RPtrToVoid &&
4459 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004460 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004461 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00004462 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00004463 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004464 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00004465 }
Steve Naroff14108da2009-07-10 23:34:53 +00004466 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004467 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00004468 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4469 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff20373222008-06-03 14:04:54 +00004470 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004471 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00004472 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00004473 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004474 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004475 unsigned DiagID = 0;
4476 if (RHSIsNull) {
4477 if (isRelational)
4478 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4479 } else if (isRelational)
4480 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4481 else
4482 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4483
4484 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004485 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004486 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004487 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00004488 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004489 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004490 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004491 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004492 unsigned DiagID = 0;
4493 if (LHSIsNull) {
4494 if (isRelational)
4495 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4496 } else if (isRelational)
4497 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4498 else
4499 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Chris Lattner6365e3e2009-08-22 18:58:31 +00004500
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004501 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004502 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004503 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004504 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00004505 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004506 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004507 }
Steve Naroff39218df2008-09-04 16:56:14 +00004508 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00004509 if (!isRelational && RHSIsNull
4510 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff39218df2008-09-04 16:56:14 +00004511 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004512 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004513 }
Mike Stumpaf199f32009-05-07 18:43:07 +00004514 if (!isRelational && LHSIsNull
4515 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff39218df2008-09-04 16:56:14 +00004516 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004517 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004518 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004519 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004520}
4521
Nate Begemanbe2341d2008-07-14 18:02:46 +00004522/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00004523/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004524/// like a scalar comparison, a vector comparison produces a vector of integer
4525/// types.
4526QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004527 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004528 bool isRelational) {
4529 // Check to make sure we're operating on vectors of the same type and width,
4530 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004531 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004532 if (vType.isNull())
4533 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004534
Nate Begemanbe2341d2008-07-14 18:02:46 +00004535 QualType lType = lex->getType();
4536 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004537
Nate Begemanbe2341d2008-07-14 18:02:46 +00004538 // For non-floating point types, check for self-comparisons of the form
4539 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4540 // often indicate logic errors in the program.
4541 if (!lType->isFloatingType()) {
4542 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4543 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4544 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004545 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004546 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004547
Nate Begemanbe2341d2008-07-14 18:02:46 +00004548 // Check for comparisons of floating point operands using != and ==.
4549 if (!isRelational && lType->isFloatingType()) {
4550 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004551 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004552 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004553
Nate Begemanbe2341d2008-07-14 18:02:46 +00004554 // Return the type for the comparison, which is the same as vector type for
4555 // integer vectors, or an integer type of identical size and number of
4556 // elements for floating point vectors.
4557 if (lType->isIntegerType())
4558 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004559
Nate Begemanbe2341d2008-07-14 18:02:46 +00004560 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00004561 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00004562 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00004563 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00004564 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00004565 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4566
Mike Stumpeed9cac2009-02-19 03:04:26 +00004567 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00004568 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00004569 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4570}
4571
Reid Spencer5f016e22007-07-11 17:01:13 +00004572inline QualType Sema::CheckBitwiseOperands(
Mike Stumpeed9cac2009-02-19 03:04:26 +00004573 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Reid Spencer5f016e22007-07-11 17:01:13 +00004574{
Steve Naroff3e5e5562007-07-16 22:23:01 +00004575 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004576 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00004577
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004578 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004579
Steve Naroffa4332e22007-07-17 00:58:39 +00004580 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004581 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004582 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004583}
4584
4585inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stumpeed9cac2009-02-19 03:04:26 +00004586 Expr *&lex, Expr *&rex, SourceLocation Loc)
Reid Spencer5f016e22007-07-11 17:01:13 +00004587{
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004588 UsualUnaryConversions(lex);
4589 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004590
Eli Friedman5773a6c2008-05-13 20:16:47 +00004591 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004592 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004593 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004594}
4595
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004596/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4597/// is a read-only property; return true if so. A readonly property expression
4598/// depends on various declarations and thus must be treated specially.
4599///
Mike Stumpeed9cac2009-02-19 03:04:26 +00004600static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004601{
4602 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4603 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4604 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4605 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00004606 if (const ObjCObjectPointerType *OPT =
4607 BaseType->getAsObjCInterfacePointerType())
4608 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4609 if (S.isPropertyReadonly(PDecl, IFace))
4610 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004611 }
4612 }
4613 return false;
4614}
4615
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004616/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4617/// emit an error and return true. If so, return false.
4618static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004619 SourceLocation OrigLoc = Loc;
4620 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4621 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004622 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4623 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004624 if (IsLV == Expr::MLV_Valid)
4625 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004626
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004627 unsigned Diag = 0;
4628 bool NeedType = false;
4629 switch (IsLV) { // C99 6.5.16p2
4630 default: assert(0 && "Unknown result from isModifiableLvalue!");
4631 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004632 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004633 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4634 NeedType = true;
4635 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004636 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004637 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4638 NeedType = true;
4639 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00004640 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004641 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4642 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004643 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004644 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4645 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004646 case Expr::MLV_IncompleteType:
4647 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00004648 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00004649 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4650 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00004651 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004652 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4653 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00004654 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004655 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4656 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00004657 case Expr::MLV_ReadonlyProperty:
4658 Diag = diag::error_readonly_property_assignment;
4659 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00004660 case Expr::MLV_NoSetterProperty:
4661 Diag = diag::error_nosetter_property_assignment;
4662 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004663 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00004664
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004665 SourceRange Assign;
4666 if (Loc != OrigLoc)
4667 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004668 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004669 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004670 else
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004671 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004672 return true;
4673}
4674
4675
4676
4677// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004678QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4679 SourceLocation Loc,
4680 QualType CompoundType) {
4681 // Verify that LHS is a modifiable lvalue, and emit error if not.
4682 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004683 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004684
4685 QualType LHSType = LHS->getType();
4686 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004687
Chris Lattner5cf216b2008-01-04 18:04:52 +00004688 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004689 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00004690 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004691 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004692 // Special case of NSObject attributes on c-style pointer types.
4693 if (ConvTy == IncompatiblePointer &&
4694 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00004695 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004696 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00004697 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004698 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004699
Chris Lattner2c156472008-08-21 18:04:13 +00004700 // If the RHS is a unary plus or minus, check to see if they = and + are
4701 // right next to each other. If so, the user may have typo'd "x =+ 4"
4702 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004703 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00004704 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4705 RHSCheck = ICE->getSubExpr();
4706 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4707 if ((UO->getOpcode() == UnaryOperator::Plus ||
4708 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004709 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00004710 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00004711 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4712 // And there is a space or other character before the subexpr of the
4713 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00004714 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4715 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004716 Diag(Loc, diag::warn_not_compound_assign)
4717 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4718 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00004719 }
Chris Lattner2c156472008-08-21 18:04:13 +00004720 }
4721 } else {
4722 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00004723 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00004724 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004725
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004726 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4727 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004728 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004729
Reid Spencer5f016e22007-07-11 17:01:13 +00004730 // C99 6.5.16p3: The type of an assignment expression is the type of the
4731 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00004732 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00004733 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4734 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004735 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00004736 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004737 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004738}
4739
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004740// C99 6.5.17
4741QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00004742 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004743 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004744
4745 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4746 // incomplete in C++).
4747
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004748 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004749}
4750
Steve Naroff49b45262007-07-13 16:58:59 +00004751/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4752/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004753QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4754 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00004755 if (Op->isTypeDependent())
4756 return Context.DependentTy;
4757
Chris Lattner3528d352008-11-21 07:05:48 +00004758 QualType ResType = Op->getType();
4759 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00004760
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004761 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4762 // Decrement of bool is not allowed.
4763 if (!isInc) {
4764 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4765 return QualType();
4766 }
4767 // Increment of bool sets it to true, but is deprecated.
4768 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4769 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00004770 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004771 } else if (ResType->isAnyPointerType()) {
4772 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00004773
Chris Lattner3528d352008-11-21 07:05:48 +00004774 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00004775 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00004776 if (getLangOptions().CPlusPlus) {
4777 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4778 << Op->getSourceRange();
4779 return QualType();
4780 }
4781
4782 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00004783 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00004784 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00004785 if (getLangOptions().CPlusPlus) {
4786 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4787 << Op->getType() << Op->getSourceRange();
4788 return QualType();
4789 }
4790
4791 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00004792 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00004793 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00004794 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4795 << Op->getSourceRange()
4796 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004797 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00004798 // Diagnose bad cases where we step over interface counts.
4799 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4800 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4801 << PointeeTy << Op->getSourceRange();
4802 return QualType();
4803 }
Chris Lattner3528d352008-11-21 07:05:48 +00004804 } else if (ResType->isComplexType()) {
4805 // C99 does not support ++/-- on complex types, we allow as an extension.
4806 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00004807 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00004808 } else {
4809 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00004810 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00004811 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004812 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004813 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00004814 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00004815 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00004816 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00004817 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004818}
4819
Anders Carlsson369dee42008-02-01 07:15:58 +00004820/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00004821/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004822/// where the declaration is needed for type checking. We only need to
4823/// handle cases when the expression references a function designator
4824/// or is an lvalue. Here are some examples:
4825/// - &(x) => x
4826/// - &*****f => f for f a function designator.
4827/// - &s.xx => s
4828/// - &s.zz[1].yy -> s, if zz is an array
4829/// - *(x + 1) -> x, if x is an array
4830/// - &"123"[2] -> 0
4831/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004832static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00004833 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004834 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00004835 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00004836 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00004837 case Stmt::MemberExprClass:
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00004838 case Stmt::CXXQualifiedMemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00004839 // If this is an arrow operator, the address is an offset from
4840 // the base's value, so the object the base refers to is
4841 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00004842 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00004843 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00004844 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00004845 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00004846 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00004847 // FIXME: This code shouldn't be necessary! We should catch the implicit
4848 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00004849 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4850 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4851 if (ICE->getSubExpr()->getType()->isArrayType())
4852 return getPrimaryDecl(ICE->getSubExpr());
4853 }
4854 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00004855 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004856 case Stmt::UnaryOperatorClass: {
4857 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004858
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004859 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004860 case UnaryOperator::Real:
4861 case UnaryOperator::Imag:
4862 case UnaryOperator::Extension:
4863 return getPrimaryDecl(UO->getSubExpr());
4864 default:
4865 return 0;
4866 }
4867 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004868 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00004869 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00004870 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00004871 // If the result of an implicit cast is an l-value, we care about
4872 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00004873 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00004874 default:
4875 return 0;
4876 }
4877}
4878
4879/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00004880/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00004881/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004882/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00004883/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004884/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00004885/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00004886QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00004887 // Make sure to ignore parentheses in subsequent checks
4888 op = op->IgnoreParens();
4889
Douglas Gregor9103bb22008-12-17 22:52:20 +00004890 if (op->isTypeDependent())
4891 return Context.DependentTy;
4892
Steve Naroff08f19672008-01-13 17:10:08 +00004893 if (getLangOptions().C99) {
4894 // Implement C99-only parts of addressof rules.
4895 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4896 if (uOp->getOpcode() == UnaryOperator::Deref)
4897 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4898 // (assuming the deref expression is valid).
4899 return uOp->getSubExpr()->getType();
4900 }
4901 // Technically, there should be a check for array subscript
4902 // expressions here, but the result of one is always an lvalue anyway.
4903 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004904 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00004905 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00004906
Eli Friedman441cf102009-05-16 23:27:50 +00004907 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4908 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00004909 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00004910 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00004911 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00004912 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4913 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004914 return QualType();
4915 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00004916 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00004917 // The operand cannot be a bit-field
4918 Diag(OpLoc, diag::err_typecheck_address_of)
4919 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00004920 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00004921 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4922 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00004923 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004924 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00004925 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00004926 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00004927 } else if (isa<ObjCPropertyRefExpr>(op)) {
4928 // cannot take address of a property expression.
4929 Diag(OpLoc, diag::err_typecheck_address_of)
4930 << "property expression" << op->getSourceRange();
4931 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00004932 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00004933 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00004934 // with the register storage-class specifier.
4935 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4936 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004937 Diag(OpLoc, diag::err_typecheck_address_of)
4938 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004939 return QualType();
4940 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00004941 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4942 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00004943 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00004944 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00004945 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00004946 // Could be a pointer to member, though, if there is an explicit
4947 // scope qualifier for the class.
4948 if (isa<QualifiedDeclRefExpr>(op)) {
4949 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00004950 if (Ctx && Ctx->isRecord()) {
4951 if (FD->getType()->isReferenceType()) {
4952 Diag(OpLoc,
4953 diag::err_cannot_form_pointer_to_member_of_reference_type)
4954 << FD->getDeclName() << FD->getType();
4955 return QualType();
4956 }
4957
Sebastian Redlebc07d52009-02-03 20:19:35 +00004958 return Context.getMemberPointerType(op->getType(),
4959 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00004960 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00004961 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00004962 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00004963 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00004964 // As above.
Anders Carlsson196f7d02009-05-16 21:43:42 +00004965 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4966 return Context.getMemberPointerType(op->getType(),
4967 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4968 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00004969 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00004970 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00004971
Eli Friedman441cf102009-05-16 23:27:50 +00004972 if (lval == Expr::LV_IncompleteVoidType) {
4973 // Taking the address of a void variable is technically illegal, but we
4974 // allow it in cases which are otherwise valid.
4975 // Example: "extern void x; void* y = &x;".
4976 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4977 }
4978
Reid Spencer5f016e22007-07-11 17:01:13 +00004979 // If the operand has type "type", the result has type "pointer to type".
4980 return Context.getPointerType(op->getType());
4981}
4982
Chris Lattner22caddc2008-11-23 09:13:29 +00004983QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00004984 if (Op->isTypeDependent())
4985 return Context.DependentTy;
4986
Chris Lattner22caddc2008-11-23 09:13:29 +00004987 UsualUnaryConversions(Op);
4988 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004989
Chris Lattner22caddc2008-11-23 09:13:29 +00004990 // Note that per both C89 and C99, this is always legal, even if ptype is an
4991 // incomplete type or void. It would be possible to warn about dereferencing
4992 // a void pointer, but it's completely well-defined, and such a warning is
4993 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00004994 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00004995 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004996
Steve Naroff14108da2009-07-10 23:34:53 +00004997 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
4998 return OPT->getPointeeType();
4999
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005000 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005001 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005002 return QualType();
5003}
5004
5005static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5006 tok::TokenKind Kind) {
5007 BinaryOperator::Opcode Opc;
5008 switch (Kind) {
5009 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005010 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5011 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005012 case tok::star: Opc = BinaryOperator::Mul; break;
5013 case tok::slash: Opc = BinaryOperator::Div; break;
5014 case tok::percent: Opc = BinaryOperator::Rem; break;
5015 case tok::plus: Opc = BinaryOperator::Add; break;
5016 case tok::minus: Opc = BinaryOperator::Sub; break;
5017 case tok::lessless: Opc = BinaryOperator::Shl; break;
5018 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5019 case tok::lessequal: Opc = BinaryOperator::LE; break;
5020 case tok::less: Opc = BinaryOperator::LT; break;
5021 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5022 case tok::greater: Opc = BinaryOperator::GT; break;
5023 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5024 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5025 case tok::amp: Opc = BinaryOperator::And; break;
5026 case tok::caret: Opc = BinaryOperator::Xor; break;
5027 case tok::pipe: Opc = BinaryOperator::Or; break;
5028 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5029 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5030 case tok::equal: Opc = BinaryOperator::Assign; break;
5031 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5032 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5033 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5034 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5035 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5036 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5037 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5038 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5039 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5040 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5041 case tok::comma: Opc = BinaryOperator::Comma; break;
5042 }
5043 return Opc;
5044}
5045
5046static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5047 tok::TokenKind Kind) {
5048 UnaryOperator::Opcode Opc;
5049 switch (Kind) {
5050 default: assert(0 && "Unknown unary op!");
5051 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5052 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5053 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5054 case tok::star: Opc = UnaryOperator::Deref; break;
5055 case tok::plus: Opc = UnaryOperator::Plus; break;
5056 case tok::minus: Opc = UnaryOperator::Minus; break;
5057 case tok::tilde: Opc = UnaryOperator::Not; break;
5058 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005059 case tok::kw___real: Opc = UnaryOperator::Real; break;
5060 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5061 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5062 }
5063 return Opc;
5064}
5065
Douglas Gregoreaebc752008-11-06 23:29:22 +00005066/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5067/// operator @p Opc at location @c TokLoc. This routine only supports
5068/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005069Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5070 unsigned Op,
5071 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005072 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005073 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005074 // The following two variables are used for compound assignment operators
5075 QualType CompLHSTy; // Type of LHS after promotions for computation
5076 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005077
5078 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005079 case BinaryOperator::Assign:
5080 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5081 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005082 case BinaryOperator::PtrMemD:
5083 case BinaryOperator::PtrMemI:
5084 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5085 Opc == BinaryOperator::PtrMemI);
5086 break;
5087 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005088 case BinaryOperator::Div:
5089 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5090 break;
5091 case BinaryOperator::Rem:
5092 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5093 break;
5094 case BinaryOperator::Add:
5095 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5096 break;
5097 case BinaryOperator::Sub:
5098 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5099 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005100 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005101 case BinaryOperator::Shr:
5102 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5103 break;
5104 case BinaryOperator::LE:
5105 case BinaryOperator::LT:
5106 case BinaryOperator::GE:
5107 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005108 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005109 break;
5110 case BinaryOperator::EQ:
5111 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005112 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005113 break;
5114 case BinaryOperator::And:
5115 case BinaryOperator::Xor:
5116 case BinaryOperator::Or:
5117 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5118 break;
5119 case BinaryOperator::LAnd:
5120 case BinaryOperator::LOr:
5121 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5122 break;
5123 case BinaryOperator::MulAssign:
5124 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005125 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5126 CompLHSTy = CompResultTy;
5127 if (!CompResultTy.isNull())
5128 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005129 break;
5130 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005131 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5132 CompLHSTy = CompResultTy;
5133 if (!CompResultTy.isNull())
5134 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005135 break;
5136 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005137 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5138 if (!CompResultTy.isNull())
5139 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005140 break;
5141 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005142 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5143 if (!CompResultTy.isNull())
5144 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005145 break;
5146 case BinaryOperator::ShlAssign:
5147 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005148 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5149 CompLHSTy = CompResultTy;
5150 if (!CompResultTy.isNull())
5151 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005152 break;
5153 case BinaryOperator::AndAssign:
5154 case BinaryOperator::XorAssign:
5155 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005156 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5157 CompLHSTy = CompResultTy;
5158 if (!CompResultTy.isNull())
5159 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005160 break;
5161 case BinaryOperator::Comma:
5162 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5163 break;
5164 }
5165 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005166 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005167 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005168 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5169 else
5170 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005171 CompLHSTy, CompResultTy,
5172 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005173}
5174
Reid Spencer5f016e22007-07-11 17:01:13 +00005175// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005176Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5177 tok::TokenKind Kind,
5178 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005179 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00005180 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00005181
Steve Narofff69936d2007-09-16 03:34:24 +00005182 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5183 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005184
Douglas Gregor063daf62009-03-13 18:40:31 +00005185 if (getLangOptions().CPlusPlus &&
5186 (lhs->getType()->isOverloadableType() ||
5187 rhs->getType()->isOverloadableType())) {
5188 // Find all of the overloaded operators visible from this
5189 // point. We perform both an operator-name lookup from the local
5190 // scope and an argument-dependent lookup based on the types of
5191 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005192 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00005193 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5194 if (OverOp != OO_None) {
5195 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5196 Functions);
5197 Expr *Args[2] = { lhs, rhs };
5198 DeclarationName OpName
5199 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5200 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005201 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005202
Douglas Gregor063daf62009-03-13 18:40:31 +00005203 // Build the (potentially-overloaded, potentially-dependent)
5204 // binary operation.
5205 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005206 }
5207
Douglas Gregoreaebc752008-11-06 23:29:22 +00005208 // Build a built-in binary operation.
5209 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00005210}
5211
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005212Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5213 unsigned OpcIn,
5214 ExprArg InputArg) {
5215 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00005216
Mike Stump390b4cc2009-05-16 07:39:55 +00005217 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005218 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00005219 QualType resultType;
5220 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005221 case UnaryOperator::OffsetOf:
5222 assert(false && "Invalid unary operator");
5223 break;
5224
Reid Spencer5f016e22007-07-11 17:01:13 +00005225 case UnaryOperator::PreInc:
5226 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00005227 case UnaryOperator::PostInc:
5228 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005229 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00005230 Opc == UnaryOperator::PreInc ||
5231 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005232 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005233 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00005234 resultType = CheckAddressOfOperand(Input, OpLoc);
5235 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005236 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00005237 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00005238 resultType = CheckIndirectionOperand(Input, OpLoc);
5239 break;
5240 case UnaryOperator::Plus:
5241 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005242 UsualUnaryConversions(Input);
5243 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005244 if (resultType->isDependentType())
5245 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005246 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5247 break;
5248 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5249 resultType->isEnumeralType())
5250 break;
5251 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5252 Opc == UnaryOperator::Plus &&
5253 resultType->isPointerType())
5254 break;
5255
Sebastian Redl0eb23302009-01-19 00:08:26 +00005256 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5257 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005258 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005259 UsualUnaryConversions(Input);
5260 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005261 if (resultType->isDependentType())
5262 break;
Chris Lattner02a65142008-07-25 23:52:49 +00005263 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5264 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5265 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005266 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005267 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00005268 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005269 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5270 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005271 break;
5272 case UnaryOperator::LNot: // logical negation
5273 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005274 DefaultFunctionArrayConversion(Input);
5275 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005276 if (resultType->isDependentType())
5277 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005278 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00005279 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5280 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005281 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00005282 // In C++, it's bool. C++ 5.3.1p8
5283 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005284 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00005285 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00005286 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00005287 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00005288 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005289 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00005290 resultType = Input->getType();
5291 break;
5292 }
5293 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005294 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005295
5296 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00005297 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005298}
5299
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005300// Unary Operators. 'Tok' is the token for the operator.
5301Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5302 tok::TokenKind Op, ExprArg input) {
5303 Expr *Input = (Expr*)input.get();
5304 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5305
5306 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5307 // Find all of the overloaded operators visible from this
5308 // point. We perform both an operator-name lookup from the local
5309 // scope and an argument-dependent lookup based on the types of
5310 // the arguments.
5311 FunctionSet Functions;
5312 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5313 if (OverOp != OO_None) {
5314 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5315 Functions);
5316 DeclarationName OpName
5317 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5318 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5319 }
5320
5321 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5322 }
5323
5324 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5325}
5326
Steve Naroff1b273c42007-09-16 14:56:35 +00005327/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00005328Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5329 SourceLocation LabLoc,
5330 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005331 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00005332 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00005333
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00005334 // If we haven't seen this label yet, create a forward reference. It
5335 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00005336 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00005337 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005338
Reid Spencer5f016e22007-07-11 17:01:13 +00005339 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00005340 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5341 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00005342}
5343
Sebastian Redlf53597f2009-03-15 17:47:39 +00005344Sema::OwningExprResult
5345Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5346 SourceLocation RPLoc) { // "({..})"
5347 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005348 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5349 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5350
Eli Friedmandca2b732009-01-24 23:09:00 +00005351 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00005352 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005353 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00005354
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005355 // FIXME: there are a variety of strange constraints to enforce here, for
5356 // example, it is not possible to goto into a stmt expression apparently.
5357 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005358
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005359 // If there are sub stmts in the compound stmt, take the type of the last one
5360 // as the type of the stmtexpr.
5361 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005362
Chris Lattner611b2ec2008-07-26 19:51:01 +00005363 if (!Compound->body_empty()) {
5364 Stmt *LastStmt = Compound->body_back();
5365 // If LastStmt is a label, skip down through into the body.
5366 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5367 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005368
Chris Lattner611b2ec2008-07-26 19:51:01 +00005369 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005370 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00005371 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005372
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005373 // FIXME: Check that expression type is complete/non-abstract; statement
5374 // expressions are not lvalues.
5375
Sebastian Redlf53597f2009-03-15 17:47:39 +00005376 substmt.release();
5377 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005378}
Steve Naroffd34e9152007-08-01 22:05:33 +00005379
Sebastian Redlf53597f2009-03-15 17:47:39 +00005380Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5381 SourceLocation BuiltinLoc,
5382 SourceLocation TypeLoc,
5383 TypeTy *argty,
5384 OffsetOfComponent *CompPtr,
5385 unsigned NumComponents,
5386 SourceLocation RPLoc) {
5387 // FIXME: This function leaks all expressions in the offset components on
5388 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005389 // FIXME: Preserve type source info.
5390 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005391 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005392
Sebastian Redl28507842009-02-26 14:39:58 +00005393 bool Dependent = ArgTy->isDependentType();
5394
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005395 // We must have at least one component that refers to the type, and the first
5396 // one is known to be a field designator. Verify that the ArgTy represents
5397 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00005398 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005399 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005400
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005401 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5402 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00005403
Eli Friedman35183ac2009-02-27 06:44:11 +00005404 // Otherwise, create a null pointer as the base, and iteratively process
5405 // the offsetof designators.
5406 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5407 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005408 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00005409 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00005410
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005411 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5412 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00005413 // FIXME: This diagnostic isn't actually visible because the location is in
5414 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005415 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005416 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5417 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005418
Sebastian Redl28507842009-02-26 14:39:58 +00005419 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00005420 bool DidWarnAboutNonPOD = false;
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005421
Sebastian Redl28507842009-02-26 14:39:58 +00005422 // FIXME: Dependent case loses a lot of information here. And probably
5423 // leaks like a sieve.
5424 for (unsigned i = 0; i != NumComponents; ++i) {
5425 const OffsetOfComponent &OC = CompPtr[i];
5426 if (OC.isBrackets) {
5427 // Offset of an array sub-field. TODO: Should we allow vector elements?
5428 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5429 if (!AT) {
5430 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005431 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5432 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005433 }
5434
5435 // FIXME: C++: Verify that operator[] isn't overloaded.
5436
Eli Friedman35183ac2009-02-27 06:44:11 +00005437 // Promote the array so it looks more like a normal array subscript
5438 // expression.
5439 DefaultFunctionArrayConversion(Res);
5440
Sebastian Redl28507842009-02-26 14:39:58 +00005441 // C99 6.5.2.1p1
5442 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005443 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005444 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005445 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00005446 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005447 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00005448
5449 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5450 OC.LocEnd);
5451 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005452 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005453
Ted Kremenek6217b802009-07-29 21:53:49 +00005454 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00005455 if (!RC) {
5456 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005457 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5458 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005459 }
Chris Lattner704fe352007-08-30 17:59:59 +00005460
Sebastian Redl28507842009-02-26 14:39:58 +00005461 // Get the decl corresponding to this.
5462 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005463 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005464 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00005465 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5466 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5467 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005468 DidWarnAboutNonPOD = true;
5469 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005470 }
5471
Sebastian Redl28507842009-02-26 14:39:58 +00005472 FieldDecl *MemberDecl
5473 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5474 LookupMemberName)
5475 .getAsDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +00005476 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005477 if (!MemberDecl)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005478 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5479 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00005480
Sebastian Redl28507842009-02-26 14:39:58 +00005481 // FIXME: C++: Verify that MemberDecl isn't a static field.
5482 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00005483 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005484 Res = BuildAnonymousStructUnionMemberReference(
5485 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00005486 } else {
5487 // MemberDecl->getType() doesn't get the right qualifiers, but it
5488 // doesn't matter here.
5489 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5490 MemberDecl->getType().getNonReferenceType());
5491 }
Sebastian Redl28507842009-02-26 14:39:58 +00005492 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005493 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005494
Sebastian Redlf53597f2009-03-15 17:47:39 +00005495 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5496 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005497}
5498
5499
Sebastian Redlf53597f2009-03-15 17:47:39 +00005500Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5501 TypeTy *arg1,TypeTy *arg2,
5502 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005503 // FIXME: Preserve type source info.
5504 QualType argT1 = GetTypeFromParser(arg1);
5505 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005506
Steve Naroffd34e9152007-08-01 22:05:33 +00005507 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005508
Douglas Gregorc12a9c52009-05-19 22:28:02 +00005509 if (getLangOptions().CPlusPlus) {
5510 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5511 << SourceRange(BuiltinLoc, RPLoc);
5512 return ExprError();
5513 }
5514
Sebastian Redlf53597f2009-03-15 17:47:39 +00005515 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5516 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00005517}
5518
Sebastian Redlf53597f2009-03-15 17:47:39 +00005519Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5520 ExprArg cond,
5521 ExprArg expr1, ExprArg expr2,
5522 SourceLocation RPLoc) {
5523 Expr *CondExpr = static_cast<Expr*>(cond.get());
5524 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5525 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005526
Steve Naroffd04fdd52007-08-03 21:21:27 +00005527 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5528
Sebastian Redl28507842009-02-26 14:39:58 +00005529 QualType resType;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00005530 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00005531 resType = Context.DependentTy;
5532 } else {
5533 // The conditional expression is required to be a constant expression.
5534 llvm::APSInt condEval(32);
5535 SourceLocation ExpLoc;
5536 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00005537 return ExprError(Diag(ExpLoc,
5538 diag::err_typecheck_choose_expr_requires_constant)
5539 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00005540
Sebastian Redl28507842009-02-26 14:39:58 +00005541 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5542 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5543 }
5544
Sebastian Redlf53597f2009-03-15 17:47:39 +00005545 cond.release(); expr1.release(); expr2.release();
5546 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5547 resType, RPLoc));
Steve Naroffd04fdd52007-08-03 21:21:27 +00005548}
5549
Steve Naroff4eb206b2008-09-03 18:15:37 +00005550//===----------------------------------------------------------------------===//
5551// Clang Extensions.
5552//===----------------------------------------------------------------------===//
5553
5554/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00005555void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005556 // Analyze block parameters.
5557 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005558
Steve Naroff4eb206b2008-09-03 18:15:37 +00005559 // Add BSI to CurBlock.
5560 BSI->PrevBlockInfo = CurBlock;
5561 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005562
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005563 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005564 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00005565 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00005566 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00005567 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5568 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005569
Steve Naroff090276f2008-10-10 01:28:17 +00005570 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00005571 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00005572}
5573
Mike Stump98eb8a72009-02-04 22:31:32 +00005574void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00005575 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00005576
5577 if (ParamInfo.getNumTypeObjects() == 0
5578 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005579 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00005580 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5581
Mike Stump4eeab842009-04-28 01:10:27 +00005582 if (T->isArrayType()) {
5583 Diag(ParamInfo.getSourceRange().getBegin(),
5584 diag::err_block_returns_array);
5585 return;
5586 }
5587
Mike Stump98eb8a72009-02-04 22:31:32 +00005588 // The parameter list is optional, if there was none, assume ().
5589 if (!T->isFunctionType())
5590 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5591
5592 CurBlock->hasPrototype = true;
5593 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005594 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005595 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005596 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00005597 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005598 // FIXME: remove the attribute.
5599 }
Chris Lattner9097af12009-04-11 19:27:54 +00005600 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5601
5602 // Do not allow returning a objc interface by-value.
5603 if (RetTy->isObjCInterfaceType()) {
5604 Diag(ParamInfo.getSourceRange().getBegin(),
5605 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5606 return;
5607 }
Mike Stump98eb8a72009-02-04 22:31:32 +00005608 return;
5609 }
5610
Steve Naroff4eb206b2008-09-03 18:15:37 +00005611 // Analyze arguments to block.
5612 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5613 "Not a function declarator!");
5614 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005615
Steve Naroff090276f2008-10-10 01:28:17 +00005616 CurBlock->hasPrototype = FTI.hasPrototype;
5617 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005618
Steve Naroff4eb206b2008-09-03 18:15:37 +00005619 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5620 // no arguments, not a function that takes a single void argument.
5621 if (FTI.hasPrototype &&
5622 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00005623 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5624 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005625 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00005626 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005627 } else if (FTI.hasPrototype) {
5628 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00005629 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00005630 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005631 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00005632 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00005633 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00005634 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005635 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00005636 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5637 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5638 // If this has an identifier, add it to the scope stack.
5639 if ((*AI)->getIdentifier())
5640 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00005641
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005642 // Check for a valid sentinel attribute on this block.
Douglas Gregor68584ed2009-06-18 16:11:24 +00005643 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005644 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005645 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00005646 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005647 // FIXME: remove the attribute.
5648 }
5649
Chris Lattner9097af12009-04-11 19:27:54 +00005650 // Analyze the return type.
5651 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5652 QualType RetTy = T->getAsFunctionType()->getResultType();
5653
5654 // Do not allow returning a objc interface by-value.
5655 if (RetTy->isObjCInterfaceType()) {
5656 Diag(ParamInfo.getSourceRange().getBegin(),
5657 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5658 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005659 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005660}
5661
5662/// ActOnBlockError - If there is an error parsing a block, this callback
5663/// is invoked to pop the information about the block from the action impl.
5664void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5665 // Ensure that CurBlock is deleted.
5666 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005667
Chris Lattner17a78302009-04-19 05:28:12 +00005668 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5669
Steve Naroff4eb206b2008-09-03 18:15:37 +00005670 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00005671 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005672 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005673 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00005674}
5675
5676/// ActOnBlockStmtExpr - This is called when the body of a block statement
5677/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00005678Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5679 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00005680 // If blocks are disabled, emit an error.
5681 if (!LangOpts.Blocks)
5682 Diag(CaretLoc, diag::err_blocks_disable);
5683
Steve Naroff4eb206b2008-09-03 18:15:37 +00005684 // Ensure that CurBlock is deleted.
5685 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00005686
Steve Naroff090276f2008-10-10 01:28:17 +00005687 PopDeclContext();
5688
Steve Naroff4eb206b2008-09-03 18:15:37 +00005689 // Pop off CurBlock, handle nested blocks.
5690 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005691
Steve Naroff4eb206b2008-09-03 18:15:37 +00005692 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005693 if (!BSI->ReturnType.isNull())
5694 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005695
Steve Naroff4eb206b2008-09-03 18:15:37 +00005696 llvm::SmallVector<QualType, 8> ArgTypes;
5697 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5698 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005699
Mike Stump56925862009-07-28 22:04:01 +00005700 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005701 QualType BlockTy;
5702 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00005703 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5704 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00005705 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00005706 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00005707 BSI->isVariadic, 0, false, false, 0, 0,
5708 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005709
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005710 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00005711 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00005712 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005713
Chris Lattner17a78302009-04-19 05:28:12 +00005714 // If needed, diagnose invalid gotos and switches in the block.
5715 if (CurFunctionNeedsScopeChecking)
5716 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5717 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5718
Anders Carlssone9146f22009-05-01 19:49:17 +00005719 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00005720 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00005721 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5722 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00005723}
5724
Sebastian Redlf53597f2009-03-15 17:47:39 +00005725Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5726 ExprArg expr, TypeTy *type,
5727 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005728 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00005729 Expr *E = static_cast<Expr*>(expr.get());
5730 Expr *OrigExpr = E;
5731
Anders Carlsson7c50aca2007-10-15 20:28:48 +00005732 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00005733
5734 // Get the va_list type
5735 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00005736 if (VaListType->isArrayType()) {
5737 // Deal with implicit array decay; for example, on x86-64,
5738 // va_list is an array, but it's supposed to decay to
5739 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00005740 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00005741 // Make sure the input expression also decays appropriately.
5742 UsualUnaryConversions(E);
5743 } else {
5744 // Otherwise, the va_list argument must be an l-value because
5745 // it is modified by va_arg.
Douglas Gregordd027302009-05-19 23:10:31 +00005746 if (!E->isTypeDependent() &&
5747 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00005748 return ExprError();
5749 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00005750
Douglas Gregordd027302009-05-19 23:10:31 +00005751 if (!E->isTypeDependent() &&
5752 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00005753 return ExprError(Diag(E->getLocStart(),
5754 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00005755 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00005756 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005757
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005758 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00005759 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005760
Sebastian Redlf53597f2009-03-15 17:47:39 +00005761 expr.release();
5762 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5763 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00005764}
5765
Sebastian Redlf53597f2009-03-15 17:47:39 +00005766Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00005767 // The type of __null will be int or long, depending on the size of
5768 // pointers on the target.
5769 QualType Ty;
5770 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5771 Ty = Context.IntTy;
5772 else
5773 Ty = Context.LongTy;
5774
Sebastian Redlf53597f2009-03-15 17:47:39 +00005775 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00005776}
5777
Chris Lattner5cf216b2008-01-04 18:04:52 +00005778bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5779 SourceLocation Loc,
5780 QualType DstType, QualType SrcType,
5781 Expr *SrcExpr, const char *Flavor) {
5782 // Decode the result (notice that AST's are still created for extensions).
5783 bool isInvalid = false;
5784 unsigned DiagKind;
5785 switch (ConvTy) {
5786 default: assert(0 && "Unknown conversion type");
5787 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005788 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00005789 DiagKind = diag::ext_typecheck_convert_pointer_int;
5790 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005791 case IntToPointer:
5792 DiagKind = diag::ext_typecheck_convert_int_pointer;
5793 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005794 case IncompatiblePointer:
5795 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5796 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005797 case IncompatiblePointerSign:
5798 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5799 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005800 case FunctionVoidPointer:
5801 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5802 break;
5803 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00005804 // If the qualifiers lost were because we were applying the
5805 // (deprecated) C++ conversion from a string literal to a char*
5806 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5807 // Ideally, this check would be performed in
5808 // CheckPointerTypesForAssignment. However, that would require a
5809 // bit of refactoring (so that the second argument is an
5810 // expression, rather than a type), which should be done as part
5811 // of a larger effort to fix CheckPointerTypesForAssignment for
5812 // C++ semantics.
5813 if (getLangOptions().CPlusPlus &&
5814 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5815 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005816 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5817 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005818 case IntToBlockPointer:
5819 DiagKind = diag::err_int_to_block_pointer;
5820 break;
5821 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00005822 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005823 break;
Steve Naroff39579072008-10-14 22:18:38 +00005824 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00005825 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00005826 // it can give a more specific diagnostic.
5827 DiagKind = diag::warn_incompatible_qualified_id;
5828 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005829 case IncompatibleVectors:
5830 DiagKind = diag::warn_incompatible_vectors;
5831 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005832 case Incompatible:
5833 DiagKind = diag::err_typecheck_convert_incompatible;
5834 isInvalid = true;
5835 break;
5836 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005837
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005838 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5839 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00005840 return isInvalid;
5841}
Anders Carlssone21555e2008-11-30 19:50:32 +00005842
Chris Lattner3bf68932009-04-25 21:59:05 +00005843bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00005844 llvm::APSInt ICEResult;
5845 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5846 if (Result)
5847 *Result = ICEResult;
5848 return false;
5849 }
5850
Anders Carlssone21555e2008-11-30 19:50:32 +00005851 Expr::EvalResult EvalResult;
5852
Mike Stumpeed9cac2009-02-19 03:04:26 +00005853 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00005854 EvalResult.HasSideEffects) {
5855 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5856
5857 if (EvalResult.Diag) {
5858 // We only show the note if it's not the usual "invalid subexpression"
5859 // or if it's actually in a subexpression.
5860 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5861 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5862 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5863 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005864
Anders Carlssone21555e2008-11-30 19:50:32 +00005865 return true;
5866 }
5867
Eli Friedman3b5ccca2009-04-25 22:26:58 +00005868 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5869 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00005870
Eli Friedman3b5ccca2009-04-25 22:26:58 +00005871 if (EvalResult.Diag &&
5872 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5873 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005874
Anders Carlssone21555e2008-11-30 19:50:32 +00005875 if (Result)
5876 *Result = EvalResult.Val.getInt();
5877 return false;
5878}
Douglas Gregore0762c92009-06-19 23:52:42 +00005879
Douglas Gregorac7610d2009-06-22 20:57:11 +00005880Sema::ExpressionEvaluationContext
5881Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5882 // Introduce a new set of potentially referenced declarations to the stack.
5883 if (NewContext == PotentiallyPotentiallyEvaluated)
5884 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5885
5886 std::swap(ExprEvalContext, NewContext);
5887 return NewContext;
5888}
5889
5890void
5891Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5892 ExpressionEvaluationContext NewContext) {
5893 ExprEvalContext = NewContext;
5894
5895 if (OldContext == PotentiallyPotentiallyEvaluated) {
5896 // Mark any remaining declarations in the current position of the stack
5897 // as "referenced". If they were not meant to be referenced, semantic
5898 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5899 PotentiallyReferencedDecls RemainingDecls;
5900 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5901 PotentiallyReferencedDeclStack.pop_back();
5902
5903 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5904 IEnd = RemainingDecls.end();
5905 I != IEnd; ++I)
5906 MarkDeclarationReferenced(I->first, I->second);
5907 }
5908}
Douglas Gregore0762c92009-06-19 23:52:42 +00005909
5910/// \brief Note that the given declaration was referenced in the source code.
5911///
5912/// This routine should be invoke whenever a given declaration is referenced
5913/// in the source code, and where that reference occurred. If this declaration
5914/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5915/// C99 6.9p3), then the declaration will be marked as used.
5916///
5917/// \param Loc the location where the declaration was referenced.
5918///
5919/// \param D the declaration that has been referenced by the source code.
5920void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5921 assert(D && "No declaration?");
5922
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005923 if (D->isUsed())
5924 return;
5925
Douglas Gregore0762c92009-06-19 23:52:42 +00005926 // Mark a parameter declaration "used", regardless of whether we're in a
5927 // template or not.
5928 if (isa<ParmVarDecl>(D))
5929 D->setUsed(true);
5930
5931 // Do not mark anything as "used" within a dependent context; wait for
5932 // an instantiation.
5933 if (CurContext->isDependentContext())
5934 return;
5935
Douglas Gregorac7610d2009-06-22 20:57:11 +00005936 switch (ExprEvalContext) {
5937 case Unevaluated:
5938 // We are in an expression that is not potentially evaluated; do nothing.
5939 return;
5940
5941 case PotentiallyEvaluated:
5942 // We are in a potentially-evaluated expression, so this declaration is
5943 // "used"; handle this below.
5944 break;
5945
5946 case PotentiallyPotentiallyEvaluated:
5947 // We are in an expression that may be potentially evaluated; queue this
5948 // declaration reference until we know whether the expression is
5949 // potentially evaluated.
5950 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5951 return;
5952 }
5953
Douglas Gregore0762c92009-06-19 23:52:42 +00005954 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00005955 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005956 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00005957 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5958 if (!Constructor->isUsed())
5959 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005960 } else if (Constructor->isImplicit() &&
5961 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00005962 if (!Constructor->isUsed())
5963 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5964 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00005965 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5966 if (Destructor->isImplicit() && !Destructor->isUsed())
5967 DefineImplicitDestructor(Loc, Destructor);
5968
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00005969 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5970 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5971 MethodDecl->getOverloadedOperator() == OO_Equal) {
5972 if (!MethodDecl->isUsed())
5973 DefineImplicitOverloadedAssign(Loc, MethodDecl);
5974 }
5975 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00005976 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +00005977 // Implicit instantiation of function templates and member functions of
5978 // class templates.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005979 if (!Function->getBody()) {
Douglas Gregor1637be72009-06-26 00:10:03 +00005980 // FIXME: distinguish between implicit instantiations of function
5981 // templates and explicit specializations (the latter don't get
5982 // instantiated, naturally).
5983 if (Function->getInstantiatedFromMemberFunction() ||
5984 Function->getPrimaryTemplate())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00005985 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005986 }
5987
5988
Douglas Gregore0762c92009-06-19 23:52:42 +00005989 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00005990 Function->setUsed(true);
5991 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00005992 }
Douglas Gregore0762c92009-06-19 23:52:42 +00005993
5994 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00005995 // Implicit instantiation of static data members of class templates.
5996 // FIXME: distinguish between implicit instantiations (which we need to
5997 // actually instantiate) and explicit specializations.
5998 if (Var->isStaticDataMember() &&
5999 Var->getInstantiatedFromStaticDataMember())
6000 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6001
Douglas Gregore0762c92009-06-19 23:52:42 +00006002 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006003
Douglas Gregore0762c92009-06-19 23:52:42 +00006004 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006005 return;
6006}
Douglas Gregore0762c92009-06-19 23:52:42 +00006007}
6008