blob: 723d6d7dfadc6bf6a1e2c130e7bded257641e842 [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;
Mike Stump1eb44332009-09-09 15:08:12 +000049
Chris Lattnerf15970c2009-02-16 19:35:30 +000050 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>();
Mike Stump1eb44332009-09-09 15:08:12 +000054
Chris Lattnerf15970c2009-02-16 19:35:30 +000055 // 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())) {
Mike Stump1eb44332009-09-09 15:08:12 +000062
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 }
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattnerf15970c2009-02-16 19:35:30 +000070 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
Mike Stump1eb44332009-09-09 15:08:12 +000093/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000094/// attribute. It warns if call does not have the sentinel argument.
95///
96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +000097 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000099 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000100 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000101 int sentinelPos = attr->getSentinel();
102 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +0000103
Mike Stump390b4cc2009-05-16 07:39:55 +0000104 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000106 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000107 bool warnNotEnoughArgs = false;
108 int isMethod = 0;
109 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = MD->param_end();
112 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
119 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000120 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000121 // skip over named parameters.
122 ObjCMethodDecl::param_iterator P, E = FD->param_end();
123 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124 if (nullPos)
125 --nullPos;
126 else
127 ++i;
128 }
129 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000130 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000131 // block or function pointer call.
132 QualType Ty = V->getType();
133 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000134 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenek6217b802009-07-29 21:53:49 +0000135 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
136 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000137 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138 unsigned NumArgsInProto = Proto->getNumArgs();
139 unsigned k;
140 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141 if (nullPos)
142 --nullPos;
143 else
144 ++i;
145 }
146 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147 }
148 if (Ty->isBlockPointerType())
149 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000150 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000151 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000152 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000153 return;
154
155 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000158 return;
159 }
160 int sentinel = i;
161 while (sentinelPos > 0 && i < NumArgs-1) {
162 --sentinelPos;
163 ++i;
164 }
165 if (sentinelPos > 0) {
166 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000167 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000168 return;
169 }
170 while (i < NumArgs-1) {
171 ++i;
172 ++sentinel;
173 }
174 Expr *sentinelExpr = Args[sentinel];
175 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
176 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000177 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000178 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000179 }
180 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000181}
182
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000183SourceRange Sema::getExprRange(ExprTy *E) const {
184 Expr *Ex = (Expr *)E;
185 return Ex? Ex->getSourceRange() : SourceRange();
186}
187
Chris Lattnere7a2e912008-07-25 21:10:04 +0000188//===----------------------------------------------------------------------===//
189// Standard Promotions and Conversions
190//===----------------------------------------------------------------------===//
191
Chris Lattnere7a2e912008-07-25 21:10:04 +0000192/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
193void Sema::DefaultFunctionArrayConversion(Expr *&E) {
194 QualType Ty = E->getType();
195 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
196
Chris Lattnere7a2e912008-07-25 21:10:04 +0000197 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000198 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000199 CastExpr::CK_FunctionToPointerDecay);
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
Mike Stump1eb44332009-09-09 15:08:12 +0000220/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000221/// 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");
Mike Stump1eb44332009-09-09 15:08:12 +0000227
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
Mike Stump1eb44332009-09-09 15:08:12 +0000257/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000258/// 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");
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Chris Lattner05faf172008-07-25 22:25:12 +0000263 // 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);
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattner05faf172008-07-25 22:25:12 +0000268 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);
Mike Stump1eb44332009-09-09 15:08:12 +0000277
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 }
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Chris Lattner312531a2009-04-12 08:11:20 +0000285 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
Mike Stump1eb44332009-09-09 15:08:12 +0000295/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000296/// 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
Mike Stump1eb44332009-09-09 15:08:12 +0000306 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000307 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000308 QualType lhs =
309 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000310 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000311 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);
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000376 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000377 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;
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner639e2d32008-10-20 05:16:36 +0000398 // 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;
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000409 // 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;
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000423 // Otherwise, the DeclRef from the inner block causes the outer one to need
424 // a snapshot as well.
425 NextBlock->hasBlockDeclRefExprs = true;
426 }
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Chris Lattner639e2d32008-10-20 05:16:36 +0000428 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000429}
430
Chris Lattner639e2d32008-10-20 05:16:36 +0000431
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,
Mike Stump1eb44332009-09-09 15:08:12 +0000456 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000457 << D->getDeclName();
458 return ExprError();
459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Anders Carlssone41590d2009-06-24 00:10:43 +0000461 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) {
Mike Stump1eb44332009-09-09 15:08:12 +0000465 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000466 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000467 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000468 << D->getIdentifier();
469 return ExprError();
470 }
471 }
472 }
473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Douglas Gregore0762c92009-06-19 23:52:42 +0000475 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Anders Carlssone41590d2009-06-24 00:10:43 +0000477 Expr *E;
Douglas Gregorbad35182009-03-19 03:51:16 +0000478 if (SS && !SS->isEmpty()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000479 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
Anders Carlssone41590d2009-06-24 00:10:43 +0000480 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);
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Anders Carlssone41590d2009-06-24 00:10:43 +0000485 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) {
Mike Stump1eb44332009-09-09 15:08:12 +0000493 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000494 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000495
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();
Mike Stump1eb44332009-09-09 15:08:12 +0000500 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000501 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();
Mike Stump1eb44332009-09-09 15:08:12 +0000549 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000550 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;
Mike Stump1eb44332009-09-09 15:08:12 +0000561 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000562 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());
Mike Stump1eb44332009-09-09 15:08:12 +0000577 ExtraQuals
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000578 = 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()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000595 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000596 = Context.getTagDeclType(
597 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
598 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000599 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000600 == 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
Mike Stump1eb44332009-09-09 15:08:12 +0000614 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()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000628 unsigned combinedQualifiers
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000629 = 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,
Mike Stump1eb44332009-09-09 15:08:12 +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,
Mike Stump1eb44332009-09-09 15:08:12 +0000680 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 }
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner5cb10d32009-04-24 22:30:50 +0000695 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
Mike Stump1eb44332009-09-09 15:08:12 +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
Fariborz Jahanian077c1e72009-03-02 21:55:29 +0000705 // 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();
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattner5cb10d32009-04-24 22:30:50 +0000714 // 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();
Mike Stump1eb44332009-09-09 15:08:12 +0000718
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);
Mike Stump1eb44332009-09-09 15:08:12 +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;
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Steve Naroffdd53eb52009-03-05 20:12:00 +0000756 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.
Mike Stump1eb44332009-09-09 15:08:12 +0000767 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000768 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.
Anders Carlssonf4d84b62009-08-30 00:54:35 +0000792 if (SS && !SS->isEmpty()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000793 DiagnoseMissingMember(Loc, Name,
Anders Carlssonf4d84b62009-08-30 00:54:35 +0000794 (NestedNameSpecifier *)SS->getScopeRep(),
795 SS->getRange());
796 return ExprError();
797 } else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregor10c42622008-11-18 15:03:34 +0000798 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000799 return ExprError(Diag(Loc, diag::err_undeclared_use)
800 << Name.getAsString());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000801 else
Sebastian Redlcd965b92009-01-18 18:53:16 +0000802 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +0000803 }
804 }
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Douglas Gregor751f9a42009-06-30 15:47:41 +0000806 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
807 // Warn about constructs like:
808 // if (void *X = foo()) { ... } else { X }.
809 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Douglas Gregor751f9a42009-06-30 15:47:41 +0000811 // FIXME: In a template instantiation, we don't have scope
812 // information to check this property.
813 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
814 Scope *CheckS = S;
815 while (CheckS) {
Mike Stump1eb44332009-09-09 15:08:12 +0000816 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +0000817 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
818 if (Var->getType()->isBooleanType())
819 ExprError(Diag(Loc, diag::warn_value_always_false)
820 << Var->getDeclName());
821 else
822 ExprError(Diag(Loc, diag::warn_value_always_zero)
823 << Var->getDeclName());
824 break;
825 }
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Douglas Gregor751f9a42009-06-30 15:47:41 +0000827 // Move up one more control parent to check again.
828 CheckS = CheckS->getControlParent();
829 if (CheckS)
830 CheckS = CheckS->getParent();
831 }
832 }
833 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
834 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
835 // C99 DR 316 says that, if a function type comes from a
836 // function definition (without a prototype), that type is only
837 // used for checking compatibility. Therefore, when referencing
838 // the function, we pretend that we don't have the full function
839 // type.
840 if (DiagnoseUseOfDecl(Func, Loc))
841 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000842
Douglas Gregor751f9a42009-06-30 15:47:41 +0000843 QualType T = Func->getType();
844 QualType NoProtoType = T;
845 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
846 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
847 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
848 }
849 }
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Douglas Gregor751f9a42009-06-30 15:47:41 +0000851 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
852}
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000853/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000854bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000855Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
856 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +0000857 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000858 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000859 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000860 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000861 if (DestType->isDependentType() || From->getType()->isDependentType())
862 return false;
863 QualType FromRecordType = From->getType();
864 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +0000865 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000866 DestType = Context.getPointerType(DestType);
867 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000868 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +0000869 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
870 CheckDerivedToBaseConversion(FromRecordType,
871 DestRecordType,
872 From->getSourceRange().getBegin(),
873 From->getSourceRange()))
874 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +0000875 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
876 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000877 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +0000878 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +0000879}
Douglas Gregor751f9a42009-06-30 15:47:41 +0000880
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000881/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +0000882static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
883 const CXXScopeSpec *SS, NamedDecl *Member,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000884 SourceLocation Loc, QualType Ty) {
885 if (SS && SS->isSet())
Mike Stump1eb44332009-09-09 15:08:12 +0000886 return MemberExpr::Create(C, Base, isArrow,
Douglas Gregor83f6faf2009-08-31 23:41:50 +0000887 (NestedNameSpecifier *)SS->getScopeRep(),
Mike Stump1eb44332009-09-09 15:08:12 +0000888 SS->getRange(), Member, Loc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +0000889 // FIXME: Explicit template argument lists
890 false, SourceLocation(), 0, 0, SourceLocation(),
891 Ty);
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000893 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
894}
895
Douglas Gregor751f9a42009-06-30 15:47:41 +0000896/// \brief Complete semantic analysis for a reference to the given declaration.
897Sema::OwningExprResult
898Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
899 bool HasTrailingLParen,
Mike Stump1eb44332009-09-09 15:08:12 +0000900 const CXXScopeSpec *SS,
Douglas Gregor751f9a42009-06-30 15:47:41 +0000901 bool isAddressOfOperand) {
902 assert(D && "Cannot refer to a NULL declaration");
903 DeclarationName Name = D->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Sebastian Redlebc07d52009-02-03 20:19:35 +0000905 // If this is an expression of the form &Class::member, don't build an
906 // implicit member ref, because we want a pointer to the member in general,
907 // not any specific instance's member.
908 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregore4e5b052009-03-19 00:18:19 +0000909 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000910 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redlebc07d52009-02-03 20:19:35 +0000911 QualType DType;
912 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
913 DType = FD->getType().getNonReferenceType();
914 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
915 DType = Method->getType();
916 } else if (isa<OverloadedFunctionDecl>(D)) {
917 DType = Context.OverloadTy;
918 }
919 // Could be an inner type. That's diagnosed below, so ignore it here.
920 if (!DType.isNull()) {
921 // The pointer is type- and value-dependent if it points into something
922 // dependent.
Douglas Gregor00c44862009-05-29 14:49:33 +0000923 bool Dependent = DC->isDependentContext();
Anders Carlssone41590d2009-06-24 00:10:43 +0000924 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redlebc07d52009-02-03 20:19:35 +0000925 }
926 }
927 }
928
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000929 // We may have found a field within an anonymous union or struct
930 // (C++ [class.union]).
931 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
932 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
933 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +0000934
Douglas Gregor88a35142008-12-22 05:46:06 +0000935 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
936 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000937 // C++ [class.mfct.nonstatic]p2:
Douglas Gregor88a35142008-12-22 05:46:06 +0000938 // [...] if name lookup (3.4.1) resolves the name in the
939 // id-expression to a nonstatic nontype member of class X or of
940 // a base class of X, the id-expression is transformed into a
941 // class member access expression (5.2.5) using (*this) (9.3.2)
942 // as the postfix-expression to the left of the '.' operator.
943 DeclContext *Ctx = 0;
944 QualType MemberType;
945 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
946 Ctx = FD->getDeclContext();
947 MemberType = FD->getType();
948
Ted Kremenek6217b802009-07-29 21:53:49 +0000949 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor88a35142008-12-22 05:46:06 +0000950 MemberType = RefType->getPointeeType();
951 else if (!FD->isMutable()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000952 unsigned combinedQualifiers
Douglas Gregor88a35142008-12-22 05:46:06 +0000953 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
954 MemberType = MemberType.getQualifiedType(combinedQualifiers);
955 }
956 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
957 if (!Method->isStatic()) {
958 Ctx = Method->getParent();
959 MemberType = Method->getType();
960 }
Mike Stump1eb44332009-09-09 15:08:12 +0000961 } else if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6b906862009-08-21 00:16:32 +0000962 = dyn_cast<FunctionTemplateDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000963 if (CXXMethodDecl *Method
Douglas Gregor6b906862009-08-21 00:16:32 +0000964 = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000965 if (!Method->isStatic()) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000966 Ctx = Method->getParent();
967 MemberType = Context.OverloadTy;
968 }
969 }
Mike Stump1eb44332009-09-09 15:08:12 +0000970 } else if (OverloadedFunctionDecl *Ovl
Douglas Gregor88a35142008-12-22 05:46:06 +0000971 = dyn_cast<OverloadedFunctionDecl>(D)) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000972 // FIXME: We need an abstraction for iterating over one or more function
973 // templates or functions. This code is far too repetitive!
Mike Stump1eb44332009-09-09 15:08:12 +0000974 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor88a35142008-12-22 05:46:06 +0000975 Func = Ovl->function_begin(),
976 FuncEnd = Ovl->function_end();
977 Func != FuncEnd; ++Func) {
Douglas Gregor6b906862009-08-21 00:16:32 +0000978 CXXMethodDecl *DMethod = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000979 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6b906862009-08-21 00:16:32 +0000980 = dyn_cast<FunctionTemplateDecl>(*Func))
981 DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
982 else
983 DMethod = dyn_cast<CXXMethodDecl>(*Func);
984
985 if (DMethod && !DMethod->isStatic()) {
986 Ctx = DMethod->getDeclContext();
987 MemberType = Context.OverloadTy;
988 break;
989 }
Douglas Gregor88a35142008-12-22 05:46:06 +0000990 }
991 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000992
993 if (Ctx && Ctx->isRecord()) {
Douglas Gregor88a35142008-12-22 05:46:06 +0000994 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
995 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000996 if ((Context.getCanonicalType(CtxType)
Douglas Gregor88a35142008-12-22 05:46:06 +0000997 == Context.getCanonicalType(ThisType)) ||
998 IsDerivedFrom(ThisType, CtxType)) {
999 // Build the implicit member access expression.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001000 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00001001 MD->getThisType(Context));
Douglas Gregore0762c92009-06-19 23:52:42 +00001002 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001003 if (PerformObjectMemberConversion(This, D))
1004 return ExprError();
Anders Carlsson0f44b5a2009-08-08 16:55:18 +00001005 if (DiagnoseUseOfDecl(D, Loc))
1006 return ExprError();
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001007 return Owned(BuildMemberExpr(Context, This, true, SS, D,
1008 Loc, MemberType));
Douglas Gregor88a35142008-12-22 05:46:06 +00001009 }
1010 }
1011 }
1012 }
1013
Douglas Gregor44b43212008-12-11 16:49:14 +00001014 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001015 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1016 if (MD->isStatic())
1017 // "invalid use of member 'x' in static member function"
Sebastian Redlcd965b92009-01-18 18:53:16 +00001018 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1019 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001020 }
1021
Douglas Gregor88a35142008-12-22 05:46:06 +00001022 // Any other ways we could have found the field in a well-formed
1023 // program would have been turned into implicit member expressions
1024 // above.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001025 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1026 << FD->getDeclName());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001027 }
Douglas Gregor88a35142008-12-22 05:46:06 +00001028
Reid Spencer5f016e22007-07-11 17:01:13 +00001029 if (isa<TypedefDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001030 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001031 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001032 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001033 if (isa<NamespaceDecl>(D))
Sebastian Redlcd965b92009-01-18 18:53:16 +00001034 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Reid Spencer5f016e22007-07-11 17:01:13 +00001035
Steve Naroffdd972f22008-09-05 22:11:13 +00001036 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001037 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlssone41590d2009-06-24 00:10:43 +00001038 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1039 false, false, SS);
Douglas Gregorc15cb382009-02-09 23:23:08 +00001040 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlssone41590d2009-06-24 00:10:43 +00001041 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1042 false, false, SS);
Anders Carlsson598da5b2009-08-29 01:06:32 +00001043 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
Mike Stump1eb44332009-09-09 15:08:12 +00001044 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1045 /*TypeDependent=*/true,
Anders Carlsson598da5b2009-08-29 01:06:32 +00001046 /*ValueDependent=*/true, SS);
1047
Steve Naroffdd972f22008-09-05 22:11:13 +00001048 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001049
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001050 // Check whether this declaration can be used. Note that we suppress
1051 // this check when we're going to perform argument-dependent lookup
1052 // on this function name, because this might not be the function
1053 // that overload resolution actually selects.
Mike Stump1eb44332009-09-09 15:08:12 +00001054 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001055 HasTrailingLParen;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001056 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1057 return ExprError();
1058
Steve Naroffdd972f22008-09-05 22:11:13 +00001059 // Only create DeclRefExpr's for valid Decl's.
1060 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001061 return ExprError();
1062
Chris Lattner639e2d32008-10-20 05:16:36 +00001063 // If the identifier reference is inside a block, and it refers to a value
1064 // that is outside the block, create a BlockDeclRefExpr instead of a
1065 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1066 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001067 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001068 // We do not do this for things like enum constants, global variables, etc,
1069 // as they do not get snapshotted.
1070 //
1071 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregore0762c92009-06-19 23:52:42 +00001072 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001073 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001074 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001075 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001076 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001077 // This is to record that a 'const' was actually synthesize and added.
1078 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001079 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Eli Friedman5fdeae12009-03-22 23:00:19 +00001081 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001082 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001083 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001084 }
1085 // If this reference is not in a block or if the referenced variable is
1086 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001087
Douglas Gregor898574e2008-12-05 23:32:09 +00001088 bool TypeDependent = false;
Douglas Gregor83f96f62008-12-10 20:57:37 +00001089 bool ValueDependent = false;
1090 if (getLangOptions().CPlusPlus) {
1091 // C++ [temp.dep.expr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001092 // An id-expression is type-dependent if it contains:
Douglas Gregor83f96f62008-12-10 20:57:37 +00001093 // - an identifier that was declared with a dependent type,
1094 if (VD->getType()->isDependentType())
1095 TypeDependent = true;
1096 // - FIXME: a template-id that is dependent,
1097 // - a conversion-function-id that specifies a dependent type,
1098 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1099 Name.getCXXNameType()->isDependentType())
1100 TypeDependent = true;
1101 // - a nested-name-specifier that contains a class-name that
1102 // names a dependent type.
1103 else if (SS && !SS->isEmpty()) {
Douglas Gregore4e5b052009-03-19 00:18:19 +00001104 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor83f96f62008-12-10 20:57:37 +00001105 DC; DC = DC->getParent()) {
1106 // FIXME: could stop early at namespace scope.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001107 if (DC->isRecord()) {
Douglas Gregor83f96f62008-12-10 20:57:37 +00001108 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1109 if (Context.getTypeDeclType(Record)->isDependentType()) {
1110 TypeDependent = true;
1111 break;
1112 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001113 }
1114 }
1115 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001116
Douglas Gregor83f96f62008-12-10 20:57:37 +00001117 // C++ [temp.dep.constexpr]p2:
1118 //
1119 // An identifier is value-dependent if it is:
1120 // - a name declared with a dependent type,
1121 if (TypeDependent)
1122 ValueDependent = true;
1123 // - the name of a non-type template parameter,
1124 else if (isa<NonTypeTemplateParmDecl>(VD))
1125 ValueDependent = true;
1126 // - a constant with integral or enumeration type and is
1127 // initialized with an expression that is value-dependent
Eli Friedmanc1494122009-06-11 01:11:20 +00001128 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1129 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1130 Dcl->getInit()) {
1131 ValueDependent = Dcl->getInit()->isValueDependent();
1132 }
1133 }
Douglas Gregor83f96f62008-12-10 20:57:37 +00001134 }
Douglas Gregor898574e2008-12-05 23:32:09 +00001135
Anders Carlssone41590d2009-06-24 00:10:43 +00001136 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1137 TypeDependent, ValueDependent, SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001138}
1139
Sebastian Redlcd965b92009-01-18 18:53:16 +00001140Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1141 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001142 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001143
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001145 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001146 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1147 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1148 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001149 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001150
Chris Lattnerfa28b302008-01-12 08:14:25 +00001151 // Pre-defined identifiers are of type char[x], where x is the length of the
1152 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Anders Carlsson3a082d82009-09-08 18:24:21 +00001154 Decl *currentDecl = getCurFunctionOrMethodDecl();
1155 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001156 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001157 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001158 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001159
Anders Carlsson3a082d82009-09-08 18:24:21 +00001160 unsigned Length =
1161 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001162
Chris Lattner8f978d52008-01-12 19:32:28 +00001163 llvm::APInt LengthI(32, Length + 1);
Chris Lattner1423ea42008-01-12 18:39:25 +00001164 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattner8f978d52008-01-12 19:32:28 +00001165 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff6ece14c2009-01-21 00:14:39 +00001166 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001167}
1168
Sebastian Redlcd965b92009-01-18 18:53:16 +00001169Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001170 llvm::SmallString<16> CharBuffer;
1171 CharBuffer.resize(Tok.getLength());
1172 const char *ThisTokBegin = &CharBuffer[0];
1173 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001174
Reid Spencer5f016e22007-07-11 17:01:13 +00001175 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1176 Tok.getLocation(), PP);
1177 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001178 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001179
1180 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1181
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001182 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1183 Literal.isWide(),
1184 type, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001185}
1186
Sebastian Redlcd965b92009-01-18 18:53:16 +00001187Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1188 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001189 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1190 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001191 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001192 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001193 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001194 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001195 }
Ted Kremenek28396602009-01-13 23:19:12 +00001196
Reid Spencer5f016e22007-07-11 17:01:13 +00001197 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001198 // Add padding so that NumericLiteralParser can overread by one character.
1199 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001200 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001201
Reid Spencer5f016e22007-07-11 17:01:13 +00001202 // Get the spelling of the token, which eliminates trigraphs, etc.
1203 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001204
Mike Stump1eb44332009-09-09 15:08:12 +00001205 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001206 Tok.getLocation(), PP);
1207 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001208 return ExprError();
1209
Chris Lattner5d661452007-08-26 03:42:43 +00001210 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001211
Chris Lattner5d661452007-08-26 03:42:43 +00001212 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001213 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001214 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001215 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001216 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001217 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001218 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001219 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001220
1221 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1222
Ted Kremenek720c4ec2007-11-29 00:56:49 +00001223 // isExact will be set by GetFloatValue().
1224 bool isExact = false;
Chris Lattner001d64d2009-06-29 17:34:55 +00001225 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1226 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001227
Chris Lattner5d661452007-08-26 03:42:43 +00001228 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001229 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001230 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001231 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001232
Neil Boothb9449512007-08-29 22:00:19 +00001233 // long long is a C99 feature.
1234 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001235 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001236 Diag(Tok.getLocation(), diag::ext_longlong);
1237
Reid Spencer5f016e22007-07-11 17:01:13 +00001238 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001239 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001240
Reid Spencer5f016e22007-07-11 17:01:13 +00001241 if (Literal.GetIntegerValue(ResultVal)) {
1242 // If this value didn't fit into uintmax_t, warn and force to ull.
1243 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001244 Ty = Context.UnsignedLongLongTy;
1245 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001246 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001247 } else {
1248 // If this value fits into a ULL, try to figure out what else it fits into
1249 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001250
Reid Spencer5f016e22007-07-11 17:01:13 +00001251 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1252 // be an unsigned int.
1253 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1254
1255 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001256 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001257 if (!Literal.isLong && !Literal.isLongLong) {
1258 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001259 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001260
Reid Spencer5f016e22007-07-11 17:01:13 +00001261 // Does it fit in a unsigned int?
1262 if (ResultVal.isIntN(IntSize)) {
1263 // Does it fit in a signed int?
1264 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001265 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001266 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001267 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001268 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001269 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001270 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001271
Reid Spencer5f016e22007-07-11 17:01:13 +00001272 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001273 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001274 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001275
Reid Spencer5f016e22007-07-11 17:01:13 +00001276 // Does it fit in a unsigned long?
1277 if (ResultVal.isIntN(LongSize)) {
1278 // Does it fit in a signed long?
1279 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001280 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001281 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001282 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001283 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001284 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001285 }
1286
Reid Spencer5f016e22007-07-11 17:01:13 +00001287 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001288 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001289 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001290
Reid Spencer5f016e22007-07-11 17:01:13 +00001291 // Does it fit in a unsigned long long?
1292 if (ResultVal.isIntN(LongLongSize)) {
1293 // Does it fit in a signed long long?
1294 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001295 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001296 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001297 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001298 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001299 }
1300 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001301
Reid Spencer5f016e22007-07-11 17:01:13 +00001302 // If we still couldn't decide a type, we probably have something that
1303 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001304 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001305 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001306 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001307 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001308 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001309
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001310 if (ResultVal.getBitWidth() != Width)
1311 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001312 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001313 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001314 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001315
Chris Lattner5d661452007-08-26 03:42:43 +00001316 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1317 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001318 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001319 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001320
1321 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001322}
1323
Sebastian Redlcd965b92009-01-18 18:53:16 +00001324Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1325 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001326 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001327 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001328 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001329}
1330
1331/// The UsualUnaryConversions() function is *not* called by this routine.
1332/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001333bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001334 SourceLocation OpLoc,
1335 const SourceRange &ExprRange,
1336 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001337 if (exprType->isDependentType())
1338 return false;
1339
Reid Spencer5f016e22007-07-11 17:01:13 +00001340 // C99 6.5.3.4p1:
Chris Lattner01072922009-01-24 19:46:37 +00001341 if (isa<FunctionType>(exprType)) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001342 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001343 if (isSizeof)
1344 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1345 return false;
1346 }
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Chris Lattner1efaa952009-04-24 00:30:45 +00001348 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001349 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001350 Diag(OpLoc, diag::ext_sizeof_void_type)
1351 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001352 return false;
1353 }
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Chris Lattner1efaa952009-04-24 00:30:45 +00001355 if (RequireCompleteType(OpLoc, exprType,
Mike Stump1eb44332009-09-09 15:08:12 +00001356 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssonb7906612009-08-26 23:45:07 +00001357 PDiag(diag::err_alignof_incomplete_type)
1358 << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001359 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Chris Lattner1efaa952009-04-24 00:30:45 +00001361 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001362 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001363 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001364 << exprType << isSizeof << ExprRange;
1365 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001366 }
Mike Stump1eb44332009-09-09 15:08:12 +00001367
Chris Lattner1efaa952009-04-24 00:30:45 +00001368 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001369}
1370
Chris Lattner31e21e02009-01-24 20:17:12 +00001371bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1372 const SourceRange &ExprRange) {
1373 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001374
Mike Stump1eb44332009-09-09 15:08:12 +00001375 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001376 if (isa<DeclRefExpr>(E))
1377 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001378
1379 // Cannot know anything else if the expression is dependent.
1380 if (E->isTypeDependent())
1381 return false;
1382
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001383 if (E->getBitField()) {
1384 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1385 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001386 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001387
1388 // Alignment of a field access is always okay, so long as it isn't a
1389 // bit-field.
1390 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001391 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001392 return false;
1393
Chris Lattner31e21e02009-01-24 20:17:12 +00001394 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1395}
1396
Douglas Gregorba498172009-03-13 21:01:28 +00001397/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001398Action::OwningExprResult
1399Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001400 bool isSizeOf, SourceRange R) {
1401 if (T.isNull())
1402 return ExprError();
1403
1404 if (!T->isDependentType() &&
1405 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1406 return ExprError();
1407
1408 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1409 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1410 Context.getSizeType(), OpLoc,
1411 R.getEnd()));
1412}
1413
1414/// \brief Build a sizeof or alignof expression given an expression
1415/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001416Action::OwningExprResult
1417Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001418 bool isSizeOf, SourceRange R) {
1419 // Verify that the operand is valid.
1420 bool isInvalid = false;
1421 if (E->isTypeDependent()) {
1422 // Delay type-checking for type-dependent expressions.
1423 } else if (!isSizeOf) {
1424 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001425 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001426 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1427 isInvalid = true;
1428 } else {
1429 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1430 }
1431
1432 if (isInvalid)
1433 return ExprError();
1434
1435 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1436 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1437 Context.getSizeType(), OpLoc,
1438 R.getEnd()));
1439}
1440
Sebastian Redl05189992008-11-11 17:56:53 +00001441/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1442/// the same for @c alignof and @c __alignof
1443/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001444Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001445Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1446 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001448 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001449
Sebastian Redl05189992008-11-11 17:56:53 +00001450 if (isType) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00001451 // FIXME: Preserve type source info.
1452 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregorba498172009-03-13 21:01:28 +00001453 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001454 }
Sebastian Redl05189992008-11-11 17:56:53 +00001455
Douglas Gregorba498172009-03-13 21:01:28 +00001456 // Get the end location.
1457 Expr *ArgEx = (Expr *)TyOrEx;
1458 Action::OwningExprResult Result
1459 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1460
1461 if (Result.isInvalid())
1462 DeleteExpr(ArgEx);
1463
1464 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001465}
1466
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001467QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001468 if (V->isTypeDependent())
1469 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Chris Lattnercc26ed72007-08-26 05:39:26 +00001471 // These operators return the element type of a complex type.
Chris Lattnerdbb36972007-08-24 21:16:53 +00001472 if (const ComplexType *CT = V->getType()->getAsComplexType())
1473 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Chris Lattnercc26ed72007-08-26 05:39:26 +00001475 // Otherwise they pass through real integer and floating point types here.
1476 if (V->getType()->isArithmeticType())
1477 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Chris Lattnercc26ed72007-08-26 05:39:26 +00001479 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001480 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1481 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001482 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001483}
1484
1485
Reid Spencer5f016e22007-07-11 17:01:13 +00001486
Sebastian Redl0eb23302009-01-19 00:08:26 +00001487Action::OwningExprResult
1488Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1489 tok::TokenKind Kind, ExprArg Input) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001490 // Since this might be a postfix expression, get rid of ParenListExprs.
1491 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001492 Expr *Arg = (Expr *)Input.get();
Douglas Gregor74253732008-11-19 15:42:04 +00001493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 UnaryOperator::Opcode Opc;
1495 switch (Kind) {
1496 default: assert(0 && "Unknown unary op!");
1497 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1498 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1499 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001500
Douglas Gregor74253732008-11-19 15:42:04 +00001501 if (getLangOptions().CPlusPlus &&
1502 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1503 // Which overloaded operator?
Sebastian Redl0eb23302009-01-19 00:08:26 +00001504 OverloadedOperatorKind OverOp =
Douglas Gregor74253732008-11-19 15:42:04 +00001505 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1506
1507 // C++ [over.inc]p1:
1508 //
1509 // [...] If the function is a member function with one
1510 // parameter (which shall be of type int) or a non-member
1511 // function with two parameters (the second of which shall be
1512 // of type int), it defines the postfix increment operator ++
1513 // for objects of that type. When the postfix increment is
1514 // called as a result of using the ++ operator, the int
1515 // argument will have value zero.
Mike Stump1eb44332009-09-09 15:08:12 +00001516 Expr *Args[2] = {
1517 Arg,
1518 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001519 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor74253732008-11-19 15:42:04 +00001520 };
1521
1522 // Build the candidate set for overloading
1523 OverloadCandidateSet CandidateSet;
Douglas Gregor063daf62009-03-13 18:40:31 +00001524 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor74253732008-11-19 15:42:04 +00001525
1526 // Perform overload resolution.
1527 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001528 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor74253732008-11-19 15:42:04 +00001529 case OR_Success: {
1530 // We found a built-in operator or an overloaded operator.
1531 FunctionDecl *FnDecl = Best->Function;
1532
1533 if (FnDecl) {
1534 // We matched an overloaded operator. Build a call to that
1535 // operator.
1536
1537 // Convert the arguments.
1538 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1539 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001540 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001541 } else {
1542 // Convert the arguments.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001543 if (PerformCopyInitialization(Arg,
Douglas Gregor74253732008-11-19 15:42:04 +00001544 FnDecl->getParamDecl(0)->getType(),
1545 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001546 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001547 }
1548
1549 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001550 QualType ResultTy
Douglas Gregor74253732008-11-19 15:42:04 +00001551 = FnDecl->getType()->getAsFunctionType()->getResultType();
1552 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001553
Douglas Gregor74253732008-11-19 15:42:04 +00001554 // Build the actual expression node.
Steve Naroff6ece14c2009-01-21 00:14:39 +00001555 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump488e25b2009-02-19 02:54:59 +00001556 SourceLocation());
Douglas Gregor74253732008-11-19 15:42:04 +00001557 UsualUnaryConversions(FnExpr);
1558
Sebastian Redl0eb23302009-01-19 00:08:26 +00001559 Input.release();
Douglas Gregor7ff69262009-05-27 05:00:47 +00001560 Args[0] = Arg;
Douglas Gregor063daf62009-03-13 18:40:31 +00001561 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00001562 Args, 2, ResultTy,
Douglas Gregor063daf62009-03-13 18:40:31 +00001563 OpLoc));
Douglas Gregor74253732008-11-19 15:42:04 +00001564 } else {
1565 // We matched a built-in operator. Convert the arguments, then
1566 // break out so that we will build the appropriate built-in
1567 // operator node.
1568 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1569 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001570 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001571
1572 break;
Sebastian Redl0eb23302009-01-19 00:08:26 +00001573 }
Douglas Gregor74253732008-11-19 15:42:04 +00001574 }
1575
1576 case OR_No_Viable_Function:
1577 // No viable function; fall through to handling this as a
1578 // built-in operator, which will produce an error message for us.
1579 break;
1580
1581 case OR_Ambiguous:
1582 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1583 << UnaryOperator::getOpcodeStr(Opc)
1584 << Arg->getSourceRange();
1585 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001586 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001587
1588 case OR_Deleted:
1589 Diag(OpLoc, diag::err_ovl_deleted_oper)
1590 << Best->Function->isDeleted()
1591 << UnaryOperator::getOpcodeStr(Opc)
1592 << Arg->getSourceRange();
1593 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1594 return ExprError();
Douglas Gregor74253732008-11-19 15:42:04 +00001595 }
1596
1597 // Either we found no viable overloaded operator or we matched a
1598 // built-in operator. In either case, fall through to trying to
1599 // build a built-in operation.
1600 }
1601
Eli Friedman6016cb22009-07-22 23:24:42 +00001602 Input.release();
1603 Input = Arg;
Eli Friedmande99a452009-07-22 22:25:00 +00001604 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001605}
1606
Sebastian Redl0eb23302009-01-19 00:08:26 +00001607Action::OwningExprResult
1608Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1609 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001610 // Since this might be a postfix expression, get rid of ParenListExprs.
1611 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1612
Sebastian Redl0eb23302009-01-19 00:08:26 +00001613 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1614 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Douglas Gregor337c6b92008-11-19 17:17:41 +00001616 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00001617 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1618 Base.release();
1619 Idx.release();
1620 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1621 Context.DependentTy, RLoc));
1622 }
1623
Mike Stump1eb44332009-09-09 15:08:12 +00001624 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00001625 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00001626 LHSExp->getType()->isEnumeralType() ||
1627 RHSExp->getType()->isRecordType() ||
1628 RHSExp->getType()->isEnumeralType())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001629 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor337c6b92008-11-19 17:17:41 +00001630 // to the candidate set.
1631 OverloadCandidateSet CandidateSet;
1632 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor063daf62009-03-13 18:40:31 +00001633 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1634 SourceRange(LLoc, RLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00001635
Douglas Gregor337c6b92008-11-19 17:17:41 +00001636 // Perform overload resolution.
1637 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001638 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor337c6b92008-11-19 17:17:41 +00001639 case OR_Success: {
1640 // We found a built-in operator or an overloaded operator.
1641 FunctionDecl *FnDecl = Best->Function;
1642
1643 if (FnDecl) {
1644 // We matched an overloaded operator. Build a call to that
1645 // operator.
1646
1647 // Convert the arguments.
1648 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1649 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001650 PerformCopyInitialization(RHSExp,
Douglas Gregor337c6b92008-11-19 17:17:41 +00001651 FnDecl->getParamDecl(0)->getType(),
1652 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001653 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001654 } else {
1655 // Convert the arguments.
1656 if (PerformCopyInitialization(LHSExp,
1657 FnDecl->getParamDecl(0)->getType(),
1658 "passing") ||
1659 PerformCopyInitialization(RHSExp,
1660 FnDecl->getParamDecl(1)->getType(),
1661 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001662 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001663 }
1664
1665 // Determine the result type
Sebastian Redl0eb23302009-01-19 00:08:26 +00001666 QualType ResultTy
Douglas Gregor337c6b92008-11-19 17:17:41 +00001667 = FnDecl->getType()->getAsFunctionType()->getResultType();
1668 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl0eb23302009-01-19 00:08:26 +00001669
Douglas Gregor337c6b92008-11-19 17:17:41 +00001670 // Build the actual expression node.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001671 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1672 SourceLocation());
Douglas Gregor337c6b92008-11-19 17:17:41 +00001673 UsualUnaryConversions(FnExpr);
1674
Sebastian Redl0eb23302009-01-19 00:08:26 +00001675 Base.release();
1676 Idx.release();
Douglas Gregor7ff69262009-05-27 05:00:47 +00001677 Args[0] = LHSExp;
1678 Args[1] = RHSExp;
Douglas Gregor063daf62009-03-13 18:40:31 +00001679 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Mike Stump1eb44332009-09-09 15:08:12 +00001680 FnExpr, Args, 2,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001681 ResultTy, LLoc));
Douglas Gregor337c6b92008-11-19 17:17:41 +00001682 } else {
1683 // We matched a built-in operator. Convert the arguments, then
1684 // break out so that we will build the appropriate built-in
1685 // operator node.
1686 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1687 "passing") ||
1688 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1689 "passing"))
Sebastian Redl0eb23302009-01-19 00:08:26 +00001690 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001691
1692 break;
1693 }
1694 }
1695
1696 case OR_No_Viable_Function:
1697 // No viable function; fall through to handling this as a
1698 // built-in operator, which will produce an error message for us.
1699 break;
1700
1701 case OR_Ambiguous:
1702 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1703 << "[]"
1704 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1705 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001706 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001707
1708 case OR_Deleted:
1709 Diag(LLoc, diag::err_ovl_deleted_oper)
1710 << Best->Function->isDeleted()
1711 << "[]"
1712 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1713 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1714 return ExprError();
Douglas Gregor337c6b92008-11-19 17:17:41 +00001715 }
1716
1717 // Either we found no viable overloaded operator or we matched a
1718 // built-in operator. In either case, fall through to trying to
1719 // build a built-in operation.
1720 }
1721
Chris Lattner12d9ff62007-07-16 00:14:47 +00001722 // Perform default conversions.
1723 DefaultFunctionArrayConversion(LHSExp);
1724 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00001725
Chris Lattner12d9ff62007-07-16 00:14:47 +00001726 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001727
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00001729 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00001730 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00001731 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00001732 Expr *BaseExpr, *IndexExpr;
1733 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00001734 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1735 BaseExpr = LHSExp;
1736 IndexExpr = RHSExp;
1737 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001738 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00001739 BaseExpr = LHSExp;
1740 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001741 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001742 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00001743 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00001744 BaseExpr = RHSExp;
1745 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00001746 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001747 } else if (const ObjCObjectPointerType *PTy =
Steve Naroff14108da2009-07-10 23:34:53 +00001748 LHSTy->getAsObjCObjectPointerType()) {
1749 BaseExpr = LHSExp;
1750 IndexExpr = RHSExp;
1751 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00001752 } else if (const ObjCObjectPointerType *PTy =
Steve Naroff14108da2009-07-10 23:34:53 +00001753 RHSTy->getAsObjCObjectPointerType()) {
1754 // Handle the uncommon case of "123[Ptr]".
1755 BaseExpr = RHSExp;
1756 IndexExpr = LHSExp;
1757 ResultType = PTy->getPointeeType();
Chris Lattnerc8629632007-07-31 19:29:30 +00001758 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1759 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00001760 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00001761
Chris Lattner12d9ff62007-07-16 00:14:47 +00001762 // FIXME: need to deal with const...
1763 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001764 } else if (LHSTy->isArrayType()) {
1765 // If we see an array that wasn't promoted by
1766 // DefaultFunctionArrayConversion, it must be an array that
1767 // wasn't promoted because of the C90 rule that doesn't
1768 // allow promoting non-lvalue arrays. Warn, then
1769 // force the promotion here.
1770 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1771 LHSExp->getSourceRange();
1772 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1773 LHSTy = LHSExp->getType();
1774
1775 BaseExpr = LHSExp;
1776 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001777 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00001778 } else if (RHSTy->isArrayType()) {
1779 // Same as previous, except for 123[f().a] case
1780 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1781 RHSExp->getSourceRange();
1782 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1783 RHSTy = RHSExp->getType();
1784
1785 BaseExpr = RHSExp;
1786 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001787 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00001789 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1790 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001791 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00001793 if (!(IndexExpr->getType()->isIntegerType() &&
1794 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00001795 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1796 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00001797
Douglas Gregore7450f52009-03-24 19:52:54 +00001798 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00001799 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1800 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00001801 // incomplete types are not object types.
1802 if (ResultType->isFunctionType()) {
1803 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1804 << ResultType << BaseExpr->getSourceRange();
1805 return ExprError();
1806 }
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Douglas Gregore7450f52009-03-24 19:52:54 +00001808 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00001809 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00001810 PDiag(diag::err_subscript_incomplete_type)
1811 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00001812 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Chris Lattner1efaa952009-04-24 00:30:45 +00001814 // Diagnose bad cases where we step over interface counts.
1815 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1816 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1817 << ResultType << BaseExpr->getSourceRange();
1818 return ExprError();
1819 }
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Sebastian Redl0eb23302009-01-19 00:08:26 +00001821 Base.release();
1822 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001823 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001824 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001825}
1826
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001827QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00001828CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001829 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001830 SourceLocation CompLoc) {
Nate Begeman213541a2008-04-18 23:10:10 +00001831 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begeman8a997642008-05-09 06:41:27 +00001832
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001833 // The vector accessor can't exceed the number of elements.
Anders Carlsson8f28f992009-08-26 18:25:21 +00001834 const char *compStr = CompName->getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001835
Mike Stumpeed9cac2009-02-19 03:04:26 +00001836 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00001837 // special names that indicate a subset of exactly half the elements are
1838 // to be selected.
1839 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00001840
Nate Begeman353417a2009-01-18 01:47:54 +00001841 // This flag determines whether or not CompName has an 's' char prefix,
1842 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00001843 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00001844
1845 // Check that we've found one of the special components, or that the component
1846 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001847 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00001848 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1849 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00001850 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001851 do
1852 compStr++;
1853 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00001854 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00001855 do
1856 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001857 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00001858 }
Nate Begeman353417a2009-01-18 01:47:54 +00001859
Mike Stumpeed9cac2009-02-19 03:04:26 +00001860 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001861 // We didn't get to the end of the string. This means the component names
1862 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001863 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1864 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001865 return QualType();
1866 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001867
Nate Begeman353417a2009-01-18 01:47:54 +00001868 // Ensure no component accessor exceeds the width of the vector type it
1869 // operates on.
1870 if (!HalvingSwizzle) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001871 compStr = CompName->getName();
Nate Begeman353417a2009-01-18 01:47:54 +00001872
1873 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001874 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00001875
1876 while (*compStr) {
1877 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1878 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1879 << baseType << SourceRange(CompLoc);
1880 return QualType();
1881 }
1882 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001883 }
Nate Begeman8a997642008-05-09 06:41:27 +00001884
Nate Begeman353417a2009-01-18 01:47:54 +00001885 // If this is a halving swizzle, verify that the base type has an even
1886 // number of elements.
1887 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001888 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattnerd1625842008-11-24 06:25:27 +00001889 << baseType << SourceRange(CompLoc);
Nate Begeman8a997642008-05-09 06:41:27 +00001890 return QualType();
1891 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00001892
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001893 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00001894 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001895 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00001896 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00001897 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman353417a2009-01-18 01:47:54 +00001898 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00001899 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00001900 if (HexSwizzle)
1901 CompSize--;
1902
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001903 if (CompSize == 1)
1904 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00001905
Nate Begeman213541a2008-04-18 23:10:10 +00001906 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00001907 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00001908 // diagostics look bad. We want extended vector types to appear built-in.
1909 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1910 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1911 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00001912 }
1913 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00001914}
1915
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001916static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001917 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001918 const Selector &Sel,
1919 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Anders Carlsson8f28f992009-08-26 18:25:21 +00001921 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001922 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001923 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001924 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001926 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1927 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00001928 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001929 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001930 return D;
1931 }
1932 return 0;
1933}
1934
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001935static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00001936 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00001937 const Selector &Sel,
1938 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001939 // Check protocols on qualified interfaces.
1940 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001941 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001942 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00001943 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001944 GDecl = PD;
1945 break;
1946 }
1947 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001948 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001949 GDecl = OMD;
1950 break;
1951 }
1952 }
1953 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00001954 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001955 E = QIdTy->qual_end(); I != E; ++I) {
1956 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00001957 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00001958 if (GDecl)
1959 return GDecl;
1960 }
1961 }
1962 return GDecl;
1963}
Chris Lattner76a642f2009-02-15 22:43:40 +00001964
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00001965/// FindMethodInNestedImplementations - Look up a method in current and
1966/// all base class implementations.
1967///
1968ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1969 const ObjCInterfaceDecl *IFace,
1970 const Selector &Sel) {
1971 ObjCMethodDecl *Method = 0;
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001972 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001973 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00001975 if (!Method && IFace->getSuperClass())
1976 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1977 return Method;
1978}
Mike Stump1eb44332009-09-09 15:08:12 +00001979
1980Action::OwningExprResult
Anders Carlsson8f28f992009-08-26 18:25:21 +00001981Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00001982 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001983 DeclarationName MemberName,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00001984 bool HasExplicitTemplateArgs,
1985 SourceLocation LAngleLoc,
1986 const TemplateArgument *ExplicitTemplateArgs,
1987 unsigned NumExplicitTemplateArgs,
1988 SourceLocation RAngleLoc,
Douglas Gregorc68afe22009-09-03 21:38:09 +00001989 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1990 NamedDecl *FirstQualifierInScope) {
Douglas Gregorfe85ced2009-08-06 03:17:00 +00001991 if (SS && SS->isInvalid())
1992 return ExprError();
1993
Nate Begeman2ef13e52009-08-10 23:49:36 +00001994 // Since this might be a postfix expression, get rid of ParenListExprs.
1995 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1996
Anders Carlssonf1b1d592009-05-01 19:30:39 +00001997 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregora71d8192009-09-04 17:36:40 +00001998 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001999
Steve Naroff3cc4af82007-12-16 21:42:28 +00002000 // Perform default conversions.
2001 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002002
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002003 QualType BaseType = BaseExpr->getType();
David Chisnall0f436562009-08-17 16:35:33 +00002004 // If this is an Objective-C pseudo-builtin and a definition is provided then
2005 // use that.
2006 if (BaseType->isObjCIdType()) {
2007 // We have an 'id' type. Rather than fall through, we check if this
2008 // is a reference to 'isa'.
2009 if (BaseType != Context.ObjCIdRedefinitionType) {
2010 BaseType = Context.ObjCIdRedefinitionType;
2011 ImpCastExprToType(BaseExpr, BaseType);
2012 }
2013 } else if (BaseType->isObjCClassType() &&
Douglas Gregorf328a282009-08-31 21:16:32 +00002014 BaseType != Context.ObjCClassRedefinitionType) {
David Chisnall0f436562009-08-17 16:35:33 +00002015 BaseType = Context.ObjCClassRedefinitionType;
2016 ImpCastExprToType(BaseExpr, BaseType);
2017 }
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002018 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002019
Chris Lattner68a057b2008-07-21 04:36:39 +00002020 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2021 // must have pointer type, and the accessed type is the pointee.
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 if (OpKind == tok::arrow) {
Douglas Gregorc68afe22009-09-03 21:38:09 +00002023 if (BaseType->isDependentType()) {
2024 NestedNameSpecifier *Qualifier = 0;
2025 if (SS) {
2026 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2027 if (!FirstQualifierInScope)
2028 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2029 }
Mike Stump1eb44332009-09-09 15:08:12 +00002030
2031 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002032 OpLoc, Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00002033 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002034 FirstQualifierInScope,
2035 MemberName,
2036 MemberLoc,
2037 HasExplicitTemplateArgs,
2038 LAngleLoc,
2039 ExplicitTemplateArgs,
2040 NumExplicitTemplateArgs,
2041 RAngleLoc));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002042 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002043 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002044 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002045 else if (BaseType->isObjCObjectPointerType())
2046 ;
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002047 else
Sebastian Redl0eb23302009-01-19 00:08:26 +00002048 return ExprError(Diag(MemberLoc,
2049 diag::err_typecheck_member_reference_arrow)
2050 << BaseType << BaseExpr->getSourceRange());
Anders Carlssonffce2df2009-05-15 23:10:19 +00002051 } else {
Anders Carlsson4ef27702009-05-16 20:31:20 +00002052 if (BaseType->isDependentType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002053 // Require that the base type isn't a pointer type
Anders Carlsson4ef27702009-05-16 20:31:20 +00002054 // (so we'll report an error for)
2055 // T* t;
2056 // t.f;
Mike Stump1eb44332009-09-09 15:08:12 +00002057 //
Anders Carlsson4ef27702009-05-16 20:31:20 +00002058 // In Obj-C++, however, the above expression is valid, since it could be
2059 // accessing the 'f' property if T is an Obj-C interface. The extra check
2060 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenek6217b802009-07-29 21:53:49 +00002061 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002062
Mike Stump1eb44332009-09-09 15:08:12 +00002063 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregorc68afe22009-09-03 21:38:09 +00002064 !PT->getPointeeType()->isRecordType())) {
2065 NestedNameSpecifier *Qualifier = 0;
2066 if (SS) {
2067 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2068 if (!FirstQualifierInScope)
2069 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2070 }
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002072 return Owned(CXXUnresolvedMemberExpr::Create(Context,
Mike Stump1eb44332009-09-09 15:08:12 +00002073 BaseExpr, false,
2074 OpLoc,
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002075 Qualifier,
Douglas Gregora38c6872009-09-03 16:14:30 +00002076 SS? SS->getRange() : SourceRange(),
Douglas Gregor3b6afbb2009-09-09 00:23:06 +00002077 FirstQualifierInScope,
2078 MemberName,
2079 MemberLoc,
2080 HasExplicitTemplateArgs,
2081 LAngleLoc,
2082 ExplicitTemplateArgs,
2083 NumExplicitTemplateArgs,
2084 RAngleLoc));
Douglas Gregorc68afe22009-09-03 21:38:09 +00002085 }
Anders Carlsson4ef27702009-05-16 20:31:20 +00002086 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002087 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002088
Chris Lattner68a057b2008-07-21 04:36:39 +00002089 // Handle field access to simple records. This also handles access to fields
2090 // of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002091 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002092 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor86447ec2009-03-09 16:13:40 +00002093 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002094 PDiag(diag::err_typecheck_incomplete_tag)
2095 << BaseExpr->getSourceRange()))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002096 return ExprError();
2097
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002098 DeclContext *DC = RDecl;
2099 if (SS && SS->isSet()) {
2100 // If the member name was a qualified-id, look into the
2101 // nested-name-specifier.
2102 DC = computeDeclContext(*SS, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002103
2104 // FIXME: If DC is not computable, we should build a
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002105 // CXXUnresolvedMemberExpr.
2106 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2107 }
2108
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002109 // The record definition is complete, now make sure the member is valid.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002110 LookupResult Result
Anders Carlsson8f28f992009-08-26 18:25:21 +00002111 = LookupQualifiedName(DC, MemberName, LookupMemberName, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00002112
Douglas Gregor7176fff2009-01-15 00:26:24 +00002113 if (!Result)
Anders Carlssonf4d84b62009-08-30 00:54:35 +00002114 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member_deprecated)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002115 << MemberName << BaseExpr->getSourceRange());
Chris Lattnera3d25242009-03-31 08:18:48 +00002116 if (Result.isAmbiguous()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002117 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2118 BaseExpr->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002119 return ExprError();
Chris Lattnera3d25242009-03-31 08:18:48 +00002120 }
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Douglas Gregora38c6872009-09-03 16:14:30 +00002122 if (SS && SS->isSet()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002123 QualType BaseTypeCanon
Douglas Gregora38c6872009-09-03 16:14:30 +00002124 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002125 QualType MemberTypeCanon
Douglas Gregora38c6872009-09-03 16:14:30 +00002126 = Context.getCanonicalType(
2127 Context.getTypeDeclType(
2128 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Douglas Gregora38c6872009-09-03 16:14:30 +00002130 if (BaseTypeCanon != MemberTypeCanon &&
2131 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2132 return ExprError(Diag(SS->getBeginLoc(),
2133 diag::err_not_direct_base_or_virtual)
2134 << MemberTypeCanon << BaseTypeCanon);
2135 }
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Chris Lattnera3d25242009-03-31 08:18:48 +00002137 NamedDecl *MemberDecl = Result;
Douglas Gregor44b43212008-12-11 16:49:14 +00002138
Chris Lattner56cd21b2009-02-13 22:08:30 +00002139 // If the decl being referenced had an error, return an error for this
2140 // sub-expr without emitting another error, in order to avoid cascading
2141 // error cases.
2142 if (MemberDecl->isInvalidDecl())
2143 return ExprError();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002144
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002145 // Check the use of this field
2146 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2147 return ExprError();
Chris Lattner56cd21b2009-02-13 22:08:30 +00002148
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002149 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002150 // We may have found a field within an anonymous union or struct
2151 // (C++ [class.union]).
2152 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd965b92009-01-18 18:53:16 +00002153 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl0eb23302009-01-19 00:08:26 +00002154 BaseExpr, OpLoc);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002155
Douglas Gregor86f19402008-12-20 23:49:58 +00002156 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002157 QualType MemberType = FD->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002158 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor86f19402008-12-20 23:49:58 +00002159 MemberType = Ref->getPointeeType();
2160 else {
Mon P Wangc6a38a42009-07-22 03:08:17 +00002161 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor86f19402008-12-20 23:49:58 +00002162 unsigned combinedQualifiers =
2163 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregor3fc749d2008-12-23 00:26:44 +00002164 if (FD->isMutable())
Douglas Gregor86f19402008-12-20 23:49:58 +00002165 combinedQualifiers &= ~QualType::Const;
2166 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wangc6a38a42009-07-22 03:08:17 +00002167 if (BaseAddrSpace != MemberType.getAddressSpace())
2168 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor86f19402008-12-20 23:49:58 +00002169 }
Eli Friedman51019072008-02-06 22:48:16 +00002170
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002171 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00002172 if (PerformObjectMemberConversion(BaseExpr, FD))
2173 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002174 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002175 FD, MemberLoc, MemberType));
Chris Lattnera3d25242009-03-31 08:18:48 +00002176 }
Mike Stump1eb44332009-09-09 15:08:12 +00002177
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002178 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2179 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002180 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2181 Var, MemberLoc,
2182 Var->getType().getNonReferenceType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002183 }
2184 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2185 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002186 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2187 MemberFn, MemberLoc,
2188 MemberFn->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002189 }
Mike Stump1eb44332009-09-09 15:08:12 +00002190 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor6b906862009-08-21 00:16:32 +00002191 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2192 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002194 if (HasExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002195 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2196 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002197 SS? SS->getRange() : SourceRange(),
Mike Stump1eb44332009-09-09 15:08:12 +00002198 FunTmpl, MemberLoc, true,
2199 LAngleLoc, ExplicitTemplateArgs,
2200 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002201 Context.OverloadTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002202
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002203 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2204 FunTmpl, MemberLoc,
2205 Context.OverloadTy));
Douglas Gregor6b906862009-08-21 00:16:32 +00002206 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002207 if (OverloadedFunctionDecl *Ovl
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002208 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2209 if (HasExplicitTemplateArgs)
Mike Stump1eb44332009-09-09 15:08:12 +00002210 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2211 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002212 SS? SS->getRange() : SourceRange(),
Mike Stump1eb44332009-09-09 15:08:12 +00002213 Ovl, MemberLoc, true,
2214 LAngleLoc, ExplicitTemplateArgs,
2215 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002216 Context.OverloadTy));
2217
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002218 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2219 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregorc4bf26f2009-09-01 00:37:14 +00002220 }
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002221 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2222 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00002223 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2224 Enum, MemberLoc, Enum->getType()));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002225 }
Chris Lattnera3d25242009-03-31 08:18:48 +00002226 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002227 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002228 << MemberName << int(OpKind == tok::arrow));
Eli Friedman51019072008-02-06 22:48:16 +00002229
Douglas Gregor86f19402008-12-20 23:49:58 +00002230 // We found a declaration kind that we didn't expect. This is a
2231 // generic error message that tells the user that she can't refer
2232 // to this member with '.' or '->'.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002233 return ExprError(Diag(MemberLoc,
2234 diag::err_typecheck_member_reference_unknown)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002235 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002236 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002237
Douglas Gregora71d8192009-09-04 17:36:40 +00002238 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2239 // into a record type was handled above, any destructor we see here is a
2240 // pseudo-destructor.
2241 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2242 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002243 // The left hand side of the dot operator shall be of scalar type. The
2244 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002245 // type.
2246 if (!BaseType->isScalarType())
2247 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2248 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Douglas Gregora71d8192009-09-04 17:36:40 +00002250 // [...] The type designated by the pseudo-destructor-name shall be the
2251 // same as the object type.
2252 if (!MemberName.getCXXNameType()->isDependentType() &&
2253 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2254 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2255 << BaseType << MemberName.getCXXNameType()
2256 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002257
2258 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002259 // the form
2260 //
Mike Stump1eb44332009-09-09 15:08:12 +00002261 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2262 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002263 // shall designate the same scalar type.
2264 //
2265 // FIXME: DPG can't see any way to trigger this particular clause, so it
2266 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Douglas Gregora71d8192009-09-04 17:36:40 +00002268 // FIXME: We've lost the precise spelling of the type by going through
2269 // DeclarationName. Can we do better?
2270 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00002271 OpKind == tok::arrow,
Douglas Gregora71d8192009-09-04 17:36:40 +00002272 OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002273 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregora71d8192009-09-04 17:36:40 +00002274 SS? SS->getRange() : SourceRange(),
2275 MemberName.getCXXNameType(),
2276 MemberLoc));
2277 }
Mike Stump1eb44332009-09-09 15:08:12 +00002278
Steve Naroff14108da2009-07-10 23:34:53 +00002279 // Handle properties on ObjC 'Class' types.
Steve Naroff430ee5a2009-07-13 17:19:15 +00002280 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002281 // Also must look for a getter name which uses property syntax.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002282 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2283 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002284 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2285 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2286 ObjCMethodDecl *Getter;
2287 // FIXME: need to also look locally in the implementation.
2288 if ((Getter = IFace->lookupClassMethod(Sel))) {
2289 // Check the use of this method.
2290 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2291 return ExprError();
2292 }
2293 // If we found a getter then this may be a valid dot-reference, we
2294 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002295 Selector SetterSel =
2296 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002297 PP.getSelectorTable(), Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002298 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2299 if (!Setter) {
2300 // If this reference is in an @implementation, also check for 'private'
2301 // methods.
2302 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2303 }
2304 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002305 if (!Setter)
2306 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff14108da2009-07-10 23:34:53 +00002307
2308 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2309 return ExprError();
2310
2311 if (Getter || Setter) {
2312 QualType PType;
2313
2314 if (Getter)
2315 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002316 else
2317 // Get the expression type from Setter's incoming parameter.
2318 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00002319 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002320 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff14108da2009-07-10 23:34:53 +00002321 Setter, MemberLoc, BaseExpr));
2322 }
2323 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002324 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002325 }
2326 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002327 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2328 // (*Obj).ivar.
Steve Naroff14108da2009-07-10 23:34:53 +00002329 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2330 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2331 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
Mike Stump1eb44332009-09-09 15:08:12 +00002332 const ObjCInterfaceType *IFaceT =
Steve Naroff14108da2009-07-10 23:34:53 +00002333 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002334 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002335 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2336
Steve Naroffc70e8d92009-07-16 00:25:06 +00002337 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2338 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002339 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002340
Steve Naroffc70e8d92009-07-16 00:25:06 +00002341 if (IV) {
2342 // If the decl being referenced had an error, return an error for this
2343 // sub-expr without emitting another error, in order to avoid cascading
2344 // error cases.
2345 if (IV->isInvalidDecl())
2346 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002347
Steve Naroffc70e8d92009-07-16 00:25:06 +00002348 // Check whether we can reference this field.
2349 if (DiagnoseUseOfDecl(IV, MemberLoc))
2350 return ExprError();
2351 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2352 IV->getAccessControl() != ObjCIvarDecl::Package) {
2353 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2354 if (ObjCMethodDecl *MD = getCurMethodDecl())
2355 ClassOfMethodDecl = MD->getClassInterface();
2356 else if (ObjCImpDecl && getCurFunctionDecl()) {
2357 // Case of a c-function declared inside an objc implementation.
2358 // FIXME: For a c-style function nested inside an objc implementation
2359 // class, there is no implementation context available, so we pass
2360 // down the context as argument to this routine. Ideally, this context
2361 // need be passed down in the AST node and somehow calculated from the
2362 // AST for a function decl.
2363 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002364 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002365 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2366 ClassOfMethodDecl = IMPD->getClassInterface();
2367 else if (ObjCCategoryImplDecl* CatImplClass =
2368 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2369 ClassOfMethodDecl = CatImplClass->getClassInterface();
2370 }
Mike Stump1eb44332009-09-09 15:08:12 +00002371
2372 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2373 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002374 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002375 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002376 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002377 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2378 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002379 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002380 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002381 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002382
2383 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2384 MemberLoc, BaseExpr,
2385 OpKind == tok::arrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002386 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002387 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002388 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002389 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002390 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002391 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002392 // Handle properties on 'id' and qualified "id".
Mike Stump1eb44332009-09-09 15:08:12 +00002393 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroffde2e22d2009-07-15 18:40:39 +00002394 BaseType->isObjCQualifiedIdType())) {
2395 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002396 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002397
Steve Naroff14108da2009-07-10 23:34:53 +00002398 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002399 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002400 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2401 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2402 // Check the use of this declaration
2403 if (DiagnoseUseOfDecl(PD, MemberLoc))
2404 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002405
Steve Naroff14108da2009-07-10 23:34:53 +00002406 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2407 MemberLoc, BaseExpr));
2408 }
2409 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2410 // Check the use of this method.
2411 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2412 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002413
Steve Naroff14108da2009-07-10 23:34:53 +00002414 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002415 OMD->getResultType(),
2416 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002417 NULL, 0));
2418 }
2419 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002420
Steve Naroff14108da2009-07-10 23:34:53 +00002421 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002422 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00002423 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00002424 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2425 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00002426 const ObjCObjectPointerType *OPT;
Mike Stump1eb44332009-09-09 15:08:12 +00002427 if (OpKind == tok::period &&
Steve Naroff14108da2009-07-10 23:34:53 +00002428 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2429 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2430 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002431 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002432
Daniel Dunbar2307d312008-09-03 01:05:41 +00002433 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002434 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002435 // Check whether we can reference this property.
2436 if (DiagnoseUseOfDecl(PD, MemberLoc))
2437 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002438 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002439 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002440 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00002441 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2442 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00002443 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00002444 MemberLoc, BaseExpr));
2445 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002446 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00002447 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2448 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002449 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002450 // Check whether we can reference this property.
2451 if (DiagnoseUseOfDecl(PD, MemberLoc))
2452 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00002453
Steve Naroff6ece14c2009-01-21 00:14:39 +00002454 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00002455 MemberLoc, BaseExpr));
2456 }
Steve Naroff14108da2009-07-10 23:34:53 +00002457 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2458 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002459 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff14108da2009-07-10 23:34:53 +00002460 // Check whether we can reference this property.
2461 if (DiagnoseUseOfDecl(PD, MemberLoc))
2462 return ExprError();
Daniel Dunbar2307d312008-09-03 01:05:41 +00002463
Steve Naroff14108da2009-07-10 23:34:53 +00002464 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2465 MemberLoc, BaseExpr));
2466 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00002467 // If that failed, look for an "implicit" property by seeing if the nullary
2468 // selector is implemented.
2469
2470 // FIXME: The logic for looking up nullary and unary selectors should be
2471 // shared with the code in ActOnInstanceMessage.
2472
Anders Carlsson8f28f992009-08-26 18:25:21 +00002473 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002474 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002475
Daniel Dunbar2307d312008-09-03 01:05:41 +00002476 // If this reference is in an @implementation, check for 'private' methods.
2477 if (!Getter)
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00002478 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002479
Steve Naroff7692ed62008-10-22 19:16:27 +00002480 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002481 if (!Getter)
2482 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00002483 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002484 // Check if we can reference this property.
2485 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2486 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00002487 }
2488 // If we found a getter then this may be a valid dot-reference, we
2489 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00002490 Selector SetterSel =
2491 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00002492 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002493 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002494 if (!Setter) {
2495 // If this reference is in an @implementation, also check for 'private'
2496 // methods.
Fariborz Jahanianef79bc92009-04-07 18:28:06 +00002497 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00002498 }
2499 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00002500 if (!Setter)
2501 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002502
Steve Naroff1ca66942009-03-11 13:48:17 +00002503 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2504 return ExprError();
2505
2506 if (Getter || Setter) {
2507 QualType PType;
2508
2509 if (Getter)
2510 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00002511 else
2512 // Get the expression type from Setter's incoming parameter.
2513 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00002514 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00002515 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00002516 Setter, MemberLoc, BaseExpr));
2517 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002518 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002519 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00002520 }
Mike Stump1eb44332009-09-09 15:08:12 +00002521
Steve Narofff242b1b2009-07-24 17:54:45 +00002522 // Handle the following exceptional case (*Obj).isa.
Mike Stump1eb44332009-09-09 15:08:12 +00002523 if (OpKind == tok::period &&
Steve Narofff242b1b2009-07-24 17:54:45 +00002524 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00002525 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00002526 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2527 Context.getObjCIdType()));
2528
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002529 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00002530 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002531 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002532 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2533 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002534 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002535 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002536 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002537 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002538
Douglas Gregor214f31a2009-03-27 06:00:30 +00002539 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2540 << BaseType << BaseExpr->getSourceRange();
2541
2542 // If the user is trying to apply -> or . to a function or function
2543 // pointer, it's probably because they forgot parentheses to call
2544 // the function. Suggest the addition of those parentheses.
Mike Stump1eb44332009-09-09 15:08:12 +00002545 if (BaseType == Context.OverloadTy ||
Douglas Gregor214f31a2009-03-27 06:00:30 +00002546 BaseType->isFunctionType() ||
Mike Stump1eb44332009-09-09 15:08:12 +00002547 (BaseType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002548 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor214f31a2009-03-27 06:00:30 +00002549 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2550 Diag(Loc, diag::note_member_reference_needs_call)
2551 << CodeModificationHint::CreateInsertion(Loc, "()");
2552 }
2553
2554 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002555}
2556
Anders Carlsson8f28f992009-08-26 18:25:21 +00002557Action::OwningExprResult
2558Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2559 tok::TokenKind OpKind, SourceLocation MemberLoc,
2560 IdentifierInfo &Member,
2561 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Mike Stump1eb44332009-09-09 15:08:12 +00002562 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002563 DeclarationName(&Member), ObjCImpDecl, SS);
2564}
2565
Anders Carlsson56c5e332009-08-25 03:49:14 +00002566Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2567 FunctionDecl *FD,
2568 ParmVarDecl *Param) {
2569 if (Param->hasUnparsedDefaultArg()) {
2570 Diag (CallLoc,
2571 diag::err_use_of_default_argument_to_function_declared_later) <<
2572 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00002573 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00002574 diag::note_default_argument_declared_here);
2575 } else {
2576 if (Param->hasUninstantiatedDefaultArg()) {
2577 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2578
2579 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002580 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00002581
Mike Stump1eb44332009-09-09 15:08:12 +00002582 InstantiatingTemplate Inst(*this, CallLoc, Param,
2583 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00002584 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00002585
John McCallce3ff2b2009-08-25 22:02:44 +00002586 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00002587 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00002588 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002589
2590 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson56c5e332009-08-25 03:49:14 +00002591 /*FIXME:EqualLoc*/
2592 UninstExpr->getSourceRange().getBegin()))
2593 return ExprError();
2594 }
Mike Stump1eb44332009-09-09 15:08:12 +00002595
Anders Carlsson56c5e332009-08-25 03:49:14 +00002596 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Anders Carlsson56c5e332009-08-25 03:49:14 +00002598 // If the default expression creates temporaries, we need to
2599 // push them to the current stack of expression temporaries so they'll
2600 // be properly destroyed.
Mike Stump1eb44332009-09-09 15:08:12 +00002601 if (CXXExprWithTemporaries *E
Anders Carlsson56c5e332009-08-25 03:49:14 +00002602 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002603 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson56c5e332009-08-25 03:49:14 +00002604 "Can't destroy temporaries in a default argument expr!");
2605 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2606 ExprTemporaries.push_back(E->getTemporary(I));
2607 }
2608 }
2609
2610 // We already type-checked the argument, so we know it works.
2611 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2612}
2613
Douglas Gregor88a35142008-12-22 05:46:06 +00002614/// ConvertArgumentsForCall - Converts the arguments specified in
2615/// Args/NumArgs to the parameter types of the function FDecl with
2616/// function prototype Proto. Call is the call expression itself, and
2617/// Fn is the function expression. For a C++ member function, this
2618/// routine does not attempt to convert the object argument. Returns
2619/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002620bool
2621Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00002622 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00002623 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00002624 Expr **Args, unsigned NumArgs,
2625 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002626 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00002627 // assignment, to the types of the corresponding parameter, ...
2628 unsigned NumArgsInProto = Proto->getNumArgs();
2629 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002630 bool Invalid = false;
2631
Douglas Gregor88a35142008-12-22 05:46:06 +00002632 // If too few arguments are available (and we don't have default
2633 // arguments for the remaining parameters), don't make the call.
2634 if (NumArgs < NumArgsInProto) {
2635 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2636 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2637 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2638 // Use default arguments for missing arguments
2639 NumArgsToCheck = NumArgsInProto;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002640 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00002641 }
2642
2643 // If too many are passed and not variadic, error on the extras and drop
2644 // them.
2645 if (NumArgs > NumArgsInProto) {
2646 if (!Proto->isVariadic()) {
2647 Diag(Args[NumArgsInProto]->getLocStart(),
2648 diag::err_typecheck_call_too_many_args)
2649 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2650 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2651 Args[NumArgs-1]->getLocEnd());
2652 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002653 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002654 Invalid = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00002655 }
2656 NumArgsToCheck = NumArgsInProto;
2657 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002658
Douglas Gregor88a35142008-12-22 05:46:06 +00002659 // Continue to check argument types (even if we have too few/many args).
2660 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2661 QualType ProtoArgType = Proto->getArgType(i);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002662
Douglas Gregor88a35142008-12-22 05:46:06 +00002663 Expr *Arg;
Douglas Gregor61366e92008-12-24 00:01:03 +00002664 if (i < NumArgs) {
Douglas Gregor88a35142008-12-22 05:46:06 +00002665 Arg = Args[i];
Douglas Gregor61366e92008-12-24 00:01:03 +00002666
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002667 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2668 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002669 PDiag(diag::err_call_incomplete_argument)
2670 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002671 return true;
2672
Douglas Gregor61366e92008-12-24 00:01:03 +00002673 // Pass the argument.
2674 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2675 return true;
Anders Carlsson5e300d12009-06-12 16:51:40 +00002676 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00002677 ParmVarDecl *Param = FDecl->getParamDecl(i);
Mike Stump1eb44332009-09-09 15:08:12 +00002678
2679 OwningExprResult ArgExpr =
Anders Carlsson56c5e332009-08-25 03:49:14 +00002680 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2681 FDecl, Param);
2682 if (ArgExpr.isInvalid())
2683 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002684
Anders Carlsson56c5e332009-08-25 03:49:14 +00002685 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00002686 }
Mike Stump1eb44332009-09-09 15:08:12 +00002687
Douglas Gregor88a35142008-12-22 05:46:06 +00002688 Call->setArg(i, Arg);
2689 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002690
Douglas Gregor88a35142008-12-22 05:46:06 +00002691 // If this is a variadic call, handle args passed through "...".
2692 if (Proto->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +00002693 VariadicCallType CallType = VariadicFunction;
2694 if (Fn->getType()->isBlockPointerType())
2695 CallType = VariadicBlock; // Block
2696 else if (isa<MemberExpr>(Fn))
2697 CallType = VariadicMethod;
2698
Douglas Gregor88a35142008-12-22 05:46:06 +00002699 // Promote the arguments (C99 6.5.2.2p7).
2700 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2701 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00002702 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor88a35142008-12-22 05:46:06 +00002703 Call->setArg(i, Arg);
2704 }
2705 }
2706
Douglas Gregor3fd56d72009-01-23 21:30:56 +00002707 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00002708}
2709
Steve Narofff69936d2007-09-16 03:34:24 +00002710/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00002711/// This provides the location of the left/right parens and a list of comma
2712/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002713Action::OwningExprResult
2714Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2715 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00002716 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00002717 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00002718
2719 // Since this might be a postfix expression, get rid of ParenListExprs.
2720 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00002721
Anders Carlssonf1b1d592009-05-01 19:30:39 +00002722 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00002723 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00002724 assert(Fn && "no function call expression");
Chris Lattner04421082008-04-08 04:40:51 +00002725 FunctionDecl *FDecl = NULL;
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002726 NamedDecl *NDecl = NULL;
Douglas Gregor17330012009-02-04 15:01:18 +00002727 DeclarationName UnqualifiedName;
Mike Stump1eb44332009-09-09 15:08:12 +00002728
Douglas Gregor88a35142008-12-22 05:46:06 +00002729 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002730 // If this is a pseudo-destructor expression, build the call immediately.
2731 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2732 if (NumArgs > 0) {
2733 // Pseudo-destructor calls should not have any arguments.
2734 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2735 << CodeModificationHint::CreateRemoval(
2736 SourceRange(Args[0]->getLocStart(),
2737 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Douglas Gregora71d8192009-09-04 17:36:40 +00002739 for (unsigned I = 0; I != NumArgs; ++I)
2740 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002741
Douglas Gregora71d8192009-09-04 17:36:40 +00002742 NumArgs = 0;
2743 }
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Douglas Gregora71d8192009-09-04 17:36:40 +00002745 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2746 RParenLoc));
2747 }
Mike Stump1eb44332009-09-09 15:08:12 +00002748
Douglas Gregor17330012009-02-04 15:01:18 +00002749 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00002750 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00002751 // FIXME: Will need to cache the results of name lookup (including ADL) in
2752 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00002753 bool Dependent = false;
2754 if (Fn->isTypeDependent())
2755 Dependent = true;
2756 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2757 Dependent = true;
2758
2759 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00002760 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00002761 Context.DependentTy, RParenLoc));
2762
2763 // Determine whether this is a call to an object (C++ [over.call.object]).
2764 if (Fn->getType()->isRecordType())
2765 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2766 CommaLocs, RParenLoc));
2767
Douglas Gregorfa047642009-02-04 00:32:51 +00002768 // Determine whether this is a call to a member function.
Douglas Gregore53060f2009-06-25 22:08:12 +00002769 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2770 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2771 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2772 isa<CXXMethodDecl>(MemDecl) ||
2773 (isa<FunctionTemplateDecl>(MemDecl) &&
2774 isa<CXXMethodDecl>(
2775 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002776 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2777 CommaLocs, RParenLoc));
Douglas Gregore53060f2009-06-25 22:08:12 +00002778 }
Douglas Gregor88a35142008-12-22 05:46:06 +00002779 }
2780
Douglas Gregorfa047642009-02-04 00:32:51 +00002781 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002782 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002783 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregorfa047642009-02-04 00:32:51 +00002784 Expr *FnExpr = Fn;
2785 bool ADL = true;
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002786 bool HasExplicitTemplateArgs = 0;
2787 const TemplateArgument *ExplicitTemplateArgs = 0;
2788 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregorfa047642009-02-04 00:32:51 +00002789 while (true) {
2790 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2791 FnExpr = IcExpr->getSubExpr();
2792 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002793 // Parentheses around a function disable ADL
Douglas Gregor17330012009-02-04 15:01:18 +00002794 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregorfa047642009-02-04 00:32:51 +00002795 ADL = false;
2796 FnExpr = PExpr->getSubExpr();
2797 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stumpeed9cac2009-02-19 03:04:26 +00002798 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregorfa047642009-02-04 00:32:51 +00002799 == UnaryOperator::AddrOf) {
2800 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002801 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattner90e150d2009-02-14 07:22:29 +00002802 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2803 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002804 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattner90e150d2009-02-14 07:22:29 +00002805 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002806 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattner90e150d2009-02-14 07:22:29 +00002807 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2808 UnqualifiedName = DepName->getName();
2809 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002810 } else if (TemplateIdRefExpr *TemplateIdRef
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002811 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2812 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregord99cbe62009-07-29 18:26:50 +00002813 if (!NDecl)
2814 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002815 HasExplicitTemplateArgs = true;
2816 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2817 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
Mike Stump1eb44332009-09-09 15:08:12 +00002818
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002819 // C++ [temp.arg.explicit]p6:
2820 // [Note: For simple function names, argument dependent lookup (3.4.2)
Mike Stump1eb44332009-09-09 15:08:12 +00002821 // applies even when the function name is not visible within the
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002822 // scope of the call. This is because the call still has the syntactic
2823 // form of a function call (3.4.1). But when a function template with
2824 // explicit template arguments is used, the call does not have the
Mike Stump1eb44332009-09-09 15:08:12 +00002825 // correct syntactic form unless there is a function template with
2826 // that name visible at the point of the call. If no such name is
2827 // visible, the call is not syntactically well-formed and
2828 // argument-dependent lookup does not apply. If some such name is
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002829 // visible, argument dependent lookup applies and additional function
2830 // templates may be found in other namespaces.
2831 //
2832 // The summary of this paragraph is that, if we get to this point and the
2833 // template-id was not a qualified name, then argument-dependent lookup
2834 // is still possible.
2835 if (TemplateIdRef->getQualifier())
2836 ADL = false;
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002837 break;
Douglas Gregorfa047642009-02-04 00:32:51 +00002838 } else {
Chris Lattner90e150d2009-02-14 07:22:29 +00002839 // Any kind of name that does not refer to a declaration (or
2840 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2841 ADL = false;
Douglas Gregorfa047642009-02-04 00:32:51 +00002842 break;
2843 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002844 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002845
Douglas Gregor17330012009-02-04 15:01:18 +00002846 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregore53060f2009-06-25 22:08:12 +00002847 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002848 if (NDecl) {
2849 FDecl = dyn_cast<FunctionDecl>(NDecl);
2850 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregore53060f2009-06-25 22:08:12 +00002851 FDecl = FunctionTemplate->getTemplatedDecl();
2852 else
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002853 FDecl = dyn_cast<FunctionDecl>(NDecl);
2854 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor17330012009-02-04 15:01:18 +00002855 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002856
Mike Stump1eb44332009-09-09 15:08:12 +00002857 if (Ovl || FunctionTemplate ||
Douglas Gregore53060f2009-06-25 22:08:12 +00002858 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor3e41d602009-02-13 23:20:09 +00002859 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor3c385e52009-02-14 18:57:46 +00002860 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregorfa047642009-02-04 00:32:51 +00002861 ADL = false;
2862
Douglas Gregorf9201e02009-02-11 23:02:49 +00002863 // We don't perform ADL in C.
2864 if (!getLangOptions().CPlusPlus)
2865 ADL = false;
2866
Douglas Gregore53060f2009-06-25 22:08:12 +00002867 if (Ovl || FunctionTemplate || ADL) {
Mike Stump1eb44332009-09-09 15:08:12 +00002868 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002869 HasExplicitTemplateArgs,
2870 ExplicitTemplateArgs,
2871 NumExplicitTemplateArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00002872 LParenLoc, Args, NumArgs, CommaLocs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00002873 RParenLoc, ADL);
Douglas Gregorfa047642009-02-04 00:32:51 +00002874 if (!FDecl)
2875 return ExprError();
2876
2877 // Update Fn to refer to the actual function selected.
2878 Expr *NewFn = 0;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002879 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregoredce4dd2009-06-30 22:34:41 +00002880 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregorab452ba2009-03-26 23:50:42 +00002881 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2882 QDRExpr->getLocation(),
2883 false, false,
2884 QDRExpr->getQualifierRange(),
2885 QDRExpr->getQualifier());
Douglas Gregorfa047642009-02-04 00:32:51 +00002886 else
Mike Stumpeed9cac2009-02-19 03:04:26 +00002887 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregorfa047642009-02-04 00:32:51 +00002888 Fn->getSourceRange().getBegin());
2889 Fn->Destroy(Context);
2890 Fn = NewFn;
2891 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002892 }
Chris Lattner04421082008-04-08 04:40:51 +00002893
2894 // Promote the function operand.
2895 UsualUnaryConversions(Fn);
2896
Chris Lattner925e60d2007-12-28 05:29:59 +00002897 // Make the call expr early, before semantic checks. This guarantees cleanup
2898 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00002899 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2900 Args, NumArgs,
2901 Context.BoolTy,
2902 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00002903
Steve Naroffdd972f22008-09-05 22:11:13 +00002904 const FunctionType *FuncT;
2905 if (!Fn->getType()->isBlockPointerType()) {
2906 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2907 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00002908 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00002909 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002910 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2911 << Fn->getType() << Fn->getSourceRange());
Steve Naroffdd972f22008-09-05 22:11:13 +00002912 FuncT = PT->getPointeeType()->getAsFunctionType();
2913 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00002914 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffdd972f22008-09-05 22:11:13 +00002915 getAsFunctionType();
2916 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002917 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00002918 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2919 << Fn->getType() << Fn->getSourceRange());
2920
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002921 // Check for a valid return type
2922 if (!FuncT->getResultType()->isVoidType() &&
2923 RequireCompleteType(Fn->getSourceRange().getBegin(),
2924 FuncT->getResultType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00002925 PDiag(diag::err_call_incomplete_return)
2926 << TheCall->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002927 return ExprError();
2928
Chris Lattner925e60d2007-12-28 05:29:59 +00002929 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00002930 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002931
Douglas Gregor72564e72009-02-26 23:50:07 +00002932 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00002933 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00002934 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00002935 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002936 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00002937 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002938
Douglas Gregor74734d52009-04-02 15:37:10 +00002939 if (FDecl) {
2940 // Check if we have too few/too many template arguments, based
2941 // on our knowledge of the function definition.
2942 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002943 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00002944 const FunctionProtoType *Proto =
2945 Def->getType()->getAsFunctionProtoType();
2946 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2947 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2948 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2949 }
2950 }
Douglas Gregor74734d52009-04-02 15:37:10 +00002951 }
2952
Steve Naroffb291ab62007-08-28 23:30:39 +00002953 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00002954 for (unsigned i = 0; i != NumArgs; i++) {
2955 Expr *Arg = Args[i];
2956 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002957 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2958 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00002959 PDiag(diag::err_call_incomplete_argument)
2960 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00002961 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00002962 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00002963 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002964 }
Chris Lattner925e60d2007-12-28 05:29:59 +00002965
Douglas Gregor88a35142008-12-22 05:46:06 +00002966 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2967 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00002968 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2969 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00002970
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00002971 // Check for sentinels
2972 if (NDecl)
2973 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002974
Chris Lattner59907c42007-08-10 20:18:51 +00002975 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00002976 if (FDecl) {
2977 if (CheckFunctionCall(FDecl, TheCall.get()))
2978 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002979
2980 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
Anders Carlssond406bf02009-08-16 01:56:34 +00002981 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2982 } else if (NDecl) {
2983 if (CheckBlockCall(NDecl, TheCall.get()))
2984 return ExprError();
2985 }
Chris Lattner59907c42007-08-10 20:18:51 +00002986
Anders Carlssonec74c592009-08-16 03:06:32 +00002987 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00002988}
2989
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002990Action::OwningExprResult
2991Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2992 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00002993 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00002994 //FIXME: Preserve type source info.
2995 QualType literalType = GetTypeFromParser(Ty);
Steve Naroffaff1edd2007-07-19 21:32:11 +00002996 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00002997 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00002998 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00002999
Eli Friedman6223c222008-05-20 05:22:08 +00003000 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003001 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003002 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3003 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003004 } else if (!literalType->isDependentType() &&
3005 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003006 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003007 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003008 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003009 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003010
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003011 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003012 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003013 return ExprError();
Steve Naroffe9b12192008-01-14 18:19:28 +00003014
Chris Lattner371f2582008-12-04 23:50:19 +00003015 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003016 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003017 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003018 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003019 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003020 InitExpr.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003021 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003022 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003023}
3024
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003025Action::OwningExprResult
3026Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003027 SourceLocation RBraceLoc) {
3028 unsigned NumInit = initlist.size();
3029 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003030
Steve Naroff08d92e42007-09-15 18:49:24 +00003031 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003032 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003033
Mike Stumpeed9cac2009-02-19 03:04:26 +00003034 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003035 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003036 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003037 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003038}
3039
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003040/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003041bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003042 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003043 CXXMethodDecl *& ConversionDecl,
3044 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003045 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003046 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3047 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003048
Eli Friedman199ea952009-08-15 19:02:19 +00003049 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003050
3051 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3052 // type needs to be scalar.
3053 if (castType->isVoidType()) {
3054 // Cast to void allows any expr type.
3055 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003056 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3057 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3058 (castType->isStructureType() || castType->isUnionType())) {
3059 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003060 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003061 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3062 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003063 Kind = CastExpr::CK_NoOp;
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003064 } else if (castType->isUnionType()) {
3065 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003066 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003067 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003068 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003069 Field != FieldEnd; ++Field) {
3070 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3071 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3072 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3073 << castExpr->getSourceRange();
3074 break;
3075 }
3076 }
3077 if (Field == FieldEnd)
3078 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3079 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003080 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003081 } else {
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003082 // Reject any other conversions to non-scalar types.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003083 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003084 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003085 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003086 } else if (!castExpr->getType()->isScalarType() &&
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003087 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003088 return Diag(castExpr->getLocStart(),
3089 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003090 << castExpr->getType() << castExpr->getSourceRange();
Nate Begeman58d29a42009-06-26 00:50:28 +00003091 } else if (castType->isExtVectorType()) {
3092 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003093 return true;
3094 } else if (castType->isVectorType()) {
3095 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3096 return true;
Nate Begeman58d29a42009-06-26 00:50:28 +00003097 } else if (castExpr->getType()->isVectorType()) {
3098 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3099 return true;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00003100 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003101 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman41826bb2009-05-01 02:23:58 +00003102 } else if (!castType->isArithmeticType()) {
3103 QualType castExprType = castExpr->getType();
3104 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3105 return Diag(castExpr->getLocStart(),
3106 diag::err_cast_pointer_from_non_pointer_int)
3107 << castExprType << castExpr->getSourceRange();
3108 } else if (!castExpr->getType()->isArithmeticType()) {
3109 if (!castType->isIntegralType() && castType->isArithmeticType())
3110 return Diag(castExpr->getLocStart(),
3111 diag::err_cast_pointer_to_non_pointer_int)
3112 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003113 }
Fariborz Jahanianb5ff6bf2009-05-22 21:42:52 +00003114 if (isa<ObjCSelectorExpr>(castExpr))
3115 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003116 return false;
3117}
3118
Chris Lattnerfe23e212007-12-20 00:44:32 +00003119bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003120 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003121
Anders Carlssona64db8f2007-11-27 05:51:55 +00003122 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003123 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003124 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003125 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003126 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003127 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003128 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003129 } else
3130 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003131 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003132 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003133
Anders Carlssona64db8f2007-11-27 05:51:55 +00003134 return false;
3135}
3136
Nate Begeman58d29a42009-06-26 00:50:28 +00003137bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3138 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Mike Stump1eb44332009-09-09 15:08:12 +00003139
Nate Begeman9b10da62009-06-27 22:05:55 +00003140 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3141 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003142 if (SrcTy->isVectorType()) {
3143 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3144 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3145 << DestTy << SrcTy << R;
3146 return false;
3147 }
3148
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003149 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003150 // conversion will take place first from scalar to elt type, and then
3151 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003152 if (SrcTy->isPointerType())
3153 return Diag(R.getBegin(),
3154 diag::err_invalid_conversion_between_vector_and_scalar)
3155 << DestTy << SrcTy << R;
Nate Begeman58d29a42009-06-26 00:50:28 +00003156 return false;
3157}
3158
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003159Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003160Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003161 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003162 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003163
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003164 assert((Ty != 0) && (Op.get() != 0) &&
3165 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003166
Nate Begeman2ef13e52009-08-10 23:49:36 +00003167 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003168 //FIXME: Preserve type source info.
3169 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003170
Nate Begeman2ef13e52009-08-10 23:49:36 +00003171 // If the Expr being casted is a ParenListExpr, handle it specially.
3172 if (isa<ParenListExpr>(castExpr))
3173 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003174 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003175 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003176 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003177 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003178
3179 if (Method) {
3180 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
3181 Method, move(Op));
3182
3183 if (CastArg.isInvalid())
3184 return ExprError();
3185
3186 castExpr = CastArg.takeAs<Expr>();
3187 } else {
3188 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003189 }
Mike Stump1eb44332009-09-09 15:08:12 +00003190
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003191 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003192 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003193 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003194}
3195
Nate Begeman2ef13e52009-08-10 23:49:36 +00003196/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3197/// of comma binary operators.
3198Action::OwningExprResult
3199Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3200 Expr *expr = EA.takeAs<Expr>();
3201 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3202 if (!E)
3203 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003204
Nate Begeman2ef13e52009-08-10 23:49:36 +00003205 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003206
Nate Begeman2ef13e52009-08-10 23:49:36 +00003207 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3208 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3209 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003210
Nate Begeman2ef13e52009-08-10 23:49:36 +00003211 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3212}
3213
3214Action::OwningExprResult
3215Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3216 SourceLocation RParenLoc, ExprArg Op,
3217 QualType Ty) {
3218 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003219
3220 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003221 // then handle it as such.
3222 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3223 if (PE->getNumExprs() == 0) {
3224 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3225 return ExprError();
3226 }
3227
3228 llvm::SmallVector<Expr *, 8> initExprs;
3229 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3230 initExprs.push_back(PE->getExpr(i));
3231
3232 // FIXME: This means that pretty-printing the final AST will produce curly
3233 // braces instead of the original commas.
3234 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003235 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003236 initExprs.size(), RParenLoc);
3237 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003238 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003239 Owned(E));
3240 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003241 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003242 // sequence of BinOp comma operators.
3243 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3244 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3245 }
3246}
3247
3248Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3249 SourceLocation R,
3250 MultiExprArg Val) {
3251 unsigned nexprs = Val.size();
3252 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3253 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3254 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3255 return Owned(expr);
3256}
3257
Sebastian Redl28507842009-02-26 14:39:58 +00003258/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3259/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00003260/// C99 6.5.15
3261QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3262 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003263 // C++ is sufficiently different to merit its own checker.
3264 if (getLangOptions().CPlusPlus)
3265 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3266
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003267 UsualUnaryConversions(Cond);
3268 UsualUnaryConversions(LHS);
3269 UsualUnaryConversions(RHS);
3270 QualType CondTy = Cond->getType();
3271 QualType LHSTy = LHS->getType();
3272 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00003273
Reid Spencer5f016e22007-07-11 17:01:13 +00003274 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003275 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3276 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3277 << CondTy;
3278 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003279 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003280
Chris Lattner70d67a92008-01-06 22:42:25 +00003281 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00003282 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3283 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00003284
Chris Lattner70d67a92008-01-06 22:42:25 +00003285 // If both operands have arithmetic type, do the usual arithmetic conversions
3286 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003287 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3288 UsualArithmeticConversions(LHS, RHS);
3289 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00003290 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003291
Chris Lattner70d67a92008-01-06 22:42:25 +00003292 // If both operands are the same structure or union type, the result is that
3293 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003294 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3295 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00003296 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00003297 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00003298 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003299 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003300 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00003301 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003302
Chris Lattner70d67a92008-01-06 22:42:25 +00003303 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00003304 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003305 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3306 if (!LHSTy->isVoidType())
3307 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3308 << RHS->getSourceRange();
3309 if (!RHSTy->isVoidType())
3310 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3311 << LHS->getSourceRange();
3312 ImpCastExprToType(LHS, Context.VoidTy);
3313 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedman0e724012008-06-04 19:47:51 +00003314 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00003315 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00003316 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3317 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003318 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003319 RHS->isNullPointerConstant(Context)) {
3320 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3321 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003322 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00003323 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003324 LHS->isNullPointerConstant(Context)) {
3325 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3326 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00003327 }
David Chisnall0f436562009-08-17 16:35:33 +00003328 // Handle things like Class and struct objc_class*. Here we case the result
3329 // to the pseudo-builtin, because that will be implicitly cast back to the
3330 // redefinition type if an attempt is made to access its fields.
3331 if (LHSTy->isObjCClassType() &&
3332 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3333 ImpCastExprToType(RHS, LHSTy);
3334 return LHSTy;
3335 }
3336 if (RHSTy->isObjCClassType() &&
3337 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3338 ImpCastExprToType(LHS, RHSTy);
3339 return RHSTy;
3340 }
3341 // And the same for struct objc_object* / id
3342 if (LHSTy->isObjCIdType() &&
3343 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3344 ImpCastExprToType(RHS, LHSTy);
3345 return LHSTy;
3346 }
3347 if (RHSTy->isObjCIdType() &&
3348 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3349 ImpCastExprToType(LHS, RHSTy);
3350 return RHSTy;
3351 }
Steve Naroff7154a772009-07-01 14:36:47 +00003352 // Handle block pointer types.
3353 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3354 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3355 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3356 QualType destType = Context.getPointerType(Context.VoidTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003357 ImpCastExprToType(LHS, destType);
Steve Naroff7154a772009-07-01 14:36:47 +00003358 ImpCastExprToType(RHS, destType);
3359 return destType;
3360 }
3361 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3362 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3363 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00003364 }
Steve Naroff7154a772009-07-01 14:36:47 +00003365 // We have 2 block pointer types.
3366 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3367 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00003368 return LHSTy;
3369 }
Steve Naroff7154a772009-07-01 14:36:47 +00003370 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00003371 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3372 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003373
Steve Naroff7154a772009-07-01 14:36:47 +00003374 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3375 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00003376 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3377 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3378 // In this situation, we assume void* type. No especially good
3379 // reason, but this is what gcc does, and we do have to pick
3380 // to get a consistent AST.
3381 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3382 ImpCastExprToType(LHS, incompatTy);
3383 ImpCastExprToType(RHS, incompatTy);
3384 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003385 }
Steve Naroff7154a772009-07-01 14:36:47 +00003386 // The block pointer types are compatible.
3387 ImpCastExprToType(LHS, LHSTy);
3388 ImpCastExprToType(RHS, LHSTy);
Steve Naroff91588042009-04-08 17:05:15 +00003389 return LHSTy;
3390 }
Steve Naroff7154a772009-07-01 14:36:47 +00003391 // Check constraints for Objective-C object pointers types.
Steve Naroff14108da2009-07-10 23:34:53 +00003392 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003393
Steve Naroff7154a772009-07-01 14:36:47 +00003394 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3395 // Two identical object pointer types are always compatible.
3396 return LHSTy;
3397 }
Steve Naroff14108da2009-07-10 23:34:53 +00003398 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3399 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff7154a772009-07-01 14:36:47 +00003400 QualType compositeType = LHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003401
Steve Naroff7154a772009-07-01 14:36:47 +00003402 // If both operands are interfaces and either operand can be
3403 // assigned to the other, use that type as the composite
3404 // type. This allows
3405 // xxx ? (A*) a : (B*) b
3406 // where B is a subclass of A.
3407 //
3408 // Additionally, as for assignment, if either type is 'id'
3409 // allow silent coercion. Finally, if the types are
3410 // incompatible then make sure to use 'id' as the composite
3411 // type so the result is acceptable for sending messages to.
3412
3413 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3414 // It could return the composite type.
Steve Naroff14108da2009-07-10 23:34:53 +00003415 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003416 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff14108da2009-07-10 23:34:53 +00003417 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahanian9ec22a32009-08-22 22:27:17 +00003418 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump1eb44332009-09-09 15:08:12 +00003419 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00003420 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff4084c302009-07-23 01:01:38 +00003421 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003422 // Need to handle "id<xx>" explicitly.
Steve Naroff14108da2009-07-10 23:34:53 +00003423 // GCC allows qualified id and any Objective-C type to devolve to
3424 // id. Currently localizing to here until clear this should be
3425 // part of ObjCQualifiedIdTypesAreCompatible.
3426 compositeType = Context.getObjCIdType();
3427 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff7154a772009-07-01 14:36:47 +00003428 compositeType = Context.getObjCIdType();
3429 } else {
3430 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3431 << LHSTy << RHSTy
3432 << LHS->getSourceRange() << RHS->getSourceRange();
3433 QualType incompatTy = Context.getObjCIdType();
3434 ImpCastExprToType(LHS, incompatTy);
3435 ImpCastExprToType(RHS, incompatTy);
3436 return incompatTy;
3437 }
3438 // The object pointer types are compatible.
3439 ImpCastExprToType(LHS, compositeType);
3440 ImpCastExprToType(RHS, compositeType);
3441 return compositeType;
3442 }
Steve Naroffc715e782009-07-29 15:09:39 +00003443 // Check Objective-C object pointer types and 'void *'
3444 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003445 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffc715e782009-07-29 15:09:39 +00003446 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3447 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3448 QualType destType = Context.getPointerType(destPointee);
3449 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3450 ImpCastExprToType(RHS, destType); // promote to void*
3451 return destType;
3452 }
3453 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3454 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00003455 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffc715e782009-07-29 15:09:39 +00003456 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3457 QualType destType = Context.getPointerType(destPointee);
3458 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3459 ImpCastExprToType(LHS, destType); // promote to void*
3460 return destType;
3461 }
Steve Naroff7154a772009-07-01 14:36:47 +00003462 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3463 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3464 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00003465 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3466 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00003467
3468 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3469 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3470 // Figure out necessary qualifiers (C99 6.5.15p6)
3471 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3472 QualType destType = Context.getPointerType(destPointee);
3473 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3474 ImpCastExprToType(RHS, destType); // promote to void*
3475 return destType;
3476 }
3477 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3478 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3479 QualType destType = Context.getPointerType(destPointee);
3480 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3481 ImpCastExprToType(RHS, destType); // promote to void*
3482 return destType;
3483 }
3484
3485 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3486 // Two identical pointer types are always compatible.
3487 return LHSTy;
3488 }
3489 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3490 rhptee.getUnqualifiedType())) {
3491 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3492 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3493 // In this situation, we assume void* type. No especially good
3494 // reason, but this is what gcc does, and we do have to pick
3495 // to get a consistent AST.
3496 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3497 ImpCastExprToType(LHS, incompatTy);
3498 ImpCastExprToType(RHS, incompatTy);
3499 return incompatTy;
3500 }
3501 // The pointer types are compatible.
3502 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3503 // differently qualified versions of compatible types, the result type is
3504 // a pointer to an appropriately qualified version of the *composite*
3505 // type.
3506 // FIXME: Need to calculate the composite type.
3507 // FIXME: Need to add qualifiers
3508 ImpCastExprToType(LHS, LHSTy);
3509 ImpCastExprToType(RHS, LHSTy);
3510 return LHSTy;
3511 }
Mike Stump1eb44332009-09-09 15:08:12 +00003512
Steve Naroff7154a772009-07-01 14:36:47 +00003513 // GCC compatibility: soften pointer/integer mismatch.
3514 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3515 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3516 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3517 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3518 return RHSTy;
3519 }
3520 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3521 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3522 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3523 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3524 return LHSTy;
3525 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00003526
Chris Lattner70d67a92008-01-06 22:42:25 +00003527 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00003528 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3529 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00003530 return QualType();
3531}
3532
Steve Narofff69936d2007-09-16 03:34:24 +00003533/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00003534/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003535Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3536 SourceLocation ColonLoc,
3537 ExprArg Cond, ExprArg LHS,
3538 ExprArg RHS) {
3539 Expr *CondExpr = (Expr *) Cond.get();
3540 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00003541
3542 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3543 // was the condition.
3544 bool isLHSNull = LHSExpr == 0;
3545 if (isLHSNull)
3546 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003547
3548 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00003549 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00003550 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003551 return ExprError();
3552
3553 Cond.release();
3554 LHS.release();
3555 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003556 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003557 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003558 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00003559}
3560
Reid Spencer5f016e22007-07-11 17:01:13 +00003561// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00003562// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00003563// routine is it effectively iqnores the qualifiers on the top level pointee.
3564// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3565// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003566Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003567Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3568 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003569
David Chisnall0f436562009-08-17 16:35:33 +00003570 if ((lhsType->isObjCClassType() &&
3571 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3572 (rhsType->isObjCClassType() &&
3573 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3574 return Compatible;
3575 }
3576
Reid Spencer5f016e22007-07-11 17:01:13 +00003577 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003578 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3579 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003580
Reid Spencer5f016e22007-07-11 17:01:13 +00003581 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00003582 lhptee = Context.getCanonicalType(lhptee);
3583 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00003584
Chris Lattner5cf216b2008-01-04 18:04:52 +00003585 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003586
3587 // C99 6.5.16.1p1: This following citation is common to constraints
3588 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3589 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00003590 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00003591 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00003592 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003593
Mike Stumpeed9cac2009-02-19 03:04:26 +00003594 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3595 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00003596 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003597 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003598 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003599 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003600
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003601 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003602 assert(rhptee->isFunctionType());
3603 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003604 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003605
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003606 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00003607 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00003608 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003609
3610 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00003611 assert(lhptee->isFunctionType());
3612 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00003613 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003614 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00003615 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003616 lhptee = lhptee.getUnqualifiedType();
3617 rhptee = rhptee.getUnqualifiedType();
3618 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3619 // Check if the pointee types are compatible ignoring the sign.
3620 // We explicitly check for char so that we catch "char" vs
3621 // "unsigned char" on systems where "char" is unsigned.
3622 if (lhptee->isCharType()) {
3623 lhptee = Context.UnsignedCharTy;
3624 } else if (lhptee->isSignedIntegerType()) {
3625 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3626 }
3627 if (rhptee->isCharType()) {
3628 rhptee = Context.UnsignedCharTy;
3629 } else if (rhptee->isSignedIntegerType()) {
3630 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3631 }
3632 if (lhptee == rhptee) {
3633 // Types are compatible ignoring the sign. Qualifier incompatibility
3634 // takes priority over sign incompatibility because the sign
3635 // warning can be disabled.
3636 if (ConvTy != Compatible)
3637 return ConvTy;
3638 return IncompatiblePointerSign;
3639 }
3640 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00003641 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00003642 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00003643 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003644}
3645
Steve Naroff1c7d0672008-09-04 15:10:53 +00003646/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3647/// block pointer types are compatible or whether a block and normal pointer
3648/// are compatible. It is more restrict than comparing two function pointer
3649// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003650Sema::AssignConvertType
3651Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00003652 QualType rhsType) {
3653 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003654
Steve Naroff1c7d0672008-09-04 15:10:53 +00003655 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00003656 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3657 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003658
Steve Naroff1c7d0672008-09-04 15:10:53 +00003659 // make sure we operate on the canonical type
3660 lhptee = Context.getCanonicalType(lhptee);
3661 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003662
Steve Naroff1c7d0672008-09-04 15:10:53 +00003663 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003664
Steve Naroff1c7d0672008-09-04 15:10:53 +00003665 // For blocks we enforce that qualifiers are identical.
3666 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3667 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003668
Eli Friedman26784c12009-06-08 05:08:54 +00003669 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00003670 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003671 return ConvTy;
3672}
3673
Mike Stumpeed9cac2009-02-19 03:04:26 +00003674/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3675/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00003676/// pointers. Here are some objectionable examples that GCC considers warnings:
3677///
3678/// int a, *pint;
3679/// short *pshort;
3680/// struct foo *pfoo;
3681///
3682/// pint = pshort; // warning: assignment from incompatible pointer type
3683/// a = pint; // warning: assignment makes integer from pointer without a cast
3684/// pint = a; // warning: assignment makes pointer from integer without a cast
3685/// pint = pfoo; // warning: assignment from incompatible pointer type
3686///
3687/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00003688/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00003689///
Chris Lattner5cf216b2008-01-04 18:04:52 +00003690Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00003691Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00003692 // Get canonical types. We're not formatting these types, just comparing
3693 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003694 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3695 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003696
3697 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00003698 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00003699
David Chisnall0f436562009-08-17 16:35:33 +00003700 if ((lhsType->isObjCClassType() &&
3701 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3702 (rhsType->isObjCClassType() &&
3703 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3704 return Compatible;
3705 }
3706
Douglas Gregor9d293df2008-10-28 00:22:11 +00003707 // If the left-hand side is a reference type, then we are in a
3708 // (rare!) case where we've allowed the use of references in C,
3709 // e.g., as a parameter type in a built-in function. In this case,
3710 // just make sure that the type referenced is compatible with the
3711 // right-hand side type. The caller is responsible for adjusting
3712 // lhsType so that the resulting expression does not have reference
3713 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00003714 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00003715 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00003716 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003717 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00003718 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003719 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3720 // to the same ExtVector type.
3721 if (lhsType->isExtVectorType()) {
3722 if (rhsType->isExtVectorType())
3723 return lhsType == rhsType ? Compatible : Incompatible;
3724 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3725 return Compatible;
3726 }
Mike Stump1eb44332009-09-09 15:08:12 +00003727
Nate Begemanbe2341d2008-07-14 18:02:46 +00003728 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003729 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00003730 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00003731 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00003732 if (getLangOptions().LaxVectorConversions &&
3733 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003734 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003735 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00003736 }
3737 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003738 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003739
Chris Lattnere8b3e962008-01-04 23:32:24 +00003740 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00003741 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003742
Chris Lattner78eca282008-04-07 06:49:41 +00003743 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003744 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003745 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003746
Chris Lattner78eca282008-04-07 06:49:41 +00003747 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003748 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003749
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003750 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003751 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003752 if (lhsType->isVoidPointerType()) // an exception to the rule.
3753 return Compatible;
3754 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003755 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003756 if (rhsType->getAs<BlockPointerType>()) {
3757 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003758 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00003759
3760 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003761 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003762 return Compatible;
3763 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00003764 return Incompatible;
3765 }
3766
3767 if (isa<BlockPointerType>(lhsType)) {
3768 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00003769 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003770
Steve Naroffb4406862008-09-29 18:10:17 +00003771 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00003772 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00003773 return Compatible;
3774
Steve Naroff1c7d0672008-09-04 15:10:53 +00003775 if (rhsType->isBlockPointerType())
3776 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003777
Ted Kremenek6217b802009-07-29 21:53:49 +00003778 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00003779 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003780 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00003781 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00003782 return Incompatible;
3783 }
3784
Steve Naroff14108da2009-07-10 23:34:53 +00003785 if (isa<ObjCObjectPointerType>(lhsType)) {
3786 if (rhsType->isIntegerType())
3787 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00003788
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003789 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003790 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003791 if (rhsType->isVoidPointerType()) // an exception to the rule.
3792 return Compatible;
3793 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003794 }
3795 if (rhsType->isObjCObjectPointerType()) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00003796 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3797 return Compatible;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003798 if (Context.typesAreCompatible(lhsType, rhsType))
3799 return Compatible;
Steve Naroff4084c302009-07-23 01:01:38 +00003800 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3801 return IncompatibleObjCQualifiedId;
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003802 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003803 }
Ted Kremenek6217b802009-07-29 21:53:49 +00003804 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00003805 if (RHSPT->getPointeeType()->isVoidType())
3806 return Compatible;
3807 }
3808 // Treat block pointers as objects.
3809 if (rhsType->isBlockPointerType())
3810 return Compatible;
3811 return Incompatible;
3812 }
Chris Lattner78eca282008-04-07 06:49:41 +00003813 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003814 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003815 if (lhsType == Context.BoolTy)
3816 return Compatible;
3817
3818 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00003819 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00003820
Mike Stumpeed9cac2009-02-19 03:04:26 +00003821 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003822 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00003823
3824 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003825 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00003826 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003827 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00003828 }
Steve Naroff14108da2009-07-10 23:34:53 +00003829 if (isa<ObjCObjectPointerType>(rhsType)) {
3830 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3831 if (lhsType == Context.BoolTy)
3832 return Compatible;
3833
3834 if (lhsType->isIntegerType())
3835 return PointerToInt;
3836
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003837 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00003838 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003839 if (lhsType->isVoidPointerType()) // an exception to the rule.
3840 return Compatible;
3841 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00003842 }
3843 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00003844 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00003845 return Compatible;
3846 return Incompatible;
3847 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00003848
Chris Lattnerfc144e22008-01-04 23:18:45 +00003849 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00003850 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00003851 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00003852 }
3853 return Incompatible;
3854}
3855
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003856/// \brief Constructs a transparent union from an expression that is
3857/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00003858static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003859 QualType UnionType, FieldDecl *Field) {
3860 // Build an initializer list that designates the appropriate member
3861 // of the transparent union.
3862 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3863 &E, 1,
3864 SourceLocation());
3865 Initializer->setType(UnionType);
3866 Initializer->setInitializedFieldInUnion(Field);
3867
3868 // Build a compound literal constructing a value of the transparent
3869 // union type from this initializer list.
3870 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3871 false);
3872}
3873
3874Sema::AssignConvertType
3875Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3876 QualType FromType = rExpr->getType();
3877
Mike Stump1eb44332009-09-09 15:08:12 +00003878 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003879 // transparent_union GCC extension.
3880 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00003881 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003882 return Incompatible;
3883
3884 // The field to initialize within the transparent union.
3885 RecordDecl *UD = UT->getDecl();
3886 FieldDecl *InitField = 0;
3887 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003888 for (RecordDecl::field_iterator it = UD->field_begin(),
3889 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003890 it != itend; ++it) {
3891 if (it->getType()->isPointerType()) {
3892 // If the transparent union contains a pointer type, we allow:
3893 // 1) void pointer
3894 // 2) null pointer constant
3895 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00003896 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003897 ImpCastExprToType(rExpr, it->getType());
3898 InitField = *it;
3899 break;
3900 }
Mike Stump1eb44332009-09-09 15:08:12 +00003901
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003902 if (rExpr->isNullPointerConstant(Context)) {
3903 ImpCastExprToType(rExpr, it->getType());
3904 InitField = *it;
3905 break;
3906 }
3907 }
3908
3909 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3910 == Compatible) {
3911 InitField = *it;
3912 break;
3913 }
3914 }
3915
3916 if (!InitField)
3917 return Incompatible;
3918
3919 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3920 return Compatible;
3921}
3922
Chris Lattner5cf216b2008-01-04 18:04:52 +00003923Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00003924Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00003925 if (getLangOptions().CPlusPlus) {
3926 if (!lhsType->isRecordType()) {
3927 // C++ 5.17p3: If the left operand is not of class type, the
3928 // expression is implicitly converted (C++ 4) to the
3929 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00003930 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3931 "assigning"))
Douglas Gregor98cd5992008-10-21 23:43:52 +00003932 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00003933 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00003934 }
3935
3936 // FIXME: Currently, we fall through and treat C++ classes like C
3937 // structures.
3938 }
3939
Steve Naroff529a4ad2007-11-27 17:58:44 +00003940 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3941 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00003942 if ((lhsType->isPointerType() ||
3943 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00003944 lhsType->isBlockPointerType())
Fariborz Jahanian9d3185e2008-01-03 18:46:52 +00003945 && rExpr->isNullPointerConstant(Context)) {
Chris Lattner1e0a3902008-01-16 19:17:22 +00003946 ImpCastExprToType(rExpr, lhsType);
Steve Naroff529a4ad2007-11-27 17:58:44 +00003947 return Compatible;
3948 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00003949
Chris Lattner943140e2007-10-16 02:55:40 +00003950 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00003951 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff08d92e42007-09-15 18:49:24 +00003952 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00003953 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00003954 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00003955 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00003956 if (!lhsType->isReferenceType())
3957 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00003958
Chris Lattner5cf216b2008-01-04 18:04:52 +00003959 Sema::AssignConvertType result =
3960 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00003961
Steve Narofff1120de2007-08-24 22:33:52 +00003962 // C99 6.5.16.1p2: The value of the right operand is converted to the
3963 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00003964 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3965 // so that we can use references in built-in functions even in C.
3966 // The getNonReferenceType() call makes sure that the resulting expression
3967 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00003968 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor9d293df2008-10-28 00:22:11 +00003969 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Narofff1120de2007-08-24 22:33:52 +00003970 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00003971}
3972
Chris Lattner29a1cfb2008-11-18 01:30:42 +00003973QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003974 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00003975 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00003976 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00003977 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003978}
3979
Mike Stumpeed9cac2009-02-19 03:04:26 +00003980inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff49b45262007-07-13 16:58:59 +00003981 Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003982 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003983 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00003984 QualType lhsType =
3985 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3986 QualType rhsType =
3987 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00003988
Nate Begemanbe2341d2008-07-14 18:02:46 +00003989 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00003990 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00003991 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00003992
Nate Begemanbe2341d2008-07-14 18:02:46 +00003993 // Handle the case of a vector & extvector type of the same size and element
3994 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00003995 if (getLangOptions().LaxVectorConversions) {
3996 // FIXME: Should we warn here?
3997 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00003998 if (const VectorType *RV = rhsType->getAsVectorType())
3999 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004000 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004001 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004002 }
4003 }
4004 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004005
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004006 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4007 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4008 bool swapped = false;
4009 if (rhsType->isExtVectorType()) {
4010 swapped = true;
4011 std::swap(rex, lex);
4012 std::swap(rhsType, lhsType);
4013 }
Mike Stump1eb44332009-09-09 15:08:12 +00004014
Nate Begemandde25982009-06-28 19:12:57 +00004015 // Handle the case of an ext vector and scalar.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004016 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
4017 QualType EltTy = LV->getElementType();
4018 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4019 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemandde25982009-06-28 19:12:57 +00004020 ImpCastExprToType(rex, lhsType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004021 if (swapped) std::swap(rex, lex);
4022 return lhsType;
4023 }
4024 }
4025 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4026 rhsType->isRealFloatingType()) {
4027 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemandde25982009-06-28 19:12:57 +00004028 ImpCastExprToType(rex, lhsType);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004029 if (swapped) std::swap(rex, lex);
4030 return lhsType;
4031 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004032 }
4033 }
Mike Stump1eb44332009-09-09 15:08:12 +00004034
Nate Begemandde25982009-06-28 19:12:57 +00004035 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004036 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004037 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004038 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004039 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004040}
4041
Reid Spencer5f016e22007-07-11 17:01:13 +00004042inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004043 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004044 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004045 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004046
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004047 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004048
Steve Naroffa4332e22007-07-17 00:58:39 +00004049 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004050 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004051 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004052}
4053
4054inline QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004055 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004056 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4057 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4058 return CheckVectorOperands(Loc, lex, rex);
4059 return InvalidOperands(Loc, lex, rex);
4060 }
Steve Naroff90045e82007-07-13 23:32:42 +00004061
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004062 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004063
Steve Naroffa4332e22007-07-17 00:58:39 +00004064 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004065 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004066 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004067}
4068
4069inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004070 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004071 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4072 QualType compType = CheckVectorOperands(Loc, lex, rex);
4073 if (CompLHSTy) *CompLHSTy = compType;
4074 return compType;
4075 }
Steve Naroff49b45262007-07-13 16:58:59 +00004076
Eli Friedmanab3a8522009-03-28 01:22:36 +00004077 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004078
Reid Spencer5f016e22007-07-11 17:01:13 +00004079 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004080 if (lex->getType()->isArithmeticType() &&
4081 rex->getType()->isArithmeticType()) {
4082 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004083 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004084 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004085
Eli Friedmand72d16e2008-05-18 18:08:51 +00004086 // Put any potential pointer into PExp
4087 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004088 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004089 std::swap(PExp, IExp);
4090
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004091 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Eli Friedmand72d16e2008-05-18 18:08:51 +00004093 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004094 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004095
Chris Lattnerb5f15622009-04-24 23:50:08 +00004096 // Check for arithmetic on pointers to incomplete types.
4097 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004098 if (getLangOptions().CPlusPlus) {
4099 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004100 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004101 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004102 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004103
4104 // GNU extension: arithmetic on pointer to void
4105 Diag(Loc, diag::ext_gnu_void_ptr)
4106 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004107 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004108 if (getLangOptions().CPlusPlus) {
4109 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4110 << lex->getType() << lex->getSourceRange();
4111 return QualType();
4112 }
4113
4114 // GNU extension: arithmetic on pointer to function
4115 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4116 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004117 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004118 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004119 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004120 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004121 PExp->getType()->isObjCObjectPointerType()) &&
4122 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004123 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4124 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004125 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004126 return QualType();
4127 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004128 // Diagnose bad cases where we step over interface counts.
4129 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4130 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4131 << PointeeTy << PExp->getSourceRange();
4132 return QualType();
4133 }
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Eli Friedmanab3a8522009-03-28 01:22:36 +00004135 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004136 QualType LHSTy = Context.isPromotableBitField(lex);
4137 if (LHSTy.isNull()) {
4138 LHSTy = lex->getType();
4139 if (LHSTy->isPromotableIntegerType())
4140 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004141 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004142 *CompLHSTy = LHSTy;
4143 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004144 return PExp->getType();
4145 }
4146 }
4147
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004148 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004149}
4150
Chris Lattnereca7be62008-04-07 05:30:13 +00004151// C99 6.5.6
4152QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004153 SourceLocation Loc, QualType* CompLHSTy) {
4154 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4155 QualType compType = CheckVectorOperands(Loc, lex, rex);
4156 if (CompLHSTy) *CompLHSTy = compType;
4157 return compType;
4158 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004159
Eli Friedmanab3a8522009-03-28 01:22:36 +00004160 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004161
Chris Lattner6e4ab612007-12-09 21:53:25 +00004162 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004163
Chris Lattner6e4ab612007-12-09 21:53:25 +00004164 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00004165 if (lex->getType()->isArithmeticType()
4166 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004167 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004168 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004169 }
Mike Stump1eb44332009-09-09 15:08:12 +00004170
Chris Lattner6e4ab612007-12-09 21:53:25 +00004171 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004172 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00004173 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004174
Douglas Gregore7450f52009-03-24 19:52:54 +00004175 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00004176
Douglas Gregore7450f52009-03-24 19:52:54 +00004177 bool ComplainAboutVoid = false;
4178 Expr *ComplainAboutFunc = 0;
4179 if (lpointee->isVoidType()) {
4180 if (getLangOptions().CPlusPlus) {
4181 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4182 << lex->getSourceRange() << rex->getSourceRange();
4183 return QualType();
4184 }
4185
4186 // GNU C extension: arithmetic on pointer to void
4187 ComplainAboutVoid = true;
4188 } else if (lpointee->isFunctionType()) {
4189 if (getLangOptions().CPlusPlus) {
4190 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004191 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004192 return QualType();
4193 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004194
4195 // GNU C extension: arithmetic on pointer to function
4196 ComplainAboutFunc = lex;
4197 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00004198 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004199 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00004200 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004201 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004202 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004203
Chris Lattnerb5f15622009-04-24 23:50:08 +00004204 // Diagnose bad cases where we step over interface counts.
4205 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4206 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4207 << lpointee << lex->getSourceRange();
4208 return QualType();
4209 }
Mike Stump1eb44332009-09-09 15:08:12 +00004210
Chris Lattner6e4ab612007-12-09 21:53:25 +00004211 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00004212 if (rex->getType()->isIntegerType()) {
4213 if (ComplainAboutVoid)
4214 Diag(Loc, diag::ext_gnu_void_ptr)
4215 << lex->getSourceRange() << rex->getSourceRange();
4216 if (ComplainAboutFunc)
4217 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004218 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004219 << ComplainAboutFunc->getSourceRange();
4220
Eli Friedmanab3a8522009-03-28 01:22:36 +00004221 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004222 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00004223 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004224
Chris Lattner6e4ab612007-12-09 21:53:25 +00004225 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004226 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00004227 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004228
Douglas Gregore7450f52009-03-24 19:52:54 +00004229 // RHS must be a completely-type object type.
4230 // Handle the GNU void* extension.
4231 if (rpointee->isVoidType()) {
4232 if (getLangOptions().CPlusPlus) {
4233 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4234 << lex->getSourceRange() << rex->getSourceRange();
4235 return QualType();
4236 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004237
Douglas Gregore7450f52009-03-24 19:52:54 +00004238 ComplainAboutVoid = true;
4239 } else if (rpointee->isFunctionType()) {
4240 if (getLangOptions().CPlusPlus) {
4241 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00004242 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004243 return QualType();
4244 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004245
4246 // GNU extension: arithmetic on pointer to function
4247 if (!ComplainAboutFunc)
4248 ComplainAboutFunc = rex;
4249 } else if (!rpointee->isDependentType() &&
4250 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00004251 PDiag(diag::err_typecheck_sub_ptr_object)
4252 << rex->getSourceRange()
4253 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00004254 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004255
Eli Friedman88d936b2009-05-16 13:54:38 +00004256 if (getLangOptions().CPlusPlus) {
4257 // Pointee types must be the same: C++ [expr.add]
4258 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4259 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4260 << lex->getType() << rex->getType()
4261 << lex->getSourceRange() << rex->getSourceRange();
4262 return QualType();
4263 }
4264 } else {
4265 // Pointee types must be compatible C99 6.5.6p3
4266 if (!Context.typesAreCompatible(
4267 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4268 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4269 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4270 << lex->getType() << rex->getType()
4271 << lex->getSourceRange() << rex->getSourceRange();
4272 return QualType();
4273 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00004274 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004275
Douglas Gregore7450f52009-03-24 19:52:54 +00004276 if (ComplainAboutVoid)
4277 Diag(Loc, diag::ext_gnu_void_ptr)
4278 << lex->getSourceRange() << rex->getSourceRange();
4279 if (ComplainAboutFunc)
4280 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00004281 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00004282 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00004283
4284 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00004285 return Context.getPointerDiffType();
4286 }
4287 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004288
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004289 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004290}
4291
Chris Lattnereca7be62008-04-07 05:30:13 +00004292// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004293QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00004294 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00004295 // C99 6.5.7p2: Each of the operands shall have integer type.
4296 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004297 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004298
Chris Lattnerca5eede2007-12-12 05:47:28 +00004299 // Shifts don't perform usual arithmetic conversions, they just do integer
4300 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00004301 QualType LHSTy = Context.isPromotableBitField(lex);
4302 if (LHSTy.isNull()) {
4303 LHSTy = lex->getType();
4304 if (LHSTy->isPromotableIntegerType())
4305 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004306 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00004307 if (!isCompAssign)
Eli Friedmanab3a8522009-03-28 01:22:36 +00004308 ImpCastExprToType(lex, LHSTy);
4309
Chris Lattnerca5eede2007-12-12 05:47:28 +00004310 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004311
Ryan Flynnd0439682009-08-07 16:20:20 +00004312 // Sanity-check shift operands
4313 llvm::APSInt Right;
4314 // Check right/shifter operand
4315 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00004316 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00004317 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4318 else {
4319 llvm::APInt LeftBits(Right.getBitWidth(),
4320 Context.getTypeSize(lex->getType()));
4321 if (Right.uge(LeftBits))
4322 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4323 }
4324 }
4325
Chris Lattnerca5eede2007-12-12 05:47:28 +00004326 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00004327 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004328}
4329
Douglas Gregor0c6db942009-05-04 06:07:12 +00004330// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004331QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00004332 unsigned OpaqueOpc, bool isRelational) {
4333 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4334
Nate Begemanbe2341d2008-07-14 18:02:46 +00004335 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004336 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004337
Chris Lattnera5937dd2007-08-26 01:18:55 +00004338 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00004339 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4340 UsualArithmeticConversions(lex, rex);
4341 else {
4342 UsualUnaryConversions(lex);
4343 UsualUnaryConversions(rex);
4344 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004345 QualType lType = lex->getType();
4346 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004347
Mike Stumpaf199f32009-05-07 18:43:07 +00004348 if (!lType->isFloatingType()
4349 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00004350 // For non-floating point types, check for self-comparisons of the form
4351 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4352 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00004353 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00004354 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00004355 Expr *LHSStripped = lex->IgnoreParens();
4356 Expr *RHSStripped = rex->IgnoreParens();
4357 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4358 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00004359 if (DRL->getDecl() == DRR->getDecl() &&
4360 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004361 Diag(Loc, diag::warn_selfcomparison);
Mike Stump1eb44332009-09-09 15:08:12 +00004362
Chris Lattner55660a72009-03-08 19:39:53 +00004363 if (isa<CastExpr>(LHSStripped))
4364 LHSStripped = LHSStripped->IgnoreParenCasts();
4365 if (isa<CastExpr>(RHSStripped))
4366 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00004367
Chris Lattner55660a72009-03-08 19:39:53 +00004368 // Warn about comparisons against a string constant (unless the other
4369 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00004370 Expr *literalString = 0;
4371 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00004372 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregora86b8322009-04-06 18:45:53 +00004373 !RHSStripped->isNullPointerConstant(Context)) {
4374 literalString = lex;
4375 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004376 } else if ((isa<StringLiteral>(RHSStripped) ||
4377 isa<ObjCEncodeExpr>(RHSStripped)) &&
4378 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00004379 literalString = rex;
4380 literalStringStripped = RHSStripped;
4381 }
4382
4383 if (literalString) {
4384 std::string resultComparison;
4385 switch (Opc) {
4386 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4387 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4388 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4389 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4390 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4391 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4392 default: assert(false && "Invalid comparison operator");
4393 }
4394 Diag(Loc, diag::warn_stringcompare)
4395 << isa<ObjCEncodeExpr>(literalStringStripped)
4396 << literalString->getSourceRange()
Douglas Gregora3a83512009-04-01 23:51:29 +00004397 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4398 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4399 "strcmp(")
4400 << CodeModificationHint::CreateInsertion(
4401 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregora86b8322009-04-06 18:45:53 +00004402 resultComparison);
4403 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00004404 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004405
Douglas Gregor447b69e2008-11-19 03:25:36 +00004406 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner55660a72009-03-08 19:39:53 +00004407 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00004408
Chris Lattnera5937dd2007-08-26 01:18:55 +00004409 if (isRelational) {
4410 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004411 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004412 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004413 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00004414 if (lType->isFloatingType()) {
Chris Lattner55660a72009-03-08 19:39:53 +00004415 assert(rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004416 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek6a261552007-10-29 16:40:01 +00004417 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004418
Chris Lattnera5937dd2007-08-26 01:18:55 +00004419 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00004420 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00004421 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004422
Chris Lattnerd28f8152007-08-26 01:10:14 +00004423 bool LHSIsNull = lex->isNullPointerConstant(Context);
4424 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004425
Chris Lattnera5937dd2007-08-26 01:18:55 +00004426 // All of the following pointer related warnings are GCC extensions, except
4427 // when handling null pointer constants. One day, we can consider making them
4428 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00004429 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00004430 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004431 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00004432 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00004433 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004434
Douglas Gregor0c6db942009-05-04 06:07:12 +00004435 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00004436 if (LCanPointeeTy == RCanPointeeTy)
4437 return ResultTy;
4438
Douglas Gregor0c6db942009-05-04 06:07:12 +00004439 // C++ [expr.rel]p2:
4440 // [...] Pointer conversions (4.10) and qualification
4441 // conversions (4.4) are performed on pointer operands (or on
4442 // a pointer operand and a null pointer constant) to bring
4443 // them to their composite pointer type. [...]
4444 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00004445 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00004446 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00004447 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00004448 if (T.isNull()) {
4449 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4450 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4451 return QualType();
4452 }
4453
4454 ImpCastExprToType(lex, T);
4455 ImpCastExprToType(rex, T);
4456 return ResultTy;
4457 }
Eli Friedman3075e762009-08-23 00:27:47 +00004458 // C99 6.5.9p2 and C99 6.5.8p2
4459 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4460 RCanPointeeTy.getUnqualifiedType())) {
4461 // Valid unless a relational comparison of function pointers
4462 if (isRelational && LCanPointeeTy->isFunctionType()) {
4463 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4464 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4465 }
4466 } else if (!isRelational &&
4467 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4468 // Valid unless comparison between non-null pointer and function pointer
4469 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4470 && !LHSIsNull && !RHSIsNull) {
4471 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4472 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4473 }
4474 } else {
4475 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004476 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004477 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004478 }
Eli Friedman3075e762009-08-23 00:27:47 +00004479 if (LCanPointeeTy != RCanPointeeTy)
4480 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004481 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004482 }
Mike Stump1eb44332009-09-09 15:08:12 +00004483
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004484 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00004485 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00004486 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00004487 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004488 (lType->isPointerType() ||
4489 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004490 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004491 return ResultTy;
4492 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004493 if (LHSIsNull &&
4494 (rType->isPointerType() ||
4495 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00004496 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004497 return ResultTy;
4498 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00004499
4500 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00004501 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00004502 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4503 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00004504 // In addition, pointers to members can be compared, or a pointer to
4505 // member and a null pointer constant. Pointer to member conversions
4506 // (4.11) and qualification conversions (4.4) are performed to bring
4507 // them to a common type. If one operand is a null pointer constant,
4508 // the common type is the type of the other operand. Otherwise, the
4509 // common type is a pointer to member type similar (4.4) to the type
4510 // of one of the operands, with a cv-qualification signature (4.4)
4511 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00004512 // types.
4513 QualType T = FindCompositePointerType(lex, rex);
4514 if (T.isNull()) {
4515 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4516 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4517 return QualType();
4518 }
Mike Stump1eb44332009-09-09 15:08:12 +00004519
Douglas Gregor20b3e992009-08-24 17:42:35 +00004520 ImpCastExprToType(lex, T);
4521 ImpCastExprToType(rex, T);
4522 return ResultTy;
4523 }
Mike Stump1eb44332009-09-09 15:08:12 +00004524
Douglas Gregor20b3e992009-08-24 17:42:35 +00004525 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00004526 if (lType->isNullPtrType() && rType->isNullPtrType())
4527 return ResultTy;
4528 }
Mike Stump1eb44332009-09-09 15:08:12 +00004529
Steve Naroff1c7d0672008-09-04 15:10:53 +00004530 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004531 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004532 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4533 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004534
Steve Naroff1c7d0672008-09-04 15:10:53 +00004535 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00004536 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004537 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00004538 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00004539 }
4540 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004541 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004542 }
Steve Naroff59f53942008-09-28 01:11:11 +00004543 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004544 if (!isRelational
4545 && ((lType->isBlockPointerType() && rType->isPointerType())
4546 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00004547 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004548 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004549 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004550 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00004551 ->getPointeeType()->isVoidType())))
4552 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4553 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00004554 }
4555 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004556 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00004557 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004558
Steve Naroff14108da2009-07-10 23:34:53 +00004559 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00004560 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004561 const PointerType *LPT = lType->getAs<PointerType>();
4562 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004563 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004564 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004565 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00004566 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004567
Steve Naroffa8069f12008-11-17 19:49:16 +00004568 if (!LPtrToVoid && !RPtrToVoid &&
4569 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004570 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00004571 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00004572 }
Daniel Dunbarc6cb77f2008-10-23 23:30:52 +00004573 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004574 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00004575 }
Steve Naroff14108da2009-07-10 23:34:53 +00004576 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004577 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00004578 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4579 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff20373222008-06-03 14:04:54 +00004580 ImpCastExprToType(rex, lType);
Douglas Gregor447b69e2008-11-19 03:25:36 +00004581 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00004582 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00004583 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004584 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004585 unsigned DiagID = 0;
4586 if (RHSIsNull) {
4587 if (isRelational)
4588 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4589 } else if (isRelational)
4590 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4591 else
4592 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004593
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004594 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004595 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004596 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004597 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00004598 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004599 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00004600 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004601 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004602 unsigned DiagID = 0;
4603 if (LHSIsNull) {
4604 if (isRelational)
4605 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4606 } else if (isRelational)
4607 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4608 else
4609 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00004610
Chris Lattner06c0f5b2009-08-23 00:03:44 +00004611 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00004612 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00004613 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00004614 }
Chris Lattner1e0a3902008-01-16 19:17:22 +00004615 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004616 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004617 }
Steve Naroff39218df2008-09-04 16:56:14 +00004618 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00004619 if (!isRelational && RHSIsNull
4620 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff39218df2008-09-04 16:56:14 +00004621 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004622 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004623 }
Mike Stumpaf199f32009-05-07 18:43:07 +00004624 if (!isRelational && LHSIsNull
4625 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff39218df2008-09-04 16:56:14 +00004626 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor447b69e2008-11-19 03:25:36 +00004627 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00004628 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004629 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004630}
4631
Nate Begemanbe2341d2008-07-14 18:02:46 +00004632/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00004633/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004634/// like a scalar comparison, a vector comparison produces a vector of integer
4635/// types.
4636QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004637 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00004638 bool isRelational) {
4639 // Check to make sure we're operating on vectors of the same type and width,
4640 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004641 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004642 if (vType.isNull())
4643 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004644
Nate Begemanbe2341d2008-07-14 18:02:46 +00004645 QualType lType = lex->getType();
4646 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004647
Nate Begemanbe2341d2008-07-14 18:02:46 +00004648 // For non-floating point types, check for self-comparisons of the form
4649 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4650 // often indicate logic errors in the program.
4651 if (!lType->isFloatingType()) {
4652 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4653 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4654 if (DRL->getDecl() == DRR->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004655 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004656 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004657
Nate Begemanbe2341d2008-07-14 18:02:46 +00004658 // Check for comparisons of floating point operands using != and ==.
4659 if (!isRelational && lType->isFloatingType()) {
4660 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004661 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00004662 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004663
Nate Begemanbe2341d2008-07-14 18:02:46 +00004664 // Return the type for the comparison, which is the same as vector type for
4665 // integer vectors, or an integer type of identical size and number of
4666 // elements for floating point vectors.
4667 if (lType->isIntegerType())
4668 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004669
Nate Begemanbe2341d2008-07-14 18:02:46 +00004670 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanbe2341d2008-07-14 18:02:46 +00004671 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00004672 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00004673 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00004674 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00004675 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4676
Mike Stumpeed9cac2009-02-19 03:04:26 +00004677 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00004678 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00004679 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4680}
4681
Reid Spencer5f016e22007-07-11 17:01:13 +00004682inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004683 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00004684 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004685 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00004686
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004687 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004688
Steve Naroffa4332e22007-07-17 00:58:39 +00004689 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004690 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004691 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004692}
4693
4694inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00004695 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004696 UsualUnaryConversions(lex);
4697 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004698
Eli Friedman5773a6c2008-05-13 20:16:47 +00004699 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004700 return Context.IntTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004701 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004702}
4703
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004704/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4705/// is a read-only property; return true if so. A readonly property expression
4706/// depends on various declarations and thus must be treated specially.
4707///
Mike Stump1eb44332009-09-09 15:08:12 +00004708static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004709 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4710 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4711 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4712 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004713 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00004714 BaseType->getAsObjCInterfacePointerType())
4715 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4716 if (S.isPropertyReadonly(PDecl, IFace))
4717 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004718 }
4719 }
4720 return false;
4721}
4722
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004723/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4724/// emit an error and return true. If so, return false.
4725static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004726 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00004727 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004728 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00004729 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4730 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004731 if (IsLV == Expr::MLV_Valid)
4732 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004733
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004734 unsigned Diag = 0;
4735 bool NeedType = false;
4736 switch (IsLV) { // C99 6.5.16p2
4737 default: assert(0 && "Unknown result from isModifiableLvalue!");
4738 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004739 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004740 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4741 NeedType = true;
4742 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004743 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004744 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4745 NeedType = true;
4746 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00004747 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004748 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4749 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004750 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004751 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4752 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00004753 case Expr::MLV_IncompleteType:
4754 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00004755 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00004756 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4757 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00004758 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004759 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4760 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00004761 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004762 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4763 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00004764 case Expr::MLV_ReadonlyProperty:
4765 Diag = diag::error_readonly_property_assignment;
4766 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00004767 case Expr::MLV_NoSetterProperty:
4768 Diag = diag::error_nosetter_property_assignment;
4769 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00004770 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00004771
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004772 SourceRange Assign;
4773 if (Loc != OrigLoc)
4774 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004775 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00004776 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004777 else
Mike Stump1eb44332009-09-09 15:08:12 +00004778 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004779 return true;
4780}
4781
4782
4783
4784// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004785QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4786 SourceLocation Loc,
4787 QualType CompoundType) {
4788 // Verify that LHS is a modifiable lvalue, and emit error if not.
4789 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00004790 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004791
4792 QualType LHSType = LHS->getType();
4793 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004794
Chris Lattner5cf216b2008-01-04 18:04:52 +00004795 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004796 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00004797 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004798 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004799 // Special case of NSObject attributes on c-style pointer types.
4800 if (ConvTy == IncompatiblePointer &&
4801 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00004802 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004803 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00004804 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00004805 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004806
Chris Lattner2c156472008-08-21 18:04:13 +00004807 // If the RHS is a unary plus or minus, check to see if they = and + are
4808 // right next to each other. If so, the user may have typo'd "x =+ 4"
4809 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004810 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00004811 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4812 RHSCheck = ICE->getSubExpr();
4813 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4814 if ((UO->getOpcode() == UnaryOperator::Plus ||
4815 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004816 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00004817 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00004818 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4819 // And there is a space or other character before the subexpr of the
4820 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00004821 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4822 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00004823 Diag(Loc, diag::warn_not_compound_assign)
4824 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4825 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00004826 }
Chris Lattner2c156472008-08-21 18:04:13 +00004827 }
4828 } else {
4829 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00004830 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00004831 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004832
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004833 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4834 RHS, "assigning"))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004835 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004836
Reid Spencer5f016e22007-07-11 17:01:13 +00004837 // C99 6.5.16p3: The type of an assignment expression is the type of the
4838 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00004839 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00004840 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4841 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00004842 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00004843 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004844 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004845}
4846
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004847// C99 6.5.17
4848QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00004849 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004850 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004851
4852 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4853 // incomplete in C++).
4854
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004855 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004856}
4857
Steve Naroff49b45262007-07-13 16:58:59 +00004858/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4859/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004860QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4861 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00004862 if (Op->isTypeDependent())
4863 return Context.DependentTy;
4864
Chris Lattner3528d352008-11-21 07:05:48 +00004865 QualType ResType = Op->getType();
4866 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00004867
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00004868 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4869 // Decrement of bool is not allowed.
4870 if (!isInc) {
4871 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4872 return QualType();
4873 }
4874 // Increment of bool sets it to true, but is deprecated.
4875 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4876 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00004877 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004878 } else if (ResType->isAnyPointerType()) {
4879 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004880
Chris Lattner3528d352008-11-21 07:05:48 +00004881 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00004882 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00004883 if (getLangOptions().CPlusPlus) {
4884 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4885 << Op->getSourceRange();
4886 return QualType();
4887 }
4888
4889 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00004890 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00004891 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00004892 if (getLangOptions().CPlusPlus) {
4893 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4894 << Op->getType() << Op->getSourceRange();
4895 return QualType();
4896 }
4897
4898 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00004899 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00004900 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00004901 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00004902 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004903 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004904 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00004905 // Diagnose bad cases where we step over interface counts.
4906 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4907 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4908 << PointeeTy << Op->getSourceRange();
4909 return QualType();
4910 }
Chris Lattner3528d352008-11-21 07:05:48 +00004911 } else if (ResType->isComplexType()) {
4912 // C99 does not support ++/-- on complex types, we allow as an extension.
4913 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00004914 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00004915 } else {
4916 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattnerd1625842008-11-24 06:25:27 +00004917 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00004918 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004919 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004920 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00004921 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00004922 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00004923 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00004924 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004925}
4926
Anders Carlsson369dee42008-02-01 07:15:58 +00004927/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00004928/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004929/// where the declaration is needed for type checking. We only need to
4930/// handle cases when the expression references a function designator
4931/// or is an lvalue. Here are some examples:
4932/// - &(x) => x
4933/// - &*****f => f for f a function designator.
4934/// - &s.xx => s
4935/// - &s.zz[1].yy -> s, if zz is an array
4936/// - *(x + 1) -> x, if x is an array
4937/// - &"123"[2] -> 0
4938/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004939static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00004940 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004941 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00004942 case Stmt::QualifiedDeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00004943 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00004944 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00004945 // If this is an arrow operator, the address is an offset from
4946 // the base's value, so the object the base refers to is
4947 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00004948 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00004949 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00004950 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00004951 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00004952 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00004953 // FIXME: This code shouldn't be necessary! We should catch the implicit
4954 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00004955 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4956 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4957 if (ICE->getSubExpr()->getType()->isArrayType())
4958 return getPrimaryDecl(ICE->getSubExpr());
4959 }
4960 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00004961 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004962 case Stmt::UnaryOperatorClass: {
4963 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004964
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004965 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00004966 case UnaryOperator::Real:
4967 case UnaryOperator::Imag:
4968 case UnaryOperator::Extension:
4969 return getPrimaryDecl(UO->getSubExpr());
4970 default:
4971 return 0;
4972 }
4973 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004974 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00004975 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00004976 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00004977 // If the result of an implicit cast is an l-value, we care about
4978 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00004979 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00004980 default:
4981 return 0;
4982 }
4983}
4984
4985/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00004986/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00004987/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004988/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00004989/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004990/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00004991/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00004992QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00004993 // Make sure to ignore parentheses in subsequent checks
4994 op = op->IgnoreParens();
4995
Douglas Gregor9103bb22008-12-17 22:52:20 +00004996 if (op->isTypeDependent())
4997 return Context.DependentTy;
4998
Steve Naroff08f19672008-01-13 17:10:08 +00004999 if (getLangOptions().C99) {
5000 // Implement C99-only parts of addressof rules.
5001 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5002 if (uOp->getOpcode() == UnaryOperator::Deref)
5003 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5004 // (assuming the deref expression is valid).
5005 return uOp->getSubExpr()->getType();
5006 }
5007 // Technically, there should be a check for array subscript
5008 // expressions here, but the result of one is always an lvalue anyway.
5009 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005010 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005011 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005012
Eli Friedman441cf102009-05-16 23:27:50 +00005013 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5014 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005015 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005016 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005017 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005018 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5019 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005020 return QualType();
5021 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005022 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005023 // The operand cannot be a bit-field
5024 Diag(OpLoc, diag::err_typecheck_address_of)
5025 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005026 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005027 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5028 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005029 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005030 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005031 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005032 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005033 } else if (isa<ObjCPropertyRefExpr>(op)) {
5034 // cannot take address of a property expression.
5035 Diag(OpLoc, diag::err_typecheck_address_of)
5036 << "property expression" << op->getSourceRange();
5037 return QualType();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005038 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005039 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005040 // with the register storage-class specifier.
5041 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5042 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005043 Diag(OpLoc, diag::err_typecheck_address_of)
5044 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005045 return QualType();
5046 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00005047 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5048 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005049 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005050 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005051 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005052 // Could be a pointer to member, though, if there is an explicit
5053 // scope qualifier for the class.
5054 if (isa<QualifiedDeclRefExpr>(op)) {
5055 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005056 if (Ctx && Ctx->isRecord()) {
5057 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005058 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005059 diag::err_cannot_form_pointer_to_member_of_reference_type)
5060 << FD->getDeclName() << FD->getType();
5061 return QualType();
5062 }
Mike Stump1eb44332009-09-09 15:08:12 +00005063
Sebastian Redlebc07d52009-02-03 20:19:35 +00005064 return Context.getMemberPointerType(op->getType(),
5065 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005066 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005067 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005068 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005069 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005070 // As above.
Anders Carlsson196f7d02009-05-16 21:43:42 +00005071 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
5072 return Context.getMemberPointerType(op->getType(),
5073 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5074 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005075 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005076 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005077
Eli Friedman441cf102009-05-16 23:27:50 +00005078 if (lval == Expr::LV_IncompleteVoidType) {
5079 // Taking the address of a void variable is technically illegal, but we
5080 // allow it in cases which are otherwise valid.
5081 // Example: "extern void x; void* y = &x;".
5082 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5083 }
5084
Reid Spencer5f016e22007-07-11 17:01:13 +00005085 // If the operand has type "type", the result has type "pointer to type".
5086 return Context.getPointerType(op->getType());
5087}
5088
Chris Lattner22caddc2008-11-23 09:13:29 +00005089QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005090 if (Op->isTypeDependent())
5091 return Context.DependentTy;
5092
Chris Lattner22caddc2008-11-23 09:13:29 +00005093 UsualUnaryConversions(Op);
5094 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005095
Chris Lattner22caddc2008-11-23 09:13:29 +00005096 // Note that per both C89 and C99, this is always legal, even if ptype is an
5097 // incomplete type or void. It would be possible to warn about dereferencing
5098 // a void pointer, but it's completely well-defined, and such a warning is
5099 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00005100 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00005101 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005102
Fariborz Jahanian16b10372009-09-03 00:43:07 +00005103 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5104 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00005105
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005106 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00005107 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005108 return QualType();
5109}
5110
5111static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5112 tok::TokenKind Kind) {
5113 BinaryOperator::Opcode Opc;
5114 switch (Kind) {
5115 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00005116 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5117 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005118 case tok::star: Opc = BinaryOperator::Mul; break;
5119 case tok::slash: Opc = BinaryOperator::Div; break;
5120 case tok::percent: Opc = BinaryOperator::Rem; break;
5121 case tok::plus: Opc = BinaryOperator::Add; break;
5122 case tok::minus: Opc = BinaryOperator::Sub; break;
5123 case tok::lessless: Opc = BinaryOperator::Shl; break;
5124 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5125 case tok::lessequal: Opc = BinaryOperator::LE; break;
5126 case tok::less: Opc = BinaryOperator::LT; break;
5127 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5128 case tok::greater: Opc = BinaryOperator::GT; break;
5129 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5130 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5131 case tok::amp: Opc = BinaryOperator::And; break;
5132 case tok::caret: Opc = BinaryOperator::Xor; break;
5133 case tok::pipe: Opc = BinaryOperator::Or; break;
5134 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5135 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5136 case tok::equal: Opc = BinaryOperator::Assign; break;
5137 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5138 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5139 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5140 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5141 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5142 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5143 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5144 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5145 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5146 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5147 case tok::comma: Opc = BinaryOperator::Comma; break;
5148 }
5149 return Opc;
5150}
5151
5152static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5153 tok::TokenKind Kind) {
5154 UnaryOperator::Opcode Opc;
5155 switch (Kind) {
5156 default: assert(0 && "Unknown unary op!");
5157 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5158 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5159 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5160 case tok::star: Opc = UnaryOperator::Deref; break;
5161 case tok::plus: Opc = UnaryOperator::Plus; break;
5162 case tok::minus: Opc = UnaryOperator::Minus; break;
5163 case tok::tilde: Opc = UnaryOperator::Not; break;
5164 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005165 case tok::kw___real: Opc = UnaryOperator::Real; break;
5166 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5167 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5168 }
5169 return Opc;
5170}
5171
Douglas Gregoreaebc752008-11-06 23:29:22 +00005172/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5173/// operator @p Opc at location @c TokLoc. This routine only supports
5174/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005175Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5176 unsigned Op,
5177 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005178 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00005179 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005180 // The following two variables are used for compound assignment operators
5181 QualType CompLHSTy; // Type of LHS after promotions for computation
5182 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00005183
5184 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00005185 case BinaryOperator::Assign:
5186 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5187 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005188 case BinaryOperator::PtrMemD:
5189 case BinaryOperator::PtrMemI:
5190 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5191 Opc == BinaryOperator::PtrMemI);
5192 break;
5193 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005194 case BinaryOperator::Div:
5195 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5196 break;
5197 case BinaryOperator::Rem:
5198 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5199 break;
5200 case BinaryOperator::Add:
5201 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5202 break;
5203 case BinaryOperator::Sub:
5204 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5205 break;
Sebastian Redl22460502009-02-07 00:15:38 +00005206 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00005207 case BinaryOperator::Shr:
5208 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5209 break;
5210 case BinaryOperator::LE:
5211 case BinaryOperator::LT:
5212 case BinaryOperator::GE:
5213 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00005214 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005215 break;
5216 case BinaryOperator::EQ:
5217 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00005218 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005219 break;
5220 case BinaryOperator::And:
5221 case BinaryOperator::Xor:
5222 case BinaryOperator::Or:
5223 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5224 break;
5225 case BinaryOperator::LAnd:
5226 case BinaryOperator::LOr:
5227 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5228 break;
5229 case BinaryOperator::MulAssign:
5230 case BinaryOperator::DivAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005231 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5232 CompLHSTy = CompResultTy;
5233 if (!CompResultTy.isNull())
5234 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005235 break;
5236 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005237 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5238 CompLHSTy = CompResultTy;
5239 if (!CompResultTy.isNull())
5240 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005241 break;
5242 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005243 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5244 if (!CompResultTy.isNull())
5245 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005246 break;
5247 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005248 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5249 if (!CompResultTy.isNull())
5250 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005251 break;
5252 case BinaryOperator::ShlAssign:
5253 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005254 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5255 CompLHSTy = CompResultTy;
5256 if (!CompResultTy.isNull())
5257 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005258 break;
5259 case BinaryOperator::AndAssign:
5260 case BinaryOperator::XorAssign:
5261 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00005262 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5263 CompLHSTy = CompResultTy;
5264 if (!CompResultTy.isNull())
5265 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00005266 break;
5267 case BinaryOperator::Comma:
5268 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5269 break;
5270 }
5271 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005272 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005273 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00005274 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5275 else
5276 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005277 CompLHSTy, CompResultTy,
5278 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00005279}
5280
Reid Spencer5f016e22007-07-11 17:01:13 +00005281// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005282Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5283 tok::TokenKind Kind,
5284 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005285 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00005286 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00005287
Steve Narofff69936d2007-09-16 03:34:24 +00005288 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5289 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005290
Douglas Gregor063daf62009-03-13 18:40:31 +00005291 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00005292 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00005293 rhs->getType()->isOverloadableType())) {
5294 // Find all of the overloaded operators visible from this
5295 // point. We perform both an operator-name lookup from the local
5296 // scope and an argument-dependent lookup based on the types of
5297 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005298 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00005299 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5300 if (OverOp != OO_None) {
5301 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5302 Functions);
5303 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00005304 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00005305 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5306 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005307 }
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005308
Douglas Gregor063daf62009-03-13 18:40:31 +00005309 // Build the (potentially-overloaded, potentially-dependent)
5310 // binary operation.
5311 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00005312 }
5313
Douglas Gregoreaebc752008-11-06 23:29:22 +00005314 // Build a built-in binary operation.
5315 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00005316}
5317
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005318Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00005319 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005320 ExprArg InputArg) {
5321 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00005322
Mike Stump390b4cc2009-05-16 07:39:55 +00005323 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005324 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00005325 QualType resultType;
5326 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005327 case UnaryOperator::OffsetOf:
5328 assert(false && "Invalid unary operator");
5329 break;
5330
Reid Spencer5f016e22007-07-11 17:01:13 +00005331 case UnaryOperator::PreInc:
5332 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00005333 case UnaryOperator::PostInc:
5334 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005335 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00005336 Opc == UnaryOperator::PreInc ||
5337 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00005338 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005339 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00005340 resultType = CheckAddressOfOperand(Input, OpLoc);
5341 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005342 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00005343 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00005344 resultType = CheckIndirectionOperand(Input, OpLoc);
5345 break;
5346 case UnaryOperator::Plus:
5347 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005348 UsualUnaryConversions(Input);
5349 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005350 if (resultType->isDependentType())
5351 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005352 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5353 break;
5354 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5355 resultType->isEnumeralType())
5356 break;
5357 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5358 Opc == UnaryOperator::Plus &&
5359 resultType->isPointerType())
5360 break;
5361
Sebastian Redl0eb23302009-01-19 00:08:26 +00005362 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5363 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005364 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005365 UsualUnaryConversions(Input);
5366 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005367 if (resultType->isDependentType())
5368 break;
Chris Lattner02a65142008-07-25 23:52:49 +00005369 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5370 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5371 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005372 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005373 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00005374 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005375 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5376 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005377 break;
5378 case UnaryOperator::LNot: // logical negation
5379 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005380 DefaultFunctionArrayConversion(Input);
5381 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00005382 if (resultType->isDependentType())
5383 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005384 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00005385 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5386 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00005387 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00005388 // In C++, it's bool. C++ 5.3.1p8
5389 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005390 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00005391 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00005392 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00005393 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00005394 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005395 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00005396 resultType = Input->getType();
5397 break;
5398 }
5399 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00005400 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005401
5402 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00005403 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00005404}
5405
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005406// Unary Operators. 'Tok' is the token for the operator.
5407Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5408 tok::TokenKind Op, ExprArg input) {
5409 Expr *Input = (Expr*)input.get();
5410 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5411
5412 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5413 // Find all of the overloaded operators visible from this
5414 // point. We perform both an operator-name lookup from the local
5415 // scope and an argument-dependent lookup based on the types of
5416 // the arguments.
5417 FunctionSet Functions;
5418 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5419 if (OverOp != OO_None) {
5420 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5421 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00005422 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00005423 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5424 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5425 }
5426
5427 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5428 }
5429
5430 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5431}
5432
Steve Naroff1b273c42007-09-16 14:56:35 +00005433/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00005434Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5435 SourceLocation LabLoc,
5436 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005437 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00005438 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00005439
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00005440 // If we haven't seen this label yet, create a forward reference. It
5441 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00005442 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00005443 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005444
Reid Spencer5f016e22007-07-11 17:01:13 +00005445 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00005446 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5447 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00005448}
5449
Sebastian Redlf53597f2009-03-15 17:47:39 +00005450Sema::OwningExprResult
5451Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5452 SourceLocation RPLoc) { // "({..})"
5453 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005454 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5455 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5456
Eli Friedmandca2b732009-01-24 23:09:00 +00005457 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00005458 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005459 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00005460
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005461 // FIXME: there are a variety of strange constraints to enforce here, for
5462 // example, it is not possible to goto into a stmt expression apparently.
5463 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005464
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005465 // If there are sub stmts in the compound stmt, take the type of the last one
5466 // as the type of the stmtexpr.
5467 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005468
Chris Lattner611b2ec2008-07-26 19:51:01 +00005469 if (!Compound->body_empty()) {
5470 Stmt *LastStmt = Compound->body_back();
5471 // If LastStmt is a label, skip down through into the body.
5472 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5473 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005474
Chris Lattner611b2ec2008-07-26 19:51:01 +00005475 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005476 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00005477 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005478
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005479 // FIXME: Check that expression type is complete/non-abstract; statement
5480 // expressions are not lvalues.
5481
Sebastian Redlf53597f2009-03-15 17:47:39 +00005482 substmt.release();
5483 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00005484}
Steve Naroffd34e9152007-08-01 22:05:33 +00005485
Sebastian Redlf53597f2009-03-15 17:47:39 +00005486Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5487 SourceLocation BuiltinLoc,
5488 SourceLocation TypeLoc,
5489 TypeTy *argty,
5490 OffsetOfComponent *CompPtr,
5491 unsigned NumComponents,
5492 SourceLocation RPLoc) {
5493 // FIXME: This function leaks all expressions in the offset components on
5494 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005495 // FIXME: Preserve type source info.
5496 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005497 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005498
Sebastian Redl28507842009-02-26 14:39:58 +00005499 bool Dependent = ArgTy->isDependentType();
5500
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005501 // We must have at least one component that refers to the type, and the first
5502 // one is known to be a field designator. Verify that the ArgTy represents
5503 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00005504 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005505 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005506
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005507 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5508 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00005509
Eli Friedman35183ac2009-02-27 06:44:11 +00005510 // Otherwise, create a null pointer as the base, and iteratively process
5511 // the offsetof designators.
5512 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5513 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005514 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00005515 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00005516
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005517 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5518 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00005519 // FIXME: This diagnostic isn't actually visible because the location is in
5520 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00005521 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005522 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5523 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005524
Sebastian Redl28507842009-02-26 14:39:58 +00005525 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00005526 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00005527
Sebastian Redl28507842009-02-26 14:39:58 +00005528 // FIXME: Dependent case loses a lot of information here. And probably
5529 // leaks like a sieve.
5530 for (unsigned i = 0; i != NumComponents; ++i) {
5531 const OffsetOfComponent &OC = CompPtr[i];
5532 if (OC.isBrackets) {
5533 // Offset of an array sub-field. TODO: Should we allow vector elements?
5534 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5535 if (!AT) {
5536 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005537 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5538 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005539 }
5540
5541 // FIXME: C++: Verify that operator[] isn't overloaded.
5542
Eli Friedman35183ac2009-02-27 06:44:11 +00005543 // Promote the array so it looks more like a normal array subscript
5544 // expression.
5545 DefaultFunctionArrayConversion(Res);
5546
Sebastian Redl28507842009-02-26 14:39:58 +00005547 // C99 6.5.2.1p1
5548 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005549 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005550 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00005551 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00005552 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005553 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00005554
5555 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5556 OC.LocEnd);
5557 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005558 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005559
Ted Kremenek6217b802009-07-29 21:53:49 +00005560 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00005561 if (!RC) {
5562 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00005563 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5564 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00005565 }
Chris Lattner704fe352007-08-30 17:59:59 +00005566
Sebastian Redl28507842009-02-26 14:39:58 +00005567 // Get the decl corresponding to this.
5568 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005569 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005570 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonf9b8bc62009-05-02 17:45:47 +00005571 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5572 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5573 << Res->getType());
Anders Carlsson5992e4a2009-05-02 18:36:10 +00005574 DidWarnAboutNonPOD = true;
5575 }
Anders Carlsson6d7f1492009-05-01 23:20:30 +00005576 }
Mike Stump1eb44332009-09-09 15:08:12 +00005577
Sebastian Redl28507842009-02-26 14:39:58 +00005578 FieldDecl *MemberDecl
5579 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5580 LookupMemberName)
5581 .getAsDecl());
Sebastian Redlf53597f2009-03-15 17:47:39 +00005582 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00005583 if (!MemberDecl)
Anders Carlssonf4d84b62009-08-30 00:54:35 +00005584 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member_deprecated)
Sebastian Redlf53597f2009-03-15 17:47:39 +00005585 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00005586
Sebastian Redl28507842009-02-26 14:39:58 +00005587 // FIXME: C++: Verify that MemberDecl isn't a static field.
5588 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00005589 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00005590 Res = BuildAnonymousStructUnionMemberReference(
5591 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00005592 } else {
5593 // MemberDecl->getType() doesn't get the right qualifiers, but it
5594 // doesn't matter here.
5595 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5596 MemberDecl->getType().getNonReferenceType());
5597 }
Sebastian Redl28507842009-02-26 14:39:58 +00005598 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005599 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005600
Sebastian Redlf53597f2009-03-15 17:47:39 +00005601 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5602 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005603}
5604
5605
Sebastian Redlf53597f2009-03-15 17:47:39 +00005606Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5607 TypeTy *arg1,TypeTy *arg2,
5608 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005609 // FIXME: Preserve type source info.
5610 QualType argT1 = GetTypeFromParser(arg1);
5611 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005612
Steve Naroffd34e9152007-08-01 22:05:33 +00005613 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00005614
Douglas Gregorc12a9c52009-05-19 22:28:02 +00005615 if (getLangOptions().CPlusPlus) {
5616 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5617 << SourceRange(BuiltinLoc, RPLoc);
5618 return ExprError();
5619 }
5620
Sebastian Redlf53597f2009-03-15 17:47:39 +00005621 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5622 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00005623}
5624
Sebastian Redlf53597f2009-03-15 17:47:39 +00005625Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5626 ExprArg cond,
5627 ExprArg expr1, ExprArg expr2,
5628 SourceLocation RPLoc) {
5629 Expr *CondExpr = static_cast<Expr*>(cond.get());
5630 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5631 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005632
Steve Naroffd04fdd52007-08-03 21:21:27 +00005633 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5634
Sebastian Redl28507842009-02-26 14:39:58 +00005635 QualType resType;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00005636 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00005637 resType = Context.DependentTy;
5638 } else {
5639 // The conditional expression is required to be a constant expression.
5640 llvm::APSInt condEval(32);
5641 SourceLocation ExpLoc;
5642 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00005643 return ExprError(Diag(ExpLoc,
5644 diag::err_typecheck_choose_expr_requires_constant)
5645 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00005646
Sebastian Redl28507842009-02-26 14:39:58 +00005647 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5648 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5649 }
5650
Sebastian Redlf53597f2009-03-15 17:47:39 +00005651 cond.release(); expr1.release(); expr2.release();
5652 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5653 resType, RPLoc));
Steve Naroffd04fdd52007-08-03 21:21:27 +00005654}
5655
Steve Naroff4eb206b2008-09-03 18:15:37 +00005656//===----------------------------------------------------------------------===//
5657// Clang Extensions.
5658//===----------------------------------------------------------------------===//
5659
5660/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00005661void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005662 // Analyze block parameters.
5663 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005664
Steve Naroff4eb206b2008-09-03 18:15:37 +00005665 // Add BSI to CurBlock.
5666 BSI->PrevBlockInfo = CurBlock;
5667 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005668
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005669 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005670 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00005671 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00005672 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00005673 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5674 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005675
Steve Naroff090276f2008-10-10 01:28:17 +00005676 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00005677 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00005678}
5679
Mike Stump98eb8a72009-02-04 22:31:32 +00005680void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00005681 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00005682
5683 if (ParamInfo.getNumTypeObjects() == 0
5684 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005685 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00005686 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5687
Mike Stump4eeab842009-04-28 01:10:27 +00005688 if (T->isArrayType()) {
5689 Diag(ParamInfo.getSourceRange().getBegin(),
5690 diag::err_block_returns_array);
5691 return;
5692 }
5693
Mike Stump98eb8a72009-02-04 22:31:32 +00005694 // The parameter list is optional, if there was none, assume ().
5695 if (!T->isFunctionType())
5696 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5697
5698 CurBlock->hasPrototype = true;
5699 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005700 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005701 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005702 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00005703 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005704 // FIXME: remove the attribute.
5705 }
Chris Lattner9097af12009-04-11 19:27:54 +00005706 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00005707
Chris Lattner9097af12009-04-11 19:27:54 +00005708 // Do not allow returning a objc interface by-value.
5709 if (RetTy->isObjCInterfaceType()) {
5710 Diag(ParamInfo.getSourceRange().getBegin(),
5711 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5712 return;
5713 }
Mike Stump98eb8a72009-02-04 22:31:32 +00005714 return;
5715 }
5716
Steve Naroff4eb206b2008-09-03 18:15:37 +00005717 // Analyze arguments to block.
5718 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5719 "Not a function declarator!");
5720 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005721
Steve Naroff090276f2008-10-10 01:28:17 +00005722 CurBlock->hasPrototype = FTI.hasPrototype;
5723 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005724
Steve Naroff4eb206b2008-09-03 18:15:37 +00005725 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5726 // no arguments, not a function that takes a single void argument.
5727 if (FTI.hasPrototype &&
5728 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00005729 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5730 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00005731 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00005732 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005733 } else if (FTI.hasPrototype) {
5734 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00005735 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00005736 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005737 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00005738 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00005739 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00005740 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00005741 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00005742 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5743 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5744 // If this has an identifier, add it to the scope stack.
5745 if ((*AI)->getIdentifier())
5746 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00005747
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005748 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00005749 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005750 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005751 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00005752 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00005753 // FIXME: remove the attribute.
5754 }
Mike Stump1eb44332009-09-09 15:08:12 +00005755
Chris Lattner9097af12009-04-11 19:27:54 +00005756 // Analyze the return type.
5757 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5758 QualType RetTy = T->getAsFunctionType()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00005759
Chris Lattner9097af12009-04-11 19:27:54 +00005760 // Do not allow returning a objc interface by-value.
5761 if (RetTy->isObjCInterfaceType()) {
5762 Diag(ParamInfo.getSourceRange().getBegin(),
5763 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5764 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005765 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005766}
5767
5768/// ActOnBlockError - If there is an error parsing a block, this callback
5769/// is invoked to pop the information about the block from the action impl.
5770void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5771 // Ensure that CurBlock is deleted.
5772 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005773
Chris Lattner17a78302009-04-19 05:28:12 +00005774 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5775
Steve Naroff4eb206b2008-09-03 18:15:37 +00005776 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00005777 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005778 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00005779 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00005780}
5781
5782/// ActOnBlockStmtExpr - This is called when the body of a block statement
5783/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00005784Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5785 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00005786 // If blocks are disabled, emit an error.
5787 if (!LangOpts.Blocks)
5788 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00005789
Steve Naroff4eb206b2008-09-03 18:15:37 +00005790 // Ensure that CurBlock is deleted.
5791 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00005792
Steve Naroff090276f2008-10-10 01:28:17 +00005793 PopDeclContext();
5794
Steve Naroff4eb206b2008-09-03 18:15:37 +00005795 // Pop off CurBlock, handle nested blocks.
5796 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005797
Steve Naroff4eb206b2008-09-03 18:15:37 +00005798 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00005799 if (!BSI->ReturnType.isNull())
5800 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005801
Steve Naroff4eb206b2008-09-03 18:15:37 +00005802 llvm::SmallVector<QualType, 8> ArgTypes;
5803 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5804 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005805
Mike Stump56925862009-07-28 22:04:01 +00005806 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00005807 QualType BlockTy;
5808 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00005809 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5810 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00005811 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00005812 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00005813 BSI->isVariadic, 0, false, false, 0, 0,
5814 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005815
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005816 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00005817 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00005818 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005819
Chris Lattner17a78302009-04-19 05:28:12 +00005820 // If needed, diagnose invalid gotos and switches in the block.
5821 if (CurFunctionNeedsScopeChecking)
5822 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5823 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00005824
Anders Carlssone9146f22009-05-01 19:49:17 +00005825 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump56925862009-07-28 22:04:01 +00005826 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redlf53597f2009-03-15 17:47:39 +00005827 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5828 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00005829}
5830
Sebastian Redlf53597f2009-03-15 17:47:39 +00005831Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5832 ExprArg expr, TypeTy *type,
5833 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00005834 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00005835 Expr *E = static_cast<Expr*>(expr.get());
5836 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00005837
Anders Carlsson7c50aca2007-10-15 20:28:48 +00005838 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00005839
5840 // Get the va_list type
5841 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00005842 if (VaListType->isArrayType()) {
5843 // Deal with implicit array decay; for example, on x86-64,
5844 // va_list is an array, but it's supposed to decay to
5845 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00005846 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00005847 // Make sure the input expression also decays appropriately.
5848 UsualUnaryConversions(E);
5849 } else {
5850 // Otherwise, the va_list argument must be an l-value because
5851 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00005852 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00005853 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00005854 return ExprError();
5855 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00005856
Douglas Gregordd027302009-05-19 23:10:31 +00005857 if (!E->isTypeDependent() &&
5858 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00005859 return ExprError(Diag(E->getLocStart(),
5860 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00005861 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00005862 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005863
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005864 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00005865 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005866
Sebastian Redlf53597f2009-03-15 17:47:39 +00005867 expr.release();
5868 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5869 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00005870}
5871
Sebastian Redlf53597f2009-03-15 17:47:39 +00005872Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00005873 // The type of __null will be int or long, depending on the size of
5874 // pointers on the target.
5875 QualType Ty;
5876 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5877 Ty = Context.IntTy;
5878 else
5879 Ty = Context.LongTy;
5880
Sebastian Redlf53597f2009-03-15 17:47:39 +00005881 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00005882}
5883
Chris Lattner5cf216b2008-01-04 18:04:52 +00005884bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5885 SourceLocation Loc,
5886 QualType DstType, QualType SrcType,
5887 Expr *SrcExpr, const char *Flavor) {
5888 // Decode the result (notice that AST's are still created for extensions).
5889 bool isInvalid = false;
5890 unsigned DiagKind;
5891 switch (ConvTy) {
5892 default: assert(0 && "Unknown conversion type");
5893 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005894 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00005895 DiagKind = diag::ext_typecheck_convert_pointer_int;
5896 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00005897 case IntToPointer:
5898 DiagKind = diag::ext_typecheck_convert_int_pointer;
5899 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005900 case IncompatiblePointer:
5901 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5902 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00005903 case IncompatiblePointerSign:
5904 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5905 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005906 case FunctionVoidPointer:
5907 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5908 break;
5909 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00005910 // If the qualifiers lost were because we were applying the
5911 // (deprecated) C++ conversion from a string literal to a char*
5912 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5913 // Ideally, this check would be performed in
5914 // CheckPointerTypesForAssignment. However, that would require a
5915 // bit of refactoring (so that the second argument is an
5916 // expression, rather than a type), which should be done as part
5917 // of a larger effort to fix CheckPointerTypesForAssignment for
5918 // C++ semantics.
5919 if (getLangOptions().CPlusPlus &&
5920 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5921 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005922 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5923 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005924 case IntToBlockPointer:
5925 DiagKind = diag::err_int_to_block_pointer;
5926 break;
5927 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00005928 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005929 break;
Steve Naroff39579072008-10-14 22:18:38 +00005930 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00005931 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00005932 // it can give a more specific diagnostic.
5933 DiagKind = diag::warn_incompatible_qualified_id;
5934 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005935 case IncompatibleVectors:
5936 DiagKind = diag::warn_incompatible_vectors;
5937 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005938 case Incompatible:
5939 DiagKind = diag::err_typecheck_convert_incompatible;
5940 isInvalid = true;
5941 break;
5942 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005943
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005944 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5945 << SrcExpr->getSourceRange();
Chris Lattner5cf216b2008-01-04 18:04:52 +00005946 return isInvalid;
5947}
Anders Carlssone21555e2008-11-30 19:50:32 +00005948
Chris Lattner3bf68932009-04-25 21:59:05 +00005949bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00005950 llvm::APSInt ICEResult;
5951 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5952 if (Result)
5953 *Result = ICEResult;
5954 return false;
5955 }
5956
Anders Carlssone21555e2008-11-30 19:50:32 +00005957 Expr::EvalResult EvalResult;
5958
Mike Stumpeed9cac2009-02-19 03:04:26 +00005959 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00005960 EvalResult.HasSideEffects) {
5961 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5962
5963 if (EvalResult.Diag) {
5964 // We only show the note if it's not the usual "invalid subexpression"
5965 // or if it's actually in a subexpression.
5966 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5967 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5968 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5969 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005970
Anders Carlssone21555e2008-11-30 19:50:32 +00005971 return true;
5972 }
5973
Eli Friedman3b5ccca2009-04-25 22:26:58 +00005974 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5975 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00005976
Eli Friedman3b5ccca2009-04-25 22:26:58 +00005977 if (EvalResult.Diag &&
5978 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5979 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005980
Anders Carlssone21555e2008-11-30 19:50:32 +00005981 if (Result)
5982 *Result = EvalResult.Val.getInt();
5983 return false;
5984}
Douglas Gregore0762c92009-06-19 23:52:42 +00005985
Mike Stump1eb44332009-09-09 15:08:12 +00005986Sema::ExpressionEvaluationContext
5987Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00005988 // Introduce a new set of potentially referenced declarations to the stack.
5989 if (NewContext == PotentiallyPotentiallyEvaluated)
5990 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump1eb44332009-09-09 15:08:12 +00005991
Douglas Gregorac7610d2009-06-22 20:57:11 +00005992 std::swap(ExprEvalContext, NewContext);
5993 return NewContext;
5994}
5995
Mike Stump1eb44332009-09-09 15:08:12 +00005996void
Douglas Gregorac7610d2009-06-22 20:57:11 +00005997Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5998 ExpressionEvaluationContext NewContext) {
5999 ExprEvalContext = NewContext;
6000
6001 if (OldContext == PotentiallyPotentiallyEvaluated) {
6002 // Mark any remaining declarations in the current position of the stack
6003 // as "referenced". If they were not meant to be referenced, semantic
6004 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6005 PotentiallyReferencedDecls RemainingDecls;
6006 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6007 PotentiallyReferencedDeclStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00006008
Douglas Gregorac7610d2009-06-22 20:57:11 +00006009 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6010 IEnd = RemainingDecls.end();
6011 I != IEnd; ++I)
6012 MarkDeclarationReferenced(I->first, I->second);
6013 }
6014}
Douglas Gregore0762c92009-06-19 23:52:42 +00006015
6016/// \brief Note that the given declaration was referenced in the source code.
6017///
6018/// This routine should be invoke whenever a given declaration is referenced
6019/// in the source code, and where that reference occurred. If this declaration
6020/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6021/// C99 6.9p3), then the declaration will be marked as used.
6022///
6023/// \param Loc the location where the declaration was referenced.
6024///
6025/// \param D the declaration that has been referenced by the source code.
6026void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6027 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00006028
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006029 if (D->isUsed())
6030 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006031
Douglas Gregore0762c92009-06-19 23:52:42 +00006032 // Mark a parameter declaration "used", regardless of whether we're in a
6033 // template or not.
6034 if (isa<ParmVarDecl>(D))
6035 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00006036
Douglas Gregore0762c92009-06-19 23:52:42 +00006037 // Do not mark anything as "used" within a dependent context; wait for
6038 // an instantiation.
6039 if (CurContext->isDependentContext())
6040 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006041
Douglas Gregorac7610d2009-06-22 20:57:11 +00006042 switch (ExprEvalContext) {
6043 case Unevaluated:
6044 // We are in an expression that is not potentially evaluated; do nothing.
6045 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006046
Douglas Gregorac7610d2009-06-22 20:57:11 +00006047 case PotentiallyEvaluated:
6048 // We are in a potentially-evaluated expression, so this declaration is
6049 // "used"; handle this below.
6050 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006051
Douglas Gregorac7610d2009-06-22 20:57:11 +00006052 case PotentiallyPotentiallyEvaluated:
6053 // We are in an expression that may be potentially evaluated; queue this
6054 // declaration reference until we know whether the expression is
6055 // potentially evaluated.
6056 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6057 return;
6058 }
Mike Stump1eb44332009-09-09 15:08:12 +00006059
Douglas Gregore0762c92009-06-19 23:52:42 +00006060 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00006061 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006062 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00006063 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6064 if (!Constructor->isUsed())
6065 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006066 } else if (Constructor->isImplicit() &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00006067 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00006068 if (!Constructor->isUsed())
6069 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6070 }
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00006071 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6072 if (Destructor->isImplicit() && !Destructor->isUsed())
6073 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00006074
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00006075 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6076 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6077 MethodDecl->getOverloadedOperator() == OO_Equal) {
6078 if (!MethodDecl->isUsed())
6079 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6080 }
6081 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00006082 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006083 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00006084 // class templates.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00006085 if (!Function->getBody()) {
Douglas Gregor1637be72009-06-26 00:10:03 +00006086 // FIXME: distinguish between implicit instantiations of function
6087 // templates and explicit specializations (the latter don't get
6088 // instantiated, naturally).
6089 if (Function->getInstantiatedFromMemberFunction() ||
6090 Function->getPrimaryTemplate())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00006091 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006092 }
Mike Stump1eb44332009-09-09 15:08:12 +00006093
6094
Douglas Gregore0762c92009-06-19 23:52:42 +00006095 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00006096 Function->setUsed(true);
6097 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00006098 }
Mike Stump1eb44332009-09-09 15:08:12 +00006099
Douglas Gregore0762c92009-06-19 23:52:42 +00006100 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00006101 // Implicit instantiation of static data members of class templates.
6102 // FIXME: distinguish between implicit instantiations (which we need to
6103 // actually instantiate) and explicit specializations.
Mike Stump1eb44332009-09-09 15:08:12 +00006104 if (Var->isStaticDataMember() &&
Douglas Gregor7caa6822009-07-24 20:34:43 +00006105 Var->getInstantiatedFromStaticDataMember())
6106 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
Mike Stump1eb44332009-09-09 15:08:12 +00006107
Douglas Gregore0762c92009-06-19 23:52:42 +00006108 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00006109
Douglas Gregore0762c92009-06-19 23:52:42 +00006110 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00006111 return;
6112}
Douglas Gregore0762c92009-06-19 23:52:42 +00006113}
6114