blob: e02dbd6bebdd4a5f81dd3546aab8f00b549b9187 [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"
Douglas Gregor99a2e602009-12-16 01:38:02 +000015#include "SemaInit.h"
John McCall7d384dd2009-11-18 07:57:50 +000016#include "Lookup.h"
Mike Stumpfa6ef182010-01-13 02:59:54 +000017#include "clang/Analysis/PathSensitive/AnalysisContext.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000020#include "clang/AST/DeclTemplate.h"
Chris Lattner04421082008-04-08 04:40:51 +000021#include "clang/AST/ExprCXX.h"
Steve Narofff494b572008-05-29 21:12:08 +000022#include "clang/AST/ExprObjC.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000023#include "clang/Basic/PartialDiagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025#include "clang/Basic/TargetInfo.h"
Anders Carlssond497ba72009-08-26 22:59:12 +000026#include "clang/Lex/LiteralSupport.h"
27#include "clang/Lex/Preprocessor.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000028#include "clang/Parse/DeclSpec.h"
Chris Lattner418f6c72008-10-26 23:43:26 +000029#include "clang/Parse/Designator.h"
Steve Naroff4eb206b2008-09-03 18:15:37 +000030#include "clang/Parse/Scope.h"
Douglas Gregor314b97f2009-11-10 19:49:08 +000031#include "clang/Parse/Template.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
David Chisnall0f436562009-08-17 16:35:33 +000034
Douglas Gregor48f3bb92009-02-18 21:56:37 +000035/// \brief Determine whether the use of this declaration is valid, and
36/// emit any corresponding diagnostics.
37///
38/// This routine diagnoses various problems with referencing
39/// declarations that can occur when using a declaration. For example,
40/// it might warn if a deprecated or unavailable declaration is being
41/// used, or produce an error (and return true) if a C++0x deleted
42/// function is being used.
43///
Chris Lattner52338262009-10-25 22:31:57 +000044/// If IgnoreDeprecated is set to true, this should not want about deprecated
45/// decls.
46///
Douglas Gregor48f3bb92009-02-18 21:56:37 +000047/// \returns true if there was an error (this declaration cannot be
48/// referenced), false otherwise.
Chris Lattner52338262009-10-25 22:31:57 +000049///
John McCall54abf7d2009-11-04 02:18:39 +000050bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner76a642f2009-02-15 22:43:40 +000051 // See if the decl is deprecated.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000052 if (D->getAttr<DeprecatedAttr>()) {
John McCall54abf7d2009-11-04 02:18:39 +000053 EmitDeprecationWarning(D, Loc);
Chris Lattner76a642f2009-02-15 22:43:40 +000054 }
55
Chris Lattnerffb93682009-10-25 17:21:40 +000056 // See if the decl is unavailable
57 if (D->getAttr<UnavailableAttr>()) {
58 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
59 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
60 }
61
Douglas Gregor48f3bb92009-02-18 21:56:37 +000062 // See if this is a deleted function.
Douglas Gregor25d944a2009-02-24 04:26:15 +000063 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000064 if (FD->isDeleted()) {
65 Diag(Loc, diag::err_deleted_function_use);
66 Diag(D->getLocation(), diag::note_unavailable_here) << true;
67 return true;
68 }
Douglas Gregor25d944a2009-02-24 04:26:15 +000069 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +000070
Douglas Gregor48f3bb92009-02-18 21:56:37 +000071 return false;
Chris Lattner76a642f2009-02-15 22:43:40 +000072}
73
Fariborz Jahanian5b530052009-05-13 18:09:35 +000074/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump1eb44332009-09-09 15:08:12 +000075/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian5b530052009-05-13 18:09:35 +000076/// attribute. It warns if call does not have the sentinel argument.
77///
78void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +000079 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +000080 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump1eb44332009-09-09 15:08:12 +000081 if (!attr)
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000082 return;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000083 int sentinelPos = attr->getSentinel();
84 int nullPos = attr->getNullPos();
Mike Stump1eb44332009-09-09 15:08:12 +000085
Mike Stump390b4cc2009-05-16 07:39:55 +000086 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
87 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +000088 unsigned int i = 0;
Fariborz Jahanian236673e2009-05-14 18:00:00 +000089 bool warnNotEnoughArgs = false;
90 int isMethod = 0;
91 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
92 // skip over named parameters.
93 ObjCMethodDecl::param_iterator P, E = MD->param_end();
94 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
95 if (nullPos)
96 --nullPos;
97 else
98 ++i;
99 }
100 warnNotEnoughArgs = (P != E || i >= NumArgs);
101 isMethod = 1;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000102 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000103 // skip over named parameters.
104 ObjCMethodDecl::param_iterator P, E = FD->param_end();
105 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
106 if (nullPos)
107 --nullPos;
108 else
109 ++i;
110 }
111 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000112 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000113 // block or function pointer call.
114 QualType Ty = V->getType();
115 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000116 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall183700f2009-09-21 23:43:11 +0000117 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
118 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000119 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
120 unsigned NumArgsInProto = Proto->getNumArgs();
121 unsigned k;
122 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
123 if (nullPos)
124 --nullPos;
125 else
126 ++i;
127 }
128 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
129 }
130 if (Ty->isBlockPointerType())
131 isMethod = 2;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000132 } else
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000133 return;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000134 } else
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000135 return;
136
137 if (warnNotEnoughArgs) {
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000138 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000139 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000140 return;
141 }
142 int sentinel = i;
143 while (sentinelPos > 0 && i < NumArgs-1) {
144 --sentinelPos;
145 ++i;
146 }
147 if (sentinelPos > 0) {
148 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000149 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000150 return;
151 }
152 while (i < NumArgs-1) {
153 ++i;
154 ++sentinel;
155 }
156 Expr *sentinelExpr = Args[sentinel];
Anders Carlssone4d2bdd2009-11-24 17:24:21 +0000157 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
158 (!sentinelExpr->getType()->isPointerType() ||
159 !sentinelExpr->isNullPointerConstant(Context,
160 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahaniandaf04152009-05-15 20:33:25 +0000161 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian236673e2009-05-14 18:00:00 +0000162 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian88f1ba02009-05-13 23:20:50 +0000163 }
164 return;
Fariborz Jahanian5b530052009-05-13 18:09:35 +0000165}
166
Douglas Gregor4b2d3f72009-02-26 21:00:50 +0000167SourceRange Sema::getExprRange(ExprTy *E) const {
168 Expr *Ex = (Expr *)E;
169 return Ex? Ex->getSourceRange() : SourceRange();
170}
171
Chris Lattnere7a2e912008-07-25 21:10:04 +0000172//===----------------------------------------------------------------------===//
173// Standard Promotions and Conversions
174//===----------------------------------------------------------------------===//
175
Chris Lattnere7a2e912008-07-25 21:10:04 +0000176/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
177void Sema::DefaultFunctionArrayConversion(Expr *&E) {
178 QualType Ty = E->getType();
179 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
180
Chris Lattnere7a2e912008-07-25 21:10:04 +0000181 if (Ty->isFunctionType())
Mike Stump1eb44332009-09-09 15:08:12 +0000182 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlssonb633c4e2009-09-01 20:37:18 +0000183 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000184 else if (Ty->isArrayType()) {
185 // In C90 mode, arrays only promote to pointers if the array expression is
186 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
187 // type 'array of type' is converted to an expression that has type 'pointer
188 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
189 // that has type 'array of type' ...". The relevant change is "an lvalue"
190 // (C90) to "an expression" (C99).
Argyrios Kyrtzidisc39a3d72008-09-11 04:25:59 +0000191 //
192 // C++ 4.2p1:
193 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
194 // T" can be converted to an rvalue of type "pointer to T".
195 //
196 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
197 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson112a0a82009-08-07 23:48:20 +0000198 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
199 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner67d33d82008-07-25 21:33:13 +0000200 }
Chris Lattnere7a2e912008-07-25 21:10:04 +0000201}
202
203/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000204/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000205/// sometimes surpressed. For example, the array->pointer conversion doesn't
206/// apply if the array is an argument to the sizeof or address (&) operators.
207/// In these instances, this routine should *not* be called.
208Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
209 QualType Ty = Expr->getType();
210 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Douglas Gregorfc24e442009-05-01 20:41:21 +0000212 // C99 6.3.1.1p2:
213 //
214 // The following may be used in an expression wherever an int or
215 // unsigned int may be used:
216 // - an object or expression with an integer type whose integer
217 // conversion rank is less than or equal to the rank of int
218 // and unsigned int.
219 // - A bit-field of type _Bool, int, signed int, or unsigned int.
220 //
221 // If an int can represent all values of the original type, the
222 // value is converted to an int; otherwise, it is converted to an
223 // unsigned int. These are called the integer promotions. All
224 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000225 QualType PTy = Context.isPromotableBitField(Expr);
226 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000227 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000228 return Expr;
229 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000230 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000231 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000232 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000233 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000234 }
235
Douglas Gregorfc24e442009-05-01 20:41:21 +0000236 DefaultFunctionArrayConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000237 return Expr;
238}
239
Chris Lattner05faf172008-07-25 22:25:12 +0000240/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000241/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000242/// double. All other argument types are converted by UsualUnaryConversions().
243void Sema::DefaultArgumentPromotion(Expr *&Expr) {
244 QualType Ty = Expr->getType();
245 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattner05faf172008-07-25 22:25:12 +0000247 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000248 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000249 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000250 return ImpCastExprToType(Expr, Context.DoubleTy,
251 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Chris Lattner05faf172008-07-25 22:25:12 +0000253 UsualUnaryConversions(Expr);
254}
255
Chris Lattner312531a2009-04-12 08:11:20 +0000256/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
257/// will warn if the resulting type is not a POD type, and rejects ObjC
258/// interfaces passed by value. This returns true if the argument type is
259/// completely illegal.
260bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000261 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000262
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000263 if (Expr->getType()->isObjCInterfaceType() &&
264 DiagRuntimeBehavior(Expr->getLocStart(),
265 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
266 << Expr->getType() << CT))
267 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000268
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000269 if (!Expr->getType()->isPODType() &&
270 DiagRuntimeBehavior(Expr->getLocStart(),
271 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
272 << Expr->getType() << CT))
273 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000274
275 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000276}
277
278
Chris Lattnere7a2e912008-07-25 21:10:04 +0000279/// UsualArithmeticConversions - Performs various conversions that are common to
280/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000281/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000282/// responsible for emitting appropriate error diagnostics.
283/// FIXME: verify the conversion rules for "complex int" are consistent with
284/// GCC.
285QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
286 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000287 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000288 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000289
290 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000291
Mike Stump1eb44332009-09-09 15:08:12 +0000292 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000293 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000294 QualType lhs =
295 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000296 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000297 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000298
299 // If both types are identical, no conversion is needed.
300 if (lhs == rhs)
301 return lhs;
302
303 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
304 // The caller can deal with this (e.g. pointer + int).
305 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
306 return lhs;
307
Douglas Gregor2d833e32009-05-02 00:36:19 +0000308 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000309 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000310 if (!LHSBitfieldPromoteTy.isNull())
311 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000312 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000313 if (!RHSBitfieldPromoteTy.isNull())
314 rhs = RHSBitfieldPromoteTy;
315
Eli Friedmana95d7572009-08-19 07:44:53 +0000316 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000317 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000318 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
319 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000320 return destType;
321}
322
Chris Lattnere7a2e912008-07-25 21:10:04 +0000323//===----------------------------------------------------------------------===//
324// Semantic Analysis for various Expression Types
325//===----------------------------------------------------------------------===//
326
327
Steve Narofff69936d2007-09-16 03:34:24 +0000328/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000329/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
330/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
331/// multiple tokens. However, the common case is that StringToks points to one
332/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000333///
334Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000335Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000336 assert(NumStringToks && "Must have at least one string!");
337
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000338 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000339 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000340 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000341
342 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
343 for (unsigned i = 0; i != NumStringToks; ++i)
344 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000345
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000346 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000347 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000348 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000349
350 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
351 if (getLangOptions().CPlusPlus)
352 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000353
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000354 // Get an array type for the string, according to C99 6.4.5. This includes
355 // the nul terminator character as well as the string length for pascal
356 // strings.
357 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000358 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000359 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000362 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000363 Literal.GetStringLength(),
364 Literal.AnyWide, StrTy,
365 &StringTokLocs[0],
366 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000367}
368
Chris Lattner639e2d32008-10-20 05:16:36 +0000369/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
370/// CurBlock to VD should cause it to be snapshotted (as we do for auto
371/// variables defined outside the block) or false if this is not needed (e.g.
372/// for values inside the block or for globals).
373///
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000374/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
375/// up-to-date.
376///
Chris Lattner639e2d32008-10-20 05:16:36 +0000377static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
378 ValueDecl *VD) {
379 // If the value is defined inside the block, we couldn't snapshot it even if
380 // we wanted to.
381 if (CurBlock->TheDecl == VD->getDeclContext())
382 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Chris Lattner639e2d32008-10-20 05:16:36 +0000384 // If this is an enum constant or function, it is constant, don't snapshot.
385 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
386 return false;
387
388 // If this is a reference to an extern, static, or global variable, no need to
389 // snapshot it.
390 // FIXME: What about 'const' variables in C++?
391 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000392 if (!Var->hasLocalStorage())
393 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000395 // Blocks that have these can't be constant.
396 CurBlock->hasBlockDeclRefExprs = true;
397
398 // If we have nested blocks, the decl may be declared in an outer block (in
399 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
400 // be defined outside all of the current blocks (in which case the blocks do
401 // all get the bit). Walk the nesting chain.
402 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
403 NextBlock = NextBlock->PrevBlockInfo) {
404 // If we found the defining block for the variable, don't mark the block as
405 // having a reference outside it.
406 if (NextBlock->TheDecl == VD->getDeclContext())
407 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000409 // Otherwise, the DeclRef from the inner block causes the outer one to need
410 // a snapshot as well.
411 NextBlock->hasBlockDeclRefExprs = true;
412 }
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner639e2d32008-10-20 05:16:36 +0000414 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000415}
416
Chris Lattner639e2d32008-10-20 05:16:36 +0000417
418
Douglas Gregora2813ce2009-10-23 18:54:35 +0000419/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000420Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000421Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000422 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000423 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
424 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000425 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000426 << D->getDeclName();
427 return ExprError();
428 }
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Anders Carlssone41590d2009-06-24 00:10:43 +0000430 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
431 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
432 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
433 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000434 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000435 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000436 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000437 << D->getIdentifier();
438 return ExprError();
439 }
440 }
441 }
442 }
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Douglas Gregore0762c92009-06-19 23:52:42 +0000444 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Douglas Gregora2813ce2009-10-23 18:54:35 +0000446 return Owned(DeclRefExpr::Create(Context,
447 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
448 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000449 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000450}
451
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000452/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
453/// variable corresponding to the anonymous union or struct whose type
454/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000455static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
456 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000457 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000458 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Mike Stump390b4cc2009-05-16 07:39:55 +0000460 // FIXME: Once Decls are directly linked together, this will be an O(1)
461 // operation rather than a slow walk through DeclContext's vector (which
462 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000463 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000464 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000465 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000466 D != DEnd; ++D) {
467 if (*D == Record) {
468 // The object for the anonymous struct/union directly
469 // follows its type in the list of declarations.
470 ++D;
471 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000472 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000473 return *D;
474 }
475 }
476
477 assert(false && "Missing object for anonymous record");
478 return 0;
479}
480
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000481/// \brief Given a field that represents a member of an anonymous
482/// struct/union, build the path from that field's context to the
483/// actual member.
484///
485/// Construct the sequence of field member references we'll have to
486/// perform to get to the field in the anonymous union/struct. The
487/// list of members is built from the field outward, so traverse it
488/// backwards to go from an object in the current context to the field
489/// we found.
490///
491/// \returns The variable from which the field access should begin,
492/// for an anonymous struct/union that is not a member of another
493/// class. Otherwise, returns NULL.
494VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
495 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000496 assert(Field->getDeclContext()->isRecord() &&
497 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
498 && "Field must be stored inside an anonymous struct or union");
499
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000500 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000501 VarDecl *BaseObject = 0;
502 DeclContext *Ctx = Field->getDeclContext();
503 do {
504 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000505 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000506 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000507 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000508 else {
509 BaseObject = cast<VarDecl>(AnonObject);
510 break;
511 }
512 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000513 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000514 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000515
516 return BaseObject;
517}
518
519Sema::OwningExprResult
520Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
521 FieldDecl *Field,
522 Expr *BaseObjectExpr,
523 SourceLocation OpLoc) {
524 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000525 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000526 AnonFields);
527
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000528 // Build the expression that refers to the base object, from
529 // which we will build a sequence of member references to each
530 // of the anonymous union objects and, eventually, the field we
531 // found via name lookup.
532 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000533 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000534 if (BaseObject) {
535 // BaseObject is an anonymous struct/union variable (and is,
536 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000537 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000538 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000539 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000540 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000541 BaseQuals
542 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000543 } else if (BaseObjectExpr) {
544 // The caller provided the base object expression. Determine
545 // whether its a pointer and whether it adds any qualifiers to the
546 // anonymous struct/union fields we're looking into.
547 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000548 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000549 BaseObjectIsPointer = true;
550 ObjectType = ObjectPtr->getPointeeType();
551 }
John McCall0953e762009-09-24 19:53:00 +0000552 BaseQuals
553 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000554 } else {
555 // We've found a member of an anonymous struct/union that is
556 // inside a non-anonymous struct/union, so in a well-formed
557 // program our base object expression is "this".
558 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
559 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000560 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000561 = Context.getTagDeclType(
562 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
563 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000564 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000565 == Context.getCanonicalType(ThisType)) ||
566 IsDerivedFrom(ThisType, AnonFieldType)) {
567 // Our base object expression is "this".
Douglas Gregor8aa5f402009-12-24 20:23:34 +0000568 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000569 MD->getThisType(Context),
570 /*isImplicit=*/true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000571 BaseObjectIsPointer = true;
572 }
573 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000574 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
575 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000576 }
John McCall0953e762009-09-24 19:53:00 +0000577 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000578 }
579
Mike Stump1eb44332009-09-09 15:08:12 +0000580 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000581 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
582 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000583 }
584
585 // Build the implicit member references to the field of the
586 // anonymous struct/union.
587 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000588 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000589 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
590 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
591 FI != FIEnd; ++FI) {
592 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000593 Qualifiers MemberTypeQuals =
594 Context.getCanonicalType(MemberType).getQualifiers();
595
596 // CVR attributes from the base are picked up by members,
597 // except that 'mutable' members don't pick up 'const'.
598 if ((*FI)->isMutable())
599 ResultQuals.removeConst();
600
601 // GC attributes are never picked up by members.
602 ResultQuals.removeObjCGCAttr();
603
604 // TR 18037 does not allow fields to be declared with address spaces.
605 assert(!MemberTypeQuals.hasAddressSpace());
606
607 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
608 if (NewQuals != MemberTypeQuals)
609 MemberType = Context.getQualifiedType(MemberType, NewQuals);
610
Douglas Gregore0762c92009-06-19 23:52:42 +0000611 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman16c53782009-12-04 07:18:51 +0000612 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000613 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000614 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
615 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000616 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000617 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000618 }
619
Sebastian Redlcd965b92009-01-18 18:53:16 +0000620 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000621}
622
John McCall129e2df2009-11-30 22:42:35 +0000623/// Decomposes the given name into a DeclarationName, its location, and
624/// possibly a list of template arguments.
625///
626/// If this produces template arguments, it is permitted to call
627/// DecomposeTemplateName.
628///
629/// This actually loses a lot of source location information for
630/// non-standard name kinds; we should consider preserving that in
631/// some way.
632static void DecomposeUnqualifiedId(Sema &SemaRef,
633 const UnqualifiedId &Id,
634 TemplateArgumentListInfo &Buffer,
635 DeclarationName &Name,
636 SourceLocation &NameLoc,
637 const TemplateArgumentListInfo *&TemplateArgs) {
638 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
639 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
640 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
641
642 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
643 Id.TemplateId->getTemplateArgs(),
644 Id.TemplateId->NumArgs);
645 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
646 TemplateArgsPtr.release();
647
648 TemplateName TName =
649 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
650
651 Name = SemaRef.Context.getNameForTemplate(TName);
652 NameLoc = Id.TemplateId->TemplateNameLoc;
653 TemplateArgs = &Buffer;
654 } else {
655 Name = SemaRef.GetNameFromUnqualifiedId(Id);
656 NameLoc = Id.StartLocation;
657 TemplateArgs = 0;
658 }
659}
660
661/// Decompose the given template name into a list of lookup results.
662///
663/// The unqualified ID must name a non-dependent template, which can
664/// be more easily tested by checking whether DecomposeUnqualifiedId
665/// found template arguments.
666static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
667 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
668 TemplateName TName =
669 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
670
John McCallf7a1a742009-11-24 19:00:30 +0000671 if (TemplateDecl *TD = TName.getAsTemplateDecl())
672 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000673 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
674 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
675 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000676 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000677
John McCallf7a1a742009-11-24 19:00:30 +0000678 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000679}
680
John McCall129e2df2009-11-30 22:42:35 +0000681static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
682 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
683 E = Record->bases_end(); I != E; ++I) {
684 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
685 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
686 if (!BaseRT) return false;
687
688 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
689 if (!BaseRecord->isDefinition() ||
690 !IsFullyFormedScope(SemaRef, BaseRecord))
691 return false;
692 }
693
694 return true;
695}
696
John McCalle1599ce2009-11-30 23:50:49 +0000697/// Determines whether we can lookup this id-expression now or whether
698/// we have to wait until template instantiation is complete.
699static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000700 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000701
John McCalle1599ce2009-11-30 23:50:49 +0000702 // If the qualifier scope isn't computable, it's definitely dependent.
703 if (!DC) return true;
704
705 // If the qualifier scope doesn't name a record, we can always look into it.
706 if (!isa<CXXRecordDecl>(DC)) return false;
707
708 // We can't look into record types unless they're fully-formed.
709 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
710
John McCallaa81e162009-12-01 22:10:20 +0000711 return false;
712}
John McCalle1599ce2009-11-30 23:50:49 +0000713
John McCallaa81e162009-12-01 22:10:20 +0000714/// Determines if the given class is provably not derived from all of
715/// the prospective base classes.
716static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
717 CXXRecordDecl *Record,
718 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000719 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000720 return false;
721
John McCallb1b42562009-12-01 22:28:41 +0000722 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
723 if (!RD) return false;
724 Record = cast<CXXRecordDecl>(RD);
725
John McCallaa81e162009-12-01 22:10:20 +0000726 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
727 E = Record->bases_end(); I != E; ++I) {
728 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
729 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
730 if (!BaseRT) return false;
731
732 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000733 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
734 return false;
735 }
736
737 return true;
738}
739
John McCall144238e2009-12-02 20:26:00 +0000740/// Determines if this is an instance member of a class.
741static bool IsInstanceMember(NamedDecl *D) {
John McCall3b4294e2009-12-16 12:17:52 +0000742 assert(D->isCXXClassMember() &&
John McCallaa81e162009-12-01 22:10:20 +0000743 "checking whether non-member is instance member");
744
745 if (isa<FieldDecl>(D)) return true;
746
747 if (isa<CXXMethodDecl>(D))
748 return !cast<CXXMethodDecl>(D)->isStatic();
749
750 if (isa<FunctionTemplateDecl>(D)) {
751 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
752 return !cast<CXXMethodDecl>(D)->isStatic();
753 }
754
755 return false;
756}
757
758enum IMAKind {
759 /// The reference is definitely not an instance member access.
760 IMA_Static,
761
762 /// The reference may be an implicit instance member access.
763 IMA_Mixed,
764
765 /// The reference may be to an instance member, but it is invalid if
766 /// so, because the context is not an instance method.
767 IMA_Mixed_StaticContext,
768
769 /// The reference may be to an instance member, but it is invalid if
770 /// so, because the context is from an unrelated class.
771 IMA_Mixed_Unrelated,
772
773 /// The reference is definitely an implicit instance member access.
774 IMA_Instance,
775
776 /// The reference may be to an unresolved using declaration.
777 IMA_Unresolved,
778
779 /// The reference may be to an unresolved using declaration and the
780 /// context is not an instance method.
781 IMA_Unresolved_StaticContext,
782
783 /// The reference is to a member of an anonymous structure in a
784 /// non-class context.
785 IMA_AnonymousMember,
786
787 /// All possible referrents are instance members and the current
788 /// context is not an instance method.
789 IMA_Error_StaticContext,
790
791 /// All possible referrents are instance members of an unrelated
792 /// class.
793 IMA_Error_Unrelated
794};
795
796/// The given lookup names class member(s) and is not being used for
797/// an address-of-member expression. Classify the type of access
798/// according to whether it's possible that this reference names an
799/// instance member. This is best-effort; it is okay to
800/// conservatively answer "yes", in which case some errors will simply
801/// not be caught until template-instantiation.
802static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
803 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +0000804 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +0000805
806 bool isStaticContext =
807 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
808 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
809
810 if (R.isUnresolvableResult())
811 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
812
813 // Collect all the declaring classes of instance members we find.
814 bool hasNonInstance = false;
815 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
816 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
817 NamedDecl *D = (*I)->getUnderlyingDecl();
818 if (IsInstanceMember(D)) {
819 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
820
821 // If this is a member of an anonymous record, move out to the
822 // innermost non-anonymous struct or union. If there isn't one,
823 // that's a special case.
824 while (R->isAnonymousStructOrUnion()) {
825 R = dyn_cast<CXXRecordDecl>(R->getParent());
826 if (!R) return IMA_AnonymousMember;
827 }
828 Classes.insert(R->getCanonicalDecl());
829 }
830 else
831 hasNonInstance = true;
832 }
833
834 // If we didn't find any instance members, it can't be an implicit
835 // member reference.
836 if (Classes.empty())
837 return IMA_Static;
838
839 // If the current context is not an instance method, it can't be
840 // an implicit member reference.
841 if (isStaticContext)
842 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
843
844 // If we can prove that the current context is unrelated to all the
845 // declaring classes, it can't be an implicit member reference (in
846 // which case it's an error if any of those members are selected).
847 if (IsProvablyNotDerivedFrom(SemaRef,
848 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
849 Classes))
850 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
851
852 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
853}
854
855/// Diagnose a reference to a field with no object available.
856static void DiagnoseInstanceReference(Sema &SemaRef,
857 const CXXScopeSpec &SS,
858 const LookupResult &R) {
859 SourceLocation Loc = R.getNameLoc();
860 SourceRange Range(Loc);
861 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
862
863 if (R.getAsSingle<FieldDecl>()) {
864 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
865 if (MD->isStatic()) {
866 // "invalid use of member 'x' in static member function"
867 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
868 << Range << R.getLookupName();
869 return;
870 }
871 }
872
873 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
874 << R.getLookupName() << Range;
875 return;
876 }
877
878 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000879}
880
John McCall578b69b2009-12-16 08:11:27 +0000881/// Diagnose an empty lookup.
882///
883/// \return false if new lookup candidates were found
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000884bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
John McCall578b69b2009-12-16 08:11:27 +0000885 LookupResult &R) {
886 DeclarationName Name = R.getLookupName();
887
John McCall578b69b2009-12-16 08:11:27 +0000888 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000889 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +0000890 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
891 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000892 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +0000893 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000894 diagnostic_suggest = diag::err_undeclared_use_suggest;
895 }
John McCall578b69b2009-12-16 08:11:27 +0000896
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000897 // If the original lookup was an unqualified lookup, fake an
898 // unqualified lookup. This is useful when (for example) the
899 // original lookup would not have found something because it was a
900 // dependent name.
901 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
902 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +0000903 if (isa<CXXRecordDecl>(DC)) {
904 LookupQualifiedName(R, DC);
905
906 if (!R.empty()) {
907 // Don't give errors about ambiguities in this lookup.
908 R.suppressDiagnostics();
909
910 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
911 bool isInstance = CurMethod &&
912 CurMethod->isInstance() &&
913 DC == CurMethod->getParent();
914
915 // Give a code modification hint to insert 'this->'.
916 // TODO: fixit for inserting 'Base<T>::' in the other cases.
917 // Actually quite difficult!
918 if (isInstance)
919 Diag(R.getNameLoc(), diagnostic) << Name
920 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
921 "this->");
922 else
923 Diag(R.getNameLoc(), diagnostic) << Name;
924
925 // Do we really want to note all of these?
926 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
927 Diag((*I)->getLocation(), diag::note_dependent_var_use);
928
929 // Tell the callee to try to recover.
930 return false;
931 }
932 }
933 }
934
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000935 // We didn't find anything, so try to correct for a typo.
Douglas Gregord203a162010-01-01 00:15:04 +0000936 if (S && CorrectTypo(R, S, &SS)) {
937 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
938 if (SS.isEmpty())
939 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
940 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000941 R.getLookupName().getAsString());
Douglas Gregord203a162010-01-01 00:15:04 +0000942 else
943 Diag(R.getNameLoc(), diag::err_no_member_suggest)
944 << Name << computeDeclContext(SS, false) << R.getLookupName()
945 << SS.getRange()
946 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000947 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000948 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
949 Diag(ND->getLocation(), diag::note_previous_decl)
950 << ND->getDeclName();
951
Douglas Gregord203a162010-01-01 00:15:04 +0000952 // Tell the callee to try to recover.
953 return false;
954 }
955
956 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
957 // FIXME: If we ended up with a typo for a type name or
958 // Objective-C class name, we're in trouble because the parser
959 // is in the wrong place to recover. Suggest the typo
960 // correction, but don't make it a fix-it since we're not going
961 // to recover well anyway.
962 if (SS.isEmpty())
963 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
964 else
965 Diag(R.getNameLoc(), diag::err_no_member_suggest)
966 << Name << computeDeclContext(SS, false) << R.getLookupName()
967 << SS.getRange();
968
969 // Don't try to recover; it won't work.
970 return true;
971 }
972
973 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000974 }
975
976 // Emit a special diagnostic for failed member lookups.
977 // FIXME: computing the declaration context might fail here (?)
978 if (!SS.isEmpty()) {
979 Diag(R.getNameLoc(), diag::err_no_member)
980 << Name << computeDeclContext(SS, false)
981 << SS.getRange();
982 return true;
983 }
984
John McCall578b69b2009-12-16 08:11:27 +0000985 // Give up, we can't recover.
986 Diag(R.getNameLoc(), diagnostic) << Name;
987 return true;
988}
989
John McCallf7a1a742009-11-24 19:00:30 +0000990Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
991 const CXXScopeSpec &SS,
992 UnqualifiedId &Id,
993 bool HasTrailingLParen,
994 bool isAddressOfOperand) {
995 assert(!(isAddressOfOperand && HasTrailingLParen) &&
996 "cannot be direct & operand and have a trailing lparen");
997
998 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000999 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001000
John McCall129e2df2009-11-30 22:42:35 +00001001 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001002
1003 // Decompose the UnqualifiedId into the following data.
1004 DeclarationName Name;
1005 SourceLocation NameLoc;
1006 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +00001007 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1008 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001009
Douglas Gregor10c42622008-11-18 15:03:34 +00001010 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +00001011
John McCallf7a1a742009-11-24 19:00:30 +00001012 // C++ [temp.dep.expr]p3:
1013 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001014 // -- an identifier that was declared with a dependent type,
1015 // (note: handled after lookup)
1016 // -- a template-id that is dependent,
1017 // (note: handled in BuildTemplateIdExpr)
1018 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001019 // -- a nested-name-specifier that contains a class-name that
1020 // names a dependent type.
1021 // Determine whether this is a member of an unknown specialization;
1022 // we need to handle these differently.
Douglas Gregor48026d22010-01-11 18:40:55 +00001023 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1024 Name.getCXXNameType()->isDependentType()) ||
1025 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCallf7a1a742009-11-24 19:00:30 +00001026 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +00001027 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001028 TemplateArgs);
1029 }
John McCallba135432009-11-21 08:51:07 +00001030
John McCallf7a1a742009-11-24 19:00:30 +00001031 // Perform the required lookup.
1032 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1033 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +00001034 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +00001035 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +00001036 } else {
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001037 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1038 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001039
John McCallf7a1a742009-11-24 19:00:30 +00001040 // If this reference is in an Objective-C method, then we need to do
1041 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001042 if (IvarLookupFollowUp) {
1043 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001044 if (E.isInvalid())
1045 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001046
John McCallf7a1a742009-11-24 19:00:30 +00001047 Expr *Ex = E.takeAs<Expr>();
1048 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001049 }
Chris Lattner8a934232008-03-31 00:36:02 +00001050 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001051
John McCallf7a1a742009-11-24 19:00:30 +00001052 if (R.isAmbiguous())
1053 return ExprError();
1054
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001055 // Determine whether this name might be a candidate for
1056 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001057 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001058
John McCallf7a1a742009-11-24 19:00:30 +00001059 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001061 // in C90, extension in C99, forbidden in C++).
1062 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1063 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1064 if (D) R.addDecl(D);
1065 }
1066
1067 // If this name wasn't predeclared and if this is not a function
1068 // call, diagnose the problem.
1069 if (R.empty()) {
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001070 if (DiagnoseEmptyLookup(S, SS, R))
John McCall578b69b2009-12-16 08:11:27 +00001071 return ExprError();
1072
1073 assert(!R.empty() &&
1074 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001075
1076 // If we found an Objective-C instance variable, let
1077 // LookupInObjCMethod build the appropriate expression to
1078 // reference the ivar.
1079 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1080 R.clear();
1081 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1082 assert(E.isInvalid() || E.get());
1083 return move(E);
1084 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 }
1086 }
Mike Stump1eb44332009-09-09 15:08:12 +00001087
John McCallf7a1a742009-11-24 19:00:30 +00001088 // This is guaranteed from this point on.
1089 assert(!R.empty() || ADL);
1090
1091 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001092 // Warn about constructs like:
1093 // if (void *X = foo()) { ... } else { X }.
1094 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Douglas Gregor751f9a42009-06-30 15:47:41 +00001096 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1097 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001098 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001099 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001100 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001101 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001102 << Var->getDeclName()
1103 << (Var->getType()->isPointerType()? 2 :
1104 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001105 break;
1106 }
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001108 // Move to the parent of this scope.
1109 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001110 }
1111 }
John McCallf7a1a742009-11-24 19:00:30 +00001112 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001113 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1114 // C99 DR 316 says that, if a function type comes from a
1115 // function definition (without a prototype), that type is only
1116 // used for checking compatibility. Therefore, when referencing
1117 // the function, we pretend that we don't have the full function
1118 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001119 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001120 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001121
Douglas Gregor751f9a42009-06-30 15:47:41 +00001122 QualType T = Func->getType();
1123 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001124 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001125 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001126 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001127 }
1128 }
Mike Stump1eb44332009-09-09 15:08:12 +00001129
John McCallaa81e162009-12-01 22:10:20 +00001130 // Check whether this might be a C++ implicit instance member access.
1131 // C++ [expr.prim.general]p6:
1132 // Within the definition of a non-static member function, an
1133 // identifier that names a non-static member is transformed to a
1134 // class member access expression.
1135 // But note that &SomeClass::foo is grammatically distinct, even
1136 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001137 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001138 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001139 if (!isAbstractMemberPointer)
1140 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001141 }
1142
John McCallf7a1a742009-11-24 19:00:30 +00001143 if (TemplateArgs)
1144 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001145
John McCallf7a1a742009-11-24 19:00:30 +00001146 return BuildDeclarationNameExpr(SS, R, ADL);
1147}
1148
John McCall3b4294e2009-12-16 12:17:52 +00001149/// Builds an expression which might be an implicit member expression.
1150Sema::OwningExprResult
1151Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1152 LookupResult &R,
1153 const TemplateArgumentListInfo *TemplateArgs) {
1154 switch (ClassifyImplicitMemberAccess(*this, R)) {
1155 case IMA_Instance:
1156 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1157
1158 case IMA_AnonymousMember:
1159 assert(R.isSingleResult());
1160 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1161 R.getAsSingle<FieldDecl>());
1162
1163 case IMA_Mixed:
1164 case IMA_Mixed_Unrelated:
1165 case IMA_Unresolved:
1166 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1167
1168 case IMA_Static:
1169 case IMA_Mixed_StaticContext:
1170 case IMA_Unresolved_StaticContext:
1171 if (TemplateArgs)
1172 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1173 return BuildDeclarationNameExpr(SS, R, false);
1174
1175 case IMA_Error_StaticContext:
1176 case IMA_Error_Unrelated:
1177 DiagnoseInstanceReference(*this, SS, R);
1178 return ExprError();
1179 }
1180
1181 llvm_unreachable("unexpected instance member access kind");
1182 return ExprError();
1183}
1184
John McCall129e2df2009-11-30 22:42:35 +00001185/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1186/// declaration name, generally during template instantiation.
1187/// There's a large number of things which don't need to be done along
1188/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001189Sema::OwningExprResult
1190Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1191 DeclarationName Name,
1192 SourceLocation NameLoc) {
1193 DeclContext *DC;
1194 if (!(DC = computeDeclContext(SS, false)) ||
1195 DC->isDependentContext() ||
1196 RequireCompleteDeclContext(SS))
1197 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1198
1199 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1200 LookupQualifiedName(R, DC);
1201
1202 if (R.isAmbiguous())
1203 return ExprError();
1204
1205 if (R.empty()) {
1206 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1207 return ExprError();
1208 }
1209
1210 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1211}
1212
1213/// LookupInObjCMethod - The parser has read a name in, and Sema has
1214/// detected that we're currently inside an ObjC method. Perform some
1215/// additional lookup.
1216///
1217/// Ideally, most of this would be done by lookup, but there's
1218/// actually quite a lot of extra work involved.
1219///
1220/// Returns a null sentinel to indicate trivial success.
1221Sema::OwningExprResult
1222Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001223 IdentifierInfo *II,
1224 bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001225 SourceLocation Loc = Lookup.getNameLoc();
1226
1227 // There are two cases to handle here. 1) scoped lookup could have failed,
1228 // in which case we should look for an ivar. 2) scoped lookup could have
1229 // found a decl, but that decl is outside the current instance method (i.e.
1230 // a global variable). In these two cases, we do a lookup for an ivar with
1231 // this name, if the lookup sucedes, we replace it our current decl.
1232
1233 // If we're in a class method, we don't normally want to look for
1234 // ivars. But if we don't find anything else, and there's an
1235 // ivar, that's an error.
1236 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1237
1238 bool LookForIvars;
1239 if (Lookup.empty())
1240 LookForIvars = true;
1241 else if (IsClassMethod)
1242 LookForIvars = false;
1243 else
1244 LookForIvars = (Lookup.isSingleResult() &&
1245 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1246
1247 if (LookForIvars) {
1248 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1249 ObjCInterfaceDecl *ClassDeclared;
1250 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1251 // Diagnose using an ivar in a class method.
1252 if (IsClassMethod)
1253 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1254 << IV->getDeclName());
1255
1256 // If we're referencing an invalid decl, just return this as a silent
1257 // error node. The error diagnostic was already emitted on the decl.
1258 if (IV->isInvalidDecl())
1259 return ExprError();
1260
1261 // Check if referencing a field with __attribute__((deprecated)).
1262 if (DiagnoseUseOfDecl(IV, Loc))
1263 return ExprError();
1264
1265 // Diagnose the use of an ivar outside of the declaring class.
1266 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1267 ClassDeclared != IFace)
1268 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1269
1270 // FIXME: This should use a new expr for a direct reference, don't
1271 // turn this into Self->ivar, just return a BareIVarExpr or something.
1272 IdentifierInfo &II = Context.Idents.get("self");
1273 UnqualifiedId SelfName;
1274 SelfName.setIdentifier(&II, SourceLocation());
1275 CXXScopeSpec SelfScopeSpec;
1276 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1277 SelfName, false, false);
1278 MarkDeclarationReferenced(Loc, IV);
1279 return Owned(new (Context)
1280 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1281 SelfExpr.takeAs<Expr>(), true, true));
1282 }
1283 } else if (getCurMethodDecl()->isInstanceMethod()) {
1284 // We should warn if a local variable hides an ivar.
1285 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1286 ObjCInterfaceDecl *ClassDeclared;
1287 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1288 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1289 IFace == ClassDeclared)
1290 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1291 }
1292 }
1293
1294 // Needed to implement property "super.method" notation.
1295 if (Lookup.empty() && II->isStr("super")) {
1296 QualType T;
1297
1298 if (getCurMethodDecl()->isInstanceMethod())
1299 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1300 getCurMethodDecl()->getClassInterface()));
1301 else
1302 T = Context.getObjCClassType();
1303 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1304 }
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001305 if (Lookup.empty() && II && AllowBuiltinCreation) {
1306 // FIXME. Consolidate this with similar code in LookupName.
1307 if (unsigned BuiltinID = II->getBuiltinID()) {
1308 if (!(getLangOptions().CPlusPlus &&
1309 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1310 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1311 S, Lookup.isForRedeclaration(),
1312 Lookup.getNameLoc());
1313 if (D) Lookup.addDecl(D);
1314 }
1315 }
1316 }
John McCallf7a1a742009-11-24 19:00:30 +00001317 // Sentinel value saying that we didn't do anything special.
1318 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001319}
John McCallba135432009-11-21 08:51:07 +00001320
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001321/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001322bool
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001323Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1324 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump1eb44332009-09-09 15:08:12 +00001325 if (CXXRecordDecl *RD =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001326 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001327 QualType DestType =
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001328 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001329 if (DestType->isDependentType() || From->getType()->isDependentType())
1330 return false;
1331 QualType FromRecordType = From->getType();
1332 QualType DestRecordType = DestType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001333 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001334 DestType = Context.getPointerType(DestType);
1335 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001336 }
Fariborz Jahanian96e2fa92009-07-29 20:41:46 +00001337 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1338 CheckDerivedToBaseConversion(FromRecordType,
1339 DestRecordType,
1340 From->getSourceRange().getBegin(),
1341 From->getSourceRange()))
1342 return true;
Anders Carlsson3503d042009-07-31 01:23:52 +00001343 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1344 /*isLvalue=*/true);
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001345 }
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001346 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001347}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001348
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001349/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001350static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001351 const CXXScopeSpec &SS, ValueDecl *Member,
John McCallf7a1a742009-11-24 19:00:30 +00001352 SourceLocation Loc, QualType Ty,
1353 const TemplateArgumentListInfo *TemplateArgs = 0) {
1354 NestedNameSpecifier *Qualifier = 0;
1355 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001356 if (SS.isSet()) {
1357 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1358 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001359 }
Mike Stump1eb44332009-09-09 15:08:12 +00001360
John McCallf7a1a742009-11-24 19:00:30 +00001361 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1362 Member, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001363}
1364
John McCallaa81e162009-12-01 22:10:20 +00001365/// Builds an implicit member access expression. The current context
1366/// is known to be an instance method, and the given unqualified lookup
1367/// set is known to contain only instance members, at least one of which
1368/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001369Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001370Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1371 LookupResult &R,
1372 const TemplateArgumentListInfo *TemplateArgs,
1373 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001374 assert(!R.empty() && !R.isAmbiguous());
1375
John McCallba135432009-11-21 08:51:07 +00001376 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001377
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001378 // We may have found a field within an anonymous union or struct
1379 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001380 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001381 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001382 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001383 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001384 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001385
John McCallaa81e162009-12-01 22:10:20 +00001386 // If this is known to be an instance access, go ahead and build a
1387 // 'this' expression now.
1388 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1389 Expr *This = 0; // null signifies implicit access
1390 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00001391 SourceLocation Loc = R.getNameLoc();
1392 if (SS.getRange().isValid())
1393 Loc = SS.getRange().getBegin();
1394 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00001395 }
1396
John McCallaa81e162009-12-01 22:10:20 +00001397 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1398 /*OpLoc*/ SourceLocation(),
1399 /*IsArrow*/ true,
1400 SS, R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001401}
1402
John McCallf7a1a742009-11-24 19:00:30 +00001403bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001404 const LookupResult &R,
1405 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001406 // Only when used directly as the postfix-expression of a call.
1407 if (!HasTrailingLParen)
1408 return false;
1409
1410 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001411 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001412 return false;
1413
1414 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001415 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001416 return false;
1417
1418 // Turn off ADL when we find certain kinds of declarations during
1419 // normal lookup:
1420 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1421 NamedDecl *D = *I;
1422
1423 // C++0x [basic.lookup.argdep]p3:
1424 // -- a declaration of a class member
1425 // Since using decls preserve this property, we check this on the
1426 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001427 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001428 return false;
1429
1430 // C++0x [basic.lookup.argdep]p3:
1431 // -- a block-scope function declaration that is not a
1432 // using-declaration
1433 // NOTE: we also trigger this for function templates (in fact, we
1434 // don't check the decl type at all, since all other decl types
1435 // turn off ADL anyway).
1436 if (isa<UsingShadowDecl>(D))
1437 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1438 else if (D->getDeclContext()->isFunctionOrMethod())
1439 return false;
1440
1441 // C++0x [basic.lookup.argdep]p3:
1442 // -- a declaration that is neither a function or a function
1443 // template
1444 // And also for builtin functions.
1445 if (isa<FunctionDecl>(D)) {
1446 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1447
1448 // But also builtin functions.
1449 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1450 return false;
1451 } else if (!isa<FunctionTemplateDecl>(D))
1452 return false;
1453 }
1454
1455 return true;
1456}
1457
1458
John McCallba135432009-11-21 08:51:07 +00001459/// Diagnoses obvious problems with the use of the given declaration
1460/// as an expression. This is only actually called for lookups that
1461/// were not overloaded, and it doesn't promise that the declaration
1462/// will in fact be used.
1463static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1464 if (isa<TypedefDecl>(D)) {
1465 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1466 return true;
1467 }
1468
1469 if (isa<ObjCInterfaceDecl>(D)) {
1470 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1471 return true;
1472 }
1473
1474 if (isa<NamespaceDecl>(D)) {
1475 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1476 return true;
1477 }
1478
1479 return false;
1480}
1481
1482Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001483Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001484 LookupResult &R,
1485 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001486 // If this is a single, fully-resolved result and we don't need ADL,
1487 // just build an ordinary singleton decl ref.
1488 if (!NeedsADL && R.isSingleResult())
John McCall5b3f9132009-11-22 01:44:31 +00001489 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001490
1491 // We only need to check the declaration if there's exactly one
1492 // result, because in the overloaded case the results can only be
1493 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001494 if (R.isSingleResult() &&
1495 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001496 return ExprError();
1497
John McCallf7a1a742009-11-24 19:00:30 +00001498 bool Dependent
1499 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001500 UnresolvedLookupExpr *ULE
John McCallf7a1a742009-11-24 19:00:30 +00001501 = UnresolvedLookupExpr::Create(Context, Dependent,
1502 (NestedNameSpecifier*) SS.getScopeRep(),
1503 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001504 R.getLookupName(), R.getNameLoc(),
1505 NeedsADL, R.isOverloadedResult());
1506 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1507 ULE->addDecl(*I);
John McCallba135432009-11-21 08:51:07 +00001508
1509 return Owned(ULE);
1510}
1511
1512
1513/// \brief Complete semantic analysis for a reference to the given declaration.
1514Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001515Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001516 SourceLocation Loc, NamedDecl *D) {
1517 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001518 assert(!isa<FunctionTemplateDecl>(D) &&
1519 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001520
1521 if (CheckDeclInExpr(*this, Loc, D))
1522 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001523
Douglas Gregor9af2f522009-12-01 16:58:18 +00001524 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1525 // Specifically diagnose references to class templates that are missing
1526 // a template argument list.
1527 Diag(Loc, diag::err_template_decl_ref)
1528 << Template << SS.getRange();
1529 Diag(Template->getLocation(), diag::note_template_decl_here);
1530 return ExprError();
1531 }
1532
1533 // Make sure that we're referring to a value.
1534 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1535 if (!VD) {
1536 Diag(Loc, diag::err_ref_non_value)
1537 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00001538 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001539 return ExprError();
1540 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001541
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001542 // Check whether this declaration can be used. Note that we suppress
1543 // this check when we're going to perform argument-dependent lookup
1544 // on this function name, because this might not be the function
1545 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001546 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001547 return ExprError();
1548
Steve Naroffdd972f22008-09-05 22:11:13 +00001549 // Only create DeclRefExpr's for valid Decl's.
1550 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001551 return ExprError();
1552
Chris Lattner639e2d32008-10-20 05:16:36 +00001553 // If the identifier reference is inside a block, and it refers to a value
1554 // that is outside the block, create a BlockDeclRefExpr instead of a
1555 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1556 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001557 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001558 // We do not do this for things like enum constants, global variables, etc,
1559 // as they do not get snapshotted.
1560 //
1561 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Mike Stump0d6fd572010-01-05 02:56:35 +00001562 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1563 Diag(Loc, diag::err_ref_vm_type);
1564 Diag(D->getLocation(), diag::note_declared_at);
1565 return ExprError();
1566 }
1567
Mike Stump28497342010-01-05 03:10:36 +00001568 if (VD->getType()->isArrayType()) {
1569 Diag(Loc, diag::err_ref_array_type);
1570 Diag(D->getLocation(), diag::note_declared_at);
1571 return ExprError();
1572 }
1573
Douglas Gregore0762c92009-06-19 23:52:42 +00001574 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001575 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001576 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001577 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001578 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001579 // This is to record that a 'const' was actually synthesize and added.
1580 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001581 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Eli Friedman5fdeae12009-03-22 23:00:19 +00001583 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001584 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001585 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001586 }
1587 // If this reference is not in a block or if the referenced variable is
1588 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001589
John McCallf7a1a742009-11-24 19:00:30 +00001590 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001591}
1592
Sebastian Redlcd965b92009-01-18 18:53:16 +00001593Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1594 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001595 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001596
Reid Spencer5f016e22007-07-11 17:01:13 +00001597 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001598 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001599 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1600 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1601 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001602 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001603
Chris Lattnerfa28b302008-01-12 08:14:25 +00001604 // Pre-defined identifiers are of type char[x], where x is the length of the
1605 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Anders Carlsson3a082d82009-09-08 18:24:21 +00001607 Decl *currentDecl = getCurFunctionOrMethodDecl();
1608 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001609 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001610 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001611 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001612
Anders Carlsson773f3972009-09-11 01:22:35 +00001613 QualType ResTy;
1614 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1615 ResTy = Context.DependentTy;
1616 } else {
1617 unsigned Length =
1618 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001619
Anders Carlsson773f3972009-09-11 01:22:35 +00001620 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001621 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001622 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1623 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001624 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001625}
1626
Sebastian Redlcd965b92009-01-18 18:53:16 +00001627Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001628 llvm::SmallString<16> CharBuffer;
1629 CharBuffer.resize(Tok.getLength());
1630 const char *ThisTokBegin = &CharBuffer[0];
1631 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001632
Reid Spencer5f016e22007-07-11 17:01:13 +00001633 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1634 Tok.getLocation(), PP);
1635 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001636 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001637
Chris Lattnere8337df2009-12-30 21:19:39 +00001638 QualType Ty;
1639 if (!getLangOptions().CPlusPlus)
1640 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1641 else if (Literal.isWide())
1642 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
1643 else
1644 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001645
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001646 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1647 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00001648 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001649}
1650
Sebastian Redlcd965b92009-01-18 18:53:16 +00001651Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1652 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001653 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1654 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001655 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001656 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001657 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001658 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001659 }
Ted Kremenek28396602009-01-13 23:19:12 +00001660
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001662 // Add padding so that NumericLiteralParser can overread by one character.
1663 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001665
Reid Spencer5f016e22007-07-11 17:01:13 +00001666 // Get the spelling of the token, which eliminates trigraphs, etc.
1667 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001668
Mike Stump1eb44332009-09-09 15:08:12 +00001669 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001670 Tok.getLocation(), PP);
1671 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001672 return ExprError();
1673
Chris Lattner5d661452007-08-26 03:42:43 +00001674 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001675
Chris Lattner5d661452007-08-26 03:42:43 +00001676 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001677 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001678 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001679 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001680 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001681 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001682 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001683 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001684
1685 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1686
John McCall94c939d2009-12-24 09:08:04 +00001687 using llvm::APFloat;
1688 APFloat Val(Format);
1689
1690 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00001691
1692 // Overflow is always an error, but underflow is only an error if
1693 // we underflowed to zero (APFloat reports denormals as underflow).
1694 if ((result & APFloat::opOverflow) ||
1695 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00001696 unsigned diagnostic;
1697 llvm::SmallVector<char, 20> buffer;
1698 if (result & APFloat::opOverflow) {
1699 diagnostic = diag::err_float_overflow;
1700 APFloat::getLargest(Format).toString(buffer);
1701 } else {
1702 diagnostic = diag::err_float_underflow;
1703 APFloat::getSmallest(Format).toString(buffer);
1704 }
1705
1706 Diag(Tok.getLocation(), diagnostic)
1707 << Ty
1708 << llvm::StringRef(buffer.data(), buffer.size());
1709 }
1710
1711 bool isExact = (result == APFloat::opOK);
Chris Lattner001d64d2009-06-29 17:34:55 +00001712 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001713
Chris Lattner5d661452007-08-26 03:42:43 +00001714 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001715 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001716 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001717 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001718
Neil Boothb9449512007-08-29 22:00:19 +00001719 // long long is a C99 feature.
1720 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001721 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001722 Diag(Tok.getLocation(), diag::ext_longlong);
1723
Reid Spencer5f016e22007-07-11 17:01:13 +00001724 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001725 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001726
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 if (Literal.GetIntegerValue(ResultVal)) {
1728 // If this value didn't fit into uintmax_t, warn and force to ull.
1729 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001730 Ty = Context.UnsignedLongLongTy;
1731 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001732 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001733 } else {
1734 // If this value fits into a ULL, try to figure out what else it fits into
1735 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001736
Reid Spencer5f016e22007-07-11 17:01:13 +00001737 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1738 // be an unsigned int.
1739 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1740
1741 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001742 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001743 if (!Literal.isLong && !Literal.isLongLong) {
1744 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001745 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001746
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 // Does it fit in a unsigned int?
1748 if (ResultVal.isIntN(IntSize)) {
1749 // Does it fit in a signed int?
1750 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001751 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001752 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001753 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001754 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001755 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001756 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001757
Reid Spencer5f016e22007-07-11 17:01:13 +00001758 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001759 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001760 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001761
Reid Spencer5f016e22007-07-11 17:01:13 +00001762 // Does it fit in a unsigned long?
1763 if (ResultVal.isIntN(LongSize)) {
1764 // Does it fit in a signed long?
1765 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001766 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001767 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001768 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001769 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001770 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001771 }
1772
Reid Spencer5f016e22007-07-11 17:01:13 +00001773 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001774 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001775 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001776
Reid Spencer5f016e22007-07-11 17:01:13 +00001777 // Does it fit in a unsigned long long?
1778 if (ResultVal.isIntN(LongLongSize)) {
1779 // Does it fit in a signed long long?
1780 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001781 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001782 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001783 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001784 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001785 }
1786 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001787
Reid Spencer5f016e22007-07-11 17:01:13 +00001788 // If we still couldn't decide a type, we probably have something that
1789 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001790 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001792 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001793 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001794 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001795
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001796 if (ResultVal.getBitWidth() != Width)
1797 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001798 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001799 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001800 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001801
Chris Lattner5d661452007-08-26 03:42:43 +00001802 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1803 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001804 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001805 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001806
1807 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001808}
1809
Sebastian Redlcd965b92009-01-18 18:53:16 +00001810Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1811 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001812 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001813 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00001814 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00001815}
1816
1817/// The UsualUnaryConversions() function is *not* called by this routine.
1818/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00001819bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00001820 SourceLocation OpLoc,
1821 const SourceRange &ExprRange,
1822 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00001823 if (exprType->isDependentType())
1824 return false;
1825
Sebastian Redl5d484e82009-11-23 17:18:46 +00001826 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1827 // the result is the size of the referenced type."
1828 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1829 // result shall be the alignment of the referenced type."
1830 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1831 exprType = Ref->getPointeeType();
1832
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00001834 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001835 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001836 if (isSizeof)
1837 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1838 return false;
1839 }
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Chris Lattner1efaa952009-04-24 00:30:45 +00001841 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00001842 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001843 Diag(OpLoc, diag::ext_sizeof_void_type)
1844 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00001845 return false;
1846 }
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Chris Lattner1efaa952009-04-24 00:30:45 +00001848 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00001849 PDiag(diag::err_sizeof_alignof_incomplete_type)
1850 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00001851 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Chris Lattner1efaa952009-04-24 00:30:45 +00001853 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00001854 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00001855 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00001856 << exprType << isSizeof << ExprRange;
1857 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00001858 }
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Chris Lattner1efaa952009-04-24 00:30:45 +00001860 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001861}
1862
Chris Lattner31e21e02009-01-24 20:17:12 +00001863bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1864 const SourceRange &ExprRange) {
1865 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00001866
Mike Stump1eb44332009-09-09 15:08:12 +00001867 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00001868 if (isa<DeclRefExpr>(E))
1869 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00001870
1871 // Cannot know anything else if the expression is dependent.
1872 if (E->isTypeDependent())
1873 return false;
1874
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001875 if (E->getBitField()) {
1876 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1877 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00001878 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001879
1880 // Alignment of a field access is always okay, so long as it isn't a
1881 // bit-field.
1882 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00001883 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001884 return false;
1885
Chris Lattner31e21e02009-01-24 20:17:12 +00001886 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1887}
1888
Douglas Gregorba498172009-03-13 21:01:28 +00001889/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001890Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00001891Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00001892 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001893 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00001894 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00001895 return ExprError();
1896
John McCalla93c9342009-12-07 02:54:59 +00001897 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00001898
Douglas Gregorba498172009-03-13 21:01:28 +00001899 if (!T->isDependentType() &&
1900 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1901 return ExprError();
1902
1903 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00001904 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00001905 Context.getSizeType(), OpLoc,
1906 R.getEnd()));
1907}
1908
1909/// \brief Build a sizeof or alignof expression given an expression
1910/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00001911Action::OwningExprResult
1912Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00001913 bool isSizeOf, SourceRange R) {
1914 // Verify that the operand is valid.
1915 bool isInvalid = false;
1916 if (E->isTypeDependent()) {
1917 // Delay type-checking for type-dependent expressions.
1918 } else if (!isSizeOf) {
1919 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001920 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00001921 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1922 isInvalid = true;
1923 } else {
1924 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1925 }
1926
1927 if (isInvalid)
1928 return ExprError();
1929
1930 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1931 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1932 Context.getSizeType(), OpLoc,
1933 R.getEnd()));
1934}
1935
Sebastian Redl05189992008-11-11 17:56:53 +00001936/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1937/// the same for @c alignof and @c __alignof
1938/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001939Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00001940Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1941 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001942 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001943 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001944
Sebastian Redl05189992008-11-11 17:56:53 +00001945 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00001946 TypeSourceInfo *TInfo;
1947 (void) GetTypeFromParser(TyOrEx, &TInfo);
1948 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00001949 }
Sebastian Redl05189992008-11-11 17:56:53 +00001950
Douglas Gregorba498172009-03-13 21:01:28 +00001951 Expr *ArgEx = (Expr *)TyOrEx;
1952 Action::OwningExprResult Result
1953 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1954
1955 if (Result.isInvalid())
1956 DeleteExpr(ArgEx);
1957
1958 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00001959}
1960
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001961QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00001962 if (V->isTypeDependent())
1963 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Chris Lattnercc26ed72007-08-26 05:39:26 +00001965 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00001966 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00001967 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Chris Lattnercc26ed72007-08-26 05:39:26 +00001969 // Otherwise they pass through real integer and floating point types here.
1970 if (V->getType()->isArithmeticType())
1971 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Chris Lattnercc26ed72007-08-26 05:39:26 +00001973 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00001974 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1975 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00001976 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00001977}
1978
1979
Reid Spencer5f016e22007-07-11 17:01:13 +00001980
Sebastian Redl0eb23302009-01-19 00:08:26 +00001981Action::OwningExprResult
1982Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1983 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001984 UnaryOperator::Opcode Opc;
1985 switch (Kind) {
1986 default: assert(0 && "Unknown unary op!");
1987 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1988 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1989 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00001990
Eli Friedmane4216e92009-11-18 03:38:04 +00001991 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00001992}
1993
Sebastian Redl0eb23302009-01-19 00:08:26 +00001994Action::OwningExprResult
1995Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1996 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00001997 // Since this might be a postfix expression, get rid of ParenListExprs.
1998 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1999
Sebastian Redl0eb23302009-01-19 00:08:26 +00002000 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2001 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Douglas Gregor337c6b92008-11-19 17:17:41 +00002003 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002004 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2005 Base.release();
2006 Idx.release();
2007 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2008 Context.DependentTy, RLoc));
2009 }
2010
Mike Stump1eb44332009-09-09 15:08:12 +00002011 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002012 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002013 LHSExp->getType()->isEnumeralType() ||
2014 RHSExp->getType()->isRecordType() ||
2015 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00002016 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00002017 }
2018
Sebastian Redlf322ed62009-10-29 20:17:01 +00002019 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2020}
2021
2022
2023Action::OwningExprResult
2024Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2025 ExprArg Idx, SourceLocation RLoc) {
2026 Expr *LHSExp = static_cast<Expr*>(Base.get());
2027 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2028
Chris Lattner12d9ff62007-07-16 00:14:47 +00002029 // Perform default conversions.
2030 DefaultFunctionArrayConversion(LHSExp);
2031 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002032
Chris Lattner12d9ff62007-07-16 00:14:47 +00002033 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002034
Reid Spencer5f016e22007-07-11 17:01:13 +00002035 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002036 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002037 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002038 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002039 Expr *BaseExpr, *IndexExpr;
2040 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002041 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2042 BaseExpr = LHSExp;
2043 IndexExpr = RHSExp;
2044 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002045 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002046 BaseExpr = LHSExp;
2047 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002048 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002049 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002050 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002051 BaseExpr = RHSExp;
2052 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002053 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002054 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002055 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002056 BaseExpr = LHSExp;
2057 IndexExpr = RHSExp;
2058 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002059 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002060 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002061 // Handle the uncommon case of "123[Ptr]".
2062 BaseExpr = RHSExp;
2063 IndexExpr = LHSExp;
2064 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002065 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002066 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002067 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00002068
Chris Lattner12d9ff62007-07-16 00:14:47 +00002069 // FIXME: need to deal with const...
2070 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002071 } else if (LHSTy->isArrayType()) {
2072 // If we see an array that wasn't promoted by
2073 // DefaultFunctionArrayConversion, it must be an array that
2074 // wasn't promoted because of the C90 rule that doesn't
2075 // allow promoting non-lvalue arrays. Warn, then
2076 // force the promotion here.
2077 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2078 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002079 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2080 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002081 LHSTy = LHSExp->getType();
2082
2083 BaseExpr = LHSExp;
2084 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002085 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002086 } else if (RHSTy->isArrayType()) {
2087 // Same as previous, except for 123[f().a] case
2088 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2089 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002090 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2091 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002092 RHSTy = RHSExp->getType();
2093
2094 BaseExpr = RHSExp;
2095 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002096 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002097 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002098 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2099 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002100 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002101 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00002102 if (!(IndexExpr->getType()->isIntegerType() &&
2103 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002104 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2105 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002106
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002107 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002108 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2109 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002110 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2111
Douglas Gregore7450f52009-03-24 19:52:54 +00002112 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002113 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2114 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002115 // incomplete types are not object types.
2116 if (ResultType->isFunctionType()) {
2117 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2118 << ResultType << BaseExpr->getSourceRange();
2119 return ExprError();
2120 }
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Douglas Gregore7450f52009-03-24 19:52:54 +00002122 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002123 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002124 PDiag(diag::err_subscript_incomplete_type)
2125 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002126 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Chris Lattner1efaa952009-04-24 00:30:45 +00002128 // Diagnose bad cases where we step over interface counts.
2129 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2130 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2131 << ResultType << BaseExpr->getSourceRange();
2132 return ExprError();
2133 }
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Sebastian Redl0eb23302009-01-19 00:08:26 +00002135 Base.release();
2136 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002137 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002138 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002139}
2140
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002141QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002142CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002143 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002144 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002145 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2146 // see FIXME there.
2147 //
2148 // FIXME: This logic can be greatly simplified by splitting it along
2149 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002150 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002151
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002152 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002153 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002154
Mike Stumpeed9cac2009-02-19 03:04:26 +00002155 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002156 // special names that indicate a subset of exactly half the elements are
2157 // to be selected.
2158 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002159
Nate Begeman353417a2009-01-18 01:47:54 +00002160 // This flag determines whether or not CompName has an 's' char prefix,
2161 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002162 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002163
2164 // Check that we've found one of the special components, or that the component
2165 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002166 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002167 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2168 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002169 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002170 do
2171 compStr++;
2172 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002173 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002174 do
2175 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002176 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002177 }
Nate Begeman353417a2009-01-18 01:47:54 +00002178
Mike Stumpeed9cac2009-02-19 03:04:26 +00002179 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002180 // We didn't get to the end of the string. This means the component names
2181 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002182 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2183 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002184 return QualType();
2185 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002186
Nate Begeman353417a2009-01-18 01:47:54 +00002187 // Ensure no component accessor exceeds the width of the vector type it
2188 // operates on.
2189 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002190 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002191
2192 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002193 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002194
2195 while (*compStr) {
2196 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2197 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2198 << baseType << SourceRange(CompLoc);
2199 return QualType();
2200 }
2201 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002202 }
Nate Begeman8a997642008-05-09 06:41:27 +00002203
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002204 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002205 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002206 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002207 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002208 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002209 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002210 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002211 if (HexSwizzle)
2212 CompSize--;
2213
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002214 if (CompSize == 1)
2215 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002216
Nate Begeman213541a2008-04-18 23:10:10 +00002217 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002218 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002219 // diagostics look bad. We want extended vector types to appear built-in.
2220 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2221 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2222 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002223 }
2224 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002225}
2226
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002227static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002228 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002229 const Selector &Sel,
2230 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Anders Carlsson8f28f992009-08-26 18:25:21 +00002232 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002233 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002234 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002235 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002237 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2238 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002239 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002240 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002241 return D;
2242 }
2243 return 0;
2244}
2245
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002246static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002247 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002248 const Selector &Sel,
2249 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002250 // Check protocols on qualified interfaces.
2251 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002252 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002253 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002254 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002255 GDecl = PD;
2256 break;
2257 }
2258 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002259 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002260 GDecl = OMD;
2261 break;
2262 }
2263 }
2264 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002265 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002266 E = QIdTy->qual_end(); I != E; ++I) {
2267 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002268 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002269 if (GDecl)
2270 return GDecl;
2271 }
2272 }
2273 return GDecl;
2274}
Chris Lattner76a642f2009-02-15 22:43:40 +00002275
John McCall129e2df2009-11-30 22:42:35 +00002276Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002277Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2278 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002279 const CXXScopeSpec &SS,
2280 NamedDecl *FirstQualifierInScope,
2281 DeclarationName Name, SourceLocation NameLoc,
2282 const TemplateArgumentListInfo *TemplateArgs) {
2283 Expr *BaseExpr = Base.takeAs<Expr>();
2284
2285 // Even in dependent contexts, try to diagnose base expressions with
2286 // obviously wrong types, e.g.:
2287 //
2288 // T* t;
2289 // t.f;
2290 //
2291 // In Obj-C++, however, the above expression is valid, since it could be
2292 // accessing the 'f' property if T is an Obj-C interface. The extra check
2293 // allows this, while still reporting an error if T is a struct pointer.
2294 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002295 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002296 if (PT && (!getLangOptions().ObjC1 ||
2297 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002298 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002299 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002300 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002301 return ExprError();
2302 }
2303 }
2304
Douglas Gregor48026d22010-01-11 18:40:55 +00002305 assert(BaseType->isDependentType() || Name.isDependentName());
John McCall129e2df2009-11-30 22:42:35 +00002306
2307 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2308 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002309 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002310 IsArrow, OpLoc,
2311 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2312 SS.getRange(),
2313 FirstQualifierInScope,
2314 Name, NameLoc,
2315 TemplateArgs));
2316}
2317
2318/// We know that the given qualified member reference points only to
2319/// declarations which do not belong to the static type of the base
2320/// expression. Diagnose the problem.
2321static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2322 Expr *BaseExpr,
2323 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002324 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002325 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002326 // If this is an implicit member access, use a different set of
2327 // diagnostics.
2328 if (!BaseExpr)
2329 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002330
2331 // FIXME: this is an exceedingly lame diagnostic for some of the more
2332 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002333 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002334 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002335 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002336}
2337
2338// Check whether the declarations we found through a nested-name
2339// specifier in a member expression are actually members of the base
2340// type. The restriction here is:
2341//
2342// C++ [expr.ref]p2:
2343// ... In these cases, the id-expression shall name a
2344// member of the class or of one of its base classes.
2345//
2346// So it's perfectly legitimate for the nested-name specifier to name
2347// an unrelated class, and for us to find an overload set including
2348// decls from classes which are not superclasses, as long as the decl
2349// we actually pick through overload resolution is from a superclass.
2350bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2351 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002352 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002353 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002354 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2355 if (!BaseRT) {
2356 // We can't check this yet because the base type is still
2357 // dependent.
2358 assert(BaseType->isDependentType());
2359 return false;
2360 }
2361 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002362
2363 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002364 // If this is an implicit member reference and we find a
2365 // non-instance member, it's not an error.
2366 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2367 return false;
John McCall129e2df2009-11-30 22:42:35 +00002368
John McCallaa81e162009-12-01 22:10:20 +00002369 // Note that we use the DC of the decl, not the underlying decl.
2370 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2371 while (RecordD->isAnonymousStructOrUnion())
2372 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2373
2374 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2375 MemberRecord.insert(RecordD->getCanonicalDecl());
2376
2377 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2378 return false;
2379 }
2380
John McCall2f841ba2009-12-02 03:53:29 +00002381 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002382 return true;
2383}
2384
2385static bool
2386LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2387 SourceRange BaseRange, const RecordType *RTy,
2388 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2389 RecordDecl *RDecl = RTy->getDecl();
2390 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2391 PDiag(diag::err_typecheck_incomplete_tag)
2392 << BaseRange))
2393 return true;
2394
2395 DeclContext *DC = RDecl;
2396 if (SS.isSet()) {
2397 // If the member name was a qualified-id, look into the
2398 // nested-name-specifier.
2399 DC = SemaRef.computeDeclContext(SS, false);
2400
John McCall2f841ba2009-12-02 03:53:29 +00002401 if (SemaRef.RequireCompleteDeclContext(SS)) {
2402 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2403 << SS.getRange() << DC;
2404 return true;
2405 }
2406
John McCallaa81e162009-12-01 22:10:20 +00002407 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2408
2409 if (!isa<TypeDecl>(DC)) {
2410 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2411 << DC << SS.getRange();
2412 return true;
John McCall129e2df2009-11-30 22:42:35 +00002413 }
2414 }
2415
John McCallaa81e162009-12-01 22:10:20 +00002416 // The record definition is complete, now look up the member.
2417 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002418
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002419 if (!R.empty())
2420 return false;
2421
2422 // We didn't find anything with the given name, so try to correct
2423 // for typos.
2424 DeclarationName Name = R.getLookupName();
2425 if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
2426 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2427 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2428 << Name << DC << R.getLookupName() << SS.getRange()
2429 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2430 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002431 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2432 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2433 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002434 return false;
2435 } else {
2436 R.clear();
2437 }
2438
John McCall129e2df2009-11-30 22:42:35 +00002439 return false;
2440}
2441
2442Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002443Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002444 SourceLocation OpLoc, bool IsArrow,
2445 const CXXScopeSpec &SS,
2446 NamedDecl *FirstQualifierInScope,
2447 DeclarationName Name, SourceLocation NameLoc,
2448 const TemplateArgumentListInfo *TemplateArgs) {
2449 Expr *Base = BaseArg.takeAs<Expr>();
2450
John McCall2f841ba2009-12-02 03:53:29 +00002451 if (BaseType->isDependentType() ||
2452 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002453 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002454 IsArrow, OpLoc,
2455 SS, FirstQualifierInScope,
2456 Name, NameLoc,
2457 TemplateArgs);
2458
2459 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002460
John McCallaa81e162009-12-01 22:10:20 +00002461 // Implicit member accesses.
2462 if (!Base) {
2463 QualType RecordTy = BaseType;
2464 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2465 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2466 RecordTy->getAs<RecordType>(),
2467 OpLoc, SS))
2468 return ExprError();
2469
2470 // Explicit member accesses.
2471 } else {
2472 OwningExprResult Result =
2473 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2474 SS, FirstQualifierInScope,
2475 /*ObjCImpDecl*/ DeclPtrTy());
2476
2477 if (Result.isInvalid()) {
2478 Owned(Base);
2479 return ExprError();
2480 }
2481
2482 if (Result.get())
2483 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002484 }
2485
John McCallaa81e162009-12-01 22:10:20 +00002486 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2487 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002488}
2489
2490Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002491Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2492 SourceLocation OpLoc, bool IsArrow,
2493 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002494 LookupResult &R,
2495 const TemplateArgumentListInfo *TemplateArgs) {
2496 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002497 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002498 if (IsArrow) {
2499 assert(BaseType->isPointerType());
2500 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2501 }
2502
2503 NestedNameSpecifier *Qualifier =
2504 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2505 DeclarationName MemberName = R.getLookupName();
2506 SourceLocation MemberLoc = R.getNameLoc();
2507
2508 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002509 return ExprError();
2510
John McCall129e2df2009-11-30 22:42:35 +00002511 if (R.empty()) {
2512 // Rederive where we looked up.
2513 DeclContext *DC = (SS.isSet()
2514 ? computeDeclContext(SS, false)
2515 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002516
John McCall129e2df2009-11-30 22:42:35 +00002517 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002518 << MemberName << DC
2519 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002520 return ExprError();
2521 }
2522
John McCall2f841ba2009-12-02 03:53:29 +00002523 // Diagnose qualified lookups that find only declarations from a
2524 // non-base type. Note that it's okay for lookup to find
2525 // declarations from a non-base type as long as those aren't the
2526 // ones picked by overload resolution.
2527 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002528 return ExprError();
2529
2530 // Construct an unresolved result if we in fact got an unresolved
2531 // result.
2532 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002533 bool Dependent =
John McCall410a3f32009-12-19 02:05:44 +00002534 BaseExprType->isDependentType() ||
John McCallaa81e162009-12-01 22:10:20 +00002535 R.isUnresolvableResult() ||
2536 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002537
2538 UnresolvedMemberExpr *MemExpr
2539 = UnresolvedMemberExpr::Create(Context, Dependent,
2540 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002541 BaseExpr, BaseExprType,
2542 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002543 Qualifier, SS.getRange(),
2544 MemberName, MemberLoc,
2545 TemplateArgs);
2546 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2547 MemExpr->addDecl(*I);
2548
2549 return Owned(MemExpr);
2550 }
2551
2552 assert(R.isSingleResult());
2553 NamedDecl *MemberDecl = R.getFoundDecl();
2554
2555 // FIXME: diagnose the presence of template arguments now.
2556
2557 // If the decl being referenced had an error, return an error for this
2558 // sub-expr without emitting another error, in order to avoid cascading
2559 // error cases.
2560 if (MemberDecl->isInvalidDecl())
2561 return ExprError();
2562
John McCallaa81e162009-12-01 22:10:20 +00002563 // Handle the implicit-member-access case.
2564 if (!BaseExpr) {
2565 // If this is not an instance member, convert to a non-member access.
2566 if (!IsInstanceMember(MemberDecl))
2567 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2568
Douglas Gregor828a1972010-01-07 23:12:05 +00002569 SourceLocation Loc = R.getNameLoc();
2570 if (SS.getRange().isValid())
2571 Loc = SS.getRange().getBegin();
2572 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00002573 }
2574
John McCall129e2df2009-11-30 22:42:35 +00002575 bool ShouldCheckUse = true;
2576 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2577 // Don't diagnose the use of a virtual member function unless it's
2578 // explicitly qualified.
2579 if (MD->isVirtual() && !SS.isSet())
2580 ShouldCheckUse = false;
2581 }
2582
2583 // Check the use of this member.
2584 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2585 Owned(BaseExpr);
2586 return ExprError();
2587 }
2588
2589 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2590 // We may have found a field within an anonymous union or struct
2591 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002592 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2593 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002594 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2595 BaseExpr, OpLoc);
2596
2597 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2598 QualType MemberType = FD->getType();
2599 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2600 MemberType = Ref->getPointeeType();
2601 else {
2602 Qualifiers BaseQuals = BaseType.getQualifiers();
2603 BaseQuals.removeObjCGCAttr();
2604 if (FD->isMutable()) BaseQuals.removeConst();
2605
2606 Qualifiers MemberQuals
2607 = Context.getCanonicalType(MemberType).getQualifiers();
2608
2609 Qualifiers Combined = BaseQuals + MemberQuals;
2610 if (Combined != MemberQuals)
2611 MemberType = Context.getQualifiedType(MemberType, Combined);
2612 }
2613
2614 MarkDeclarationReferenced(MemberLoc, FD);
2615 if (PerformObjectMemberConversion(BaseExpr, FD))
2616 return ExprError();
2617 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2618 FD, MemberLoc, MemberType));
2619 }
2620
2621 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2622 MarkDeclarationReferenced(MemberLoc, Var);
2623 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2624 Var, MemberLoc,
2625 Var->getType().getNonReferenceType()));
2626 }
2627
2628 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2629 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2630 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2631 MemberFn, MemberLoc,
2632 MemberFn->getType()));
2633 }
2634
2635 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2636 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2637 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2638 Enum, MemberLoc, Enum->getType()));
2639 }
2640
2641 Owned(BaseExpr);
2642
2643 if (isa<TypeDecl>(MemberDecl))
2644 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2645 << MemberName << int(IsArrow));
2646
2647 // We found a declaration kind that we didn't expect. This is a
2648 // generic error message that tells the user that she can't refer
2649 // to this member with '.' or '->'.
2650 return ExprError(Diag(MemberLoc,
2651 diag::err_typecheck_member_reference_unknown)
2652 << MemberName << int(IsArrow));
2653}
2654
2655/// Look up the given member of the given non-type-dependent
2656/// expression. This can return in one of two ways:
2657/// * If it returns a sentinel null-but-valid result, the caller will
2658/// assume that lookup was performed and the results written into
2659/// the provided structure. It will take over from there.
2660/// * Otherwise, the returned expression will be produced in place of
2661/// an ordinary member expression.
2662///
2663/// The ObjCImpDecl bit is a gross hack that will need to be properly
2664/// fixed for ObjC++.
2665Sema::OwningExprResult
2666Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002667 bool &IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002668 const CXXScopeSpec &SS,
2669 NamedDecl *FirstQualifierInScope,
2670 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002671 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002672
Steve Naroff3cc4af82007-12-16 21:42:28 +00002673 // Perform default conversions.
2674 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002675
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002676 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002677 assert(!BaseType->isDependentType());
2678
2679 DeclarationName MemberName = R.getLookupName();
2680 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002681
2682 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002683 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002684 // function. Suggest the addition of those parentheses, build the
2685 // call, and continue on.
2686 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2687 if (const FunctionProtoType *Fun
2688 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2689 QualType ResultTy = Fun->getResultType();
2690 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002691 ((!IsArrow && ResultTy->isRecordType()) ||
2692 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002693 ResultTy->getAs<PointerType>()->getPointeeType()
2694 ->isRecordType()))) {
2695 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2696 Diag(Loc, diag::err_member_reference_needs_call)
2697 << QualType(Fun, 0)
2698 << CodeModificationHint::CreateInsertion(Loc, "()");
2699
2700 OwningExprResult NewBase
John McCall129e2df2009-11-30 22:42:35 +00002701 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002702 MultiExprArg(*this, 0, 0), 0, Loc);
2703 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002704 return ExprError();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002705
2706 BaseExpr = NewBase.takeAs<Expr>();
2707 DefaultFunctionArrayConversion(BaseExpr);
2708 BaseType = BaseExpr->getType();
2709 }
2710 }
2711 }
2712
David Chisnall0f436562009-08-17 16:35:33 +00002713 // If this is an Objective-C pseudo-builtin and a definition is provided then
2714 // use that.
2715 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002716 if (IsArrow) {
2717 // Handle the following exceptional case PObj->isa.
2718 if (const ObjCObjectPointerType *OPT =
2719 BaseType->getAs<ObjCObjectPointerType>()) {
2720 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2721 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002722 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2723 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002724 }
2725 }
David Chisnall0f436562009-08-17 16:35:33 +00002726 // We have an 'id' type. Rather than fall through, we check if this
2727 // is a reference to 'isa'.
2728 if (BaseType != Context.ObjCIdRedefinitionType) {
2729 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002730 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002731 }
David Chisnall0f436562009-08-17 16:35:33 +00002732 }
John McCall129e2df2009-11-30 22:42:35 +00002733
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002734 // If this is an Objective-C pseudo-builtin and a definition is provided then
2735 // use that.
2736 if (Context.isObjCSelType(BaseType)) {
2737 // We have an 'SEL' type. Rather than fall through, we check if this
2738 // is a reference to 'sel_id'.
2739 if (BaseType != Context.ObjCSelRedefinitionType) {
2740 BaseType = Context.ObjCSelRedefinitionType;
2741 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2742 }
2743 }
John McCall129e2df2009-11-30 22:42:35 +00002744
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002745 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002746
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002747 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002748 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002749 // Also must look for a getter name which uses property syntax.
2750 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2751 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2752 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2753 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2754 ObjCMethodDecl *Getter;
2755 // FIXME: need to also look locally in the implementation.
2756 if ((Getter = IFace->lookupClassMethod(Sel))) {
2757 // Check the use of this method.
2758 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2759 return ExprError();
2760 }
2761 // If we found a getter then this may be a valid dot-reference, we
2762 // will look for the matching setter, in case it is needed.
2763 Selector SetterSel =
2764 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2765 PP.getSelectorTable(), Member);
2766 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2767 if (!Setter) {
2768 // If this reference is in an @implementation, also check for 'private'
2769 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002770 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002771 }
2772 // Look through local category implementations associated with the class.
2773 if (!Setter)
2774 Setter = IFace->getCategoryClassMethod(SetterSel);
2775
2776 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2777 return ExprError();
2778
2779 if (Getter || Setter) {
2780 QualType PType;
2781
2782 if (Getter)
2783 PType = Getter->getResultType();
2784 else
2785 // Get the expression type from Setter's incoming parameter.
2786 PType = (*(Setter->param_end() -1))->getType();
2787 // FIXME: we must check that the setter has property type.
2788 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2789 PType,
2790 Setter, MemberLoc, BaseExpr));
2791 }
2792 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2793 << MemberName << BaseType);
2794 }
2795 }
2796
2797 if (BaseType->isObjCClassType() &&
2798 BaseType != Context.ObjCClassRedefinitionType) {
2799 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002800 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002801 }
Mike Stump1eb44332009-09-09 15:08:12 +00002802
John McCall129e2df2009-11-30 22:42:35 +00002803 if (IsArrow) {
2804 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002805 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00002806 else if (BaseType->isObjCObjectPointerType())
2807 ;
John McCall812c1542009-12-07 22:46:59 +00002808 else if (BaseType->isRecordType()) {
2809 // Recover from arrow accesses to records, e.g.:
2810 // struct MyRecord foo;
2811 // foo->bar
2812 // This is actually well-formed in C++ if MyRecord has an
2813 // overloaded operator->, but that should have been dealt with
2814 // by now.
2815 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2816 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2817 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2818 IsArrow = false;
2819 } else {
John McCall129e2df2009-11-30 22:42:35 +00002820 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2821 << BaseType << BaseExpr->getSourceRange();
2822 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00002823 }
John McCall812c1542009-12-07 22:46:59 +00002824 } else {
2825 // Recover from dot accesses to pointers, e.g.:
2826 // type *foo;
2827 // foo.bar
2828 // This is actually well-formed in two cases:
2829 // - 'type' is an Objective C type
2830 // - 'bar' is a pseudo-destructor name which happens to refer to
2831 // the appropriate pointer type
2832 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2833 const PointerType *PT = BaseType->getAs<PointerType>();
2834 if (PT && PT->getPointeeType()->isRecordType()) {
2835 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2836 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2837 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2838 BaseType = PT->getPointeeType();
2839 IsArrow = true;
2840 }
2841 }
John McCall129e2df2009-11-30 22:42:35 +00002842 }
John McCall812c1542009-12-07 22:46:59 +00002843
John McCall129e2df2009-11-30 22:42:35 +00002844 // Handle field access to simple records. This also handles access
2845 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00002846 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00002847 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2848 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002849 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00002850 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002851 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002852
Douglas Gregora71d8192009-09-04 17:36:40 +00002853 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2854 // into a record type was handled above, any destructor we see here is a
2855 // pseudo-destructor.
2856 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2857 // C++ [expr.pseudo]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00002858 // The left hand side of the dot operator shall be of scalar type. The
2859 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregora71d8192009-09-04 17:36:40 +00002860 // type.
2861 if (!BaseType->isScalarType())
2862 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2863 << BaseType << BaseExpr->getSourceRange());
Mike Stump1eb44332009-09-09 15:08:12 +00002864
Douglas Gregora71d8192009-09-04 17:36:40 +00002865 // [...] The type designated by the pseudo-destructor-name shall be the
2866 // same as the object type.
2867 if (!MemberName.getCXXNameType()->isDependentType() &&
2868 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2869 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2870 << BaseType << MemberName.getCXXNameType()
2871 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump1eb44332009-09-09 15:08:12 +00002872
2873 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregora71d8192009-09-04 17:36:40 +00002874 // the form
2875 //
Mike Stump1eb44332009-09-09 15:08:12 +00002876 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2877 //
Douglas Gregora71d8192009-09-04 17:36:40 +00002878 // shall designate the same scalar type.
2879 //
2880 // FIXME: DPG can't see any way to trigger this particular clause, so it
2881 // isn't checked here.
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Douglas Gregora71d8192009-09-04 17:36:40 +00002883 // FIXME: We've lost the precise spelling of the type by going through
2884 // DeclarationName. Can we do better?
2885 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002886 IsArrow, OpLoc,
2887 (NestedNameSpecifier *) SS.getScopeRep(),
2888 SS.getRange(),
Douglas Gregora71d8192009-09-04 17:36:40 +00002889 MemberName.getCXXNameType(),
2890 MemberLoc));
2891 }
Mike Stump1eb44332009-09-09 15:08:12 +00002892
Chris Lattnera38e6b12008-07-21 04:59:05 +00002893 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2894 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00002895 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2896 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00002897 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002898 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00002899 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00002900 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002901 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2902
Steve Naroffc70e8d92009-07-16 00:25:06 +00002903 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2904 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00002905 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00002906
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002907 if (!IV) {
2908 // Attempt to correct for typos in ivar names.
2909 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
2910 LookupMemberName);
2911 if (CorrectTypo(Res, 0, 0, IDecl) &&
2912 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
2913 Diag(R.getNameLoc(),
2914 diag::err_typecheck_member_reference_ivar_suggest)
2915 << IDecl->getDeclName() << MemberName << IV->getDeclName()
2916 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2917 IV->getNameAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002918 Diag(IV->getLocation(), diag::note_previous_decl)
2919 << IV->getDeclName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00002920 }
2921 }
2922
Steve Naroffc70e8d92009-07-16 00:25:06 +00002923 if (IV) {
2924 // If the decl being referenced had an error, return an error for this
2925 // sub-expr without emitting another error, in order to avoid cascading
2926 // error cases.
2927 if (IV->isInvalidDecl())
2928 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002929
Steve Naroffc70e8d92009-07-16 00:25:06 +00002930 // Check whether we can reference this field.
2931 if (DiagnoseUseOfDecl(IV, MemberLoc))
2932 return ExprError();
2933 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2934 IV->getAccessControl() != ObjCIvarDecl::Package) {
2935 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2936 if (ObjCMethodDecl *MD = getCurMethodDecl())
2937 ClassOfMethodDecl = MD->getClassInterface();
2938 else if (ObjCImpDecl && getCurFunctionDecl()) {
2939 // Case of a c-function declared inside an objc implementation.
2940 // FIXME: For a c-style function nested inside an objc implementation
2941 // class, there is no implementation context available, so we pass
2942 // down the context as argument to this routine. Ideally, this context
2943 // need be passed down in the AST node and somehow calculated from the
2944 // AST for a function decl.
2945 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00002946 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00002947 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2948 ClassOfMethodDecl = IMPD->getClassInterface();
2949 else if (ObjCCategoryImplDecl* CatImplClass =
2950 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2951 ClassOfMethodDecl = CatImplClass->getClassInterface();
2952 }
Mike Stump1eb44332009-09-09 15:08:12 +00002953
2954 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2955 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00002956 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00002957 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002958 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002959 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2960 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00002961 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00002962 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00002963 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002964
2965 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2966 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00002967 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00002968 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00002969 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00002970 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00002971 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00002972 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00002973 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00002974 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00002975 if (!IsArrow && (BaseType->isObjCIdType() ||
2976 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00002977 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00002978 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00002979
Steve Naroff14108da2009-07-10 23:34:53 +00002980 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00002981 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00002982 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2983 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2984 // Check the use of this declaration
2985 if (DiagnoseUseOfDecl(PD, MemberLoc))
2986 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002987
Steve Naroff14108da2009-07-10 23:34:53 +00002988 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2989 MemberLoc, BaseExpr));
2990 }
2991 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2992 // Check the use of this method.
2993 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2994 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002995
Steve Naroff14108da2009-07-10 23:34:53 +00002996 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00002997 OMD->getResultType(),
2998 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00002999 NULL, 0));
3000 }
3001 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003002
Steve Naroff14108da2009-07-10 23:34:53 +00003003 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003004 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003005 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00003006 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3007 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00003008 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00003009 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00003010 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
3011 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003012 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00003013
Daniel Dunbar2307d312008-09-03 01:05:41 +00003014 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003015 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003016 // Check whether we can reference this property.
3017 if (DiagnoseUseOfDecl(PD, MemberLoc))
3018 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00003019 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003020 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003021 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00003022 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
3023 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00003024 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00003025 MemberLoc, BaseExpr));
3026 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00003027 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003028 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3029 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003030 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003031 // Check whether we can reference this property.
3032 if (DiagnoseUseOfDecl(PD, MemberLoc))
3033 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00003034
Steve Naroff6ece14c2009-01-21 00:14:39 +00003035 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00003036 MemberLoc, BaseExpr));
3037 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00003038 // If that failed, look for an "implicit" property by seeing if the nullary
3039 // selector is implemented.
3040
3041 // FIXME: The logic for looking up nullary and unary selectors should be
3042 // shared with the code in ActOnInstanceMessage.
3043
Anders Carlsson8f28f992009-08-26 18:25:21 +00003044 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003045 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003046
Daniel Dunbar2307d312008-09-03 01:05:41 +00003047 // If this reference is in an @implementation, check for 'private' methods.
3048 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00003049 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00003050
Steve Naroff7692ed62008-10-22 19:16:27 +00003051 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00003052 if (!Getter)
3053 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00003054 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003055 // Check if we can reference this property.
3056 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3057 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00003058 }
3059 // If we found a getter then this may be a valid dot-reference, we
3060 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00003061 Selector SetterSel =
3062 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00003063 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003064 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00003065 if (!Setter) {
3066 // If this reference is in an @implementation, also check for 'private'
3067 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00003068 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00003069 }
3070 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00003071 if (!Setter)
3072 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003073
Steve Naroff1ca66942009-03-11 13:48:17 +00003074 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3075 return ExprError();
3076
3077 if (Getter || Setter) {
3078 QualType PType;
3079
3080 if (Getter)
3081 PType = Getter->getResultType();
Fariborz Jahanian154440e2009-08-18 20:50:23 +00003082 else
3083 // Get the expression type from Setter's incoming parameter.
3084 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1ca66942009-03-11 13:48:17 +00003085 // FIXME: we must check that the setter has property type.
Fariborz Jahanian09105f52009-08-20 17:02:02 +00003086 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00003087 Setter, MemberLoc, BaseExpr));
3088 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003089
3090 // Attempt to correct for typos in property names.
3091 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3092 LookupOrdinaryName);
3093 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
3094 Res.getAsSingle<ObjCPropertyDecl>()) {
3095 Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
3096 << MemberName << BaseType << Res.getLookupName()
3097 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
3098 Res.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003099 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3100 Diag(Property->getLocation(), diag::note_previous_decl)
3101 << Property->getDeclName();
3102
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003103 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
3104 FirstQualifierInScope, ObjCImpDecl);
3105 }
3106
Sebastian Redl0eb23302009-01-19 00:08:26 +00003107 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003108 << MemberName << BaseType);
Fariborz Jahanian232220c2007-11-12 22:29:28 +00003109 }
Mike Stump1eb44332009-09-09 15:08:12 +00003110
Steve Narofff242b1b2009-07-24 17:54:45 +00003111 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00003112 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00003113 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00003114 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00003115 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003116 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00003117
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003118 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003119 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003120 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003121 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3122 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003123 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003124 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003125 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003126 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003127
Douglas Gregor214f31a2009-03-27 06:00:30 +00003128 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3129 << BaseType << BaseExpr->getSourceRange();
3130
Douglas Gregor214f31a2009-03-27 06:00:30 +00003131 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003132}
3133
John McCall129e2df2009-11-30 22:42:35 +00003134static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
3135 SourceLocation NameLoc,
3136 Sema::ExprArg MemExpr) {
3137 Expr *E = (Expr *) MemExpr.get();
3138 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
3139 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor2d1c2142009-11-03 19:44:04 +00003140 << isa<CXXPseudoDestructorExpr>(E)
3141 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3142
John McCall129e2df2009-11-30 22:42:35 +00003143 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
3144 move(MemExpr),
3145 /*LPLoc*/ ExpectedLParenLoc,
3146 Sema::MultiExprArg(SemaRef, 0, 0),
3147 /*CommaLocs*/ 0,
3148 /*RPLoc*/ ExpectedLParenLoc);
3149}
3150
3151/// The main callback when the parser finds something like
3152/// expression . [nested-name-specifier] identifier
3153/// expression -> [nested-name-specifier] identifier
3154/// where 'identifier' encompasses a fairly broad spectrum of
3155/// possibilities, including destructor and operator references.
3156///
3157/// \param OpKind either tok::arrow or tok::period
3158/// \param HasTrailingLParen whether the next token is '(', which
3159/// is used to diagnose mis-uses of special members that can
3160/// only be called
3161/// \param ObjCImpDecl the current ObjC @implementation decl;
3162/// this is an ugly hack around the fact that ObjC @implementations
3163/// aren't properly put in the context chain
3164Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3165 SourceLocation OpLoc,
3166 tok::TokenKind OpKind,
3167 const CXXScopeSpec &SS,
3168 UnqualifiedId &Id,
3169 DeclPtrTy ObjCImpDecl,
3170 bool HasTrailingLParen) {
3171 if (SS.isSet() && SS.isInvalid())
3172 return ExprError();
3173
3174 TemplateArgumentListInfo TemplateArgsBuffer;
3175
3176 // Decompose the name into its component parts.
3177 DeclarationName Name;
3178 SourceLocation NameLoc;
3179 const TemplateArgumentListInfo *TemplateArgs;
3180 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3181 Name, NameLoc, TemplateArgs);
3182
3183 bool IsArrow = (OpKind == tok::arrow);
3184
3185 NamedDecl *FirstQualifierInScope
3186 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3187 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3188
3189 // This is a postfix expression, so get rid of ParenListExprs.
3190 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3191
3192 Expr *Base = BaseArg.takeAs<Expr>();
3193 OwningExprResult Result(*this);
Douglas Gregor48026d22010-01-11 18:40:55 +00003194 if (Base->getType()->isDependentType() || Name.isDependentName()) {
John McCallaa81e162009-12-01 22:10:20 +00003195 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003196 IsArrow, OpLoc,
3197 SS, FirstQualifierInScope,
3198 Name, NameLoc,
3199 TemplateArgs);
3200 } else {
3201 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3202 if (TemplateArgs) {
3203 // Re-use the lookup done for the template name.
3204 DecomposeTemplateName(R, Id);
3205 } else {
3206 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3207 SS, FirstQualifierInScope,
3208 ObjCImpDecl);
3209
3210 if (Result.isInvalid()) {
3211 Owned(Base);
3212 return ExprError();
3213 }
3214
3215 if (Result.get()) {
3216 // The only way a reference to a destructor can be used is to
3217 // immediately call it, which falls into this case. If the
3218 // next token is not a '(', produce a diagnostic and build the
3219 // call now.
3220 if (!HasTrailingLParen &&
3221 Id.getKind() == UnqualifiedId::IK_DestructorName)
3222 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3223
3224 return move(Result);
3225 }
3226 }
3227
John McCallaa81e162009-12-01 22:10:20 +00003228 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3229 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003230 }
3231
3232 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003233}
3234
Anders Carlsson56c5e332009-08-25 03:49:14 +00003235Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3236 FunctionDecl *FD,
3237 ParmVarDecl *Param) {
3238 if (Param->hasUnparsedDefaultArg()) {
3239 Diag (CallLoc,
3240 diag::err_use_of_default_argument_to_function_declared_later) <<
3241 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003242 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003243 diag::note_default_argument_declared_here);
3244 } else {
3245 if (Param->hasUninstantiatedDefaultArg()) {
3246 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3247
3248 // Instantiate the expression.
Douglas Gregord6350ae2009-08-28 20:31:08 +00003249 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003250
Mike Stump1eb44332009-09-09 15:08:12 +00003251 InstantiatingTemplate Inst(*this, CallLoc, Param,
3252 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003253 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003254
John McCallce3ff2b2009-08-25 22:02:44 +00003255 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003256 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003257 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003258
Douglas Gregor65222e82009-12-23 18:19:08 +00003259 // Check the expression as an initializer for the parameter.
3260 InitializedEntity Entity
3261 = InitializedEntity::InitializeParameter(Param);
3262 InitializationKind Kind
3263 = InitializationKind::CreateCopy(Param->getLocation(),
3264 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3265 Expr *ResultE = Result.takeAs<Expr>();
3266
3267 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3268 Result = InitSeq.Perform(*this, Entity, Kind,
3269 MultiExprArg(*this, (void**)&ResultE, 1));
3270 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003271 return ExprError();
Douglas Gregor65222e82009-12-23 18:19:08 +00003272
3273 // Build the default argument expression.
Douglas Gregor036aed12009-12-23 23:03:06 +00003274 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor65222e82009-12-23 18:19:08 +00003275 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003276 }
Mike Stump1eb44332009-09-09 15:08:12 +00003277
Anders Carlsson56c5e332009-08-25 03:49:14 +00003278 // If the default expression creates temporaries, we need to
3279 // push them to the current stack of expression temporaries so they'll
3280 // be properly destroyed.
Douglas Gregor65222e82009-12-23 18:19:08 +00003281 // FIXME: We should really be rebuilding the default argument with new
3282 // bound temporaries; see the comment in PR5810.
Anders Carlsson337cba42009-12-15 19:16:31 +00003283 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3284 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003285 }
3286
3287 // We already type-checked the argument, so we know it works.
Douglas Gregor036aed12009-12-23 23:03:06 +00003288 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003289}
3290
Douglas Gregor88a35142008-12-22 05:46:06 +00003291/// ConvertArgumentsForCall - Converts the arguments specified in
3292/// Args/NumArgs to the parameter types of the function FDecl with
3293/// function prototype Proto. Call is the call expression itself, and
3294/// Fn is the function expression. For a C++ member function, this
3295/// routine does not attempt to convert the object argument. Returns
3296/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003297bool
3298Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003299 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003300 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003301 Expr **Args, unsigned NumArgs,
3302 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003303 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003304 // assignment, to the types of the corresponding parameter, ...
3305 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003306 bool Invalid = false;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003307
Douglas Gregor88a35142008-12-22 05:46:06 +00003308 // If too few arguments are available (and we don't have default
3309 // arguments for the remaining parameters), don't make the call.
3310 if (NumArgs < NumArgsInProto) {
3311 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3312 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3313 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003314 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003315 }
3316
3317 // If too many are passed and not variadic, error on the extras and drop
3318 // them.
3319 if (NumArgs > NumArgsInProto) {
3320 if (!Proto->isVariadic()) {
3321 Diag(Args[NumArgsInProto]->getLocStart(),
3322 diag::err_typecheck_call_too_many_args)
3323 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3324 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3325 Args[NumArgs-1]->getLocEnd());
3326 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003327 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003328 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003329 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003330 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003331 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003332 VariadicCallType CallType =
3333 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3334 if (Fn->getType()->isBlockPointerType())
3335 CallType = VariadicBlock; // Block
3336 else if (isa<MemberExpr>(Fn))
3337 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003338 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003339 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003340 if (Invalid)
3341 return true;
3342 unsigned TotalNumArgs = AllArgs.size();
3343 for (unsigned i = 0; i < TotalNumArgs; ++i)
3344 Call->setArg(i, AllArgs[i]);
3345
3346 return false;
3347}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003348
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003349bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3350 FunctionDecl *FDecl,
3351 const FunctionProtoType *Proto,
3352 unsigned FirstProtoArg,
3353 Expr **Args, unsigned NumArgs,
3354 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003355 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003356 unsigned NumArgsInProto = Proto->getNumArgs();
3357 unsigned NumArgsToCheck = NumArgs;
3358 bool Invalid = false;
3359 if (NumArgs != NumArgsInProto)
3360 // Use default arguments for missing arguments
3361 NumArgsToCheck = NumArgsInProto;
3362 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003363 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003364 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003365 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003366
Douglas Gregor88a35142008-12-22 05:46:06 +00003367 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003368 if (ArgIx < NumArgs) {
3369 Arg = Args[ArgIx++];
3370
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003371 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3372 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003373 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003374 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003375 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003376
Douglas Gregora188ff22009-12-22 16:09:06 +00003377 // Pass the argument
3378 ParmVarDecl *Param = 0;
3379 if (FDecl && i < FDecl->getNumParams())
3380 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003381
Douglas Gregora188ff22009-12-22 16:09:06 +00003382
3383 InitializedEntity Entity =
3384 Param? InitializedEntity::InitializeParameter(Param)
3385 : InitializedEntity::InitializeParameter(ProtoArgType);
3386 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3387 SourceLocation(),
3388 Owned(Arg));
3389 if (ArgE.isInvalid())
3390 return true;
3391
3392 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003393 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003394 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003395
Mike Stump1eb44332009-09-09 15:08:12 +00003396 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003397 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003398 if (ArgExpr.isInvalid())
3399 return true;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003400
Anders Carlsson56c5e332009-08-25 03:49:14 +00003401 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003402 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003403 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003404 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003405
Douglas Gregor88a35142008-12-22 05:46:06 +00003406 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003407 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003408 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003409 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003410 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003411 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003412 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003413 }
3414 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003415 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003416}
3417
Steve Narofff69936d2007-09-16 03:34:24 +00003418/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003419/// This provides the location of the left/right parens and a list of comma
3420/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003421Action::OwningExprResult
3422Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3423 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003424 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003425 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003426
3427 // Since this might be a postfix expression, get rid of ParenListExprs.
3428 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003430 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003431 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003432 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003433
Douglas Gregor88a35142008-12-22 05:46:06 +00003434 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003435 // If this is a pseudo-destructor expression, build the call immediately.
3436 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3437 if (NumArgs > 0) {
3438 // Pseudo-destructor calls should not have any arguments.
3439 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3440 << CodeModificationHint::CreateRemoval(
3441 SourceRange(Args[0]->getLocStart(),
3442 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003443
Douglas Gregora71d8192009-09-04 17:36:40 +00003444 for (unsigned I = 0; I != NumArgs; ++I)
3445 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Douglas Gregora71d8192009-09-04 17:36:40 +00003447 NumArgs = 0;
3448 }
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Douglas Gregora71d8192009-09-04 17:36:40 +00003450 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3451 RParenLoc));
3452 }
Mike Stump1eb44332009-09-09 15:08:12 +00003453
Douglas Gregor17330012009-02-04 15:01:18 +00003454 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003455 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003456 // FIXME: Will need to cache the results of name lookup (including ADL) in
3457 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003458 bool Dependent = false;
3459 if (Fn->isTypeDependent())
3460 Dependent = true;
3461 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3462 Dependent = true;
3463
3464 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003465 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003466 Context.DependentTy, RParenLoc));
3467
3468 // Determine whether this is a call to an object (C++ [over.call.object]).
3469 if (Fn->getType()->isRecordType())
3470 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3471 CommaLocs, RParenLoc));
3472
John McCall129e2df2009-11-30 22:42:35 +00003473 Expr *NakedFn = Fn->IgnoreParens();
3474
3475 // Determine whether this is a call to an unresolved member function.
3476 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3477 // If lookup was unresolved but not dependent (i.e. didn't find
3478 // an unresolved using declaration), it has to be an overloaded
3479 // function set, which means it must contain either multiple
3480 // declarations (all methods or method templates) or a single
3481 // method template.
3482 assert((MemE->getNumDecls() > 1) ||
3483 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003484 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003485
John McCallaa81e162009-12-01 22:10:20 +00003486 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3487 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003488 }
3489
Douglas Gregorfa047642009-02-04 00:32:51 +00003490 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003491 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003492 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003493 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003494 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3495 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003496 }
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003497
3498 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003499 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003500 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3501 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003502 if (const FunctionProtoType *FPT =
3503 dyn_cast<FunctionProtoType>(BO->getType())) {
3504 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003505
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003506 ExprOwningPtr<CXXMemberCallExpr>
3507 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3508 NumArgs, ResultTy,
3509 RParenLoc));
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003510
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003511 if (CheckCallReturnType(FPT->getResultType(),
3512 BO->getRHS()->getSourceRange().getBegin(),
3513 TheCall.get(), 0))
3514 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003515
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003516 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3517 RParenLoc))
3518 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003519
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003520 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3521 }
3522 return ExprError(Diag(Fn->getLocStart(),
3523 diag::err_typecheck_call_not_function)
3524 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003525 }
3526 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003527 }
3528
Douglas Gregorfa047642009-02-04 00:32:51 +00003529 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003530 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003531 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003532
Eli Friedmanefa42f72009-12-26 03:35:45 +00003533 Expr *NakedFn = Fn->IgnoreParens();
John McCall3b4294e2009-12-16 12:17:52 +00003534 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3535 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3536 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3537 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003538 }
Chris Lattner04421082008-04-08 04:40:51 +00003539
John McCall3b4294e2009-12-16 12:17:52 +00003540 NamedDecl *NDecl = 0;
3541 if (isa<DeclRefExpr>(NakedFn))
3542 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3543
John McCallaa81e162009-12-01 22:10:20 +00003544 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3545}
3546
John McCall3b4294e2009-12-16 12:17:52 +00003547/// BuildResolvedCallExpr - Build a call to a resolved expression,
3548/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003549/// unary-convert to an expression of function-pointer or
3550/// block-pointer type.
3551///
3552/// \param NDecl the declaration being called, if available
3553Sema::OwningExprResult
3554Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3555 SourceLocation LParenLoc,
3556 Expr **Args, unsigned NumArgs,
3557 SourceLocation RParenLoc) {
3558 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3559
Chris Lattner04421082008-04-08 04:40:51 +00003560 // Promote the function operand.
3561 UsualUnaryConversions(Fn);
3562
Chris Lattner925e60d2007-12-28 05:29:59 +00003563 // Make the call expr early, before semantic checks. This guarantees cleanup
3564 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003565 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3566 Args, NumArgs,
3567 Context.BoolTy,
3568 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003569
Steve Naroffdd972f22008-09-05 22:11:13 +00003570 const FunctionType *FuncT;
3571 if (!Fn->getType()->isBlockPointerType()) {
3572 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3573 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003574 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003575 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003576 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3577 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003578 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003579 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003580 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003581 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003582 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003583 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003584 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3585 << Fn->getType() << Fn->getSourceRange());
3586
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003587 // Check for a valid return type
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003588 if (CheckCallReturnType(FuncT->getResultType(),
3589 Fn->getSourceRange().getBegin(), TheCall.get(),
3590 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003591 return ExprError();
3592
Chris Lattner925e60d2007-12-28 05:29:59 +00003593 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003594 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003595
Douglas Gregor72564e72009-02-26 23:50:07 +00003596 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003597 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003598 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003599 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003600 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003601 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003602
Douglas Gregor74734d52009-04-02 15:37:10 +00003603 if (FDecl) {
3604 // Check if we have too few/too many template arguments, based
3605 // on our knowledge of the function definition.
3606 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003607 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003608 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003609 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003610 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3611 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3612 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3613 }
3614 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003615 }
3616
Steve Naroffb291ab62007-08-28 23:30:39 +00003617 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003618 for (unsigned i = 0; i != NumArgs; i++) {
3619 Expr *Arg = Args[i];
3620 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003621 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3622 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003623 PDiag(diag::err_call_incomplete_argument)
3624 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003625 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003626 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003627 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003628 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003629
Douglas Gregor88a35142008-12-22 05:46:06 +00003630 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3631 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003632 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3633 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003634
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003635 // Check for sentinels
3636 if (NDecl)
3637 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003638
Chris Lattner59907c42007-08-10 20:18:51 +00003639 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003640 if (FDecl) {
3641 if (CheckFunctionCall(FDecl, TheCall.get()))
3642 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003643
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003644 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003645 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3646 } else if (NDecl) {
3647 if (CheckBlockCall(NDecl, TheCall.get()))
3648 return ExprError();
3649 }
Chris Lattner59907c42007-08-10 20:18:51 +00003650
Anders Carlssonec74c592009-08-16 03:06:32 +00003651 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003652}
3653
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003654Action::OwningExprResult
3655Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3656 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003657 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Douglas Gregor99a2e602009-12-16 01:38:02 +00003658
Douglas Gregord6542d82009-12-22 15:35:07 +00003659 QualType literalType = GetTypeFromParser(Ty);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003660
Steve Naroffaff1edd2007-07-19 21:32:11 +00003661 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003662 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003663 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003664
Eli Friedman6223c222008-05-20 05:22:08 +00003665 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003666 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003667 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3668 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003669 } else if (!literalType->isDependentType() &&
3670 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003671 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003672 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003673 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003674 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003675
Douglas Gregor99a2e602009-12-16 01:38:02 +00003676 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003677 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003678 InitializationKind Kind
3679 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3680 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00003681 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3682 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3683 MultiExprArg(*this, (void**)&literalExpr, 1),
3684 &literalType);
3685 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003686 return ExprError();
Eli Friedman08544622009-12-22 02:35:53 +00003687 InitExpr.release();
3688 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffe9b12192008-01-14 18:19:28 +00003689
Chris Lattner371f2582008-12-04 23:50:19 +00003690 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003691 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003692 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003693 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003694 }
Eli Friedman08544622009-12-22 02:35:53 +00003695
3696 Result.release();
Douglas Gregor99a2e602009-12-16 01:38:02 +00003697
3698 // FIXME: Store the TInfo to preserve type information better.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003699 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003700 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003701}
3702
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003703Action::OwningExprResult
3704Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003705 SourceLocation RBraceLoc) {
3706 unsigned NumInit = initlist.size();
3707 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003708
Steve Naroff08d92e42007-09-15 18:49:24 +00003709 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003710 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003711
Mike Stumpeed9cac2009-02-19 03:04:26 +00003712 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor4c678342009-01-28 21:54:33 +00003713 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003714 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003715 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003716}
3717
Anders Carlsson82debc72009-10-18 18:12:03 +00003718static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3719 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003720 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003721 return CastExpr::CK_NoOp;
3722
3723 if (SrcTy->hasPointerRepresentation()) {
3724 if (DestTy->hasPointerRepresentation())
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003725 return DestTy->isObjCObjectPointerType() ?
3726 CastExpr::CK_AnyPointerToObjCPointerCast :
3727 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003728 if (DestTy->isIntegerType())
3729 return CastExpr::CK_PointerToIntegral;
3730 }
3731
3732 if (SrcTy->isIntegerType()) {
3733 if (DestTy->isIntegerType())
3734 return CastExpr::CK_IntegralCast;
3735 if (DestTy->hasPointerRepresentation())
3736 return CastExpr::CK_IntegralToPointer;
3737 if (DestTy->isRealFloatingType())
3738 return CastExpr::CK_IntegralToFloating;
3739 }
3740
3741 if (SrcTy->isRealFloatingType()) {
3742 if (DestTy->isRealFloatingType())
3743 return CastExpr::CK_FloatingCast;
3744 if (DestTy->isIntegerType())
3745 return CastExpr::CK_FloatingToIntegral;
3746 }
3747
3748 // FIXME: Assert here.
3749 // assert(false && "Unhandled cast combination!");
3750 return CastExpr::CK_Unknown;
3751}
3752
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003753/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003754bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003755 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003756 CXXMethodDecl *& ConversionDecl,
3757 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003758 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003759 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3760 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003761
Eli Friedman199ea952009-08-15 19:02:19 +00003762 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003763
3764 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3765 // type needs to be scalar.
3766 if (castType->isVoidType()) {
3767 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003768 Kind = CastExpr::CK_ToVoid;
3769 return false;
3770 }
3771
3772 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003773 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003774 (castType->isStructureType() || castType->isUnionType())) {
3775 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003776 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003777 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3778 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003779 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003780 return false;
3781 }
3782
3783 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003784 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003785 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003786 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003787 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003788 Field != FieldEnd; ++Field) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003789 if (Context.hasSameUnqualifiedType(Field->getType(),
3790 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003791 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3792 << castExpr->getSourceRange();
3793 break;
3794 }
3795 }
3796 if (Field == FieldEnd)
3797 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3798 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003799 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003800 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003801 }
Anders Carlssonc3516322009-10-16 02:48:28 +00003802
3803 // Reject any other conversions to non-scalar types.
3804 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3805 << castType << castExpr->getSourceRange();
3806 }
3807
3808 if (!castExpr->getType()->isScalarType() &&
3809 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003810 return Diag(castExpr->getLocStart(),
3811 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003812 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003813 }
3814
Anders Carlsson16a89042009-10-16 05:23:41 +00003815 if (castType->isExtVectorType())
3816 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3817
Anders Carlssonc3516322009-10-16 02:48:28 +00003818 if (castType->isVectorType())
3819 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3820 if (castExpr->getType()->isVectorType())
3821 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3822
3823 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003824 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlssonc3516322009-10-16 02:48:28 +00003825
Anders Carlsson16a89042009-10-16 05:23:41 +00003826 if (isa<ObjCSelectorExpr>(castExpr))
3827 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3828
Anders Carlssonc3516322009-10-16 02:48:28 +00003829 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003830 QualType castExprType = castExpr->getType();
3831 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3832 return Diag(castExpr->getLocStart(),
3833 diag::err_cast_pointer_from_non_pointer_int)
3834 << castExprType << castExpr->getSourceRange();
3835 } else if (!castExpr->getType()->isArithmeticType()) {
3836 if (!castType->isIntegralType() && castType->isArithmeticType())
3837 return Diag(castExpr->getLocStart(),
3838 diag::err_cast_pointer_to_non_pointer_int)
3839 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003840 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003841
3842 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003843 return false;
3844}
3845
Anders Carlssonc3516322009-10-16 02:48:28 +00003846bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3847 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003848 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003849
Anders Carlssona64db8f2007-11-27 05:51:55 +00003850 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003851 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003852 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00003853 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00003854 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003855 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00003856 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003857 } else
3858 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003859 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00003860 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00003861
Anders Carlssonc3516322009-10-16 02:48:28 +00003862 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00003863 return false;
3864}
3865
Anders Carlsson16a89042009-10-16 05:23:41 +00003866bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3867 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00003868 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson16a89042009-10-16 05:23:41 +00003869
3870 QualType SrcTy = CastExpr->getType();
3871
Nate Begeman9b10da62009-06-27 22:05:55 +00003872 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3873 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00003874 if (SrcTy->isVectorType()) {
3875 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3876 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3877 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00003878 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00003879 return false;
3880 }
3881
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003882 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00003883 // conversion will take place first from scalar to elt type, and then
3884 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00003885 if (SrcTy->isPointerType())
3886 return Diag(R.getBegin(),
3887 diag::err_invalid_conversion_between_vector_and_scalar)
3888 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00003889
3890 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3891 ImpCastExprToType(CastExpr, DestElemTy,
3892 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson16a89042009-10-16 05:23:41 +00003893
3894 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00003895 return false;
3896}
3897
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003898Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00003899Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003900 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssoncdb61972009-08-07 22:21:05 +00003901 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump1eb44332009-09-09 15:08:12 +00003902
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003903 assert((Ty != 0) && (Op.get() != 0) &&
3904 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00003905
Nate Begeman2ef13e52009-08-10 23:49:36 +00003906 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00003907 //FIXME: Preserve type source info.
3908 QualType castType = GetTypeFromParser(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003909
Nate Begeman2ef13e52009-08-10 23:49:36 +00003910 // If the Expr being casted is a ParenListExpr, handle it specially.
3911 if (isa<ParenListExpr>(castExpr))
3912 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlsson0aebc812009-09-09 21:33:21 +00003913 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003914 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003915 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003916 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00003917
3918 if (Method) {
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003919 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlsson0aebc812009-09-09 21:33:21 +00003920 Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003921
Anders Carlsson0aebc812009-09-09 21:33:21 +00003922 if (CastArg.isInvalid())
3923 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00003924
Anders Carlsson0aebc812009-09-09 21:33:21 +00003925 castExpr = CastArg.takeAs<Expr>();
3926 } else {
3927 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00003928 }
Mike Stump1eb44332009-09-09 15:08:12 +00003929
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003930 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump1eb44332009-09-09 15:08:12 +00003931 Kind, castExpr, castType,
Anders Carlssoncdb61972009-08-07 22:21:05 +00003932 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00003933}
3934
Nate Begeman2ef13e52009-08-10 23:49:36 +00003935/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3936/// of comma binary operators.
3937Action::OwningExprResult
3938Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3939 Expr *expr = EA.takeAs<Expr>();
3940 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3941 if (!E)
3942 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00003943
Nate Begeman2ef13e52009-08-10 23:49:36 +00003944 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00003945
Nate Begeman2ef13e52009-08-10 23:49:36 +00003946 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3947 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3948 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Nate Begeman2ef13e52009-08-10 23:49:36 +00003950 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3951}
3952
3953Action::OwningExprResult
3954Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3955 SourceLocation RParenLoc, ExprArg Op,
3956 QualType Ty) {
3957 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump1eb44332009-09-09 15:08:12 +00003958
3959 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00003960 // then handle it as such.
3961 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3962 if (PE->getNumExprs() == 0) {
3963 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3964 return ExprError();
3965 }
3966
3967 llvm::SmallVector<Expr *, 8> initExprs;
3968 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3969 initExprs.push_back(PE->getExpr(i));
3970
3971 // FIXME: This means that pretty-printing the final AST will produce curly
3972 // braces instead of the original commas.
3973 Op.release();
Mike Stump1eb44332009-09-09 15:08:12 +00003974 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00003975 initExprs.size(), RParenLoc);
3976 E->setType(Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00003977 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003978 Owned(E));
3979 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003980 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00003981 // sequence of BinOp comma operators.
3982 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3983 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3984 }
3985}
3986
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003987Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00003988 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003989 MultiExprArg Val,
3990 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00003991 unsigned nexprs = Val.size();
3992 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00003993 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3994 Expr *expr;
3995 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3996 expr = new (Context) ParenExpr(L, R, exprs[0]);
3997 else
3998 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00003999 return Owned(expr);
4000}
4001
Sebastian Redl28507842009-02-26 14:39:58 +00004002/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4003/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004004/// C99 6.5.15
4005QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4006 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004007 // C++ is sufficiently different to merit its own checker.
4008 if (getLangOptions().CPlusPlus)
4009 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4010
John McCallb13c87f2009-11-05 09:23:39 +00004011 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
4012
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004013 UsualUnaryConversions(Cond);
4014 UsualUnaryConversions(LHS);
4015 UsualUnaryConversions(RHS);
4016 QualType CondTy = Cond->getType();
4017 QualType LHSTy = LHS->getType();
4018 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004019
Reid Spencer5f016e22007-07-11 17:01:13 +00004020 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004021 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4022 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4023 << CondTy;
4024 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004025 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004026
Chris Lattner70d67a92008-01-06 22:42:25 +00004027 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004028 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4029 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004030
Chris Lattner70d67a92008-01-06 22:42:25 +00004031 // If both operands have arithmetic type, do the usual arithmetic conversions
4032 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004033 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4034 UsualArithmeticConversions(LHS, RHS);
4035 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004036 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004037
Chris Lattner70d67a92008-01-06 22:42:25 +00004038 // If both operands are the same structure or union type, the result is that
4039 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004040 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4041 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004042 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004043 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004044 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004045 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004046 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004047 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004048
Chris Lattner70d67a92008-01-06 22:42:25 +00004049 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004050 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004051 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4052 if (!LHSTy->isVoidType())
4053 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4054 << RHS->getSourceRange();
4055 if (!RHSTy->isVoidType())
4056 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4057 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004058 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4059 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004060 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004061 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004062 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4063 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004064 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004065 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004066 // promote the null to a pointer.
4067 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004068 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004069 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004070 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004071 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004072 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004073 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004074 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004075
4076 // All objective-c pointer type analysis is done here.
4077 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4078 QuestionLoc);
4079 if (!compositeType.isNull())
4080 return compositeType;
4081
4082
Steve Naroff7154a772009-07-01 14:36:47 +00004083 // Handle block pointer types.
4084 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4085 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4086 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4087 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004088 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4089 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004090 return destType;
4091 }
4092 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004093 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004094 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004095 }
Steve Naroff7154a772009-07-01 14:36:47 +00004096 // We have 2 block pointer types.
4097 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4098 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004099 return LHSTy;
4100 }
Steve Naroff7154a772009-07-01 14:36:47 +00004101 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004102 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4103 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004104
Steve Naroff7154a772009-07-01 14:36:47 +00004105 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4106 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004107 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004108 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004109 // In this situation, we assume void* type. No especially good
4110 // reason, but this is what gcc does, and we do have to pick
4111 // to get a consistent AST.
4112 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004113 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4114 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004115 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004116 }
Steve Naroff7154a772009-07-01 14:36:47 +00004117 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004118 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4119 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004120 return LHSTy;
4121 }
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004122
Steve Naroff7154a772009-07-01 14:36:47 +00004123 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4124 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4125 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004126 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4127 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004128
4129 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4130 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4131 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004132 QualType destPointee
4133 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004134 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004135 // Add qualifiers if necessary.
4136 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4137 // Promote to void*.
4138 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004139 return destType;
4140 }
4141 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004142 QualType destPointee
4143 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004144 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004145 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004146 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004147 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004148 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004149 return destType;
4150 }
4151
4152 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4153 // Two identical pointer types are always compatible.
4154 return LHSTy;
4155 }
4156 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4157 rhptee.getUnqualifiedType())) {
4158 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4159 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4160 // In this situation, we assume void* type. No especially good
4161 // reason, but this is what gcc does, and we do have to pick
4162 // to get a consistent AST.
4163 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004164 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4165 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004166 return incompatTy;
4167 }
4168 // The pointer types are compatible.
4169 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4170 // differently qualified versions of compatible types, the result type is
4171 // a pointer to an appropriately qualified version of the *composite*
4172 // type.
4173 // FIXME: Need to calculate the composite type.
4174 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004175 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4176 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004177 return LHSTy;
4178 }
Mike Stump1eb44332009-09-09 15:08:12 +00004179
Steve Naroff7154a772009-07-01 14:36:47 +00004180 // GCC compatibility: soften pointer/integer mismatch.
4181 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4182 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4183 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004184 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004185 return RHSTy;
4186 }
4187 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4188 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4189 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004190 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004191 return LHSTy;
4192 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004193
Chris Lattner70d67a92008-01-06 22:42:25 +00004194 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004195 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4196 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004197 return QualType();
4198}
4199
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004200/// FindCompositeObjCPointerType - Helper method to find composite type of
4201/// two objective-c pointer types of the two input expressions.
4202QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4203 SourceLocation QuestionLoc) {
4204 QualType LHSTy = LHS->getType();
4205 QualType RHSTy = RHS->getType();
4206
4207 // Handle things like Class and struct objc_class*. Here we case the result
4208 // to the pseudo-builtin, because that will be implicitly cast back to the
4209 // redefinition type if an attempt is made to access its fields.
4210 if (LHSTy->isObjCClassType() &&
4211 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4212 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4213 return LHSTy;
4214 }
4215 if (RHSTy->isObjCClassType() &&
4216 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4217 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4218 return RHSTy;
4219 }
4220 // And the same for struct objc_object* / id
4221 if (LHSTy->isObjCIdType() &&
4222 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4223 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4224 return LHSTy;
4225 }
4226 if (RHSTy->isObjCIdType() &&
4227 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4228 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4229 return RHSTy;
4230 }
4231 // And the same for struct objc_selector* / SEL
4232 if (Context.isObjCSelType(LHSTy) &&
4233 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4234 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4235 return LHSTy;
4236 }
4237 if (Context.isObjCSelType(RHSTy) &&
4238 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4239 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4240 return RHSTy;
4241 }
4242 // Check constraints for Objective-C object pointers types.
4243 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4244
4245 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4246 // Two identical object pointer types are always compatible.
4247 return LHSTy;
4248 }
4249 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4250 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4251 QualType compositeType = LHSTy;
4252
4253 // If both operands are interfaces and either operand can be
4254 // assigned to the other, use that type as the composite
4255 // type. This allows
4256 // xxx ? (A*) a : (B*) b
4257 // where B is a subclass of A.
4258 //
4259 // Additionally, as for assignment, if either type is 'id'
4260 // allow silent coercion. Finally, if the types are
4261 // incompatible then make sure to use 'id' as the composite
4262 // type so the result is acceptable for sending messages to.
4263
4264 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4265 // It could return the composite type.
4266 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4267 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4268 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4269 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4270 } else if ((LHSTy->isObjCQualifiedIdType() ||
4271 RHSTy->isObjCQualifiedIdType()) &&
4272 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4273 // Need to handle "id<xx>" explicitly.
4274 // GCC allows qualified id and any Objective-C type to devolve to
4275 // id. Currently localizing to here until clear this should be
4276 // part of ObjCQualifiedIdTypesAreCompatible.
4277 compositeType = Context.getObjCIdType();
4278 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4279 compositeType = Context.getObjCIdType();
4280 } else if (!(compositeType =
4281 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4282 ;
4283 else {
4284 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4285 << LHSTy << RHSTy
4286 << LHS->getSourceRange() << RHS->getSourceRange();
4287 QualType incompatTy = Context.getObjCIdType();
4288 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4289 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4290 return incompatTy;
4291 }
4292 // The object pointer types are compatible.
4293 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4294 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4295 return compositeType;
4296 }
4297 // Check Objective-C object pointer types and 'void *'
4298 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4299 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4300 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4301 QualType destPointee
4302 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4303 QualType destType = Context.getPointerType(destPointee);
4304 // Add qualifiers if necessary.
4305 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4306 // Promote to void*.
4307 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4308 return destType;
4309 }
4310 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4311 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4312 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4313 QualType destPointee
4314 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4315 QualType destType = Context.getPointerType(destPointee);
4316 // Add qualifiers if necessary.
4317 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4318 // Promote to void*.
4319 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4320 return destType;
4321 }
4322 return QualType();
4323}
4324
Steve Narofff69936d2007-09-16 03:34:24 +00004325/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004326/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004327Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4328 SourceLocation ColonLoc,
4329 ExprArg Cond, ExprArg LHS,
4330 ExprArg RHS) {
4331 Expr *CondExpr = (Expr *) Cond.get();
4332 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004333
4334 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4335 // was the condition.
4336 bool isLHSNull = LHSExpr == 0;
4337 if (isLHSNull)
4338 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004339
4340 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004341 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004342 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004343 return ExprError();
4344
4345 Cond.release();
4346 LHS.release();
4347 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004348 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004349 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004350 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004351}
4352
Reid Spencer5f016e22007-07-11 17:01:13 +00004353// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004354// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004355// routine is it effectively iqnores the qualifiers on the top level pointee.
4356// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4357// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004358Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004359Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4360 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004361
David Chisnall0f436562009-08-17 16:35:33 +00004362 if ((lhsType->isObjCClassType() &&
4363 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4364 (rhsType->isObjCClassType() &&
4365 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4366 return Compatible;
4367 }
4368
Reid Spencer5f016e22007-07-11 17:01:13 +00004369 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004370 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4371 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004372
Reid Spencer5f016e22007-07-11 17:01:13 +00004373 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004374 lhptee = Context.getCanonicalType(lhptee);
4375 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004376
Chris Lattner5cf216b2008-01-04 18:04:52 +00004377 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004378
4379 // C99 6.5.16.1p1: This following citation is common to constraints
4380 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4381 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004382 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004383 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004384 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004385
Mike Stumpeed9cac2009-02-19 03:04:26 +00004386 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4387 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004388 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004389 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004390 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004391 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004392
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004393 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004394 assert(rhptee->isFunctionType());
4395 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004396 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004397
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004398 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004399 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004400 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004401
4402 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004403 assert(lhptee->isFunctionType());
4404 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004405 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004406 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004407 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004408 lhptee = lhptee.getUnqualifiedType();
4409 rhptee = rhptee.getUnqualifiedType();
4410 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4411 // Check if the pointee types are compatible ignoring the sign.
4412 // We explicitly check for char so that we catch "char" vs
4413 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004414 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004415 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004416 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004417 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004418
4419 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004420 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004421 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004422 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004423
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004424 if (lhptee == rhptee) {
4425 // Types are compatible ignoring the sign. Qualifier incompatibility
4426 // takes priority over sign incompatibility because the sign
4427 // warning can be disabled.
4428 if (ConvTy != Compatible)
4429 return ConvTy;
4430 return IncompatiblePointerSign;
4431 }
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004432
4433 // If we are a multi-level pointer, it's possible that our issue is simply
4434 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4435 // the eventual target type is the same and the pointers have the same
4436 // level of indirection, this must be the issue.
4437 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4438 do {
4439 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4440 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4441
4442 lhptee = Context.getCanonicalType(lhptee);
4443 rhptee = Context.getCanonicalType(rhptee);
4444 } while (lhptee->isPointerType() && rhptee->isPointerType());
4445
Douglas Gregora4923eb2009-11-16 21:35:15 +00004446 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004447 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004448 }
4449
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004450 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004451 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004452 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004453 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004454}
4455
Steve Naroff1c7d0672008-09-04 15:10:53 +00004456/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4457/// block pointer types are compatible or whether a block and normal pointer
4458/// are compatible. It is more restrict than comparing two function pointer
4459// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004460Sema::AssignConvertType
4461Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004462 QualType rhsType) {
4463 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004464
Steve Naroff1c7d0672008-09-04 15:10:53 +00004465 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004466 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4467 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004468
Steve Naroff1c7d0672008-09-04 15:10:53 +00004469 // make sure we operate on the canonical type
4470 lhptee = Context.getCanonicalType(lhptee);
4471 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004472
Steve Naroff1c7d0672008-09-04 15:10:53 +00004473 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004474
Steve Naroff1c7d0672008-09-04 15:10:53 +00004475 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004476 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004477 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004478
Eli Friedman26784c12009-06-08 05:08:54 +00004479 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004480 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004481 return ConvTy;
4482}
4483
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004484/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4485/// for assignment compatibility.
4486Sema::AssignConvertType
4487Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4488 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4489 return Compatible;
4490 QualType lhptee =
4491 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4492 QualType rhptee =
4493 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4494 // make sure we operate on the canonical type
4495 lhptee = Context.getCanonicalType(lhptee);
4496 rhptee = Context.getCanonicalType(rhptee);
4497 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4498 return CompatiblePointerDiscardsQualifiers;
4499
4500 if (Context.typesAreCompatible(lhsType, rhsType))
4501 return Compatible;
4502 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4503 return IncompatibleObjCQualifiedId;
4504 return IncompatiblePointer;
4505}
4506
Mike Stumpeed9cac2009-02-19 03:04:26 +00004507/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4508/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004509/// pointers. Here are some objectionable examples that GCC considers warnings:
4510///
4511/// int a, *pint;
4512/// short *pshort;
4513/// struct foo *pfoo;
4514///
4515/// pint = pshort; // warning: assignment from incompatible pointer type
4516/// a = pint; // warning: assignment makes integer from pointer without a cast
4517/// pint = a; // warning: assignment makes pointer from integer without a cast
4518/// pint = pfoo; // warning: assignment from incompatible pointer type
4519///
4520/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004521/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004522///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004523Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004524Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004525 // Get canonical types. We're not formatting these types, just comparing
4526 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004527 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4528 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004529
4530 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004531 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004532
David Chisnall0f436562009-08-17 16:35:33 +00004533 if ((lhsType->isObjCClassType() &&
4534 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4535 (rhsType->isObjCClassType() &&
4536 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4537 return Compatible;
4538 }
4539
Douglas Gregor9d293df2008-10-28 00:22:11 +00004540 // If the left-hand side is a reference type, then we are in a
4541 // (rare!) case where we've allowed the use of references in C,
4542 // e.g., as a parameter type in a built-in function. In this case,
4543 // just make sure that the type referenced is compatible with the
4544 // right-hand side type. The caller is responsible for adjusting
4545 // lhsType so that the resulting expression does not have reference
4546 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004547 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004548 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004549 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004550 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004551 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004552 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4553 // to the same ExtVector type.
4554 if (lhsType->isExtVectorType()) {
4555 if (rhsType->isExtVectorType())
4556 return lhsType == rhsType ? Compatible : Incompatible;
4557 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4558 return Compatible;
4559 }
Mike Stump1eb44332009-09-09 15:08:12 +00004560
Nate Begemanbe2341d2008-07-14 18:02:46 +00004561 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004562 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004563 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004564 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004565 if (getLangOptions().LaxVectorConversions &&
4566 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004567 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004568 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004569 }
4570 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004571 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004572
Chris Lattnere8b3e962008-01-04 23:32:24 +00004573 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004574 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004575
Chris Lattner78eca282008-04-07 06:49:41 +00004576 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004577 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004578 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004579
Chris Lattner78eca282008-04-07 06:49:41 +00004580 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004581 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004582
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004583 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004584 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004585 if (lhsType->isVoidPointerType()) // an exception to the rule.
4586 return Compatible;
4587 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004588 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004589 if (rhsType->getAs<BlockPointerType>()) {
4590 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004591 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004592
4593 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004594 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004595 return Compatible;
4596 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004597 return Incompatible;
4598 }
4599
4600 if (isa<BlockPointerType>(lhsType)) {
4601 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004602 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004603
Steve Naroffb4406862008-09-29 18:10:17 +00004604 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004605 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004606 return Compatible;
4607
Steve Naroff1c7d0672008-09-04 15:10:53 +00004608 if (rhsType->isBlockPointerType())
4609 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004610
Ted Kremenek6217b802009-07-29 21:53:49 +00004611 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004612 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004613 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004614 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004615 return Incompatible;
4616 }
4617
Steve Naroff14108da2009-07-10 23:34:53 +00004618 if (isa<ObjCObjectPointerType>(lhsType)) {
4619 if (rhsType->isIntegerType())
4620 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004621
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004622 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004623 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004624 if (rhsType->isVoidPointerType()) // an exception to the rule.
4625 return Compatible;
4626 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004627 }
4628 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004629 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004630 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004631 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004632 if (RHSPT->getPointeeType()->isVoidType())
4633 return Compatible;
4634 }
4635 // Treat block pointers as objects.
4636 if (rhsType->isBlockPointerType())
4637 return Compatible;
4638 return Incompatible;
4639 }
Chris Lattner78eca282008-04-07 06:49:41 +00004640 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004641 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004642 if (lhsType == Context.BoolTy)
4643 return Compatible;
4644
4645 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004646 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004647
Mike Stumpeed9cac2009-02-19 03:04:26 +00004648 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004649 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004650
4651 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004652 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004653 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004654 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004655 }
Steve Naroff14108da2009-07-10 23:34:53 +00004656 if (isa<ObjCObjectPointerType>(rhsType)) {
4657 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4658 if (lhsType == Context.BoolTy)
4659 return Compatible;
4660
4661 if (lhsType->isIntegerType())
4662 return PointerToInt;
4663
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004664 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004665 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004666 if (lhsType->isVoidPointerType()) // an exception to the rule.
4667 return Compatible;
4668 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004669 }
4670 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004671 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004672 return Compatible;
4673 return Incompatible;
4674 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004675
Chris Lattnerfc144e22008-01-04 23:18:45 +00004676 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004677 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004678 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004679 }
4680 return Incompatible;
4681}
4682
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004683/// \brief Constructs a transparent union from an expression that is
4684/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004685static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004686 QualType UnionType, FieldDecl *Field) {
4687 // Build an initializer list that designates the appropriate member
4688 // of the transparent union.
4689 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4690 &E, 1,
4691 SourceLocation());
4692 Initializer->setType(UnionType);
4693 Initializer->setInitializedFieldInUnion(Field);
4694
4695 // Build a compound literal constructing a value of the transparent
4696 // union type from this initializer list.
4697 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4698 false);
4699}
4700
4701Sema::AssignConvertType
4702Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4703 QualType FromType = rExpr->getType();
4704
Mike Stump1eb44332009-09-09 15:08:12 +00004705 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004706 // transparent_union GCC extension.
4707 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004708 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004709 return Incompatible;
4710
4711 // The field to initialize within the transparent union.
4712 RecordDecl *UD = UT->getDecl();
4713 FieldDecl *InitField = 0;
4714 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004715 for (RecordDecl::field_iterator it = UD->field_begin(),
4716 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004717 it != itend; ++it) {
4718 if (it->getType()->isPointerType()) {
4719 // If the transparent union contains a pointer type, we allow:
4720 // 1) void pointer
4721 // 2) null pointer constant
4722 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004723 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004724 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004725 InitField = *it;
4726 break;
4727 }
Mike Stump1eb44332009-09-09 15:08:12 +00004728
Douglas Gregorce940492009-09-25 04:25:58 +00004729 if (rExpr->isNullPointerConstant(Context,
4730 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004731 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004732 InitField = *it;
4733 break;
4734 }
4735 }
4736
4737 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4738 == Compatible) {
4739 InitField = *it;
4740 break;
4741 }
4742 }
4743
4744 if (!InitField)
4745 return Incompatible;
4746
4747 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4748 return Compatible;
4749}
4750
Chris Lattner5cf216b2008-01-04 18:04:52 +00004751Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004752Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004753 if (getLangOptions().CPlusPlus) {
4754 if (!lhsType->isRecordType()) {
4755 // C++ 5.17p3: If the left operand is not of class type, the
4756 // expression is implicitly converted (C++ 4) to the
4757 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004758 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004759 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004760 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004761 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004762 }
4763
4764 // FIXME: Currently, we fall through and treat C++ classes like C
4765 // structures.
4766 }
4767
Steve Naroff529a4ad2007-11-27 17:58:44 +00004768 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4769 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004770 if ((lhsType->isPointerType() ||
4771 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004772 lhsType->isBlockPointerType())
Douglas Gregorce940492009-09-25 04:25:58 +00004773 && rExpr->isNullPointerConstant(Context,
4774 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004775 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004776 return Compatible;
4777 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004778
Chris Lattner943140e2007-10-16 02:55:40 +00004779 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004780 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004781 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004782 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004783 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004784 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004785 if (!lhsType->isReferenceType())
4786 DefaultFunctionArrayConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004787
Chris Lattner5cf216b2008-01-04 18:04:52 +00004788 Sema::AssignConvertType result =
4789 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004790
Steve Narofff1120de2007-08-24 22:33:52 +00004791 // C99 6.5.16.1p2: The value of the right operand is converted to the
4792 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004793 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4794 // so that we can use references in built-in functions even in C.
4795 // The getNonReferenceType() call makes sure that the resulting expression
4796 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004797 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004798 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4799 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004800 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004801}
4802
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004803QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004804 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004805 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004806 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004807 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004808}
4809
Chris Lattner7ef655a2010-01-12 21:23:57 +00004810QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004811 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004812 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004813 QualType lhsType =
4814 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4815 QualType rhsType =
4816 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004817
Nate Begemanbe2341d2008-07-14 18:02:46 +00004818 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004819 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004820 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004821
Nate Begemanbe2341d2008-07-14 18:02:46 +00004822 // Handle the case of a vector & extvector type of the same size and element
4823 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004824 if (getLangOptions().LaxVectorConversions) {
4825 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00004826 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4827 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00004828 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004829 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004830 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004831 }
4832 }
4833 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004834
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004835 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4836 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4837 bool swapped = false;
4838 if (rhsType->isExtVectorType()) {
4839 swapped = true;
4840 std::swap(rex, lex);
4841 std::swap(rhsType, lhsType);
4842 }
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Nate Begemandde25982009-06-28 19:12:57 +00004844 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00004845 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004846 QualType EltTy = LV->getElementType();
4847 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4848 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004849 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004850 if (swapped) std::swap(rex, lex);
4851 return lhsType;
4852 }
4853 }
4854 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4855 rhsType->isRealFloatingType()) {
4856 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004857 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004858 if (swapped) std::swap(rex, lex);
4859 return lhsType;
4860 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00004861 }
4862 }
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Nate Begemandde25982009-06-28 19:12:57 +00004864 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004865 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00004866 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004867 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004868 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00004869}
4870
Chris Lattner7ef655a2010-01-12 21:23:57 +00004871QualType Sema::CheckMultiplyDivideOperands(
4872 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00004873 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004874 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004875
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004876 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004877
Chris Lattner7ef655a2010-01-12 21:23:57 +00004878 if (!lex->getType()->isArithmeticType() ||
4879 !rex->getType()->isArithmeticType())
4880 return InvalidOperands(Loc, lex, rex);
4881
4882 // Check for division by zero.
4883 if (isDiv &&
4884 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00004885 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
4886 << rex->getSourceRange());
Chris Lattner7ef655a2010-01-12 21:23:57 +00004887
4888 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004889}
4890
Chris Lattner7ef655a2010-01-12 21:23:57 +00004891QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00004892 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00004893 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4894 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4895 return CheckVectorOperands(Loc, lex, rex);
4896 return InvalidOperands(Loc, lex, rex);
4897 }
Steve Naroff90045e82007-07-13 23:32:42 +00004898
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004899 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004900
Chris Lattner7ef655a2010-01-12 21:23:57 +00004901 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4902 return InvalidOperands(Loc, lex, rex);
4903
4904 // Check for remainder by zero.
4905 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00004906 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
4907 << rex->getSourceRange());
Chris Lattner7ef655a2010-01-12 21:23:57 +00004908
4909 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00004910}
4911
Chris Lattner7ef655a2010-01-12 21:23:57 +00004912QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00004913 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00004914 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4915 QualType compType = CheckVectorOperands(Loc, lex, rex);
4916 if (CompLHSTy) *CompLHSTy = compType;
4917 return compType;
4918 }
Steve Naroff49b45262007-07-13 16:58:59 +00004919
Eli Friedmanab3a8522009-03-28 01:22:36 +00004920 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00004921
Reid Spencer5f016e22007-07-11 17:01:13 +00004922 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00004923 if (lex->getType()->isArithmeticType() &&
4924 rex->getType()->isArithmeticType()) {
4925 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00004926 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00004927 }
Reid Spencer5f016e22007-07-11 17:01:13 +00004928
Eli Friedmand72d16e2008-05-18 18:08:51 +00004929 // Put any potential pointer into PExp
4930 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004931 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00004932 std::swap(PExp, IExp);
4933
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004934 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004935
Eli Friedmand72d16e2008-05-18 18:08:51 +00004936 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00004937 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004938
Chris Lattnerb5f15622009-04-24 23:50:08 +00004939 // Check for arithmetic on pointers to incomplete types.
4940 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004941 if (getLangOptions().CPlusPlus) {
4942 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004943 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00004944 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00004945 }
Douglas Gregore7450f52009-03-24 19:52:54 +00004946
4947 // GNU extension: arithmetic on pointer to void
4948 Diag(Loc, diag::ext_gnu_void_ptr)
4949 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00004950 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00004951 if (getLangOptions().CPlusPlus) {
4952 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4953 << lex->getType() << lex->getSourceRange();
4954 return QualType();
4955 }
4956
4957 // GNU extension: arithmetic on pointer to function
4958 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4959 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00004960 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00004961 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00004962 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00004963 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00004964 PExp->getType()->isObjCObjectPointerType()) &&
4965 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00004966 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4967 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00004968 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00004969 return QualType();
4970 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00004971 // Diagnose bad cases where we step over interface counts.
4972 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4973 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4974 << PointeeTy << PExp->getSourceRange();
4975 return QualType();
4976 }
Mike Stump1eb44332009-09-09 15:08:12 +00004977
Eli Friedmanab3a8522009-03-28 01:22:36 +00004978 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00004979 QualType LHSTy = Context.isPromotableBitField(lex);
4980 if (LHSTy.isNull()) {
4981 LHSTy = lex->getType();
4982 if (LHSTy->isPromotableIntegerType())
4983 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00004984 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00004985 *CompLHSTy = LHSTy;
4986 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00004987 return PExp->getType();
4988 }
4989 }
4990
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004991 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00004992}
4993
Chris Lattnereca7be62008-04-07 05:30:13 +00004994// C99 6.5.6
4995QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00004996 SourceLocation Loc, QualType* CompLHSTy) {
4997 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4998 QualType compType = CheckVectorOperands(Loc, lex, rex);
4999 if (CompLHSTy) *CompLHSTy = compType;
5000 return compType;
5001 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005002
Eli Friedmanab3a8522009-03-28 01:22:36 +00005003 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005004
Chris Lattner6e4ab612007-12-09 21:53:25 +00005005 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005006
Chris Lattner6e4ab612007-12-09 21:53:25 +00005007 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00005008 if (lex->getType()->isArithmeticType()
5009 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005010 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005011 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005012 }
Mike Stump1eb44332009-09-09 15:08:12 +00005013
Chris Lattner6e4ab612007-12-09 21:53:25 +00005014 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005015 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00005016 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005017
Douglas Gregore7450f52009-03-24 19:52:54 +00005018 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00005019
Douglas Gregore7450f52009-03-24 19:52:54 +00005020 bool ComplainAboutVoid = false;
5021 Expr *ComplainAboutFunc = 0;
5022 if (lpointee->isVoidType()) {
5023 if (getLangOptions().CPlusPlus) {
5024 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5025 << lex->getSourceRange() << rex->getSourceRange();
5026 return QualType();
5027 }
5028
5029 // GNU C extension: arithmetic on pointer to void
5030 ComplainAboutVoid = true;
5031 } else if (lpointee->isFunctionType()) {
5032 if (getLangOptions().CPlusPlus) {
5033 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005034 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005035 return QualType();
5036 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005037
5038 // GNU C extension: arithmetic on pointer to function
5039 ComplainAboutFunc = lex;
5040 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005041 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005042 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00005043 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005044 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005045 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005046
Chris Lattnerb5f15622009-04-24 23:50:08 +00005047 // Diagnose bad cases where we step over interface counts.
5048 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5049 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5050 << lpointee << lex->getSourceRange();
5051 return QualType();
5052 }
Mike Stump1eb44332009-09-09 15:08:12 +00005053
Chris Lattner6e4ab612007-12-09 21:53:25 +00005054 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00005055 if (rex->getType()->isIntegerType()) {
5056 if (ComplainAboutVoid)
5057 Diag(Loc, diag::ext_gnu_void_ptr)
5058 << lex->getSourceRange() << rex->getSourceRange();
5059 if (ComplainAboutFunc)
5060 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005061 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005062 << ComplainAboutFunc->getSourceRange();
5063
Eli Friedmanab3a8522009-03-28 01:22:36 +00005064 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005065 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005066 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005067
Chris Lattner6e4ab612007-12-09 21:53:25 +00005068 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005069 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005070 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005071
Douglas Gregore7450f52009-03-24 19:52:54 +00005072 // RHS must be a completely-type object type.
5073 // Handle the GNU void* extension.
5074 if (rpointee->isVoidType()) {
5075 if (getLangOptions().CPlusPlus) {
5076 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5077 << lex->getSourceRange() << rex->getSourceRange();
5078 return QualType();
5079 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005080
Douglas Gregore7450f52009-03-24 19:52:54 +00005081 ComplainAboutVoid = true;
5082 } else if (rpointee->isFunctionType()) {
5083 if (getLangOptions().CPlusPlus) {
5084 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005085 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005086 return QualType();
5087 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005088
5089 // GNU extension: arithmetic on pointer to function
5090 if (!ComplainAboutFunc)
5091 ComplainAboutFunc = rex;
5092 } else if (!rpointee->isDependentType() &&
5093 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005094 PDiag(diag::err_typecheck_sub_ptr_object)
5095 << rex->getSourceRange()
5096 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005097 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005098
Eli Friedman88d936b2009-05-16 13:54:38 +00005099 if (getLangOptions().CPlusPlus) {
5100 // Pointee types must be the same: C++ [expr.add]
5101 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5102 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5103 << lex->getType() << rex->getType()
5104 << lex->getSourceRange() << rex->getSourceRange();
5105 return QualType();
5106 }
5107 } else {
5108 // Pointee types must be compatible C99 6.5.6p3
5109 if (!Context.typesAreCompatible(
5110 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5111 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5112 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5113 << lex->getType() << rex->getType()
5114 << lex->getSourceRange() << rex->getSourceRange();
5115 return QualType();
5116 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005117 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005118
Douglas Gregore7450f52009-03-24 19:52:54 +00005119 if (ComplainAboutVoid)
5120 Diag(Loc, diag::ext_gnu_void_ptr)
5121 << lex->getSourceRange() << rex->getSourceRange();
5122 if (ComplainAboutFunc)
5123 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005124 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005125 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005126
5127 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005128 return Context.getPointerDiffType();
5129 }
5130 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005131
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005132 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005133}
5134
Chris Lattnereca7be62008-04-07 05:30:13 +00005135// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005136QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005137 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005138 // C99 6.5.7p2: Each of the operands shall have integer type.
5139 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005140 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005141
Nate Begeman2207d792009-10-25 02:26:48 +00005142 // Vector shifts promote their scalar inputs to vector type.
5143 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5144 return CheckVectorOperands(Loc, lex, rex);
5145
Chris Lattnerca5eede2007-12-12 05:47:28 +00005146 // Shifts don't perform usual arithmetic conversions, they just do integer
5147 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005148 QualType LHSTy = Context.isPromotableBitField(lex);
5149 if (LHSTy.isNull()) {
5150 LHSTy = lex->getType();
5151 if (LHSTy->isPromotableIntegerType())
5152 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005153 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005154 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005155 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005156
Chris Lattnerca5eede2007-12-12 05:47:28 +00005157 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005158
Ryan Flynnd0439682009-08-07 16:20:20 +00005159 // Sanity-check shift operands
5160 llvm::APSInt Right;
5161 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005162 if (!rex->isValueDependent() &&
5163 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005164 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005165 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5166 else {
5167 llvm::APInt LeftBits(Right.getBitWidth(),
5168 Context.getTypeSize(lex->getType()));
5169 if (Right.uge(LeftBits))
5170 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5171 }
5172 }
5173
Chris Lattnerca5eede2007-12-12 05:47:28 +00005174 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005175 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005176}
5177
Douglas Gregor0c6db942009-05-04 06:07:12 +00005178// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005179QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005180 unsigned OpaqueOpc, bool isRelational) {
5181 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5182
Chris Lattner02dd4b12009-12-05 05:40:13 +00005183 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005184 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005185 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005186
John McCall5dbad3d2009-11-06 08:49:08 +00005187 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5188 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall45aa4552009-11-05 00:40:04 +00005189
Chris Lattnera5937dd2007-08-26 01:18:55 +00005190 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005191 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5192 UsualArithmeticConversions(lex, rex);
5193 else {
5194 UsualUnaryConversions(lex);
5195 UsualUnaryConversions(rex);
5196 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005197 QualType lType = lex->getType();
5198 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005199
Mike Stumpaf199f32009-05-07 18:43:07 +00005200 if (!lType->isFloatingType()
5201 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005202 // For non-floating point types, check for self-comparisons of the form
5203 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5204 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005205 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005206 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005207 Expr *LHSStripped = lex->IgnoreParens();
5208 Expr *RHSStripped = rex->IgnoreParens();
5209 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5210 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005211 if (DRL->getDecl() == DRR->getDecl() &&
5212 !isa<EnumConstantDecl>(DRL->getDecl()))
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005213 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Mike Stump1eb44332009-09-09 15:08:12 +00005214
Chris Lattner55660a72009-03-08 19:39:53 +00005215 if (isa<CastExpr>(LHSStripped))
5216 LHSStripped = LHSStripped->IgnoreParenCasts();
5217 if (isa<CastExpr>(RHSStripped))
5218 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005219
Chris Lattner55660a72009-03-08 19:39:53 +00005220 // Warn about comparisons against a string constant (unless the other
5221 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005222 Expr *literalString = 0;
5223 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005224 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005225 !RHSStripped->isNullPointerConstant(Context,
5226 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005227 literalString = lex;
5228 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005229 } else if ((isa<StringLiteral>(RHSStripped) ||
5230 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregorce940492009-09-25 04:25:58 +00005231 !LHSStripped->isNullPointerConstant(Context,
5232 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005233 literalString = rex;
5234 literalStringStripped = RHSStripped;
5235 }
5236
5237 if (literalString) {
5238 std::string resultComparison;
5239 switch (Opc) {
5240 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5241 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5242 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5243 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5244 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5245 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5246 default: assert(false && "Invalid comparison operator");
5247 }
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005248
5249 DiagRuntimeBehavior(Loc,
5250 PDiag(diag::warn_stringcompare)
5251 << isa<ObjCEncodeExpr>(literalStringStripped)
5252 << literalString->getSourceRange()
5253 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5254 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5255 "strcmp(")
5256 << CodeModificationHint::CreateInsertion(
5257 PP.getLocForEndOfToken(rex->getLocEnd()),
5258 resultComparison));
Douglas Gregora86b8322009-04-06 18:45:53 +00005259 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005260 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005261
Douglas Gregor447b69e2008-11-19 03:25:36 +00005262 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005263 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005264
Chris Lattnera5937dd2007-08-26 01:18:55 +00005265 if (isRelational) {
5266 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005267 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005268 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005269 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005270 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005271 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005272
Chris Lattnera5937dd2007-08-26 01:18:55 +00005273 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005274 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005275 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005276
Douglas Gregorce940492009-09-25 04:25:58 +00005277 bool LHSIsNull = lex->isNullPointerConstant(Context,
5278 Expr::NPC_ValueDependentIsNull);
5279 bool RHSIsNull = rex->isNullPointerConstant(Context,
5280 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005281
Chris Lattnera5937dd2007-08-26 01:18:55 +00005282 // All of the following pointer related warnings are GCC extensions, except
5283 // when handling null pointer constants. One day, we can consider making them
5284 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005285 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005286 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005287 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005288 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005289 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005290
Douglas Gregor0c6db942009-05-04 06:07:12 +00005291 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005292 if (LCanPointeeTy == RCanPointeeTy)
5293 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005294 if (!isRelational &&
5295 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5296 // Valid unless comparison between non-null pointer and function pointer
5297 // This is a gcc extension compatibility comparison.
5298 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5299 && !LHSIsNull && !RHSIsNull) {
5300 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5301 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5302 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5303 return ResultTy;
5304 }
5305 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005306 // C++ [expr.rel]p2:
5307 // [...] Pointer conversions (4.10) and qualification
5308 // conversions (4.4) are performed on pointer operands (or on
5309 // a pointer operand and a null pointer constant) to bring
5310 // them to their composite pointer type. [...]
5311 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005312 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005313 // comparisons of pointers.
Douglas Gregorde866f32009-05-05 04:50:50 +00005314 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005315 if (T.isNull()) {
5316 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5317 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5318 return QualType();
5319 }
5320
Eli Friedman73c39ab2009-10-20 08:27:19 +00005321 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5322 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005323 return ResultTy;
5324 }
Eli Friedman3075e762009-08-23 00:27:47 +00005325 // C99 6.5.9p2 and C99 6.5.8p2
5326 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5327 RCanPointeeTy.getUnqualifiedType())) {
5328 // Valid unless a relational comparison of function pointers
5329 if (isRelational && LCanPointeeTy->isFunctionType()) {
5330 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5331 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5332 }
5333 } else if (!isRelational &&
5334 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5335 // Valid unless comparison between non-null pointer and function pointer
5336 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5337 && !LHSIsNull && !RHSIsNull) {
5338 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5339 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5340 }
5341 } else {
5342 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005343 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005344 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005345 }
Eli Friedman3075e762009-08-23 00:27:47 +00005346 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005347 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005348 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005349 }
Mike Stump1eb44332009-09-09 15:08:12 +00005350
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005351 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005352 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005353 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005354 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005355 (lType->isPointerType() ||
5356 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005357 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005358 return ResultTy;
5359 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005360 if (LHSIsNull &&
5361 (rType->isPointerType() ||
5362 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005363 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005364 return ResultTy;
5365 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005366
5367 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005368 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005369 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5370 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005371 // In addition, pointers to members can be compared, or a pointer to
5372 // member and a null pointer constant. Pointer to member conversions
5373 // (4.11) and qualification conversions (4.4) are performed to bring
5374 // them to a common type. If one operand is a null pointer constant,
5375 // the common type is the type of the other operand. Otherwise, the
5376 // common type is a pointer to member type similar (4.4) to the type
5377 // of one of the operands, with a cv-qualification signature (4.4)
5378 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005379 // types.
5380 QualType T = FindCompositePointerType(lex, rex);
5381 if (T.isNull()) {
5382 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5383 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5384 return QualType();
5385 }
Mike Stump1eb44332009-09-09 15:08:12 +00005386
Eli Friedman73c39ab2009-10-20 08:27:19 +00005387 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5388 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005389 return ResultTy;
5390 }
Mike Stump1eb44332009-09-09 15:08:12 +00005391
Douglas Gregor20b3e992009-08-24 17:42:35 +00005392 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005393 if (lType->isNullPtrType() && rType->isNullPtrType())
5394 return ResultTy;
5395 }
Mike Stump1eb44332009-09-09 15:08:12 +00005396
Steve Naroff1c7d0672008-09-04 15:10:53 +00005397 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005398 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005399 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5400 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005401
Steve Naroff1c7d0672008-09-04 15:10:53 +00005402 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005403 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005404 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005405 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005406 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005407 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005408 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005409 }
Steve Naroff59f53942008-09-28 01:11:11 +00005410 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005411 if (!isRelational
5412 && ((lType->isBlockPointerType() && rType->isPointerType())
5413 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005414 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005415 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005416 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005417 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005418 ->getPointeeType()->isVoidType())))
5419 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5420 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005421 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005422 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005423 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005424 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005425
Steve Naroff14108da2009-07-10 23:34:53 +00005426 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005427 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005428 const PointerType *LPT = lType->getAs<PointerType>();
5429 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005430 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005431 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005432 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005433 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005434
Steve Naroffa8069f12008-11-17 19:49:16 +00005435 if (!LPtrToVoid && !RPtrToVoid &&
5436 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005437 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005438 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005439 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005440 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005441 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005442 }
Steve Naroff14108da2009-07-10 23:34:53 +00005443 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005444 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005445 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5446 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005447 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005448 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005449 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005450 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005451 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005452 unsigned DiagID = 0;
5453 if (RHSIsNull) {
5454 if (isRelational)
5455 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5456 } else if (isRelational)
5457 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5458 else
5459 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005460
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005461 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005462 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005463 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005464 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005465 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005466 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005467 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005468 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005469 unsigned DiagID = 0;
5470 if (LHSIsNull) {
5471 if (isRelational)
5472 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5473 } else if (isRelational)
5474 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5475 else
5476 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005477
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005478 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005479 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005480 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005481 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005482 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005483 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005484 }
Steve Naroff39218df2008-09-04 16:56:14 +00005485 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005486 if (!isRelational && RHSIsNull
5487 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005488 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005489 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005490 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005491 if (!isRelational && LHSIsNull
5492 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005493 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005494 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005495 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005496 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005497}
5498
Nate Begemanbe2341d2008-07-14 18:02:46 +00005499/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005500/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005501/// like a scalar comparison, a vector comparison produces a vector of integer
5502/// types.
5503QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005504 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005505 bool isRelational) {
5506 // Check to make sure we're operating on vectors of the same type and width,
5507 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005508 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005509 if (vType.isNull())
5510 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005511
Nate Begemanbe2341d2008-07-14 18:02:46 +00005512 QualType lType = lex->getType();
5513 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005514
Nate Begemanbe2341d2008-07-14 18:02:46 +00005515 // For non-floating point types, check for self-comparisons of the form
5516 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5517 // often indicate logic errors in the program.
5518 if (!lType->isFloatingType()) {
5519 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5520 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5521 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005522 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Nate Begemanbe2341d2008-07-14 18:02:46 +00005523 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005524
Nate Begemanbe2341d2008-07-14 18:02:46 +00005525 // Check for comparisons of floating point operands using != and ==.
5526 if (!isRelational && lType->isFloatingType()) {
5527 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005528 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005529 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005530
Nate Begemanbe2341d2008-07-14 18:02:46 +00005531 // Return the type for the comparison, which is the same as vector type for
5532 // integer vectors, or an integer type of identical size and number of
5533 // elements for floating point vectors.
5534 if (lType->isIntegerType())
5535 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005536
John McCall183700f2009-09-21 23:43:11 +00005537 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005538 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005539 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005540 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005541 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005542 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5543
Mike Stumpeed9cac2009-02-19 03:04:26 +00005544 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005545 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005546 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5547}
5548
Reid Spencer5f016e22007-07-11 17:01:13 +00005549inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005550 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005551 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005552 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005553
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005554 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005555
Steve Naroffa4332e22007-07-17 00:58:39 +00005556 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005557 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005558 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005559}
5560
5561inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005562 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005563 if (!Context.getLangOptions().CPlusPlus) {
5564 UsualUnaryConversions(lex);
5565 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005566
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005567 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5568 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005569
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005570 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005571 }
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005572
5573 // C++ [expr.log.and]p1
5574 // C++ [expr.log.or]p1
5575 // The operands are both implicitly converted to type bool (clause 4).
5576 StandardConversionSequence LHS;
5577 if (!IsStandardConversion(lex, Context.BoolTy,
5578 /*InOverloadResolution=*/false, LHS))
5579 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005580
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005581 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005582 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005583 return InvalidOperands(Loc, lex, rex);
5584
5585 StandardConversionSequence RHS;
5586 if (!IsStandardConversion(rex, Context.BoolTy,
5587 /*InOverloadResolution=*/false, RHS))
5588 return InvalidOperands(Loc, lex, rex);
5589
5590 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005591 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005592 return InvalidOperands(Loc, lex, rex);
5593
5594 // C++ [expr.log.and]p2
5595 // C++ [expr.log.or]p2
5596 // The result is a bool.
5597 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005598}
5599
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005600/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5601/// is a read-only property; return true if so. A readonly property expression
5602/// depends on various declarations and thus must be treated specially.
5603///
Mike Stump1eb44332009-09-09 15:08:12 +00005604static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005605 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5606 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5607 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5608 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005609 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005610 BaseType->getAsObjCInterfacePointerType())
5611 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5612 if (S.isPropertyReadonly(PDecl, IFace))
5613 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005614 }
5615 }
5616 return false;
5617}
5618
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005619/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5620/// emit an error and return true. If so, return false.
5621static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005622 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005623 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005624 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005625 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5626 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005627 if (IsLV == Expr::MLV_Valid)
5628 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005629
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005630 unsigned Diag = 0;
5631 bool NeedType = false;
5632 switch (IsLV) { // C99 6.5.16p2
5633 default: assert(0 && "Unknown result from isModifiableLvalue!");
5634 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005635 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005636 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5637 NeedType = true;
5638 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005639 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005640 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5641 NeedType = true;
5642 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005643 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005644 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5645 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005646 case Expr::MLV_InvalidExpression:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005647 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5648 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005649 case Expr::MLV_IncompleteType:
5650 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005651 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00005652 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5653 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005654 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005655 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5656 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005657 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005658 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5659 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005660 case Expr::MLV_ReadonlyProperty:
5661 Diag = diag::error_readonly_property_assignment;
5662 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005663 case Expr::MLV_NoSetterProperty:
5664 Diag = diag::error_nosetter_property_assignment;
5665 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005666 case Expr::MLV_SubObjCPropertySetting:
5667 Diag = diag::error_no_subobject_property_setting;
5668 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005669 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005670
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005671 SourceRange Assign;
5672 if (Loc != OrigLoc)
5673 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005674 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005675 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005676 else
Mike Stump1eb44332009-09-09 15:08:12 +00005677 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005678 return true;
5679}
5680
5681
5682
5683// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005684QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5685 SourceLocation Loc,
5686 QualType CompoundType) {
5687 // Verify that LHS is a modifiable lvalue, and emit error if not.
5688 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005689 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005690
5691 QualType LHSType = LHS->getType();
5692 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005693
Chris Lattner5cf216b2008-01-04 18:04:52 +00005694 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005695 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005696 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005697 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005698 // Special case of NSObject attributes on c-style pointer types.
5699 if (ConvTy == IncompatiblePointer &&
5700 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005701 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005702 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005703 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005704 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005705
Chris Lattner2c156472008-08-21 18:04:13 +00005706 // If the RHS is a unary plus or minus, check to see if they = and + are
5707 // right next to each other. If so, the user may have typo'd "x =+ 4"
5708 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005709 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005710 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5711 RHSCheck = ICE->getSubExpr();
5712 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5713 if ((UO->getOpcode() == UnaryOperator::Plus ||
5714 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005715 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005716 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005717 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5718 // And there is a space or other character before the subexpr of the
5719 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005720 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5721 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005722 Diag(Loc, diag::warn_not_compound_assign)
5723 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5724 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005725 }
Chris Lattner2c156472008-08-21 18:04:13 +00005726 }
5727 } else {
5728 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005729 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005730 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005731
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005732 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00005733 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005734 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005735
Reid Spencer5f016e22007-07-11 17:01:13 +00005736 // C99 6.5.16p3: The type of an assignment expression is the type of the
5737 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005738 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005739 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5740 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005741 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005742 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005743 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005744}
5745
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005746// C99 6.5.17
5747QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005748 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005749 DefaultFunctionArrayConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005750
5751 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5752 // incomplete in C++).
5753
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005754 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005755}
5756
Steve Naroff49b45262007-07-13 16:58:59 +00005757/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5758/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005759QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5760 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005761 if (Op->isTypeDependent())
5762 return Context.DependentTy;
5763
Chris Lattner3528d352008-11-21 07:05:48 +00005764 QualType ResType = Op->getType();
5765 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005766
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005767 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5768 // Decrement of bool is not allowed.
5769 if (!isInc) {
5770 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5771 return QualType();
5772 }
5773 // Increment of bool sets it to true, but is deprecated.
5774 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5775 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005776 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005777 } else if (ResType->isAnyPointerType()) {
5778 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005779
Chris Lattner3528d352008-11-21 07:05:48 +00005780 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005781 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005782 if (getLangOptions().CPlusPlus) {
5783 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5784 << Op->getSourceRange();
5785 return QualType();
5786 }
5787
5788 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005789 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005790 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005791 if (getLangOptions().CPlusPlus) {
5792 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5793 << Op->getType() << Op->getSourceRange();
5794 return QualType();
5795 }
5796
5797 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005798 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005799 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005800 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005801 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005802 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005803 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005804 // Diagnose bad cases where we step over interface counts.
5805 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5806 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5807 << PointeeTy << Op->getSourceRange();
5808 return QualType();
5809 }
Eli Friedman5b088a12010-01-03 00:20:48 +00005810 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005811 // C99 does not support ++/-- on complex types, we allow as an extension.
5812 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00005813 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005814 } else {
5815 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00005816 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00005817 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005818 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005819 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00005820 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00005821 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00005822 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00005823 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005824}
5825
Anders Carlsson369dee42008-02-01 07:15:58 +00005826/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00005827/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005828/// where the declaration is needed for type checking. We only need to
5829/// handle cases when the expression references a function designator
5830/// or is an lvalue. Here are some examples:
5831/// - &(x) => x
5832/// - &*****f => f for f a function designator.
5833/// - &s.xx => s
5834/// - &s.zz[1].yy -> s, if zz is an array
5835/// - *(x + 1) -> x, if x is an array
5836/// - &"123"[2] -> 0
5837/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005838static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00005839 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00005840 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005841 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00005842 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005843 // If this is an arrow operator, the address is an offset from
5844 // the base's value, so the object the base refers to is
5845 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005846 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00005847 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00005848 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00005849 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00005850 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00005851 // FIXME: This code shouldn't be necessary! We should catch the implicit
5852 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00005853 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5854 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5855 if (ICE->getSubExpr()->getType()->isArrayType())
5856 return getPrimaryDecl(ICE->getSubExpr());
5857 }
5858 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00005859 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005860 case Stmt::UnaryOperatorClass: {
5861 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005862
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005863 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00005864 case UnaryOperator::Real:
5865 case UnaryOperator::Imag:
5866 case UnaryOperator::Extension:
5867 return getPrimaryDecl(UO->getSubExpr());
5868 default:
5869 return 0;
5870 }
5871 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005872 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00005873 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00005874 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00005875 // If the result of an implicit cast is an l-value, we care about
5876 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00005877 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00005878 default:
5879 return 0;
5880 }
5881}
5882
5883/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00005884/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00005885/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005886/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00005887/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005888/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00005889/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00005890QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00005891 // Make sure to ignore parentheses in subsequent checks
5892 op = op->IgnoreParens();
5893
Douglas Gregor9103bb22008-12-17 22:52:20 +00005894 if (op->isTypeDependent())
5895 return Context.DependentTy;
5896
Steve Naroff08f19672008-01-13 17:10:08 +00005897 if (getLangOptions().C99) {
5898 // Implement C99-only parts of addressof rules.
5899 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5900 if (uOp->getOpcode() == UnaryOperator::Deref)
5901 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5902 // (assuming the deref expression is valid).
5903 return uOp->getSubExpr()->getType();
5904 }
5905 // Technically, there should be a check for array subscript
5906 // expressions here, but the result of one is always an lvalue anyway.
5907 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005908 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00005909 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00005910
Sebastian Redle27d87f2010-01-11 15:56:56 +00005911 MemberExpr *ME = dyn_cast<MemberExpr>(op);
5912 if (lval == Expr::LV_MemberFunction && ME &&
5913 isa<CXXMethodDecl>(ME->getMemberDecl())) {
5914 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
5915 // &f where f is a member of the current object, or &o.f, or &p->f
5916 // All these are not allowed, and we need to catch them before the dcl
5917 // branch of the if, below.
5918 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
5919 << dcl;
5920 // FIXME: Improve this diagnostic and provide a fixit.
5921
5922 // Now recover by acting as if the function had been accessed qualified.
5923 return Context.getMemberPointerType(op->getType(),
5924 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
5925 .getTypePtr());
5926 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00005927 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005928 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00005929 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00005930 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00005931 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5932 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005933 return QualType();
5934 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00005935 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00005936 // The operand cannot be a bit-field
5937 Diag(OpLoc, diag::err_typecheck_address_of)
5938 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00005939 return QualType();
Nate Begemanb104b1f2009-02-15 22:45:20 +00005940 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5941 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman23d58ce2009-04-20 08:23:18 +00005942 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005943 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00005944 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00005945 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00005946 } else if (isa<ObjCPropertyRefExpr>(op)) {
5947 // cannot take address of a property expression.
5948 Diag(OpLoc, diag::err_typecheck_address_of)
5949 << "property expression" << op->getSourceRange();
5950 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00005951 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5952 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00005953 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5954 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00005955 } else if (isa<UnresolvedLookupExpr>(op)) {
5956 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00005957 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00005958 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00005959 // with the register storage-class specifier.
5960 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5961 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005962 Diag(OpLoc, diag::err_typecheck_address_of)
5963 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005964 return QualType();
5965 }
John McCallba135432009-11-21 08:51:07 +00005966 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005967 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005968 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00005969 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00005970 // Could be a pointer to member, though, if there is an explicit
5971 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005972 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00005973 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005974 if (Ctx && Ctx->isRecord()) {
5975 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005976 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005977 diag::err_cannot_form_pointer_to_member_of_reference_type)
5978 << FD->getDeclName() << FD->getType();
5979 return QualType();
5980 }
Mike Stump1eb44332009-09-09 15:08:12 +00005981
Sebastian Redlebc07d52009-02-03 20:19:35 +00005982 return Context.getMemberPointerType(op->getType(),
5983 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00005984 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00005985 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00005986 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00005987 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00005988 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00005989 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5990 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00005991 return Context.getMemberPointerType(op->getType(),
5992 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5993 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00005994 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00005995 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00005996
Eli Friedman441cf102009-05-16 23:27:50 +00005997 if (lval == Expr::LV_IncompleteVoidType) {
5998 // Taking the address of a void variable is technically illegal, but we
5999 // allow it in cases which are otherwise valid.
6000 // Example: "extern void x; void* y = &x;".
6001 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6002 }
6003
Reid Spencer5f016e22007-07-11 17:01:13 +00006004 // If the operand has type "type", the result has type "pointer to type".
6005 return Context.getPointerType(op->getType());
6006}
6007
Chris Lattner22caddc2008-11-23 09:13:29 +00006008QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00006009 if (Op->isTypeDependent())
6010 return Context.DependentTy;
6011
Chris Lattner22caddc2008-11-23 09:13:29 +00006012 UsualUnaryConversions(Op);
6013 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006014
Chris Lattner22caddc2008-11-23 09:13:29 +00006015 // Note that per both C89 and C99, this is always legal, even if ptype is an
6016 // incomplete type or void. It would be possible to warn about dereferencing
6017 // a void pointer, but it's completely well-defined, and such a warning is
6018 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00006019 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00006020 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006021
John McCall183700f2009-09-21 23:43:11 +00006022 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00006023 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00006024
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006025 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00006026 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006027 return QualType();
6028}
6029
6030static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6031 tok::TokenKind Kind) {
6032 BinaryOperator::Opcode Opc;
6033 switch (Kind) {
6034 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00006035 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6036 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006037 case tok::star: Opc = BinaryOperator::Mul; break;
6038 case tok::slash: Opc = BinaryOperator::Div; break;
6039 case tok::percent: Opc = BinaryOperator::Rem; break;
6040 case tok::plus: Opc = BinaryOperator::Add; break;
6041 case tok::minus: Opc = BinaryOperator::Sub; break;
6042 case tok::lessless: Opc = BinaryOperator::Shl; break;
6043 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6044 case tok::lessequal: Opc = BinaryOperator::LE; break;
6045 case tok::less: Opc = BinaryOperator::LT; break;
6046 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6047 case tok::greater: Opc = BinaryOperator::GT; break;
6048 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6049 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6050 case tok::amp: Opc = BinaryOperator::And; break;
6051 case tok::caret: Opc = BinaryOperator::Xor; break;
6052 case tok::pipe: Opc = BinaryOperator::Or; break;
6053 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6054 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6055 case tok::equal: Opc = BinaryOperator::Assign; break;
6056 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6057 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6058 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6059 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6060 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6061 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6062 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6063 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6064 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6065 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6066 case tok::comma: Opc = BinaryOperator::Comma; break;
6067 }
6068 return Opc;
6069}
6070
6071static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6072 tok::TokenKind Kind) {
6073 UnaryOperator::Opcode Opc;
6074 switch (Kind) {
6075 default: assert(0 && "Unknown unary op!");
6076 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6077 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6078 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6079 case tok::star: Opc = UnaryOperator::Deref; break;
6080 case tok::plus: Opc = UnaryOperator::Plus; break;
6081 case tok::minus: Opc = UnaryOperator::Minus; break;
6082 case tok::tilde: Opc = UnaryOperator::Not; break;
6083 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006084 case tok::kw___real: Opc = UnaryOperator::Real; break;
6085 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6086 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6087 }
6088 return Opc;
6089}
6090
Douglas Gregoreaebc752008-11-06 23:29:22 +00006091/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6092/// operator @p Opc at location @c TokLoc. This routine only supports
6093/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006094Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6095 unsigned Op,
6096 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006097 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006098 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006099 // The following two variables are used for compound assignment operators
6100 QualType CompLHSTy; // Type of LHS after promotions for computation
6101 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006102
6103 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006104 case BinaryOperator::Assign:
6105 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6106 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006107 case BinaryOperator::PtrMemD:
6108 case BinaryOperator::PtrMemI:
6109 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6110 Opc == BinaryOperator::PtrMemI);
6111 break;
6112 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006113 case BinaryOperator::Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006114 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6115 Opc == BinaryOperator::Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006116 break;
6117 case BinaryOperator::Rem:
6118 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6119 break;
6120 case BinaryOperator::Add:
6121 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6122 break;
6123 case BinaryOperator::Sub:
6124 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6125 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006126 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006127 case BinaryOperator::Shr:
6128 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6129 break;
6130 case BinaryOperator::LE:
6131 case BinaryOperator::LT:
6132 case BinaryOperator::GE:
6133 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006134 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006135 break;
6136 case BinaryOperator::EQ:
6137 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006138 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006139 break;
6140 case BinaryOperator::And:
6141 case BinaryOperator::Xor:
6142 case BinaryOperator::Or:
6143 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6144 break;
6145 case BinaryOperator::LAnd:
6146 case BinaryOperator::LOr:
6147 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6148 break;
6149 case BinaryOperator::MulAssign:
6150 case BinaryOperator::DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006151 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6152 Opc == BinaryOperator::DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006153 CompLHSTy = CompResultTy;
6154 if (!CompResultTy.isNull())
6155 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006156 break;
6157 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006158 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6159 CompLHSTy = CompResultTy;
6160 if (!CompResultTy.isNull())
6161 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006162 break;
6163 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006164 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6165 if (!CompResultTy.isNull())
6166 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006167 break;
6168 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006169 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6170 if (!CompResultTy.isNull())
6171 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006172 break;
6173 case BinaryOperator::ShlAssign:
6174 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006175 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6176 CompLHSTy = CompResultTy;
6177 if (!CompResultTy.isNull())
6178 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006179 break;
6180 case BinaryOperator::AndAssign:
6181 case BinaryOperator::XorAssign:
6182 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006183 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6184 CompLHSTy = CompResultTy;
6185 if (!CompResultTy.isNull())
6186 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006187 break;
6188 case BinaryOperator::Comma:
6189 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6190 break;
6191 }
6192 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006193 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006194 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006195 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6196 else
6197 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006198 CompLHSTy, CompResultTy,
6199 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006200}
6201
Sebastian Redlaee3c932009-10-27 12:10:02 +00006202/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6203/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006204static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6205 const PartialDiagnostic &PD,
Douglas Gregor827feec2010-01-08 00:20:23 +00006206 SourceRange ParenRange,
6207 const PartialDiagnostic &SecondPD = PartialDiagnostic(0),
6208 SourceRange SecondParenRange = SourceRange()) {
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006209 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6210 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6211 // We can't display the parentheses, so just dig the
6212 // warning/error and return.
6213 Self.Diag(Loc, PD);
6214 return;
6215 }
6216
6217 Self.Diag(Loc, PD)
6218 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6219 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Douglas Gregor827feec2010-01-08 00:20:23 +00006220
6221 if (!SecondPD.getDiagID())
6222 return;
6223
6224 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6225 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6226 // We can't display the parentheses, so just dig the
6227 // warning/error and return.
6228 Self.Diag(Loc, SecondPD);
6229 return;
6230 }
6231
6232 Self.Diag(Loc, SecondPD)
6233 << CodeModificationHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6234 << CodeModificationHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006235}
6236
Sebastian Redlaee3c932009-10-27 12:10:02 +00006237/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6238/// operators are mixed in a way that suggests that the programmer forgot that
6239/// comparison operators have higher precedence. The most typical example of
6240/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006241static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6242 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006243 typedef BinaryOperator BinOp;
6244 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6245 rhsopc = static_cast<BinOp::Opcode>(-1);
6246 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006247 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006248 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006249 rhsopc = BO->getOpcode();
6250
6251 // Subs are not binary operators.
6252 if (lhsopc == -1 && rhsopc == -1)
6253 return;
6254
6255 // Bitwise operations are sometimes used as eager logical ops.
6256 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006257 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6258 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006259 return;
6260
Sebastian Redlaee3c932009-10-27 12:10:02 +00006261 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006262 SuggestParentheses(Self, OpLoc,
6263 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006264 << SourceRange(lhs->getLocStart(), OpLoc)
6265 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor827feec2010-01-08 00:20:23 +00006266 lhs->getSourceRange(),
6267 PDiag(diag::note_precedence_bitwise_first)
6268 << BinOp::getOpcodeStr(Opc),
Sebastian Redlaee3c932009-10-27 12:10:02 +00006269 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6270 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006271 SuggestParentheses(Self, OpLoc,
6272 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006273 << SourceRange(OpLoc, rhs->getLocEnd())
6274 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor827feec2010-01-08 00:20:23 +00006275 rhs->getSourceRange(),
6276 PDiag(diag::note_precedence_bitwise_first)
6277 << BinOp::getOpcodeStr(Opc),
Sebastian Redlaee3c932009-10-27 12:10:02 +00006278 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006279}
6280
6281/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6282/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6283/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6284static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6285 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006286 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006287 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6288}
6289
Reid Spencer5f016e22007-07-11 17:01:13 +00006290// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006291Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6292 tok::TokenKind Kind,
6293 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006294 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006295 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006296
Steve Narofff69936d2007-09-16 03:34:24 +00006297 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6298 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006299
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006300 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6301 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6302
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006303 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6304}
6305
6306Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6307 BinaryOperator::Opcode Opc,
6308 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006309 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006310 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006311 rhs->getType()->isOverloadableType())) {
6312 // Find all of the overloaded operators visible from this
6313 // point. We perform both an operator-name lookup from the local
6314 // scope and an argument-dependent lookup based on the types of
6315 // the arguments.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006316 FunctionSet Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006317 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6318 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006319 if (S)
6320 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6321 Functions);
Douglas Gregor063daf62009-03-13 18:40:31 +00006322 Expr *Args[2] = { lhs, rhs };
Mike Stump1eb44332009-09-09 15:08:12 +00006323 DeclarationName OpName
Douglas Gregor063daf62009-03-13 18:40:31 +00006324 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006325 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006326 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006327
Douglas Gregor063daf62009-03-13 18:40:31 +00006328 // Build the (potentially-overloaded, potentially-dependent)
6329 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006330 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006331 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006332
Douglas Gregoreaebc752008-11-06 23:29:22 +00006333 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006334 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006335}
6336
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006337Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006338 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006339 ExprArg InputArg) {
6340 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006341
Mike Stump390b4cc2009-05-16 07:39:55 +00006342 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006343 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006344 QualType resultType;
6345 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006346 case UnaryOperator::OffsetOf:
6347 assert(false && "Invalid unary operator");
6348 break;
6349
Reid Spencer5f016e22007-07-11 17:01:13 +00006350 case UnaryOperator::PreInc:
6351 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006352 case UnaryOperator::PostInc:
6353 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006354 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006355 Opc == UnaryOperator::PreInc ||
6356 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006357 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006358 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006359 resultType = CheckAddressOfOperand(Input, OpLoc);
6360 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006361 case UnaryOperator::Deref:
Steve Naroff1ca9b112007-12-18 04:06:57 +00006362 DefaultFunctionArrayConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006363 resultType = CheckIndirectionOperand(Input, OpLoc);
6364 break;
6365 case UnaryOperator::Plus:
6366 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006367 UsualUnaryConversions(Input);
6368 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006369 if (resultType->isDependentType())
6370 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006371 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6372 break;
6373 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6374 resultType->isEnumeralType())
6375 break;
6376 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6377 Opc == UnaryOperator::Plus &&
6378 resultType->isPointerType())
6379 break;
6380
Sebastian Redl0eb23302009-01-19 00:08:26 +00006381 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6382 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006383 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006384 UsualUnaryConversions(Input);
6385 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006386 if (resultType->isDependentType())
6387 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006388 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6389 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6390 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006391 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006392 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006393 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006394 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6395 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006396 break;
6397 case UnaryOperator::LNot: // logical negation
6398 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006399 DefaultFunctionArrayConversion(Input);
6400 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006401 if (resultType->isDependentType())
6402 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006403 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006404 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6405 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006406 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006407 // In C++, it's bool. C++ 5.3.1p8
6408 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006409 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006410 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006411 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006412 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006413 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006414 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006415 resultType = Input->getType();
6416 break;
6417 }
6418 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006419 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006420
6421 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006422 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006423}
6424
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006425Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6426 UnaryOperator::Opcode Opc,
6427 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006428 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006429 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6430 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006431 // Find all of the overloaded operators visible from this
6432 // point. We perform both an operator-name lookup from the local
6433 // scope and an argument-dependent lookup based on the types of
6434 // the arguments.
6435 FunctionSet Functions;
6436 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6437 if (OverOp != OO_None) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006438 if (S)
6439 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6440 Functions);
Mike Stump1eb44332009-09-09 15:08:12 +00006441 DeclarationName OpName
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006442 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redl644be852009-10-23 19:23:15 +00006443 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006444 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006445
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006446 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6447 }
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006448
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006449 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6450}
6451
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006452// Unary Operators. 'Tok' is the token for the operator.
6453Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6454 tok::TokenKind Op, ExprArg input) {
6455 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6456}
6457
Steve Naroff1b273c42007-09-16 14:56:35 +00006458/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006459Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6460 SourceLocation LabLoc,
6461 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006462 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006463 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006464
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006465 // If we haven't seen this label yet, create a forward reference. It
6466 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006467 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006468 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006469
Reid Spencer5f016e22007-07-11 17:01:13 +00006470 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006471 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6472 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006473}
6474
Sebastian Redlf53597f2009-03-15 17:47:39 +00006475Sema::OwningExprResult
6476Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6477 SourceLocation RPLoc) { // "({..})"
6478 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006479 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6480 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6481
Eli Friedmandca2b732009-01-24 23:09:00 +00006482 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattner4a049f02009-04-25 19:11:05 +00006483 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006484 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006485
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006486 // FIXME: there are a variety of strange constraints to enforce here, for
6487 // example, it is not possible to goto into a stmt expression apparently.
6488 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006489
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006490 // If there are sub stmts in the compound stmt, take the type of the last one
6491 // as the type of the stmtexpr.
6492 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006493
Chris Lattner611b2ec2008-07-26 19:51:01 +00006494 if (!Compound->body_empty()) {
6495 Stmt *LastStmt = Compound->body_back();
6496 // If LastStmt is a label, skip down through into the body.
6497 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6498 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006499
Chris Lattner611b2ec2008-07-26 19:51:01 +00006500 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006501 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006502 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006503
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006504 // FIXME: Check that expression type is complete/non-abstract; statement
6505 // expressions are not lvalues.
6506
Sebastian Redlf53597f2009-03-15 17:47:39 +00006507 substmt.release();
6508 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006509}
Steve Naroffd34e9152007-08-01 22:05:33 +00006510
Sebastian Redlf53597f2009-03-15 17:47:39 +00006511Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6512 SourceLocation BuiltinLoc,
6513 SourceLocation TypeLoc,
6514 TypeTy *argty,
6515 OffsetOfComponent *CompPtr,
6516 unsigned NumComponents,
6517 SourceLocation RPLoc) {
6518 // FIXME: This function leaks all expressions in the offset components on
6519 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006520 // FIXME: Preserve type source info.
6521 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006522 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006523
Sebastian Redl28507842009-02-26 14:39:58 +00006524 bool Dependent = ArgTy->isDependentType();
6525
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006526 // We must have at least one component that refers to the type, and the first
6527 // one is known to be a field designator. Verify that the ArgTy represents
6528 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006529 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006530 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006531
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006532 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6533 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006534
Eli Friedman35183ac2009-02-27 06:44:11 +00006535 // Otherwise, create a null pointer as the base, and iteratively process
6536 // the offsetof designators.
6537 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6538 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006539 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006540 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006541
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006542 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6543 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006544 // FIXME: This diagnostic isn't actually visible because the location is in
6545 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006546 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006547 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6548 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006549
Sebastian Redl28507842009-02-26 14:39:58 +00006550 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006551 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006552
John McCalld00f2002009-11-04 03:03:43 +00006553 if (RequireCompleteType(TypeLoc, Res->getType(),
6554 diag::err_offsetof_incomplete_type))
6555 return ExprError();
6556
Sebastian Redl28507842009-02-26 14:39:58 +00006557 // FIXME: Dependent case loses a lot of information here. And probably
6558 // leaks like a sieve.
6559 for (unsigned i = 0; i != NumComponents; ++i) {
6560 const OffsetOfComponent &OC = CompPtr[i];
6561 if (OC.isBrackets) {
6562 // Offset of an array sub-field. TODO: Should we allow vector elements?
6563 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6564 if (!AT) {
6565 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006566 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6567 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006568 }
6569
6570 // FIXME: C++: Verify that operator[] isn't overloaded.
6571
Eli Friedman35183ac2009-02-27 06:44:11 +00006572 // Promote the array so it looks more like a normal array subscript
6573 // expression.
6574 DefaultFunctionArrayConversion(Res);
6575
Sebastian Redl28507842009-02-26 14:39:58 +00006576 // C99 6.5.2.1p1
6577 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006578 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006579 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006580 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006581 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006582 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006583
6584 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6585 OC.LocEnd);
6586 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006587 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006588
Ted Kremenek6217b802009-07-29 21:53:49 +00006589 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006590 if (!RC) {
6591 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006592 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6593 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006594 }
Chris Lattner704fe352007-08-30 17:59:59 +00006595
Sebastian Redl28507842009-02-26 14:39:58 +00006596 // Get the decl corresponding to this.
6597 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006598 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00006599 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6600 DiagRuntimeBehavior(BuiltinLoc,
6601 PDiag(diag::warn_offsetof_non_pod_type)
6602 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6603 << Res->getType()))
6604 DidWarnAboutNonPOD = true;
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006605 }
Mike Stump1eb44332009-09-09 15:08:12 +00006606
John McCalla24dc2e2009-11-17 02:14:36 +00006607 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6608 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006609
John McCall1bcee0a2009-12-02 08:25:40 +00006610 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006611 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006612 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006613 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6614 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006615
Sebastian Redl28507842009-02-26 14:39:58 +00006616 // FIXME: C++: Verify that MemberDecl isn't a static field.
6617 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006618 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006619 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006620 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006621 } else {
Eli Friedman16c53782009-12-04 07:18:51 +00006622 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006623 // MemberDecl->getType() doesn't get the right qualifiers, but it
6624 // doesn't matter here.
6625 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6626 MemberDecl->getType().getNonReferenceType());
6627 }
Sebastian Redl28507842009-02-26 14:39:58 +00006628 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006629 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006630
Sebastian Redlf53597f2009-03-15 17:47:39 +00006631 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6632 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006633}
6634
6635
Sebastian Redlf53597f2009-03-15 17:47:39 +00006636Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6637 TypeTy *arg1,TypeTy *arg2,
6638 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006639 // FIXME: Preserve type source info.
6640 QualType argT1 = GetTypeFromParser(arg1);
6641 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006642
Steve Naroffd34e9152007-08-01 22:05:33 +00006643 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006644
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006645 if (getLangOptions().CPlusPlus) {
6646 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6647 << SourceRange(BuiltinLoc, RPLoc);
6648 return ExprError();
6649 }
6650
Sebastian Redlf53597f2009-03-15 17:47:39 +00006651 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6652 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006653}
6654
Sebastian Redlf53597f2009-03-15 17:47:39 +00006655Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6656 ExprArg cond,
6657 ExprArg expr1, ExprArg expr2,
6658 SourceLocation RPLoc) {
6659 Expr *CondExpr = static_cast<Expr*>(cond.get());
6660 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6661 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006662
Steve Naroffd04fdd52007-08-03 21:21:27 +00006663 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6664
Sebastian Redl28507842009-02-26 14:39:58 +00006665 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006666 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006667 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006668 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006669 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006670 } else {
6671 // The conditional expression is required to be a constant expression.
6672 llvm::APSInt condEval(32);
6673 SourceLocation ExpLoc;
6674 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006675 return ExprError(Diag(ExpLoc,
6676 diag::err_typecheck_choose_expr_requires_constant)
6677 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006678
Sebastian Redl28507842009-02-26 14:39:58 +00006679 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6680 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006681 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6682 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006683 }
6684
Sebastian Redlf53597f2009-03-15 17:47:39 +00006685 cond.release(); expr1.release(); expr2.release();
6686 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006687 resType, RPLoc,
6688 resType->isDependentType(),
6689 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006690}
6691
Steve Naroff4eb206b2008-09-03 18:15:37 +00006692//===----------------------------------------------------------------------===//
6693// Clang Extensions.
6694//===----------------------------------------------------------------------===//
6695
6696/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006697void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006698 // Analyze block parameters.
6699 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006700
Steve Naroff4eb206b2008-09-03 18:15:37 +00006701 // Add BSI to CurBlock.
6702 BSI->PrevBlockInfo = CurBlock;
6703 CurBlock = BSI;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006704
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006705 BSI->ReturnType = QualType();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006706 BSI->TheScope = BlockScope;
Mike Stumpb83d2872009-02-19 22:01:56 +00006707 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbar1d2154c2009-07-29 01:59:17 +00006708 BSI->hasPrototype = false;
Chris Lattner17a78302009-04-19 05:28:12 +00006709 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6710 CurFunctionNeedsScopeChecking = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006711
Steve Naroff090276f2008-10-10 01:28:17 +00006712 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Ted Kremenek3cdff232009-12-07 22:01:30 +00006713 CurContext->addDecl(BSI->TheDecl);
Douglas Gregor44b43212008-12-11 16:49:14 +00006714 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff090276f2008-10-10 01:28:17 +00006715}
6716
Mike Stump98eb8a72009-02-04 22:31:32 +00006717void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006718 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump98eb8a72009-02-04 22:31:32 +00006719
6720 if (ParamInfo.getNumTypeObjects() == 0
6721 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006722 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006723 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6724
Mike Stump4eeab842009-04-28 01:10:27 +00006725 if (T->isArrayType()) {
6726 Diag(ParamInfo.getSourceRange().getBegin(),
6727 diag::err_block_returns_array);
6728 return;
6729 }
6730
Mike Stump98eb8a72009-02-04 22:31:32 +00006731 // The parameter list is optional, if there was none, assume ().
6732 if (!T->isFunctionType())
6733 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6734
6735 CurBlock->hasPrototype = true;
6736 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006737 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006738 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006739 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006740 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006741 // FIXME: remove the attribute.
6742 }
John McCall183700f2009-09-21 23:43:11 +00006743 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006744
Chris Lattner9097af12009-04-11 19:27:54 +00006745 // Do not allow returning a objc interface by-value.
6746 if (RetTy->isObjCInterfaceType()) {
6747 Diag(ParamInfo.getSourceRange().getBegin(),
6748 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6749 return;
6750 }
Mike Stump98eb8a72009-02-04 22:31:32 +00006751 return;
6752 }
6753
Steve Naroff4eb206b2008-09-03 18:15:37 +00006754 // Analyze arguments to block.
6755 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6756 "Not a function declarator!");
6757 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006758
Steve Naroff090276f2008-10-10 01:28:17 +00006759 CurBlock->hasPrototype = FTI.hasPrototype;
6760 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006761
Steve Naroff4eb206b2008-09-03 18:15:37 +00006762 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6763 // no arguments, not a function that takes a single void argument.
6764 if (FTI.hasPrototype &&
6765 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006766 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6767 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006768 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006769 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006770 } else if (FTI.hasPrototype) {
6771 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattnerb28317a2009-03-28 19:18:32 +00006772 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff090276f2008-10-10 01:28:17 +00006773 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006774 }
Jay Foadbeaaccd2009-05-21 09:52:38 +00006775 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006776 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006777 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006778 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff090276f2008-10-10 01:28:17 +00006779 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6780 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6781 // If this has an identifier, add it to the scope stack.
6782 if ((*AI)->getIdentifier())
6783 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner9097af12009-04-11 19:27:54 +00006784
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006785 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006786 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006787 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006788 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006789 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006790 // FIXME: remove the attribute.
6791 }
Mike Stump1eb44332009-09-09 15:08:12 +00006792
Chris Lattner9097af12009-04-11 19:27:54 +00006793 // Analyze the return type.
6794 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006795 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006796
Chris Lattner9097af12009-04-11 19:27:54 +00006797 // Do not allow returning a objc interface by-value.
6798 if (RetTy->isObjCInterfaceType()) {
6799 Diag(ParamInfo.getSourceRange().getBegin(),
6800 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6801 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006802 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006803}
6804
6805/// ActOnBlockError - If there is an error parsing a block, this callback
6806/// is invoked to pop the information about the block from the action impl.
6807void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6808 // Ensure that CurBlock is deleted.
6809 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006810
Chris Lattner17a78302009-04-19 05:28:12 +00006811 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6812
Steve Naroff4eb206b2008-09-03 18:15:37 +00006813 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00006814 PopDeclContext();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006815 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006816 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00006817}
6818
6819/// ActOnBlockStmtExpr - This is called when the body of a block statement
6820/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00006821Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6822 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00006823 // If blocks are disabled, emit an error.
6824 if (!LangOpts.Blocks)
6825 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00006826
Steve Naroff4eb206b2008-09-03 18:15:37 +00006827 // Ensure that CurBlock is deleted.
6828 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006829
Steve Naroff090276f2008-10-10 01:28:17 +00006830 PopDeclContext();
6831
Steve Naroff4eb206b2008-09-03 18:15:37 +00006832 // Pop off CurBlock, handle nested blocks.
6833 CurBlock = CurBlock->PrevBlockInfo;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006834
Steve Naroff4eb206b2008-09-03 18:15:37 +00006835 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006836 if (!BSI->ReturnType.isNull())
6837 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006838
Steve Naroff4eb206b2008-09-03 18:15:37 +00006839 llvm::SmallVector<QualType, 8> ArgTypes;
6840 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6841 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006842
Mike Stump56925862009-07-28 22:04:01 +00006843 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00006844 QualType BlockTy;
6845 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00006846 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6847 NoReturn);
Steve Naroff4eb206b2008-09-03 18:15:37 +00006848 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00006849 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00006850 BSI->isVariadic, 0, false, false, 0, 0,
6851 NoReturn);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006852
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006853 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00006854 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00006855 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006856
Chris Lattner17a78302009-04-19 05:28:12 +00006857 // If needed, diagnose invalid gotos and switches in the block.
6858 if (CurFunctionNeedsScopeChecking)
6859 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6860 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump1eb44332009-09-09 15:08:12 +00006861
Anders Carlssone9146f22009-05-01 19:49:17 +00006862 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stumpfa6ef182010-01-13 02:59:54 +00006863 AnalysisContext AC(BSI->TheDecl);
6864 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody(), AC);
6865 CheckUnreachable(AC);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006866 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6867 BSI->hasBlockDeclRefExprs));
Steve Naroff4eb206b2008-09-03 18:15:37 +00006868}
6869
Sebastian Redlf53597f2009-03-15 17:47:39 +00006870Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6871 ExprArg expr, TypeTy *type,
6872 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006873 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006874 Expr *E = static_cast<Expr*>(expr.get());
6875 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00006876
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006877 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006878
6879 // Get the va_list type
6880 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00006881 if (VaListType->isArrayType()) {
6882 // Deal with implicit array decay; for example, on x86-64,
6883 // va_list is an array, but it's supposed to decay to
6884 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006885 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00006886 // Make sure the input expression also decays appropriately.
6887 UsualUnaryConversions(E);
6888 } else {
6889 // Otherwise, the va_list argument must be an l-value because
6890 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00006891 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00006892 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00006893 return ExprError();
6894 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00006895
Douglas Gregordd027302009-05-19 23:10:31 +00006896 if (!E->isTypeDependent() &&
6897 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00006898 return ExprError(Diag(E->getLocStart(),
6899 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00006900 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00006901 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006902
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006903 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006904 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006905
Sebastian Redlf53597f2009-03-15 17:47:39 +00006906 expr.release();
6907 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6908 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00006909}
6910
Sebastian Redlf53597f2009-03-15 17:47:39 +00006911Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006912 // The type of __null will be int or long, depending on the size of
6913 // pointers on the target.
6914 QualType Ty;
6915 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6916 Ty = Context.IntTy;
6917 else
6918 Ty = Context.LongTy;
6919
Sebastian Redlf53597f2009-03-15 17:47:39 +00006920 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00006921}
6922
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006923static void
6924MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6925 QualType DstType,
6926 Expr *SrcExpr,
6927 CodeModificationHint &Hint) {
6928 if (!SemaRef.getLangOptions().ObjC1)
6929 return;
6930
6931 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6932 if (!PT)
6933 return;
6934
6935 // Check if the destination is of type 'id'.
6936 if (!PT->isObjCIdType()) {
6937 // Check if the destination is the 'NSString' interface.
6938 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6939 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6940 return;
6941 }
6942
6943 // Strip off any parens and casts.
6944 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6945 if (!SL || SL->isWide())
6946 return;
6947
6948 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6949}
6950
Chris Lattner5cf216b2008-01-04 18:04:52 +00006951bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6952 SourceLocation Loc,
6953 QualType DstType, QualType SrcType,
Douglas Gregor68647482009-12-16 03:45:30 +00006954 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00006955 // Decode the result (notice that AST's are still created for extensions).
6956 bool isInvalid = false;
6957 unsigned DiagKind;
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006958 CodeModificationHint Hint;
6959
Chris Lattner5cf216b2008-01-04 18:04:52 +00006960 switch (ConvTy) {
6961 default: assert(0 && "Unknown conversion type");
6962 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006963 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00006964 DiagKind = diag::ext_typecheck_convert_pointer_int;
6965 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00006966 case IntToPointer:
6967 DiagKind = diag::ext_typecheck_convert_int_pointer;
6968 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006969 case IncompatiblePointer:
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00006970 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00006971 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6972 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00006973 case IncompatiblePointerSign:
6974 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6975 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006976 case FunctionVoidPointer:
6977 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6978 break;
6979 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00006980 // If the qualifiers lost were because we were applying the
6981 // (deprecated) C++ conversion from a string literal to a char*
6982 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6983 // Ideally, this check would be performed in
6984 // CheckPointerTypesForAssignment. However, that would require a
6985 // bit of refactoring (so that the second argument is an
6986 // expression, rather than a type), which should be done as part
6987 // of a larger effort to fix CheckPointerTypesForAssignment for
6988 // C++ semantics.
6989 if (getLangOptions().CPlusPlus &&
6990 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6991 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00006992 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6993 break;
Sean Huntc9132b62009-11-08 07:46:34 +00006994 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00006995 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00006996 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00006997 case IntToBlockPointer:
6998 DiagKind = diag::err_int_to_block_pointer;
6999 break;
7000 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00007001 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007002 break;
Steve Naroff39579072008-10-14 22:18:38 +00007003 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00007004 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00007005 // it can give a more specific diagnostic.
7006 DiagKind = diag::warn_incompatible_qualified_id;
7007 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007008 case IncompatibleVectors:
7009 DiagKind = diag::warn_incompatible_vectors;
7010 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007011 case Incompatible:
7012 DiagKind = diag::err_typecheck_convert_incompatible;
7013 isInvalid = true;
7014 break;
7015 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007016
Douglas Gregor68647482009-12-16 03:45:30 +00007017 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007018 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007019 return isInvalid;
7020}
Anders Carlssone21555e2008-11-30 19:50:32 +00007021
Chris Lattner3bf68932009-04-25 21:59:05 +00007022bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007023 llvm::APSInt ICEResult;
7024 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7025 if (Result)
7026 *Result = ICEResult;
7027 return false;
7028 }
7029
Anders Carlssone21555e2008-11-30 19:50:32 +00007030 Expr::EvalResult EvalResult;
7031
Mike Stumpeed9cac2009-02-19 03:04:26 +00007032 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00007033 EvalResult.HasSideEffects) {
7034 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7035
7036 if (EvalResult.Diag) {
7037 // We only show the note if it's not the usual "invalid subexpression"
7038 // or if it's actually in a subexpression.
7039 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7040 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7041 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7042 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007043
Anders Carlssone21555e2008-11-30 19:50:32 +00007044 return true;
7045 }
7046
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007047 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7048 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00007049
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007050 if (EvalResult.Diag &&
7051 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7052 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007053
Anders Carlssone21555e2008-11-30 19:50:32 +00007054 if (Result)
7055 *Result = EvalResult.Val.getInt();
7056 return false;
7057}
Douglas Gregore0762c92009-06-19 23:52:42 +00007058
Douglas Gregor2afce722009-11-26 00:44:06 +00007059void
Mike Stump1eb44332009-09-09 15:08:12 +00007060Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00007061 ExprEvalContexts.push_back(
7062 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00007063}
7064
Mike Stump1eb44332009-09-09 15:08:12 +00007065void
Douglas Gregor2afce722009-11-26 00:44:06 +00007066Sema::PopExpressionEvaluationContext() {
7067 // Pop the current expression evaluation context off the stack.
7068 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7069 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007070
Douglas Gregor06d33692009-12-12 07:57:52 +00007071 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7072 if (Rec.PotentiallyReferenced) {
7073 // Mark any remaining declarations in the current position of the stack
7074 // as "referenced". If they were not meant to be referenced, semantic
7075 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7076 for (PotentiallyReferencedDecls::iterator
7077 I = Rec.PotentiallyReferenced->begin(),
7078 IEnd = Rec.PotentiallyReferenced->end();
7079 I != IEnd; ++I)
7080 MarkDeclarationReferenced(I->first, I->second);
7081 }
7082
7083 if (Rec.PotentiallyDiagnosed) {
7084 // Emit any pending diagnostics.
7085 for (PotentiallyEmittedDiagnostics::iterator
7086 I = Rec.PotentiallyDiagnosed->begin(),
7087 IEnd = Rec.PotentiallyDiagnosed->end();
7088 I != IEnd; ++I)
7089 Diag(I->first, I->second);
7090 }
Douglas Gregor2afce722009-11-26 00:44:06 +00007091 }
7092
7093 // When are coming out of an unevaluated context, clear out any
7094 // temporaries that we may have created as part of the evaluation of
7095 // the expression in that context: they aren't relevant because they
7096 // will never be constructed.
7097 if (Rec.Context == Unevaluated &&
7098 ExprTemporaries.size() > Rec.NumTemporaries)
7099 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7100 ExprTemporaries.end());
7101
7102 // Destroy the popped expression evaluation record.
7103 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007104}
Douglas Gregore0762c92009-06-19 23:52:42 +00007105
7106/// \brief Note that the given declaration was referenced in the source code.
7107///
7108/// This routine should be invoke whenever a given declaration is referenced
7109/// in the source code, and where that reference occurred. If this declaration
7110/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7111/// C99 6.9p3), then the declaration will be marked as used.
7112///
7113/// \param Loc the location where the declaration was referenced.
7114///
7115/// \param D the declaration that has been referenced by the source code.
7116void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7117 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007118
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007119 if (D->isUsed())
7120 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007121
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007122 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7123 // template or not. The reason for this is that unevaluated expressions
7124 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7125 // -Wunused-parameters)
7126 if (isa<ParmVarDecl>(D) ||
7127 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00007128 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00007129
Douglas Gregore0762c92009-06-19 23:52:42 +00007130 // Do not mark anything as "used" within a dependent context; wait for
7131 // an instantiation.
7132 if (CurContext->isDependentContext())
7133 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007134
Douglas Gregor2afce722009-11-26 00:44:06 +00007135 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007136 case Unevaluated:
7137 // We are in an expression that is not potentially evaluated; do nothing.
7138 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007139
Douglas Gregorac7610d2009-06-22 20:57:11 +00007140 case PotentiallyEvaluated:
7141 // We are in a potentially-evaluated expression, so this declaration is
7142 // "used"; handle this below.
7143 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007144
Douglas Gregorac7610d2009-06-22 20:57:11 +00007145 case PotentiallyPotentiallyEvaluated:
7146 // We are in an expression that may be potentially evaluated; queue this
7147 // declaration reference until we know whether the expression is
7148 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007149 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007150 return;
7151 }
Mike Stump1eb44332009-09-09 15:08:12 +00007152
Douglas Gregore0762c92009-06-19 23:52:42 +00007153 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007154 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007155 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007156 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7157 if (!Constructor->isUsed())
7158 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007159 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00007160 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007161 if (!Constructor->isUsed())
7162 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7163 }
Anders Carlssond6a637f2009-12-07 08:24:59 +00007164
7165 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007166 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7167 if (Destructor->isImplicit() && !Destructor->isUsed())
7168 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007169
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007170 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7171 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7172 MethodDecl->getOverloadedOperator() == OO_Equal) {
7173 if (!MethodDecl->isUsed())
7174 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7175 }
7176 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007177 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007178 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007179 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007180 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007181 bool AlreadyInstantiated = false;
7182 if (FunctionTemplateSpecializationInfo *SpecInfo
7183 = Function->getTemplateSpecializationInfo()) {
7184 if (SpecInfo->getPointOfInstantiation().isInvalid())
7185 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007186 else if (SpecInfo->getTemplateSpecializationKind()
7187 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007188 AlreadyInstantiated = true;
7189 } else if (MemberSpecializationInfo *MSInfo
7190 = Function->getMemberSpecializationInfo()) {
7191 if (MSInfo->getPointOfInstantiation().isInvalid())
7192 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregor3b846b62009-10-27 20:53:28 +00007193 else if (MSInfo->getTemplateSpecializationKind()
7194 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007195 AlreadyInstantiated = true;
7196 }
7197
7198 if (!AlreadyInstantiated)
7199 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7200 }
7201
Douglas Gregore0762c92009-06-19 23:52:42 +00007202 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007203 Function->setUsed(true);
7204 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007205 }
Mike Stump1eb44332009-09-09 15:08:12 +00007206
Douglas Gregore0762c92009-06-19 23:52:42 +00007207 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007208 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007209 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007210 Var->getInstantiatedFromStaticDataMember()) {
7211 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7212 assert(MSInfo && "Missing member specialization information?");
7213 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7214 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7215 MSInfo->setPointOfInstantiation(Loc);
7216 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7217 }
7218 }
Mike Stump1eb44332009-09-09 15:08:12 +00007219
Douglas Gregore0762c92009-06-19 23:52:42 +00007220 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007221
Douglas Gregore0762c92009-06-19 23:52:42 +00007222 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007223 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007224 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007225}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007226
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007227/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7228/// of the program being compiled.
7229///
7230/// This routine emits the given diagnostic when the code currently being
7231/// type-checked is "potentially evaluated", meaning that there is a
7232/// possibility that the code will actually be executable. Code in sizeof()
7233/// expressions, code used only during overload resolution, etc., are not
7234/// potentially evaluated. This routine will suppress such diagnostics or,
7235/// in the absolutely nutty case of potentially potentially evaluated
7236/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7237/// later.
7238///
7239/// This routine should be used for all diagnostics that describe the run-time
7240/// behavior of a program, such as passing a non-POD value through an ellipsis.
7241/// Failure to do so will likely result in spurious diagnostics or failures
7242/// during overload resolution or within sizeof/alignof/typeof/typeid.
7243bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7244 const PartialDiagnostic &PD) {
7245 switch (ExprEvalContexts.back().Context ) {
7246 case Unevaluated:
7247 // The argument will never be evaluated, so don't complain.
7248 break;
7249
7250 case PotentiallyEvaluated:
7251 Diag(Loc, PD);
7252 return true;
7253
7254 case PotentiallyPotentiallyEvaluated:
7255 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7256 break;
7257 }
7258
7259 return false;
7260}
7261
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007262bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7263 CallExpr *CE, FunctionDecl *FD) {
7264 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7265 return false;
7266
7267 PartialDiagnostic Note =
7268 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7269 << FD->getDeclName() : PDiag();
7270 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7271
7272 if (RequireCompleteType(Loc, ReturnType,
7273 FD ?
7274 PDiag(diag::err_call_function_incomplete_return)
7275 << CE->getSourceRange() << FD->getDeclName() :
7276 PDiag(diag::err_call_incomplete_return)
7277 << CE->getSourceRange(),
7278 std::make_pair(NoteLoc, Note)))
7279 return true;
7280
7281 return false;
7282}
7283
John McCall5a881bb2009-10-12 21:59:07 +00007284// Diagnose the common s/=/==/ typo. Note that adding parentheses
7285// will prevent this condition from triggering, which is what we want.
7286void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7287 SourceLocation Loc;
7288
John McCalla52ef082009-11-11 02:41:58 +00007289 unsigned diagnostic = diag::warn_condition_is_assignment;
7290
John McCall5a881bb2009-10-12 21:59:07 +00007291 if (isa<BinaryOperator>(E)) {
7292 BinaryOperator *Op = cast<BinaryOperator>(E);
7293 if (Op->getOpcode() != BinaryOperator::Assign)
7294 return;
7295
John McCallc8d8ac52009-11-12 00:06:05 +00007296 // Greylist some idioms by putting them into a warning subcategory.
7297 if (ObjCMessageExpr *ME
7298 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7299 Selector Sel = ME->getSelector();
7300
John McCallc8d8ac52009-11-12 00:06:05 +00007301 // self = [<foo> init...]
7302 if (isSelfExpr(Op->getLHS())
7303 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7304 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7305
7306 // <foo> = [<bar> nextObject]
7307 else if (Sel.isUnarySelector() &&
7308 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7309 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7310 }
John McCalla52ef082009-11-11 02:41:58 +00007311
John McCall5a881bb2009-10-12 21:59:07 +00007312 Loc = Op->getOperatorLoc();
7313 } else if (isa<CXXOperatorCallExpr>(E)) {
7314 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7315 if (Op->getOperator() != OO_Equal)
7316 return;
7317
7318 Loc = Op->getOperatorLoc();
7319 } else {
7320 // Not an assignment.
7321 return;
7322 }
7323
John McCall5a881bb2009-10-12 21:59:07 +00007324 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007325 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCall5a881bb2009-10-12 21:59:07 +00007326
John McCalla52ef082009-11-11 02:41:58 +00007327 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007328 << E->getSourceRange()
7329 << CodeModificationHint::CreateInsertion(Open, "(")
7330 << CodeModificationHint::CreateInsertion(Close, ")");
Douglas Gregor827feec2010-01-08 00:20:23 +00007331 Diag(Loc, diag::note_condition_assign_to_comparison)
7332 << CodeModificationHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00007333}
7334
7335bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7336 DiagnoseAssignmentAsCondition(E);
7337
7338 if (!E->isTypeDependent()) {
7339 DefaultFunctionArrayConversion(E);
7340
7341 QualType T = E->getType();
7342
7343 if (getLangOptions().CPlusPlus) {
7344 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7345 return true;
7346 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7347 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7348 << T << E->getSourceRange();
7349 return true;
7350 }
7351 }
7352
7353 return false;
7354}