blob: fbdf080bc4a74a0786d764bcedddfd9e944f38bf [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"
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +000017#include "AnalysisBasedWarnings.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 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000061
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
Douglas Gregora873dfc2010-02-03 00:27:59 +0000203void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
204 DefaultFunctionArrayConversion(E);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000205
Douglas Gregora873dfc2010-02-03 00:27:59 +0000206 QualType Ty = E->getType();
207 assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
208 if (!Ty->isDependentType() && Ty.hasQualifiers() &&
209 (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
210 E->isLvalue(Context) == Expr::LV_Valid) {
211 // C++ [conv.lval]p1:
212 // [...] If T is a non-class type, the type of the rvalue is the
213 // cv-unqualified version of T. Otherwise, the type of the
214 // rvalue is T
215 //
216 // C99 6.3.2.1p2:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000217 // If the lvalue has qualified type, the value has the unqualified
218 // version of the type of the lvalue; otherwise, the value has the
Douglas Gregora873dfc2010-02-03 00:27:59 +0000219 // type of the lvalue.
220 ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
221 }
222}
223
224
Chris Lattnere7a2e912008-07-25 21:10:04 +0000225/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump1eb44332009-09-09 15:08:12 +0000226/// operators (C99 6.3). The conversions of array and function types are
Chris Lattnere7a2e912008-07-25 21:10:04 +0000227/// sometimes surpressed. For example, the array->pointer conversion doesn't
228/// apply if the array is an argument to the sizeof or address (&) operators.
229/// In these instances, this routine should *not* be called.
230Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
231 QualType Ty = Expr->getType();
232 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Douglas Gregorfc24e442009-05-01 20:41:21 +0000234 // C99 6.3.1.1p2:
235 //
236 // The following may be used in an expression wherever an int or
237 // unsigned int may be used:
238 // - an object or expression with an integer type whose integer
239 // conversion rank is less than or equal to the rank of int
240 // and unsigned int.
241 // - A bit-field of type _Bool, int, signed int, or unsigned int.
242 //
243 // If an int can represent all values of the original type, the
244 // value is converted to an int; otherwise, it is converted to an
245 // unsigned int. These are called the integer promotions. All
246 // other types are unchanged by the integer promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000247 QualType PTy = Context.isPromotableBitField(Expr);
248 if (!PTy.isNull()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000249 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman04e83572009-08-20 04:21:42 +0000250 return Expr;
251 }
Douglas Gregorfc24e442009-05-01 20:41:21 +0000252 if (Ty->isPromotableIntegerType()) {
Eli Friedmana95d7572009-08-19 07:44:53 +0000253 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman73c39ab2009-10-20 08:27:19 +0000254 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregorfc24e442009-05-01 20:41:21 +0000255 return Expr;
Eli Friedman04e83572009-08-20 04:21:42 +0000256 }
257
Douglas Gregora873dfc2010-02-03 00:27:59 +0000258 DefaultFunctionArrayLvalueConversion(Expr);
Chris Lattnere7a2e912008-07-25 21:10:04 +0000259 return Expr;
260}
261
Chris Lattner05faf172008-07-25 22:25:12 +0000262/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump1eb44332009-09-09 15:08:12 +0000263/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner05faf172008-07-25 22:25:12 +0000264/// double. All other argument types are converted by UsualUnaryConversions().
265void Sema::DefaultArgumentPromotion(Expr *&Expr) {
266 QualType Ty = Expr->getType();
267 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump1eb44332009-09-09 15:08:12 +0000268
Chris Lattner05faf172008-07-25 22:25:12 +0000269 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall183700f2009-09-21 23:43:11 +0000270 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner05faf172008-07-25 22:25:12 +0000271 if (BT->getKind() == BuiltinType::Float)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000272 return ImpCastExprToType(Expr, Context.DoubleTy,
273 CastExpr::CK_FloatingCast);
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattner05faf172008-07-25 22:25:12 +0000275 UsualUnaryConversions(Expr);
276}
277
Chris Lattner312531a2009-04-12 08:11:20 +0000278/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
279/// will warn if the resulting type is not a POD type, and rejects ObjC
280/// interfaces passed by value. This returns true if the argument type is
281/// completely illegal.
282bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000283 DefaultArgumentPromotion(Expr);
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000285 if (Expr->getType()->isObjCInterfaceType() &&
286 DiagRuntimeBehavior(Expr->getLocStart(),
287 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
288 << Expr->getType() << CT))
289 return true;
Douglas Gregor75b699a2009-12-12 07:25:49 +0000290
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000291 if (!Expr->getType()->isPODType() &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000292 DiagRuntimeBehavior(Expr->getLocStart(),
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +0000293 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
294 << Expr->getType() << CT))
295 return true;
Chris Lattner312531a2009-04-12 08:11:20 +0000296
297 return false;
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000298}
299
300
Chris Lattnere7a2e912008-07-25 21:10:04 +0000301/// UsualArithmeticConversions - Performs various conversions that are common to
302/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump1eb44332009-09-09 15:08:12 +0000303/// routine returns the first non-arithmetic type found. The client is
Chris Lattnere7a2e912008-07-25 21:10:04 +0000304/// responsible for emitting appropriate error diagnostics.
305/// FIXME: verify the conversion rules for "complex int" are consistent with
306/// GCC.
307QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
308 bool isCompAssign) {
Eli Friedmanab3a8522009-03-28 01:22:36 +0000309 if (!isCompAssign)
Chris Lattnere7a2e912008-07-25 21:10:04 +0000310 UsualUnaryConversions(lhsExpr);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000311
312 UsualUnaryConversions(rhsExpr);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000313
Mike Stump1eb44332009-09-09 15:08:12 +0000314 // For conversion purposes, we ignore any qualifiers.
Chris Lattnere7a2e912008-07-25 21:10:04 +0000315 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +0000316 QualType lhs =
317 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000318 QualType rhs =
Chris Lattnerb77792e2008-07-26 22:17:49 +0000319 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000320
321 // If both types are identical, no conversion is needed.
322 if (lhs == rhs)
323 return lhs;
324
325 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
326 // The caller can deal with this (e.g. pointer + int).
327 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
328 return lhs;
329
Douglas Gregor2d833e32009-05-02 00:36:19 +0000330 // Perform bitfield promotions.
Eli Friedman04e83572009-08-20 04:21:42 +0000331 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000332 if (!LHSBitfieldPromoteTy.isNull())
333 lhs = LHSBitfieldPromoteTy;
Eli Friedman04e83572009-08-20 04:21:42 +0000334 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregor2d833e32009-05-02 00:36:19 +0000335 if (!RHSBitfieldPromoteTy.isNull())
336 rhs = RHSBitfieldPromoteTy;
337
Eli Friedmana95d7572009-08-19 07:44:53 +0000338 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000339 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +0000340 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
341 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000342 return destType;
343}
344
Chris Lattnere7a2e912008-07-25 21:10:04 +0000345//===----------------------------------------------------------------------===//
346// Semantic Analysis for various Expression Types
347//===----------------------------------------------------------------------===//
348
349
Steve Narofff69936d2007-09-16 03:34:24 +0000350/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Reid Spencer5f016e22007-07-11 17:01:13 +0000351/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
352/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
353/// multiple tokens. However, the common case is that StringToks points to one
354/// string.
Sebastian Redlcd965b92009-01-18 18:53:16 +0000355///
356Action::OwningExprResult
Steve Narofff69936d2007-09-16 03:34:24 +0000357Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000358 assert(NumStringToks && "Must have at least one string!");
359
Chris Lattnerbbee00b2009-01-16 18:51:42 +0000360 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Reid Spencer5f016e22007-07-11 17:01:13 +0000361 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000362 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +0000363
364 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
365 for (unsigned i = 0; i != NumStringToks; ++i)
366 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000367
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000368 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidis55f4b022008-08-09 17:20:01 +0000369 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000370 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor77a52232008-09-12 00:47:35 +0000371
372 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000373 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings )
Douglas Gregor77a52232008-09-12 00:47:35 +0000374 StrTy.addConst();
Sebastian Redlcd965b92009-01-18 18:53:16 +0000375
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000376 // Get an array type for the string, according to C99 6.4.5. This includes
377 // the nul terminator character as well as the string length for pascal
378 // strings.
379 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerdbb1ecc2009-02-26 23:01:51 +0000380 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000381 ArrayType::Normal, 0);
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Reid Spencer5f016e22007-07-11 17:01:13 +0000383 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump1eb44332009-09-09 15:08:12 +0000384 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattner2085fd62009-02-18 06:40:38 +0000385 Literal.GetStringLength(),
386 Literal.AnyWide, StrTy,
387 &StringTokLocs[0],
388 StringTokLocs.size()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000389}
390
Chris Lattner639e2d32008-10-20 05:16:36 +0000391/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
392/// CurBlock to VD should cause it to be snapshotted (as we do for auto
393/// variables defined outside the block) or false if this is not needed (e.g.
394/// for values inside the block or for globals).
395///
Douglas Gregor076ceb02010-03-01 20:44:28 +0000396/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000397/// up-to-date.
398///
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000399static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
Chris Lattner639e2d32008-10-20 05:16:36 +0000400 ValueDecl *VD) {
401 // If the value is defined inside the block, we couldn't snapshot it even if
402 // we wanted to.
403 if (CurBlock->TheDecl == VD->getDeclContext())
404 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Chris Lattner639e2d32008-10-20 05:16:36 +0000406 // If this is an enum constant or function, it is constant, don't snapshot.
407 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
408 return false;
409
410 // If this is a reference to an extern, static, or global variable, no need to
411 // snapshot it.
412 // FIXME: What about 'const' variables in C++?
413 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000414 if (!Var->hasLocalStorage())
415 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000417 // Blocks that have these can't be constant.
418 CurBlock->hasBlockDeclRefExprs = true;
419
420 // If we have nested blocks, the decl may be declared in an outer block (in
421 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
422 // be defined outside all of the current blocks (in which case the blocks do
423 // all get the bit). Walk the nesting chain.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000424 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
425 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000426
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000427 if (!NextBlock)
428 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000429
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000430 // If we found the defining block for the variable, don't mark the block as
431 // having a reference outside it.
432 if (NextBlock->TheDecl == VD->getDeclContext())
433 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner17f3a6d2009-04-21 22:26:47 +0000435 // Otherwise, the DeclRef from the inner block causes the outer one to need
436 // a snapshot as well.
437 NextBlock->hasBlockDeclRefExprs = true;
438 }
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Chris Lattner639e2d32008-10-20 05:16:36 +0000440 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000441}
442
Chris Lattner639e2d32008-10-20 05:16:36 +0000443
444
Douglas Gregora2813ce2009-10-23 18:54:35 +0000445/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlssone41590d2009-06-24 00:10:43 +0000446Sema::OwningExprResult
John McCalldbd872f2009-12-08 09:08:17 +0000447Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redlebc07d52009-02-03 20:19:35 +0000448 const CXXScopeSpec *SS) {
Anders Carlssone2bb2242009-06-26 19:16:07 +0000449 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
450 Diag(Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000451 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlssone2bb2242009-06-26 19:16:07 +0000452 << D->getDeclName();
453 return ExprError();
454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Anders Carlssone41590d2009-06-24 00:10:43 +0000456 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
457 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
458 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
459 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump1eb44332009-09-09 15:08:12 +0000460 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlssone41590d2009-06-24 00:10:43 +0000461 << D->getIdentifier() << FD->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +0000462 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlssone41590d2009-06-24 00:10:43 +0000463 << D->getIdentifier();
464 return ExprError();
465 }
466 }
467 }
468 }
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Douglas Gregore0762c92009-06-19 23:52:42 +0000470 MarkDeclarationReferenced(Loc, D);
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000472 return Owned(DeclRefExpr::Create(Context,
473 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
474 SS? SS->getRange() : SourceRange(),
Douglas Gregor0da76df2009-11-23 11:41:28 +0000475 D, Loc, Ty));
Douglas Gregor1a49af92009-01-06 05:10:23 +0000476}
477
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000478/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
479/// variable corresponding to the anonymous union or struct whose type
480/// is Record.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000481static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
482 RecordDecl *Record) {
Mike Stump1eb44332009-09-09 15:08:12 +0000483 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000484 "Record must be an anonymous struct or union!");
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Mike Stump390b4cc2009-05-16 07:39:55 +0000486 // FIXME: Once Decls are directly linked together, this will be an O(1)
487 // operation rather than a slow walk through DeclContext's vector (which
488 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000489 DeclContext *Ctx = Record->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +0000490 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000491 DEnd = Ctx->decls_end();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000492 D != DEnd; ++D) {
493 if (*D == Record) {
494 // The object for the anonymous struct/union directly
495 // follows its type in the list of declarations.
496 ++D;
497 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000498 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000499 return *D;
500 }
501 }
502
503 assert(false && "Missing object for anonymous record");
504 return 0;
505}
506
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000507/// \brief Given a field that represents a member of an anonymous
508/// struct/union, build the path from that field's context to the
509/// actual member.
510///
511/// Construct the sequence of field member references we'll have to
512/// perform to get to the field in the anonymous union/struct. The
513/// list of members is built from the field outward, so traverse it
514/// backwards to go from an object in the current context to the field
515/// we found.
516///
517/// \returns The variable from which the field access should begin,
518/// for an anonymous struct/union that is not a member of another
519/// class. Otherwise, returns NULL.
520VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
521 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000522 assert(Field->getDeclContext()->isRecord() &&
523 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
524 && "Field must be stored inside an anonymous struct or union");
525
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000526 Path.push_back(Field);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000527 VarDecl *BaseObject = 0;
528 DeclContext *Ctx = Field->getDeclContext();
529 do {
530 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000531 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000532 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000533 Path.push_back(AnonField);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000534 else {
535 BaseObject = cast<VarDecl>(AnonObject);
536 break;
537 }
538 Ctx = Ctx->getParent();
Mike Stump1eb44332009-09-09 15:08:12 +0000539 } while (Ctx->isRecord() &&
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000540 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000541
542 return BaseObject;
543}
544
545Sema::OwningExprResult
546Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
547 FieldDecl *Field,
548 Expr *BaseObjectExpr,
549 SourceLocation OpLoc) {
550 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump1eb44332009-09-09 15:08:12 +0000551 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregorffb4b6e2009-04-15 06:41:24 +0000552 AnonFields);
553
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000554 // Build the expression that refers to the base object, from
555 // which we will build a sequence of member references to each
556 // of the anonymous union objects and, eventually, the field we
557 // found via name lookup.
558 bool BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000559 Qualifiers BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000560 if (BaseObject) {
561 // BaseObject is an anonymous struct/union variable (and is,
562 // therefore, not part of another non-anonymous record).
Ted Kremenek8189cde2009-02-07 01:47:29 +0000563 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregore0762c92009-06-19 23:52:42 +0000564 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff6ece14c2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stumpeed9cac2009-02-19 03:04:26 +0000566 SourceLocation());
John McCall0953e762009-09-24 19:53:00 +0000567 BaseQuals
568 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000569 } else if (BaseObjectExpr) {
570 // The caller provided the base object expression. Determine
571 // whether its a pointer and whether it adds any qualifiers to the
572 // anonymous struct/union fields we're looking into.
573 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000574 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000575 BaseObjectIsPointer = true;
576 ObjectType = ObjectPtr->getPointeeType();
577 }
John McCall0953e762009-09-24 19:53:00 +0000578 BaseQuals
579 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000580 } else {
581 // We've found a member of an anonymous struct/union that is
582 // inside a non-anonymous struct/union, so in a well-formed
583 // program our base object expression is "this".
584 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
585 if (!MD->isStatic()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000586 QualType AnonFieldType
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000587 = Context.getTagDeclType(
588 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
589 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump1eb44332009-09-09 15:08:12 +0000590 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000591 == Context.getCanonicalType(ThisType)) ||
592 IsDerivedFrom(ThisType, AnonFieldType)) {
593 // Our base object expression is "this".
Douglas Gregor8aa5f402009-12-24 20:23:34 +0000594 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
Douglas Gregor828a1972010-01-07 23:12:05 +0000595 MD->getThisType(Context),
596 /*isImplicit=*/true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000597 BaseObjectIsPointer = true;
598 }
599 } else {
Sebastian Redlcd965b92009-01-18 18:53:16 +0000600 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
601 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000602 }
John McCall0953e762009-09-24 19:53:00 +0000603 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000604 }
605
Mike Stump1eb44332009-09-09 15:08:12 +0000606 if (!BaseObjectExpr)
Sebastian Redlcd965b92009-01-18 18:53:16 +0000607 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
608 << Field->getDeclName());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000609 }
610
611 // Build the implicit member references to the field of the
612 // anonymous struct/union.
613 Expr *Result = BaseObjectExpr;
John McCall0953e762009-09-24 19:53:00 +0000614 Qualifiers ResultQuals = BaseQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000615 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
616 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
617 FI != FIEnd; ++FI) {
618 QualType MemberType = (*FI)->getType();
John McCall0953e762009-09-24 19:53:00 +0000619 Qualifiers MemberTypeQuals =
620 Context.getCanonicalType(MemberType).getQualifiers();
621
622 // CVR attributes from the base are picked up by members,
623 // except that 'mutable' members don't pick up 'const'.
624 if ((*FI)->isMutable())
625 ResultQuals.removeConst();
626
627 // GC attributes are never picked up by members.
628 ResultQuals.removeObjCGCAttr();
629
630 // TR 18037 does not allow fields to be declared with address spaces.
631 assert(!MemberTypeQuals.hasAddressSpace());
632
633 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
634 if (NewQuals != MemberTypeQuals)
635 MemberType = Context.getQualifiedType(MemberType, NewQuals);
636
Douglas Gregore0762c92009-06-19 23:52:42 +0000637 MarkDeclarationReferenced(Loc, *FI);
John McCall6bb80172010-03-30 21:47:33 +0000638 PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +0000639 // FIXME: Might this end up being a qualified name?
Steve Naroff6ece14c2009-01-21 00:14:39 +0000640 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
641 OpLoc, MemberType);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000642 BaseObjectIsPointer = false;
John McCall0953e762009-09-24 19:53:00 +0000643 ResultQuals = NewQuals;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000644 }
645
Sebastian Redlcd965b92009-01-18 18:53:16 +0000646 return Owned(Result);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000647}
648
John McCall129e2df2009-11-30 22:42:35 +0000649/// Decomposes the given name into a DeclarationName, its location, and
650/// possibly a list of template arguments.
651///
652/// If this produces template arguments, it is permitted to call
653/// DecomposeTemplateName.
654///
655/// This actually loses a lot of source location information for
656/// non-standard name kinds; we should consider preserving that in
657/// some way.
658static void DecomposeUnqualifiedId(Sema &SemaRef,
659 const UnqualifiedId &Id,
660 TemplateArgumentListInfo &Buffer,
661 DeclarationName &Name,
662 SourceLocation &NameLoc,
663 const TemplateArgumentListInfo *&TemplateArgs) {
664 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
665 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
666 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
667
668 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
669 Id.TemplateId->getTemplateArgs(),
670 Id.TemplateId->NumArgs);
671 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
672 TemplateArgsPtr.release();
673
674 TemplateName TName =
675 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
676
677 Name = SemaRef.Context.getNameForTemplate(TName);
678 NameLoc = Id.TemplateId->TemplateNameLoc;
679 TemplateArgs = &Buffer;
680 } else {
681 Name = SemaRef.GetNameFromUnqualifiedId(Id);
682 NameLoc = Id.StartLocation;
683 TemplateArgs = 0;
684 }
685}
686
687/// Decompose the given template name into a list of lookup results.
688///
689/// The unqualified ID must name a non-dependent template, which can
690/// be more easily tested by checking whether DecomposeUnqualifiedId
691/// found template arguments.
692static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
693 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
694 TemplateName TName =
695 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
696
John McCallf7a1a742009-11-24 19:00:30 +0000697 if (TemplateDecl *TD = TName.getAsTemplateDecl())
698 R.addDecl(TD);
John McCall0bd6feb2009-12-02 08:04:21 +0000699 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
700 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
701 I != E; ++I)
John McCallf7a1a742009-11-24 19:00:30 +0000702 R.addDecl(*I);
John McCallb681b612009-11-22 02:49:43 +0000703
John McCallf7a1a742009-11-24 19:00:30 +0000704 R.resolveKind();
Douglas Gregor02a24ee2009-11-03 16:56:39 +0000705}
706
John McCall4c72d3e2010-02-08 19:26:07 +0000707/// Determines whether the given record is "fully-formed" at the given
708/// location, i.e. whether a qualified lookup into it is assured of
709/// getting consistent results already.
John McCall129e2df2009-11-30 22:42:35 +0000710static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
John McCall4c72d3e2010-02-08 19:26:07 +0000711 if (!Record->hasDefinition())
712 return false;
713
John McCall129e2df2009-11-30 22:42:35 +0000714 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
715 E = Record->bases_end(); I != E; ++I) {
716 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
717 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
718 if (!BaseRT) return false;
719
720 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall4c72d3e2010-02-08 19:26:07 +0000721 if (!BaseRecord->hasDefinition() ||
John McCall129e2df2009-11-30 22:42:35 +0000722 !IsFullyFormedScope(SemaRef, BaseRecord))
723 return false;
724 }
725
726 return true;
727}
728
John McCalle1599ce2009-11-30 23:50:49 +0000729/// Determines whether we can lookup this id-expression now or whether
730/// we have to wait until template instantiation is complete.
731static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall129e2df2009-11-30 22:42:35 +0000732 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall129e2df2009-11-30 22:42:35 +0000733
John McCalle1599ce2009-11-30 23:50:49 +0000734 // If the qualifier scope isn't computable, it's definitely dependent.
735 if (!DC) return true;
736
737 // If the qualifier scope doesn't name a record, we can always look into it.
738 if (!isa<CXXRecordDecl>(DC)) return false;
739
740 // We can't look into record types unless they're fully-formed.
741 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
742
John McCallaa81e162009-12-01 22:10:20 +0000743 return false;
744}
John McCalle1599ce2009-11-30 23:50:49 +0000745
John McCallaa81e162009-12-01 22:10:20 +0000746/// Determines if the given class is provably not derived from all of
747/// the prospective base classes.
748static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
749 CXXRecordDecl *Record,
750 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCallb1b42562009-12-01 22:28:41 +0000751 if (Bases.count(Record->getCanonicalDecl()))
John McCallaa81e162009-12-01 22:10:20 +0000752 return false;
753
Douglas Gregor952b0172010-02-11 01:04:33 +0000754 RecordDecl *RD = Record->getDefinition();
John McCallb1b42562009-12-01 22:28:41 +0000755 if (!RD) return false;
756 Record = cast<CXXRecordDecl>(RD);
757
John McCallaa81e162009-12-01 22:10:20 +0000758 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
759 E = Record->bases_end(); I != E; ++I) {
760 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
761 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
762 if (!BaseRT) return false;
763
764 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCallaa81e162009-12-01 22:10:20 +0000765 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
766 return false;
767 }
768
769 return true;
770}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000771
John McCall144238e2009-12-02 20:26:00 +0000772/// Determines if this is an instance member of a class.
773static bool IsInstanceMember(NamedDecl *D) {
John McCall3b4294e2009-12-16 12:17:52 +0000774 assert(D->isCXXClassMember() &&
John McCallaa81e162009-12-01 22:10:20 +0000775 "checking whether non-member is instance member");
776
777 if (isa<FieldDecl>(D)) return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000778
John McCallaa81e162009-12-01 22:10:20 +0000779 if (isa<CXXMethodDecl>(D))
780 return !cast<CXXMethodDecl>(D)->isStatic();
781
782 if (isa<FunctionTemplateDecl>(D)) {
783 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
784 return !cast<CXXMethodDecl>(D)->isStatic();
785 }
786
787 return false;
788}
789
790enum IMAKind {
791 /// The reference is definitely not an instance member access.
792 IMA_Static,
793
794 /// The reference may be an implicit instance member access.
795 IMA_Mixed,
796
797 /// The reference may be to an instance member, but it is invalid if
798 /// so, because the context is not an instance method.
799 IMA_Mixed_StaticContext,
800
801 /// The reference may be to an instance member, but it is invalid if
802 /// so, because the context is from an unrelated class.
803 IMA_Mixed_Unrelated,
804
805 /// The reference is definitely an implicit instance member access.
806 IMA_Instance,
807
808 /// The reference may be to an unresolved using declaration.
809 IMA_Unresolved,
810
811 /// The reference may be to an unresolved using declaration and the
812 /// context is not an instance method.
813 IMA_Unresolved_StaticContext,
814
815 /// The reference is to a member of an anonymous structure in a
816 /// non-class context.
817 IMA_AnonymousMember,
818
819 /// All possible referrents are instance members and the current
820 /// context is not an instance method.
821 IMA_Error_StaticContext,
822
823 /// All possible referrents are instance members of an unrelated
824 /// class.
825 IMA_Error_Unrelated
826};
827
828/// The given lookup names class member(s) and is not being used for
829/// an address-of-member expression. Classify the type of access
830/// according to whether it's possible that this reference names an
831/// instance member. This is best-effort; it is okay to
832/// conservatively answer "yes", in which case some errors will simply
833/// not be caught until template-instantiation.
834static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
835 const LookupResult &R) {
John McCall3b4294e2009-12-16 12:17:52 +0000836 assert(!R.empty() && (*R.begin())->isCXXClassMember());
John McCallaa81e162009-12-01 22:10:20 +0000837
838 bool isStaticContext =
839 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
840 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
841
842 if (R.isUnresolvableResult())
843 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
844
845 // Collect all the declaring classes of instance members we find.
846 bool hasNonInstance = false;
847 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
848 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
849 NamedDecl *D = (*I)->getUnderlyingDecl();
850 if (IsInstanceMember(D)) {
851 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
852
853 // If this is a member of an anonymous record, move out to the
854 // innermost non-anonymous struct or union. If there isn't one,
855 // that's a special case.
856 while (R->isAnonymousStructOrUnion()) {
857 R = dyn_cast<CXXRecordDecl>(R->getParent());
858 if (!R) return IMA_AnonymousMember;
859 }
860 Classes.insert(R->getCanonicalDecl());
861 }
862 else
863 hasNonInstance = true;
864 }
865
866 // If we didn't find any instance members, it can't be an implicit
867 // member reference.
868 if (Classes.empty())
869 return IMA_Static;
870
871 // If the current context is not an instance method, it can't be
872 // an implicit member reference.
873 if (isStaticContext)
874 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
875
876 // If we can prove that the current context is unrelated to all the
877 // declaring classes, it can't be an implicit member reference (in
878 // which case it's an error if any of those members are selected).
879 if (IsProvablyNotDerivedFrom(SemaRef,
880 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
881 Classes))
882 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
883
884 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
885}
886
887/// Diagnose a reference to a field with no object available.
888static void DiagnoseInstanceReference(Sema &SemaRef,
889 const CXXScopeSpec &SS,
890 const LookupResult &R) {
891 SourceLocation Loc = R.getNameLoc();
892 SourceRange Range(Loc);
893 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
894
895 if (R.getAsSingle<FieldDecl>()) {
896 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
897 if (MD->isStatic()) {
898 // "invalid use of member 'x' in static member function"
899 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
900 << Range << R.getLookupName();
901 return;
902 }
903 }
904
905 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
906 << R.getLookupName() << Range;
907 return;
908 }
909
910 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall129e2df2009-11-30 22:42:35 +0000911}
912
John McCall578b69b2009-12-16 08:11:27 +0000913/// Diagnose an empty lookup.
914///
915/// \return false if new lookup candidates were found
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000916bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
John McCall578b69b2009-12-16 08:11:27 +0000917 LookupResult &R) {
918 DeclarationName Name = R.getLookupName();
919
John McCall578b69b2009-12-16 08:11:27 +0000920 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000921 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCall578b69b2009-12-16 08:11:27 +0000922 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
923 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000924 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCall578b69b2009-12-16 08:11:27 +0000925 diagnostic = diag::err_undeclared_use;
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000926 diagnostic_suggest = diag::err_undeclared_use_suggest;
927 }
John McCall578b69b2009-12-16 08:11:27 +0000928
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000929 // If the original lookup was an unqualified lookup, fake an
930 // unqualified lookup. This is useful when (for example) the
931 // original lookup would not have found something because it was a
932 // dependent name.
933 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
934 DC; DC = DC->getParent()) {
John McCall578b69b2009-12-16 08:11:27 +0000935 if (isa<CXXRecordDecl>(DC)) {
936 LookupQualifiedName(R, DC);
937
938 if (!R.empty()) {
939 // Don't give errors about ambiguities in this lookup.
940 R.suppressDiagnostics();
941
942 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
943 bool isInstance = CurMethod &&
944 CurMethod->isInstance() &&
945 DC == CurMethod->getParent();
946
947 // Give a code modification hint to insert 'this->'.
948 // TODO: fixit for inserting 'Base<T>::' in the other cases.
949 // Actually quite difficult!
950 if (isInstance)
951 Diag(R.getNameLoc(), diagnostic) << Name
Douglas Gregord0ebe082010-03-31 15:31:50 +0000952 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
John McCall578b69b2009-12-16 08:11:27 +0000953 else
954 Diag(R.getNameLoc(), diagnostic) << Name;
955
956 // Do we really want to note all of these?
957 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
958 Diag((*I)->getLocation(), diag::note_dependent_var_use);
959
960 // Tell the callee to try to recover.
961 return false;
962 }
963 }
964 }
965
Douglas Gregorbb092ba2009-12-31 05:20:13 +0000966 // We didn't find anything, so try to correct for a typo.
Douglas Gregord203a162010-01-01 00:15:04 +0000967 if (S && CorrectTypo(R, S, &SS)) {
968 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
969 if (SS.isEmpty())
970 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
Douglas Gregord0ebe082010-03-31 15:31:50 +0000971 << FixItHint::CreateReplacement(R.getNameLoc(),
972 R.getLookupName().getAsString());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000973 else
Douglas Gregord203a162010-01-01 00:15:04 +0000974 Diag(R.getNameLoc(), diag::err_no_member_suggest)
975 << Name << computeDeclContext(SS, false) << R.getLookupName()
976 << SS.getRange()
Douglas Gregord0ebe082010-03-31 15:31:50 +0000977 << FixItHint::CreateReplacement(R.getNameLoc(),
978 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +0000979 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
980 Diag(ND->getLocation(), diag::note_previous_decl)
981 << ND->getDeclName();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000982
Douglas Gregord203a162010-01-01 00:15:04 +0000983 // Tell the callee to try to recover.
984 return false;
985 }
986
987 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
988 // FIXME: If we ended up with a typo for a type name or
989 // Objective-C class name, we're in trouble because the parser
990 // is in the wrong place to recover. Suggest the typo
991 // correction, but don't make it a fix-it since we're not going
992 // to recover well anyway.
993 if (SS.isEmpty())
994 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000995 else
Douglas Gregord203a162010-01-01 00:15:04 +0000996 Diag(R.getNameLoc(), diag::err_no_member_suggest)
997 << Name << computeDeclContext(SS, false) << R.getLookupName()
998 << SS.getRange();
999
1000 // Don't try to recover; it won't work.
1001 return true;
1002 }
1003
1004 R.clear();
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001005 }
1006
1007 // Emit a special diagnostic for failed member lookups.
1008 // FIXME: computing the declaration context might fail here (?)
1009 if (!SS.isEmpty()) {
1010 Diag(R.getNameLoc(), diag::err_no_member)
1011 << Name << computeDeclContext(SS, false)
1012 << SS.getRange();
1013 return true;
1014 }
1015
John McCall578b69b2009-12-16 08:11:27 +00001016 // Give up, we can't recover.
1017 Diag(R.getNameLoc(), diagnostic) << Name;
1018 return true;
1019}
1020
John McCallf7a1a742009-11-24 19:00:30 +00001021Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
1022 const CXXScopeSpec &SS,
1023 UnqualifiedId &Id,
1024 bool HasTrailingLParen,
1025 bool isAddressOfOperand) {
1026 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1027 "cannot be direct & operand and have a trailing lparen");
1028
1029 if (SS.isInvalid())
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001030 return ExprError();
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001031
John McCall129e2df2009-11-30 22:42:35 +00001032 TemplateArgumentListInfo TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00001033
1034 // Decompose the UnqualifiedId into the following data.
1035 DeclarationName Name;
1036 SourceLocation NameLoc;
1037 const TemplateArgumentListInfo *TemplateArgs;
John McCall129e2df2009-11-30 22:42:35 +00001038 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1039 Name, NameLoc, TemplateArgs);
Douglas Gregor5953d8b2009-03-19 17:26:29 +00001040
Douglas Gregor10c42622008-11-18 15:03:34 +00001041 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCallba135432009-11-21 08:51:07 +00001042
John McCallf7a1a742009-11-24 19:00:30 +00001043 // C++ [temp.dep.expr]p3:
1044 // An id-expression is type-dependent if it contains:
Douglas Gregor48026d22010-01-11 18:40:55 +00001045 // -- an identifier that was declared with a dependent type,
1046 // (note: handled after lookup)
1047 // -- a template-id that is dependent,
1048 // (note: handled in BuildTemplateIdExpr)
1049 // -- a conversion-function-id that specifies a dependent type,
John McCallf7a1a742009-11-24 19:00:30 +00001050 // -- a nested-name-specifier that contains a class-name that
1051 // names a dependent type.
1052 // Determine whether this is a member of an unknown specialization;
1053 // we need to handle these differently.
Douglas Gregor48026d22010-01-11 18:40:55 +00001054 if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1055 Name.getCXXNameType()->isDependentType()) ||
1056 (SS.isSet() && IsDependentIdExpression(*this, SS))) {
John McCallf7a1a742009-11-24 19:00:30 +00001057 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCall2f841ba2009-12-02 03:53:29 +00001058 isAddressOfOperand,
John McCallf7a1a742009-11-24 19:00:30 +00001059 TemplateArgs);
1060 }
John McCallba135432009-11-21 08:51:07 +00001061
John McCallf7a1a742009-11-24 19:00:30 +00001062 // Perform the required lookup.
1063 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1064 if (TemplateArgs) {
John McCallf7a1a742009-11-24 19:00:30 +00001065 // Just re-use the lookup done by isTemplateName.
John McCall129e2df2009-11-30 22:42:35 +00001066 DecomposeTemplateName(R, Id);
John McCallf7a1a742009-11-24 19:00:30 +00001067 } else {
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001068 bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1069 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump1eb44332009-09-09 15:08:12 +00001070
John McCallf7a1a742009-11-24 19:00:30 +00001071 // If this reference is in an Objective-C method, then we need to do
1072 // some special Objective-C lookup, too.
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001073 if (IvarLookupFollowUp) {
1074 OwningExprResult E(LookupInObjCMethod(R, S, II, true));
John McCallf7a1a742009-11-24 19:00:30 +00001075 if (E.isInvalid())
1076 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001077
John McCallf7a1a742009-11-24 19:00:30 +00001078 Expr *Ex = E.takeAs<Expr>();
1079 if (Ex) return Owned(Ex);
Steve Naroffe3e9add2008-06-02 23:03:37 +00001080 }
Chris Lattner8a934232008-03-31 00:36:02 +00001081 }
Douglas Gregorc71e28c2009-02-16 19:28:42 +00001082
John McCallf7a1a742009-11-24 19:00:30 +00001083 if (R.isAmbiguous())
1084 return ExprError();
1085
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001086 // Determine whether this name might be a candidate for
1087 // argument-dependent lookup.
John McCallf7a1a742009-11-24 19:00:30 +00001088 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001089
John McCallf7a1a742009-11-24 19:00:30 +00001090 if (R.empty() && !ADL) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001091 // Otherwise, this could be an implicitly declared function reference (legal
John McCallf7a1a742009-11-24 19:00:30 +00001092 // in C90, extension in C99, forbidden in C++).
1093 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1094 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1095 if (D) R.addDecl(D);
1096 }
1097
1098 // If this name wasn't predeclared and if this is not a function
1099 // call, diagnose the problem.
1100 if (R.empty()) {
Douglas Gregorbb092ba2009-12-31 05:20:13 +00001101 if (DiagnoseEmptyLookup(S, SS, R))
John McCall578b69b2009-12-16 08:11:27 +00001102 return ExprError();
1103
1104 assert(!R.empty() &&
1105 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001106
1107 // If we found an Objective-C instance variable, let
1108 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001109 // reference the ivar.
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001110 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1111 R.clear();
1112 OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1113 assert(E.isInvalid() || E.get());
1114 return move(E);
1115 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001116 }
1117 }
Mike Stump1eb44332009-09-09 15:08:12 +00001118
John McCallf7a1a742009-11-24 19:00:30 +00001119 // This is guaranteed from this point on.
1120 assert(!R.empty() || ADL);
1121
1122 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001123 // Warn about constructs like:
1124 // if (void *X = foo()) { ... } else { X }.
1125 // In the else block, the pointer is always false.
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Douglas Gregor751f9a42009-06-30 15:47:41 +00001127 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1128 Scope *CheckS = S;
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001129 while (CheckS && CheckS->getControlParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001130 if (CheckS->isWithinElse() &&
Douglas Gregor751f9a42009-06-30 15:47:41 +00001131 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCallf7a1a742009-11-24 19:00:30 +00001132 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001133 << Var->getDeclName()
1134 << (Var->getType()->isPointerType()? 2 :
1135 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor751f9a42009-06-30 15:47:41 +00001136 break;
1137 }
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Douglas Gregor9c4b8382009-11-05 17:49:26 +00001139 // Move to the parent of this scope.
1140 CheckS = CheckS->getParent();
Douglas Gregor751f9a42009-06-30 15:47:41 +00001141 }
1142 }
John McCallf7a1a742009-11-24 19:00:30 +00001143 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor751f9a42009-06-30 15:47:41 +00001144 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1145 // C99 DR 316 says that, if a function type comes from a
1146 // function definition (without a prototype), that type is only
1147 // used for checking compatibility. Therefore, when referencing
1148 // the function, we pretend that we don't have the full function
1149 // type.
John McCallf7a1a742009-11-24 19:00:30 +00001150 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor751f9a42009-06-30 15:47:41 +00001151 return ExprError();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001152
Douglas Gregor751f9a42009-06-30 15:47:41 +00001153 QualType T = Func->getType();
1154 QualType NoProtoType = T;
John McCall183700f2009-09-21 23:43:11 +00001155 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor751f9a42009-06-30 15:47:41 +00001156 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCallf7a1a742009-11-24 19:00:30 +00001157 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001158 }
1159 }
Mike Stump1eb44332009-09-09 15:08:12 +00001160
John McCallaa81e162009-12-01 22:10:20 +00001161 // Check whether this might be a C++ implicit instance member access.
1162 // C++ [expr.prim.general]p6:
1163 // Within the definition of a non-static member function, an
1164 // identifier that names a non-static member is transformed to a
1165 // class member access expression.
1166 // But note that &SomeClass::foo is grammatically distinct, even
1167 // though we don't parse it that way.
John McCall3b4294e2009-12-16 12:17:52 +00001168 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCallf7a1a742009-11-24 19:00:30 +00001169 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCall3b4294e2009-12-16 12:17:52 +00001170 if (!isAbstractMemberPointer)
1171 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001172 }
1173
John McCallf7a1a742009-11-24 19:00:30 +00001174 if (TemplateArgs)
1175 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCall5b3f9132009-11-22 01:44:31 +00001176
John McCallf7a1a742009-11-24 19:00:30 +00001177 return BuildDeclarationNameExpr(SS, R, ADL);
1178}
1179
John McCall3b4294e2009-12-16 12:17:52 +00001180/// Builds an expression which might be an implicit member expression.
1181Sema::OwningExprResult
1182Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1183 LookupResult &R,
1184 const TemplateArgumentListInfo *TemplateArgs) {
1185 switch (ClassifyImplicitMemberAccess(*this, R)) {
1186 case IMA_Instance:
1187 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1188
1189 case IMA_AnonymousMember:
1190 assert(R.isSingleResult());
1191 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1192 R.getAsSingle<FieldDecl>());
1193
1194 case IMA_Mixed:
1195 case IMA_Mixed_Unrelated:
1196 case IMA_Unresolved:
1197 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1198
1199 case IMA_Static:
1200 case IMA_Mixed_StaticContext:
1201 case IMA_Unresolved_StaticContext:
1202 if (TemplateArgs)
1203 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1204 return BuildDeclarationNameExpr(SS, R, false);
1205
1206 case IMA_Error_StaticContext:
1207 case IMA_Error_Unrelated:
1208 DiagnoseInstanceReference(*this, SS, R);
1209 return ExprError();
1210 }
1211
1212 llvm_unreachable("unexpected instance member access kind");
1213 return ExprError();
1214}
1215
John McCall129e2df2009-11-30 22:42:35 +00001216/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1217/// declaration name, generally during template instantiation.
1218/// There's a large number of things which don't need to be done along
1219/// this path.
John McCallf7a1a742009-11-24 19:00:30 +00001220Sema::OwningExprResult
1221Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1222 DeclarationName Name,
1223 SourceLocation NameLoc) {
1224 DeclContext *DC;
1225 if (!(DC = computeDeclContext(SS, false)) ||
1226 DC->isDependentContext() ||
1227 RequireCompleteDeclContext(SS))
1228 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1229
1230 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1231 LookupQualifiedName(R, DC);
1232
1233 if (R.isAmbiguous())
1234 return ExprError();
1235
1236 if (R.empty()) {
1237 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1238 return ExprError();
1239 }
1240
1241 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1242}
1243
1244/// LookupInObjCMethod - The parser has read a name in, and Sema has
1245/// detected that we're currently inside an ObjC method. Perform some
1246/// additional lookup.
1247///
1248/// Ideally, most of this would be done by lookup, but there's
1249/// actually quite a lot of extra work involved.
1250///
1251/// Returns a null sentinel to indicate trivial success.
1252Sema::OwningExprResult
1253Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001254 IdentifierInfo *II,
1255 bool AllowBuiltinCreation) {
John McCallf7a1a742009-11-24 19:00:30 +00001256 SourceLocation Loc = Lookup.getNameLoc();
1257
1258 // There are two cases to handle here. 1) scoped lookup could have failed,
1259 // in which case we should look for an ivar. 2) scoped lookup could have
1260 // found a decl, but that decl is outside the current instance method (i.e.
1261 // a global variable). In these two cases, we do a lookup for an ivar with
1262 // this name, if the lookup sucedes, we replace it our current decl.
1263
1264 // If we're in a class method, we don't normally want to look for
1265 // ivars. But if we don't find anything else, and there's an
1266 // ivar, that's an error.
1267 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1268
1269 bool LookForIvars;
1270 if (Lookup.empty())
1271 LookForIvars = true;
1272 else if (IsClassMethod)
1273 LookForIvars = false;
1274 else
1275 LookForIvars = (Lookup.isSingleResult() &&
1276 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001277 ObjCInterfaceDecl *IFace = 0;
John McCallf7a1a742009-11-24 19:00:30 +00001278 if (LookForIvars) {
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001279 IFace = getCurMethodDecl()->getClassInterface();
John McCallf7a1a742009-11-24 19:00:30 +00001280 ObjCInterfaceDecl *ClassDeclared;
1281 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1282 // Diagnose using an ivar in a class method.
1283 if (IsClassMethod)
1284 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1285 << IV->getDeclName());
1286
1287 // If we're referencing an invalid decl, just return this as a silent
1288 // error node. The error diagnostic was already emitted on the decl.
1289 if (IV->isInvalidDecl())
1290 return ExprError();
1291
1292 // Check if referencing a field with __attribute__((deprecated)).
1293 if (DiagnoseUseOfDecl(IV, Loc))
1294 return ExprError();
1295
1296 // Diagnose the use of an ivar outside of the declaring class.
1297 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1298 ClassDeclared != IFace)
1299 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1300
1301 // FIXME: This should use a new expr for a direct reference, don't
1302 // turn this into Self->ivar, just return a BareIVarExpr or something.
1303 IdentifierInfo &II = Context.Idents.get("self");
1304 UnqualifiedId SelfName;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001305 SelfName.setIdentifier(&II, SourceLocation());
John McCallf7a1a742009-11-24 19:00:30 +00001306 CXXScopeSpec SelfScopeSpec;
1307 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1308 SelfName, false, false);
1309 MarkDeclarationReferenced(Loc, IV);
1310 return Owned(new (Context)
1311 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1312 SelfExpr.takeAs<Expr>(), true, true));
1313 }
1314 } else if (getCurMethodDecl()->isInstanceMethod()) {
1315 // We should warn if a local variable hides an ivar.
1316 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1317 ObjCInterfaceDecl *ClassDeclared;
1318 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1319 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1320 IFace == ClassDeclared)
1321 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1322 }
1323 }
1324
1325 // Needed to implement property "super.method" notation.
1326 if (Lookup.empty() && II->isStr("super")) {
1327 QualType T;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001328
John McCallf7a1a742009-11-24 19:00:30 +00001329 if (getCurMethodDecl()->isInstanceMethod())
1330 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1331 getCurMethodDecl()->getClassInterface()));
1332 else
1333 T = Context.getObjCClassType();
1334 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1335 }
Fariborz Jahanian48c2d562010-01-12 23:58:59 +00001336 if (Lookup.empty() && II && AllowBuiltinCreation) {
1337 // FIXME. Consolidate this with similar code in LookupName.
1338 if (unsigned BuiltinID = II->getBuiltinID()) {
1339 if (!(getLangOptions().CPlusPlus &&
1340 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1341 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1342 S, Lookup.isForRedeclaration(),
1343 Lookup.getNameLoc());
1344 if (D) Lookup.addDecl(D);
1345 }
1346 }
1347 }
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001348 if (LangOpts.ObjCNonFragileABI2 && LookForIvars && Lookup.empty()) {
Fariborz Jahanian77e2dde2010-02-09 21:49:50 +00001349 ObjCIvarDecl *Ivar = SynthesizeNewPropertyIvar(IFace, II);
1350 if (Ivar)
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001351 return LookupInObjCMethod(Lookup, S, II, AllowBuiltinCreation);
Fariborz Jahanian412e7982010-02-09 19:31:38 +00001352 }
John McCallf7a1a742009-11-24 19:00:30 +00001353 // Sentinel value saying that we didn't do anything special.
1354 return Owned((Expr*) 0);
Douglas Gregor751f9a42009-06-30 15:47:41 +00001355}
John McCallba135432009-11-21 08:51:07 +00001356
John McCall6bb80172010-03-30 21:47:33 +00001357/// \brief Cast a base object to a member's actual type.
1358///
1359/// Logically this happens in three phases:
1360///
1361/// * First we cast from the base type to the naming class.
1362/// The naming class is the class into which we were looking
1363/// when we found the member; it's the qualifier type if a
1364/// qualifier was provided, and otherwise it's the base type.
1365///
1366/// * Next we cast from the naming class to the declaring class.
1367/// If the member we found was brought into a class's scope by
1368/// a using declaration, this is that class; otherwise it's
1369/// the class declaring the member.
1370///
1371/// * Finally we cast from the declaring class to the "true"
1372/// declaring class of the member. This conversion does not
1373/// obey access control.
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001374bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00001375Sema::PerformObjectMemberConversion(Expr *&From,
1376 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00001377 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00001378 NamedDecl *Member) {
1379 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1380 if (!RD)
1381 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001382
Douglas Gregor5fccd362010-03-03 23:55:11 +00001383 QualType DestRecordType;
1384 QualType DestType;
1385 QualType FromRecordType;
1386 QualType FromType = From->getType();
1387 bool PointerConversions = false;
1388 if (isa<FieldDecl>(Member)) {
1389 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001390
Douglas Gregor5fccd362010-03-03 23:55:11 +00001391 if (FromType->getAs<PointerType>()) {
1392 DestType = Context.getPointerType(DestRecordType);
1393 FromRecordType = FromType->getPointeeType();
1394 PointerConversions = true;
1395 } else {
1396 DestType = DestRecordType;
1397 FromRecordType = FromType;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001398 }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001399 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1400 if (Method->isStatic())
1401 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001402
Douglas Gregor5fccd362010-03-03 23:55:11 +00001403 DestType = Method->getThisType(Context);
1404 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001405
Douglas Gregor5fccd362010-03-03 23:55:11 +00001406 if (FromType->getAs<PointerType>()) {
1407 FromRecordType = FromType->getPointeeType();
1408 PointerConversions = true;
1409 } else {
1410 FromRecordType = FromType;
1411 DestType = DestRecordType;
1412 }
1413 } else {
1414 // No conversion necessary.
1415 return false;
1416 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001417
Douglas Gregor5fccd362010-03-03 23:55:11 +00001418 if (DestType->isDependentType() || FromType->isDependentType())
1419 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001420
Douglas Gregor5fccd362010-03-03 23:55:11 +00001421 // If the unqualified types are the same, no conversion is necessary.
1422 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1423 return false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001424
John McCall6bb80172010-03-30 21:47:33 +00001425 SourceRange FromRange = From->getSourceRange();
1426 SourceLocation FromLoc = FromRange.getBegin();
1427
Douglas Gregor5fccd362010-03-03 23:55:11 +00001428 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001429 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregor5fccd362010-03-03 23:55:11 +00001430 // class name.
1431 //
1432 // If the member was a qualified name and the qualified referred to a
1433 // specific base subobject type, we'll cast to that intermediate type
1434 // first and then to the object in which the member is declared. That allows
1435 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1436 //
1437 // class Base { public: int x; };
1438 // class Derived1 : public Base { };
1439 // class Derived2 : public Base { };
1440 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1441 //
1442 // void VeryDerived::f() {
1443 // x = 17; // error: ambiguous base subobjects
1444 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1445 // }
Douglas Gregor5fccd362010-03-03 23:55:11 +00001446 if (Qualifier) {
John McCall6bb80172010-03-30 21:47:33 +00001447 QualType QType = QualType(Qualifier->getAsType(), 0);
1448 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1449 assert(QType->isRecordType() && "lookup done with non-record type");
1450
1451 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1452
1453 // In C++98, the qualifier type doesn't actually have to be a base
1454 // type of the object type, in which case we just ignore it.
1455 // Otherwise build the appropriate casts.
1456 if (IsDerivedFrom(FromRecordType, QRecordType)) {
1457 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
1458 FromLoc, FromRange))
1459 return true;
1460
Douglas Gregor5fccd362010-03-03 23:55:11 +00001461 if (PointerConversions)
John McCall6bb80172010-03-30 21:47:33 +00001462 QType = Context.getPointerType(QType);
John McCall23cba802010-03-30 23:58:03 +00001463 ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
John McCall6bb80172010-03-30 21:47:33 +00001464 /*isLvalue*/ !PointerConversions);
1465
1466 FromType = QType;
1467 FromRecordType = QRecordType;
1468
1469 // If the qualifier type was the same as the destination type,
1470 // we're done.
1471 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1472 return false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001473 }
1474 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001475
John McCall6bb80172010-03-30 21:47:33 +00001476 bool IgnoreAccess = false;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001477
John McCall6bb80172010-03-30 21:47:33 +00001478 // If we actually found the member through a using declaration, cast
1479 // down to the using declaration's type.
1480 //
1481 // Pointer equality is fine here because only one declaration of a
1482 // class ever has member declarations.
1483 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1484 assert(isa<UsingShadowDecl>(FoundDecl));
1485 QualType URecordType = Context.getTypeDeclType(
1486 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1487
1488 // We only need to do this if the naming-class to declaring-class
1489 // conversion is non-trivial.
1490 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1491 assert(IsDerivedFrom(FromRecordType, URecordType));
1492 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
1493 FromLoc, FromRange))
1494 return true;
1495
1496 QualType UType = URecordType;
1497 if (PointerConversions)
1498 UType = Context.getPointerType(UType);
John McCall23cba802010-03-30 23:58:03 +00001499 ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
John McCall6bb80172010-03-30 21:47:33 +00001500 /*isLvalue*/ !PointerConversions);
1501 FromType = UType;
1502 FromRecordType = URecordType;
1503 }
1504
1505 // We don't do access control for the conversion from the
1506 // declaring class to the true declaring class.
1507 IgnoreAccess = true;
Douglas Gregor5fccd362010-03-03 23:55:11 +00001508 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001509
Douglas Gregor5fccd362010-03-03 23:55:11 +00001510 if (CheckDerivedToBaseConversion(FromRecordType,
1511 DestRecordType,
John McCall6bb80172010-03-30 21:47:33 +00001512 FromLoc,
1513 FromRange,
1514 IgnoreAccess))
Douglas Gregor5fccd362010-03-03 23:55:11 +00001515 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001516
John McCall23cba802010-03-30 23:58:03 +00001517 ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
1518 /*isLvalue=*/ !PointerConversions);
Fariborz Jahanianf3e53d32009-07-29 19:40:11 +00001519 return false;
Fariborz Jahanian98a541e2009-07-29 18:40:24 +00001520}
Douglas Gregor751f9a42009-06-30 15:47:41 +00001521
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001522/// \brief Build a MemberExpr AST node.
Mike Stump1eb44332009-09-09 15:08:12 +00001523static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedmanf595cc42009-12-04 06:40:45 +00001524 const CXXScopeSpec &SS, ValueDecl *Member,
John McCall6bb80172010-03-30 21:47:33 +00001525 NamedDecl *FoundDecl, SourceLocation Loc,
1526 QualType Ty,
John McCallf7a1a742009-11-24 19:00:30 +00001527 const TemplateArgumentListInfo *TemplateArgs = 0) {
1528 NestedNameSpecifier *Qualifier = 0;
1529 SourceRange QualifierRange;
John McCall129e2df2009-11-30 22:42:35 +00001530 if (SS.isSet()) {
1531 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1532 QualifierRange = SS.getRange();
John McCallf7a1a742009-11-24 19:00:30 +00001533 }
Mike Stump1eb44332009-09-09 15:08:12 +00001534
John McCallf7a1a742009-11-24 19:00:30 +00001535 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
John McCall6bb80172010-03-30 21:47:33 +00001536 Member, FoundDecl, Loc, TemplateArgs, Ty);
Douglas Gregorbd4c4ae2009-08-26 22:36:53 +00001537}
1538
John McCallaa81e162009-12-01 22:10:20 +00001539/// Builds an implicit member access expression. The current context
1540/// is known to be an instance method, and the given unqualified lookup
1541/// set is known to contain only instance members, at least one of which
1542/// is from an appropriate type.
John McCall5b3f9132009-11-22 01:44:31 +00001543Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00001544Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1545 LookupResult &R,
1546 const TemplateArgumentListInfo *TemplateArgs,
1547 bool IsKnownInstance) {
John McCallf7a1a742009-11-24 19:00:30 +00001548 assert(!R.empty() && !R.isAmbiguous());
1549
John McCallba135432009-11-21 08:51:07 +00001550 SourceLocation Loc = R.getNameLoc();
Sebastian Redlebc07d52009-02-03 20:19:35 +00001551
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001552 // We may have found a field within an anonymous union or struct
1553 // (C++ [class.union]).
Douglas Gregore961afb2009-10-22 07:08:30 +00001554 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCallf7a1a742009-11-24 19:00:30 +00001555 // FIXME: template-ids inside anonymous structs?
John McCall129e2df2009-11-30 22:42:35 +00001556 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001557 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCall5b3f9132009-11-22 01:44:31 +00001558 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001559
John McCallaa81e162009-12-01 22:10:20 +00001560 // If this is known to be an instance access, go ahead and build a
1561 // 'this' expression now.
1562 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1563 Expr *This = 0; // null signifies implicit access
1564 if (IsKnownInstance) {
Douglas Gregor828a1972010-01-07 23:12:05 +00001565 SourceLocation Loc = R.getNameLoc();
1566 if (SS.getRange().isValid())
1567 Loc = SS.getRange().getBegin();
1568 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
Douglas Gregor88a35142008-12-22 05:46:06 +00001569 }
1570
John McCallaa81e162009-12-01 22:10:20 +00001571 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1572 /*OpLoc*/ SourceLocation(),
1573 /*IsArrow*/ true,
John McCallc2233c52010-01-15 08:34:02 +00001574 SS,
1575 /*FirstQualifierInScope*/ 0,
1576 R, TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00001577}
1578
John McCallf7a1a742009-11-24 19:00:30 +00001579bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001580 const LookupResult &R,
1581 bool HasTrailingLParen) {
John McCallba135432009-11-21 08:51:07 +00001582 // Only when used directly as the postfix-expression of a call.
1583 if (!HasTrailingLParen)
1584 return false;
1585
1586 // Never if a scope specifier was provided.
John McCallf7a1a742009-11-24 19:00:30 +00001587 if (SS.isSet())
John McCallba135432009-11-21 08:51:07 +00001588 return false;
1589
1590 // Only in C++ or ObjC++.
John McCall5b3f9132009-11-22 01:44:31 +00001591 if (!getLangOptions().CPlusPlus)
John McCallba135432009-11-21 08:51:07 +00001592 return false;
1593
1594 // Turn off ADL when we find certain kinds of declarations during
1595 // normal lookup:
1596 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1597 NamedDecl *D = *I;
1598
1599 // C++0x [basic.lookup.argdep]p3:
1600 // -- a declaration of a class member
1601 // Since using decls preserve this property, we check this on the
1602 // original decl.
John McCall3b4294e2009-12-16 12:17:52 +00001603 if (D->isCXXClassMember())
John McCallba135432009-11-21 08:51:07 +00001604 return false;
1605
1606 // C++0x [basic.lookup.argdep]p3:
1607 // -- a block-scope function declaration that is not a
1608 // using-declaration
1609 // NOTE: we also trigger this for function templates (in fact, we
1610 // don't check the decl type at all, since all other decl types
1611 // turn off ADL anyway).
1612 if (isa<UsingShadowDecl>(D))
1613 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1614 else if (D->getDeclContext()->isFunctionOrMethod())
1615 return false;
1616
1617 // C++0x [basic.lookup.argdep]p3:
1618 // -- a declaration that is neither a function or a function
1619 // template
1620 // And also for builtin functions.
1621 if (isa<FunctionDecl>(D)) {
1622 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1623
1624 // But also builtin functions.
1625 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1626 return false;
1627 } else if (!isa<FunctionTemplateDecl>(D))
1628 return false;
1629 }
1630
1631 return true;
1632}
1633
1634
John McCallba135432009-11-21 08:51:07 +00001635/// Diagnoses obvious problems with the use of the given declaration
1636/// as an expression. This is only actually called for lookups that
1637/// were not overloaded, and it doesn't promise that the declaration
1638/// will in fact be used.
1639static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1640 if (isa<TypedefDecl>(D)) {
1641 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1642 return true;
1643 }
1644
1645 if (isa<ObjCInterfaceDecl>(D)) {
1646 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1647 return true;
1648 }
1649
1650 if (isa<NamespaceDecl>(D)) {
1651 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1652 return true;
1653 }
1654
1655 return false;
1656}
1657
1658Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001659Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCall5b3f9132009-11-22 01:44:31 +00001660 LookupResult &R,
1661 bool NeedsADL) {
John McCallfead20c2009-12-08 22:45:53 +00001662 // If this is a single, fully-resolved result and we don't need ADL,
1663 // just build an ordinary singleton decl ref.
Douglas Gregor86b8e092010-01-29 17:15:43 +00001664 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
John McCall5b3f9132009-11-22 01:44:31 +00001665 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCallba135432009-11-21 08:51:07 +00001666
1667 // We only need to check the declaration if there's exactly one
1668 // result, because in the overloaded case the results can only be
1669 // functions and function templates.
John McCall5b3f9132009-11-22 01:44:31 +00001670 if (R.isSingleResult() &&
1671 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCallba135432009-11-21 08:51:07 +00001672 return ExprError();
1673
John McCallc373d482010-01-27 01:50:18 +00001674 // Otherwise, just build an unresolved lookup expression. Suppress
1675 // any lookup-related diagnostics; we'll hash these out later, when
1676 // we've picked a target.
1677 R.suppressDiagnostics();
1678
John McCallf7a1a742009-11-24 19:00:30 +00001679 bool Dependent
1680 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCallba135432009-11-21 08:51:07 +00001681 UnresolvedLookupExpr *ULE
John McCallc373d482010-01-27 01:50:18 +00001682 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
John McCallf7a1a742009-11-24 19:00:30 +00001683 (NestedNameSpecifier*) SS.getScopeRep(),
1684 SS.getRange(),
John McCall5b3f9132009-11-22 01:44:31 +00001685 R.getLookupName(), R.getNameLoc(),
1686 NeedsADL, R.isOverloadedResult());
John McCallc373d482010-01-27 01:50:18 +00001687 ULE->addDecls(R.begin(), R.end());
John McCallba135432009-11-21 08:51:07 +00001688
1689 return Owned(ULE);
1690}
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001691
John McCallba135432009-11-21 08:51:07 +00001692
1693/// \brief Complete semantic analysis for a reference to the given declaration.
1694Sema::OwningExprResult
John McCallf7a1a742009-11-24 19:00:30 +00001695Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallba135432009-11-21 08:51:07 +00001696 SourceLocation Loc, NamedDecl *D) {
1697 assert(D && "Cannot refer to a NULL declaration");
John McCall7453ed42009-11-22 00:44:51 +00001698 assert(!isa<FunctionTemplateDecl>(D) &&
1699 "Cannot refer unambiguously to a function template");
John McCallba135432009-11-21 08:51:07 +00001700
1701 if (CheckDeclInExpr(*this, Loc, D))
1702 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00001703
Douglas Gregor9af2f522009-12-01 16:58:18 +00001704 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1705 // Specifically diagnose references to class templates that are missing
1706 // a template argument list.
1707 Diag(Loc, diag::err_template_decl_ref)
1708 << Template << SS.getRange();
1709 Diag(Template->getLocation(), diag::note_template_decl_here);
1710 return ExprError();
1711 }
1712
1713 // Make sure that we're referring to a value.
1714 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1715 if (!VD) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001716 Diag(Loc, diag::err_ref_non_value)
Douglas Gregor9af2f522009-12-01 16:58:18 +00001717 << D << SS.getRange();
John McCall87cf6702009-12-18 18:35:10 +00001718 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregor9af2f522009-12-01 16:58:18 +00001719 return ExprError();
1720 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001721
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001722 // Check whether this declaration can be used. Note that we suppress
1723 // this check when we're going to perform argument-dependent lookup
1724 // on this function name, because this might not be the function
1725 // that overload resolution actually selects.
John McCallba135432009-11-21 08:51:07 +00001726 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001727 return ExprError();
1728
Steve Naroffdd972f22008-09-05 22:11:13 +00001729 // Only create DeclRefExpr's for valid Decl's.
1730 if (VD->isInvalidDecl())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001731 return ExprError();
1732
Chris Lattner639e2d32008-10-20 05:16:36 +00001733 // If the identifier reference is inside a block, and it refers to a value
1734 // that is outside the block, create a BlockDeclRefExpr instead of a
1735 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1736 // the block is formed.
Steve Naroffdd972f22008-09-05 22:11:13 +00001737 //
Chris Lattner639e2d32008-10-20 05:16:36 +00001738 // We do not do this for things like enum constants, global variables, etc,
1739 // as they do not get snapshotted.
1740 //
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001741 if (getCurBlock() &&
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001742 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
Mike Stump0d6fd572010-01-05 02:56:35 +00001743 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1744 Diag(Loc, diag::err_ref_vm_type);
1745 Diag(D->getLocation(), diag::note_declared_at);
1746 return ExprError();
1747 }
1748
Fariborz Jahanian8596bbe2010-03-16 23:39:51 +00001749 if (VD->getType()->isArrayType()) {
Mike Stump28497342010-01-05 03:10:36 +00001750 Diag(Loc, diag::err_ref_array_type);
1751 Diag(D->getLocation(), diag::note_declared_at);
1752 return ExprError();
1753 }
1754
Douglas Gregore0762c92009-06-19 23:52:42 +00001755 MarkDeclarationReferenced(Loc, VD);
Eli Friedman5fdeae12009-03-22 23:00:19 +00001756 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff090276f2008-10-10 01:28:17 +00001757 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001758 if (VD->getAttr<BlocksAttr>())
Eli Friedman5fdeae12009-03-22 23:00:19 +00001759 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001760 // This is to record that a 'const' was actually synthesize and added.
1761 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff090276f2008-10-10 01:28:17 +00001762 // Variable will be bound by-copy, make it const within the closure.
Mike Stump1eb44332009-09-09 15:08:12 +00001763
Eli Friedman5fdeae12009-03-22 23:00:19 +00001764 ExprTy.addConst();
Mike Stump1eb44332009-09-09 15:08:12 +00001765 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00001766 constAdded));
Steve Naroff090276f2008-10-10 01:28:17 +00001767 }
1768 // If this reference is not in a block or if the referenced variable is
1769 // within the block, create a normal DeclRefExpr.
Douglas Gregor898574e2008-12-05 23:32:09 +00001770
John McCallf7a1a742009-11-24 19:00:30 +00001771 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Reid Spencer5f016e22007-07-11 17:01:13 +00001772}
1773
Sebastian Redlcd965b92009-01-18 18:53:16 +00001774Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1775 tok::TokenKind Kind) {
Chris Lattnerd9f69102008-08-10 01:53:14 +00001776 PredefinedExpr::IdentType IT;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001777
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 switch (Kind) {
Chris Lattner1423ea42008-01-12 18:39:25 +00001779 default: assert(0 && "Unknown simple primary expr!");
Chris Lattnerd9f69102008-08-10 01:53:14 +00001780 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1781 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1782 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 }
Chris Lattner1423ea42008-01-12 18:39:25 +00001784
Chris Lattnerfa28b302008-01-12 08:14:25 +00001785 // Pre-defined identifiers are of type char[x], where x is the length of the
1786 // string.
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Anders Carlsson3a082d82009-09-08 18:24:21 +00001788 Decl *currentDecl = getCurFunctionOrMethodDecl();
1789 if (!currentDecl) {
Chris Lattnerb0da9232008-12-12 05:05:20 +00001790 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson3a082d82009-09-08 18:24:21 +00001791 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerb0da9232008-12-12 05:05:20 +00001792 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001793
Anders Carlsson773f3972009-09-11 01:22:35 +00001794 QualType ResTy;
1795 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1796 ResTy = Context.DependentTy;
1797 } else {
Anders Carlsson848fa642010-02-11 18:20:28 +00001798 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001799
Anders Carlsson773f3972009-09-11 01:22:35 +00001800 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001801 ResTy = Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001802 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1803 }
Steve Naroff6ece14c2009-01-21 00:14:39 +00001804 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Reid Spencer5f016e22007-07-11 17:01:13 +00001805}
1806
Sebastian Redlcd965b92009-01-18 18:53:16 +00001807Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001808 llvm::SmallString<16> CharBuffer;
Douglas Gregor453091c2010-03-16 22:30:13 +00001809 bool Invalid = false;
1810 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1811 if (Invalid)
1812 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001813
Benjamin Kramerddeea562010-02-27 13:44:12 +00001814 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1815 PP);
Reid Spencer5f016e22007-07-11 17:01:13 +00001816 if (Literal.hadError())
Sebastian Redlcd965b92009-01-18 18:53:16 +00001817 return ExprError();
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001818
Chris Lattnere8337df2009-12-30 21:19:39 +00001819 QualType Ty;
1820 if (!getLangOptions().CPlusPlus)
1821 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1822 else if (Literal.isWide())
1823 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
Eli Friedman136b0cd2010-02-03 18:21:45 +00001824 else if (Literal.isMultiChar())
1825 Ty = Context.IntTy; // 'wxyz' -> int in C++.
Chris Lattnere8337df2009-12-30 21:19:39 +00001826 else
1827 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattnerfc62bfd2008-03-01 08:32:21 +00001828
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001829 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1830 Literal.isWide(),
Chris Lattnere8337df2009-12-30 21:19:39 +00001831 Ty, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001832}
1833
Sebastian Redlcd965b92009-01-18 18:53:16 +00001834Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1835 // Fast path for a single digit (which is quite common). A single digit
Reid Spencer5f016e22007-07-11 17:01:13 +00001836 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1837 if (Tok.getLength() == 1) {
Chris Lattner7216dc92009-01-26 22:36:52 +00001838 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattner0c21e842009-01-16 07:10:29 +00001839 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff6ece14c2009-01-21 00:14:39 +00001840 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff0a473932009-01-20 19:53:53 +00001841 Context.IntTy, Tok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +00001842 }
Ted Kremenek28396602009-01-13 23:19:12 +00001843
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 llvm::SmallString<512> IntegerBuffer;
Chris Lattner2a299042008-09-30 20:53:45 +00001845 // Add padding so that NumericLiteralParser can overread by one character.
1846 IntegerBuffer.resize(Tok.getLength()+1);
Reid Spencer5f016e22007-07-11 17:01:13 +00001847 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd965b92009-01-18 18:53:16 +00001848
Reid Spencer5f016e22007-07-11 17:01:13 +00001849 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregor453091c2010-03-16 22:30:13 +00001850 bool Invalid = false;
1851 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1852 if (Invalid)
1853 return ExprError();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001854
Mike Stump1eb44332009-09-09 15:08:12 +00001855 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Reid Spencer5f016e22007-07-11 17:01:13 +00001856 Tok.getLocation(), PP);
1857 if (Literal.hadError)
Sebastian Redlcd965b92009-01-18 18:53:16 +00001858 return ExprError();
1859
Chris Lattner5d661452007-08-26 03:42:43 +00001860 Expr *Res;
Sebastian Redlcd965b92009-01-18 18:53:16 +00001861
Chris Lattner5d661452007-08-26 03:42:43 +00001862 if (Literal.isFloatingLiteral()) {
Chris Lattner525a0502007-09-22 18:29:59 +00001863 QualType Ty;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001864 if (Literal.isFloat)
Chris Lattner525a0502007-09-22 18:29:59 +00001865 Ty = Context.FloatTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001866 else if (!Literal.isLong)
Chris Lattner525a0502007-09-22 18:29:59 +00001867 Ty = Context.DoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001868 else
Chris Lattner9e9b6dc2008-03-08 08:52:55 +00001869 Ty = Context.LongDoubleTy;
Chris Lattnerb7cfe882008-06-30 18:32:54 +00001870
1871 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1872
John McCall94c939d2009-12-24 09:08:04 +00001873 using llvm::APFloat;
1874 APFloat Val(Format);
1875
1876 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall9f2df882009-12-24 11:09:08 +00001877
1878 // Overflow is always an error, but underflow is only an error if
1879 // we underflowed to zero (APFloat reports denormals as underflow).
1880 if ((result & APFloat::opOverflow) ||
1881 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall94c939d2009-12-24 09:08:04 +00001882 unsigned diagnostic;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00001883 llvm::SmallString<20> buffer;
John McCall94c939d2009-12-24 09:08:04 +00001884 if (result & APFloat::opOverflow) {
John McCall2a0d7572010-02-26 23:35:57 +00001885 diagnostic = diag::warn_float_overflow;
John McCall94c939d2009-12-24 09:08:04 +00001886 APFloat::getLargest(Format).toString(buffer);
1887 } else {
John McCall2a0d7572010-02-26 23:35:57 +00001888 diagnostic = diag::warn_float_underflow;
John McCall94c939d2009-12-24 09:08:04 +00001889 APFloat::getSmallest(Format).toString(buffer);
1890 }
1891
1892 Diag(Tok.getLocation(), diagnostic)
1893 << Ty
1894 << llvm::StringRef(buffer.data(), buffer.size());
1895 }
1896
1897 bool isExact = (result == APFloat::opOK);
Chris Lattner001d64d2009-06-29 17:34:55 +00001898 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd965b92009-01-18 18:53:16 +00001899
Chris Lattner5d661452007-08-26 03:42:43 +00001900 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd965b92009-01-18 18:53:16 +00001901 return ExprError();
Chris Lattner5d661452007-08-26 03:42:43 +00001902 } else {
Chris Lattnerf0467b32008-04-02 04:24:33 +00001903 QualType Ty;
Reid Spencer5f016e22007-07-11 17:01:13 +00001904
Neil Boothb9449512007-08-29 22:00:19 +00001905 // long long is a C99 feature.
1906 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth79859c32007-08-29 22:13:52 +00001907 Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +00001908 Diag(Tok.getLocation(), diag::ext_longlong);
1909
Reid Spencer5f016e22007-07-11 17:01:13 +00001910 // Get the value in the widest-possible width.
Chris Lattner98be4942008-03-05 18:54:05 +00001911 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd965b92009-01-18 18:53:16 +00001912
Reid Spencer5f016e22007-07-11 17:01:13 +00001913 if (Literal.GetIntegerValue(ResultVal)) {
1914 // If this value didn't fit into uintmax_t, warn and force to ull.
1915 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001916 Ty = Context.UnsignedLongLongTy;
1917 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner98be4942008-03-05 18:54:05 +00001918 "long long is not intmax_t?");
Reid Spencer5f016e22007-07-11 17:01:13 +00001919 } else {
1920 // If this value fits into a ULL, try to figure out what else it fits into
1921 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd965b92009-01-18 18:53:16 +00001922
Reid Spencer5f016e22007-07-11 17:01:13 +00001923 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1924 // be an unsigned int.
1925 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1926
1927 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001928 unsigned Width = 0;
Chris Lattner97c51562007-08-23 21:58:08 +00001929 if (!Literal.isLong && !Literal.isLongLong) {
1930 // Are int/unsigned possibilities?
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001931 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001932
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 // Does it fit in a unsigned int?
1934 if (ResultVal.isIntN(IntSize)) {
1935 // Does it fit in a signed int?
1936 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001937 Ty = Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001938 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001939 Ty = Context.UnsignedIntTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001940 Width = IntSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001942 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001943
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 // Are long/unsigned long possibilities?
Chris Lattnerf0467b32008-04-02 04:24:33 +00001945 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001946 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001947
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 // Does it fit in a unsigned long?
1949 if (ResultVal.isIntN(LongSize)) {
1950 // Does it fit in a signed long?
1951 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001952 Ty = Context.LongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001953 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001954 Ty = Context.UnsignedLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001955 Width = LongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001956 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001957 }
1958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959 // Finally, check long long if needed.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001960 if (Ty.isNull()) {
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001961 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd965b92009-01-18 18:53:16 +00001962
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 // Does it fit in a unsigned long long?
1964 if (ResultVal.isIntN(LongLongSize)) {
1965 // Does it fit in a signed long long?
1966 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001967 Ty = Context.LongLongTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00001968 else if (AllowUnsigned)
Chris Lattnerf0467b32008-04-02 04:24:33 +00001969 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001970 Width = LongLongSize;
Reid Spencer5f016e22007-07-11 17:01:13 +00001971 }
1972 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001973
Reid Spencer5f016e22007-07-11 17:01:13 +00001974 // If we still couldn't decide a type, we probably have something that
1975 // does not fit in a signed long long, but has no U suffix.
Chris Lattnerf0467b32008-04-02 04:24:33 +00001976 if (Ty.isNull()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattnerf0467b32008-04-02 04:24:33 +00001978 Ty = Context.UnsignedLongLongTy;
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001979 Width = Context.Target.getLongLongWidth();
Reid Spencer5f016e22007-07-11 17:01:13 +00001980 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001981
Chris Lattner8cbcb0e2008-05-09 05:59:00 +00001982 if (ResultVal.getBitWidth() != Width)
1983 ResultVal.trunc(Width);
Reid Spencer5f016e22007-07-11 17:01:13 +00001984 }
Sebastian Redle91b3bc2009-01-20 22:23:13 +00001985 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00001986 }
Sebastian Redlcd965b92009-01-18 18:53:16 +00001987
Chris Lattner5d661452007-08-26 03:42:43 +00001988 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1989 if (Literal.isImaginary)
Mike Stump1eb44332009-09-09 15:08:12 +00001990 Res = new (Context) ImaginaryLiteral(Res,
Steve Naroff6ece14c2009-01-21 00:14:39 +00001991 Context.getComplexType(Res->getType()));
Sebastian Redlcd965b92009-01-18 18:53:16 +00001992
1993 return Owned(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001994}
1995
Sebastian Redlcd965b92009-01-18 18:53:16 +00001996Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1997 SourceLocation R, ExprArg Val) {
Anders Carlssone9146f22009-05-01 19:49:17 +00001998 Expr *E = Val.takeAs<Expr>();
Chris Lattnerf0467b32008-04-02 04:24:33 +00001999 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff6ece14c2009-01-21 00:14:39 +00002000 return Owned(new (Context) ParenExpr(L, R, E));
Reid Spencer5f016e22007-07-11 17:01:13 +00002001}
2002
2003/// The UsualUnaryConversions() function is *not* called by this routine.
2004/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl28507842009-02-26 14:39:58 +00002005bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl05189992008-11-11 17:56:53 +00002006 SourceLocation OpLoc,
2007 const SourceRange &ExprRange,
2008 bool isSizeof) {
Sebastian Redl28507842009-02-26 14:39:58 +00002009 if (exprType->isDependentType())
2010 return false;
2011
Sebastian Redl5d484e82009-11-23 17:18:46 +00002012 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2013 // the result is the size of the referenced type."
2014 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2015 // result shall be the alignment of the referenced type."
2016 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2017 exprType = Ref->getPointeeType();
2018
Reid Spencer5f016e22007-07-11 17:01:13 +00002019 // C99 6.5.3.4p1:
John McCall5ab75172009-11-04 07:28:41 +00002020 if (exprType->isFunctionType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002021 // alignof(function) is allowed as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002022 if (isSizeof)
2023 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2024 return false;
2025 }
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Chris Lattner1efaa952009-04-24 00:30:45 +00002027 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner01072922009-01-24 19:46:37 +00002028 if (exprType->isVoidType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002029 Diag(OpLoc, diag::ext_sizeof_void_type)
2030 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner01072922009-01-24 19:46:37 +00002031 return false;
2032 }
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Chris Lattner1efaa952009-04-24 00:30:45 +00002034 if (RequireCompleteType(OpLoc, exprType,
Douglas Gregor5cc07df2009-12-15 16:44:32 +00002035 PDiag(diag::err_sizeof_alignof_incomplete_type)
2036 << int(!isSizeof) << ExprRange))
Chris Lattner1efaa952009-04-24 00:30:45 +00002037 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Chris Lattner1efaa952009-04-24 00:30:45 +00002039 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianced1e282009-04-24 17:34:33 +00002040 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner1efaa952009-04-24 00:30:45 +00002041 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattner5cb10d32009-04-24 22:30:50 +00002042 << exprType << isSizeof << ExprRange;
2043 return true;
Chris Lattnerca790922009-04-21 19:55:16 +00002044 }
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Chris Lattner1efaa952009-04-24 00:30:45 +00002046 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +00002047}
2048
Chris Lattner31e21e02009-01-24 20:17:12 +00002049bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2050 const SourceRange &ExprRange) {
2051 E = E->IgnoreParens();
Sebastian Redl28507842009-02-26 14:39:58 +00002052
Mike Stump1eb44332009-09-09 15:08:12 +00002053 // alignof decl is always ok.
Chris Lattner31e21e02009-01-24 20:17:12 +00002054 if (isa<DeclRefExpr>(E))
2055 return false;
Sebastian Redl28507842009-02-26 14:39:58 +00002056
2057 // Cannot know anything else if the expression is dependent.
2058 if (E->isTypeDependent())
2059 return false;
2060
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002061 if (E->getBitField()) {
2062 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2063 return true;
Chris Lattner31e21e02009-01-24 20:17:12 +00002064 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002065
2066 // Alignment of a field access is always okay, so long as it isn't a
2067 // bit-field.
2068 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump8e1fab22009-07-22 18:58:19 +00002069 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002070 return false;
2071
Chris Lattner31e21e02009-01-24 20:17:12 +00002072 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2073}
2074
Douglas Gregorba498172009-03-13 21:01:28 +00002075/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002076Action::OwningExprResult
John McCalla93c9342009-12-07 02:54:59 +00002077Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall5ab75172009-11-04 07:28:41 +00002078 SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002079 bool isSizeOf, SourceRange R) {
John McCalla93c9342009-12-07 02:54:59 +00002080 if (!TInfo)
Douglas Gregorba498172009-03-13 21:01:28 +00002081 return ExprError();
2082
John McCalla93c9342009-12-07 02:54:59 +00002083 QualType T = TInfo->getType();
John McCall5ab75172009-11-04 07:28:41 +00002084
Douglas Gregorba498172009-03-13 21:01:28 +00002085 if (!T->isDependentType() &&
2086 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2087 return ExprError();
2088
2089 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCalla93c9342009-12-07 02:54:59 +00002090 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregorba498172009-03-13 21:01:28 +00002091 Context.getSizeType(), OpLoc,
2092 R.getEnd()));
2093}
2094
2095/// \brief Build a sizeof or alignof expression given an expression
2096/// operand.
Mike Stump1eb44332009-09-09 15:08:12 +00002097Action::OwningExprResult
2098Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregorba498172009-03-13 21:01:28 +00002099 bool isSizeOf, SourceRange R) {
2100 // Verify that the operand is valid.
2101 bool isInvalid = false;
2102 if (E->isTypeDependent()) {
2103 // Delay type-checking for type-dependent expressions.
2104 } else if (!isSizeOf) {
2105 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor33bbbc52009-05-02 02:18:30 +00002106 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregorba498172009-03-13 21:01:28 +00002107 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2108 isInvalid = true;
2109 } else {
2110 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2111 }
2112
2113 if (isInvalid)
2114 return ExprError();
2115
2116 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2117 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2118 Context.getSizeType(), OpLoc,
2119 R.getEnd()));
2120}
2121
Sebastian Redl05189992008-11-11 17:56:53 +00002122/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2123/// the same for @c alignof and @c __alignof
2124/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002125Action::OwningExprResult
Sebastian Redl05189992008-11-11 17:56:53 +00002126Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2127 void *TyOrEx, const SourceRange &ArgRange) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 // If error parsing type, ignore.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002129 if (TyOrEx == 0) return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00002130
Sebastian Redl05189992008-11-11 17:56:53 +00002131 if (isType) {
John McCalla93c9342009-12-07 02:54:59 +00002132 TypeSourceInfo *TInfo;
2133 (void) GetTypeFromParser(TyOrEx, &TInfo);
2134 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump1eb44332009-09-09 15:08:12 +00002135 }
Sebastian Redl05189992008-11-11 17:56:53 +00002136
Douglas Gregorba498172009-03-13 21:01:28 +00002137 Expr *ArgEx = (Expr *)TyOrEx;
2138 Action::OwningExprResult Result
2139 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2140
2141 if (Result.isInvalid())
2142 DeleteExpr(ArgEx);
2143
2144 return move(Result);
Reid Spencer5f016e22007-07-11 17:01:13 +00002145}
2146
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002147QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl28507842009-02-26 14:39:58 +00002148 if (V->isTypeDependent())
2149 return Context.DependentTy;
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Chris Lattnercc26ed72007-08-26 05:39:26 +00002151 // These operators return the element type of a complex type.
John McCall183700f2009-09-21 23:43:11 +00002152 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattnerdbb36972007-08-24 21:16:53 +00002153 return CT->getElementType();
Mike Stump1eb44332009-09-09 15:08:12 +00002154
Chris Lattnercc26ed72007-08-26 05:39:26 +00002155 // Otherwise they pass through real integer and floating point types here.
2156 if (V->getType()->isArithmeticType())
2157 return V->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Chris Lattnercc26ed72007-08-26 05:39:26 +00002159 // Reject anything else.
Chris Lattnerba27e2a2009-02-17 08:12:06 +00002160 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2161 << (isReal ? "__real" : "__imag");
Chris Lattnercc26ed72007-08-26 05:39:26 +00002162 return QualType();
Chris Lattnerdbb36972007-08-24 21:16:53 +00002163}
2164
2165
Reid Spencer5f016e22007-07-11 17:01:13 +00002166
Sebastian Redl0eb23302009-01-19 00:08:26 +00002167Action::OwningExprResult
2168Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2169 tok::TokenKind Kind, ExprArg Input) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 UnaryOperator::Opcode Opc;
2171 switch (Kind) {
2172 default: assert(0 && "Unknown unary op!");
2173 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
2174 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2175 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00002176
Eli Friedmane4216e92009-11-18 03:38:04 +00002177 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Reid Spencer5f016e22007-07-11 17:01:13 +00002178}
2179
Sebastian Redl0eb23302009-01-19 00:08:26 +00002180Action::OwningExprResult
2181Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2182 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00002183 // Since this might be a postfix expression, get rid of ParenListExprs.
2184 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2185
Sebastian Redl0eb23302009-01-19 00:08:26 +00002186 Expr *LHSExp = static_cast<Expr*>(Base.get()),
2187 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Douglas Gregor337c6b92008-11-19 17:17:41 +00002189 if (getLangOptions().CPlusPlus &&
Douglas Gregor3384c9c2009-05-19 00:01:19 +00002190 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2191 Base.release();
2192 Idx.release();
2193 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2194 Context.DependentTy, RLoc));
2195 }
2196
Mike Stump1eb44332009-09-09 15:08:12 +00002197 if (getLangOptions().CPlusPlus &&
Sebastian Redl0eb23302009-01-19 00:08:26 +00002198 (LHSExp->getType()->isRecordType() ||
Eli Friedman03f332a2008-12-15 22:34:21 +00002199 LHSExp->getType()->isEnumeralType() ||
2200 RHSExp->getType()->isRecordType() ||
2201 RHSExp->getType()->isEnumeralType())) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00002202 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor337c6b92008-11-19 17:17:41 +00002203 }
2204
Sebastian Redlf322ed62009-10-29 20:17:01 +00002205 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2206}
2207
2208
2209Action::OwningExprResult
2210Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2211 ExprArg Idx, SourceLocation RLoc) {
2212 Expr *LHSExp = static_cast<Expr*>(Base.get());
2213 Expr *RHSExp = static_cast<Expr*>(Idx.get());
2214
Chris Lattner12d9ff62007-07-16 00:14:47 +00002215 // Perform default conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00002216 if (!LHSExp->getType()->getAs<VectorType>())
2217 DefaultFunctionArrayLvalueConversion(LHSExp);
2218 DefaultFunctionArrayLvalueConversion(RHSExp);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002219
Chris Lattner12d9ff62007-07-16 00:14:47 +00002220 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002221
Reid Spencer5f016e22007-07-11 17:01:13 +00002222 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner73d0d4f2007-08-30 17:45:32 +00002223 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stumpeed9cac2009-02-19 03:04:26 +00002224 // in the subscript position. As a result, we need to derive the array base
Reid Spencer5f016e22007-07-11 17:01:13 +00002225 // and index from the expression types.
Chris Lattner12d9ff62007-07-16 00:14:47 +00002226 Expr *BaseExpr, *IndexExpr;
2227 QualType ResultType;
Sebastian Redl28507842009-02-26 14:39:58 +00002228 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2229 BaseExpr = LHSExp;
2230 IndexExpr = RHSExp;
2231 ResultType = Context.DependentTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00002232 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner12d9ff62007-07-16 00:14:47 +00002233 BaseExpr = LHSExp;
2234 IndexExpr = RHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002235 ResultType = PTy->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002236 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner7a2e0472007-07-16 00:23:25 +00002237 // Handle the uncommon case of "123[Ptr]".
Chris Lattner12d9ff62007-07-16 00:14:47 +00002238 BaseExpr = RHSExp;
2239 IndexExpr = LHSExp;
Chris Lattner12d9ff62007-07-16 00:14:47 +00002240 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002241 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002242 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002243 BaseExpr = LHSExp;
2244 IndexExpr = RHSExp;
2245 ResultType = PTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002246 } else if (const ObjCObjectPointerType *PTy =
John McCall183700f2009-09-21 23:43:11 +00002247 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002248 // Handle the uncommon case of "123[Ptr]".
2249 BaseExpr = RHSExp;
2250 IndexExpr = LHSExp;
2251 ResultType = PTy->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00002252 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattnerc8629632007-07-31 19:29:30 +00002253 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner12d9ff62007-07-16 00:14:47 +00002254 IndexExpr = RHSExp;
Nate Begeman334a8022009-01-18 00:45:31 +00002255
Chris Lattner12d9ff62007-07-16 00:14:47 +00002256 // FIXME: need to deal with const...
2257 ResultType = VTy->getElementType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002258 } else if (LHSTy->isArrayType()) {
2259 // If we see an array that wasn't promoted by
Douglas Gregora873dfc2010-02-03 00:27:59 +00002260 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002261 // wasn't promoted because of the C90 rule that doesn't
2262 // allow promoting non-lvalue arrays. Warn, then
2263 // force the promotion here.
2264 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2265 LHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002266 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2267 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002268 LHSTy = LHSExp->getType();
2269
2270 BaseExpr = LHSExp;
2271 IndexExpr = RHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002272 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002273 } else if (RHSTy->isArrayType()) {
2274 // Same as previous, except for 123[f().a] case
2275 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2276 RHSExp->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00002277 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2278 CastExpr::CK_ArrayToPointerDecay);
Eli Friedman7c32f8e2009-04-25 23:46:54 +00002279 RHSTy = RHSExp->getType();
2280
2281 BaseExpr = RHSExp;
2282 IndexExpr = LHSExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00002283 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 } else {
Chris Lattner338395d2009-04-25 22:50:55 +00002285 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2286 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00002287 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002288 // C99 6.5.2.1p1
Nate Begeman2ef13e52009-08-10 23:49:36 +00002289 if (!(IndexExpr->getType()->isIntegerType() &&
2290 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner338395d2009-04-25 22:50:55 +00002291 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2292 << IndexExpr->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00002293
Daniel Dunbar7e88a602009-09-17 06:31:17 +00002294 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinig0f9a5b52009-09-14 20:14:57 +00002295 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2296 && !IndexExpr->isTypeDependent())
Sam Weinig76e2b712009-09-14 01:58:58 +00002297 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2298
Douglas Gregore7450f52009-03-24 19:52:54 +00002299 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump1eb44332009-09-09 15:08:12 +00002300 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2301 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregore7450f52009-03-24 19:52:54 +00002302 // incomplete types are not object types.
2303 if (ResultType->isFunctionType()) {
2304 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2305 << ResultType << BaseExpr->getSourceRange();
2306 return ExprError();
2307 }
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Douglas Gregore7450f52009-03-24 19:52:54 +00002309 if (!ResultType->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00002310 RequireCompleteType(LLoc, ResultType,
Anders Carlssonb7906612009-08-26 23:45:07 +00002311 PDiag(diag::err_subscript_incomplete_type)
2312 << BaseExpr->getSourceRange()))
Douglas Gregore7450f52009-03-24 19:52:54 +00002313 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Chris Lattner1efaa952009-04-24 00:30:45 +00002315 // Diagnose bad cases where we step over interface counts.
2316 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2317 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2318 << ResultType << BaseExpr->getSourceRange();
2319 return ExprError();
2320 }
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Sebastian Redl0eb23302009-01-19 00:08:26 +00002322 Base.release();
2323 Idx.release();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002324 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff6ece14c2009-01-21 00:14:39 +00002325 ResultType, RLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002326}
2327
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002328QualType Sema::
Nate Begeman213541a2008-04-18 23:10:10 +00002329CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00002330 const IdentifierInfo *CompName,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002331 SourceLocation CompLoc) {
Daniel Dunbar2ad32892009-10-18 02:09:38 +00002332 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2333 // see FIXME there.
2334 //
2335 // FIXME: This logic can be greatly simplified by splitting it along
2336 // halving/not halving and reworking the component checking.
John McCall183700f2009-09-21 23:43:11 +00002337 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begeman8a997642008-05-09 06:41:27 +00002338
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002339 // The vector accessor can't exceed the number of elements.
Daniel Dunbare013d682009-10-18 20:26:12 +00002340 const char *compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002341
Mike Stumpeed9cac2009-02-19 03:04:26 +00002342 // This flag determines whether or not the component is one of the four
Nate Begeman353417a2009-01-18 01:47:54 +00002343 // special names that indicate a subset of exactly half the elements are
2344 // to be selected.
2345 bool HalvingSwizzle = false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00002346
Nate Begeman353417a2009-01-18 01:47:54 +00002347 // This flag determines whether or not CompName has an 's' char prefix,
2348 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman131f4652009-06-25 21:06:09 +00002349 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begeman8a997642008-05-09 06:41:27 +00002350
2351 // Check that we've found one of the special components, or that the component
2352 // names must come from the same set.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002353 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman353417a2009-01-18 01:47:54 +00002354 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2355 HalvingSwizzle = true;
Nate Begeman8a997642008-05-09 06:41:27 +00002356 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002357 do
2358 compStr++;
2359 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman353417a2009-01-18 01:47:54 +00002360 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner88dca042007-08-02 22:33:49 +00002361 do
2362 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002363 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner88dca042007-08-02 22:33:49 +00002364 }
Nate Begeman353417a2009-01-18 01:47:54 +00002365
Mike Stumpeed9cac2009-02-19 03:04:26 +00002366 if (!HalvingSwizzle && *compStr) {
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002367 // We didn't get to the end of the string. This means the component names
2368 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002369 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2370 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002371 return QualType();
2372 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00002373
Nate Begeman353417a2009-01-18 01:47:54 +00002374 // Ensure no component accessor exceeds the width of the vector type it
2375 // operates on.
2376 if (!HalvingSwizzle) {
Daniel Dunbare013d682009-10-18 20:26:12 +00002377 compStr = CompName->getNameStart();
Nate Begeman353417a2009-01-18 01:47:54 +00002378
2379 if (HexSwizzle)
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002380 compStr++;
Nate Begeman353417a2009-01-18 01:47:54 +00002381
2382 while (*compStr) {
2383 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2384 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2385 << baseType << SourceRange(CompLoc);
2386 return QualType();
2387 }
2388 }
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002389 }
Nate Begeman8a997642008-05-09 06:41:27 +00002390
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002391 // The component accessor looks fine - now we need to compute the actual type.
Mike Stumpeed9cac2009-02-19 03:04:26 +00002392 // The vector type is implied by the component accessor. For example,
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002393 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman353417a2009-01-18 01:47:54 +00002394 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begeman8a997642008-05-09 06:41:27 +00002395 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman0479a0b2009-12-15 18:13:04 +00002396 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
Anders Carlsson8f28f992009-08-26 18:25:21 +00002397 : CompName->getLength();
Nate Begeman353417a2009-01-18 01:47:54 +00002398 if (HexSwizzle)
2399 CompSize--;
2400
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002401 if (CompSize == 1)
2402 return vecType->getElementType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00002403
Nate Begeman213541a2008-04-18 23:10:10 +00002404 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stumpeed9cac2009-02-19 03:04:26 +00002405 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begeman213541a2008-04-18 23:10:10 +00002406 // diagostics look bad. We want extended vector types to appear built-in.
2407 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2408 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2409 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffbea0b342007-07-29 16:33:31 +00002410 }
2411 return VT; // should never get here (a typedef type should always be found).
Steve Naroffe1b31fe2007-07-27 22:15:19 +00002412}
2413
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002414static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002415 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002416 const Selector &Sel,
2417 ASTContext &Context) {
Mike Stump1eb44332009-09-09 15:08:12 +00002418
Anders Carlsson8f28f992009-08-26 18:25:21 +00002419 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002420 return PD;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002421 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002422 return OMD;
Mike Stump1eb44332009-09-09 15:08:12 +00002423
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002424 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2425 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump1eb44332009-09-09 15:08:12 +00002426 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002427 Context))
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002428 return D;
2429 }
2430 return 0;
2431}
2432
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002433static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlsson8f28f992009-08-26 18:25:21 +00002434 IdentifierInfo *Member,
Douglas Gregor6ab35242009-04-09 21:40:53 +00002435 const Selector &Sel,
2436 ASTContext &Context) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002437 // Check protocols on qualified interfaces.
2438 Decl *GDecl = 0;
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002439 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002440 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00002441 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002442 GDecl = PD;
2443 break;
2444 }
2445 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002446 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002447 GDecl = OMD;
2448 break;
2449 }
2450 }
2451 if (!GDecl) {
Steve Naroffd1b3c2d2009-06-17 22:40:22 +00002452 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002453 E = QIdTy->qual_end(); I != E; ++I) {
2454 // Search in the protocol-qualifier list of current protocol.
Douglas Gregor6ab35242009-04-09 21:40:53 +00002455 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian2ce1be02009-03-19 18:15:34 +00002456 if (GDecl)
2457 return GDecl;
2458 }
2459 }
2460 return GDecl;
2461}
Chris Lattner76a642f2009-02-15 22:43:40 +00002462
John McCall129e2df2009-11-30 22:42:35 +00002463Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002464Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2465 bool IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002466 const CXXScopeSpec &SS,
2467 NamedDecl *FirstQualifierInScope,
2468 DeclarationName Name, SourceLocation NameLoc,
2469 const TemplateArgumentListInfo *TemplateArgs) {
2470 Expr *BaseExpr = Base.takeAs<Expr>();
2471
2472 // Even in dependent contexts, try to diagnose base expressions with
2473 // obviously wrong types, e.g.:
2474 //
2475 // T* t;
2476 // t.f;
2477 //
2478 // In Obj-C++, however, the above expression is valid, since it could be
2479 // accessing the 'f' property if T is an Obj-C interface. The extra check
2480 // allows this, while still reporting an error if T is a struct pointer.
2481 if (!IsArrow) {
John McCallaa81e162009-12-01 22:10:20 +00002482 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall129e2df2009-11-30 22:42:35 +00002483 if (PT && (!getLangOptions().ObjC1 ||
2484 PT->getPointeeType()->isRecordType())) {
John McCallaa81e162009-12-01 22:10:20 +00002485 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall129e2df2009-11-30 22:42:35 +00002486 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCallaa81e162009-12-01 22:10:20 +00002487 << BaseType << BaseExpr->getSourceRange();
John McCall129e2df2009-11-30 22:42:35 +00002488 return ExprError();
2489 }
2490 }
2491
Douglas Gregor48026d22010-01-11 18:40:55 +00002492 assert(BaseType->isDependentType() || Name.isDependentName());
John McCall129e2df2009-11-30 22:42:35 +00002493
2494 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2495 // must have pointer type, and the accessed type is the pointee.
John McCallaa81e162009-12-01 22:10:20 +00002496 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002497 IsArrow, OpLoc,
2498 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2499 SS.getRange(),
2500 FirstQualifierInScope,
2501 Name, NameLoc,
2502 TemplateArgs));
2503}
2504
2505/// We know that the given qualified member reference points only to
2506/// declarations which do not belong to the static type of the base
2507/// expression. Diagnose the problem.
2508static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2509 Expr *BaseExpr,
2510 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002511 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002512 const LookupResult &R) {
John McCall2f841ba2009-12-02 03:53:29 +00002513 // If this is an implicit member access, use a different set of
2514 // diagnostics.
2515 if (!BaseExpr)
2516 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall129e2df2009-11-30 22:42:35 +00002517
2518 // FIXME: this is an exceedingly lame diagnostic for some of the more
2519 // complicated cases here.
John McCall2f841ba2009-12-02 03:53:29 +00002520 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall129e2df2009-11-30 22:42:35 +00002521 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCall2f841ba2009-12-02 03:53:29 +00002522 << SS.getRange() << DC << BaseType;
John McCall129e2df2009-11-30 22:42:35 +00002523}
2524
2525// Check whether the declarations we found through a nested-name
2526// specifier in a member expression are actually members of the base
2527// type. The restriction here is:
2528//
2529// C++ [expr.ref]p2:
2530// ... In these cases, the id-expression shall name a
2531// member of the class or of one of its base classes.
2532//
2533// So it's perfectly legitimate for the nested-name specifier to name
2534// an unrelated class, and for us to find an overload set including
2535// decls from classes which are not superclasses, as long as the decl
2536// we actually pick through overload resolution is from a superclass.
2537bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2538 QualType BaseType,
John McCall2f841ba2009-12-02 03:53:29 +00002539 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002540 const LookupResult &R) {
John McCallaa81e162009-12-01 22:10:20 +00002541 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2542 if (!BaseRT) {
2543 // We can't check this yet because the base type is still
2544 // dependent.
2545 assert(BaseType->isDependentType());
2546 return false;
2547 }
2548 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall129e2df2009-11-30 22:42:35 +00002549
2550 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCallaa81e162009-12-01 22:10:20 +00002551 // If this is an implicit member reference and we find a
2552 // non-instance member, it's not an error.
2553 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2554 return false;
John McCall129e2df2009-11-30 22:42:35 +00002555
John McCallaa81e162009-12-01 22:10:20 +00002556 // Note that we use the DC of the decl, not the underlying decl.
2557 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2558 while (RecordD->isAnonymousStructOrUnion())
2559 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2560
2561 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2562 MemberRecord.insert(RecordD->getCanonicalDecl());
2563
2564 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2565 return false;
2566 }
2567
John McCall2f841ba2009-12-02 03:53:29 +00002568 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCallaa81e162009-12-01 22:10:20 +00002569 return true;
2570}
2571
2572static bool
2573LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2574 SourceRange BaseRange, const RecordType *RTy,
2575 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2576 RecordDecl *RDecl = RTy->getDecl();
2577 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00002578 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
John McCallaa81e162009-12-01 22:10:20 +00002579 << BaseRange))
2580 return true;
2581
2582 DeclContext *DC = RDecl;
2583 if (SS.isSet()) {
2584 // If the member name was a qualified-id, look into the
2585 // nested-name-specifier.
2586 DC = SemaRef.computeDeclContext(SS, false);
2587
John McCall2f841ba2009-12-02 03:53:29 +00002588 if (SemaRef.RequireCompleteDeclContext(SS)) {
2589 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2590 << SS.getRange() << DC;
2591 return true;
2592 }
2593
John McCallaa81e162009-12-01 22:10:20 +00002594 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002595
John McCallaa81e162009-12-01 22:10:20 +00002596 if (!isa<TypeDecl>(DC)) {
2597 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2598 << DC << SS.getRange();
2599 return true;
John McCall129e2df2009-11-30 22:42:35 +00002600 }
2601 }
2602
John McCallaa81e162009-12-01 22:10:20 +00002603 // The record definition is complete, now look up the member.
2604 SemaRef.LookupQualifiedName(R, DC);
John McCall129e2df2009-11-30 22:42:35 +00002605
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002606 if (!R.empty())
2607 return false;
2608
2609 // We didn't find anything with the given name, so try to correct
2610 // for typos.
2611 DeclarationName Name = R.getLookupName();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002612 if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002613 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2614 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2615 << Name << DC << R.getLookupName() << SS.getRange()
Douglas Gregord0ebe082010-03-31 15:31:50 +00002616 << FixItHint::CreateReplacement(R.getNameLoc(),
2617 R.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00002618 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2619 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2620 << ND->getDeclName();
Douglas Gregor2dcc0112009-12-31 07:42:17 +00002621 return false;
2622 } else {
2623 R.clear();
2624 }
2625
John McCall129e2df2009-11-30 22:42:35 +00002626 return false;
2627}
2628
2629Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002630Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002631 SourceLocation OpLoc, bool IsArrow,
2632 const CXXScopeSpec &SS,
2633 NamedDecl *FirstQualifierInScope,
2634 DeclarationName Name, SourceLocation NameLoc,
2635 const TemplateArgumentListInfo *TemplateArgs) {
2636 Expr *Base = BaseArg.takeAs<Expr>();
2637
John McCall2f841ba2009-12-02 03:53:29 +00002638 if (BaseType->isDependentType() ||
2639 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCallaa81e162009-12-01 22:10:20 +00002640 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall129e2df2009-11-30 22:42:35 +00002641 IsArrow, OpLoc,
2642 SS, FirstQualifierInScope,
2643 Name, NameLoc,
2644 TemplateArgs);
2645
2646 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall129e2df2009-11-30 22:42:35 +00002647
John McCallaa81e162009-12-01 22:10:20 +00002648 // Implicit member accesses.
2649 if (!Base) {
2650 QualType RecordTy = BaseType;
2651 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2652 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2653 RecordTy->getAs<RecordType>(),
2654 OpLoc, SS))
2655 return ExprError();
2656
2657 // Explicit member accesses.
2658 } else {
2659 OwningExprResult Result =
2660 LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCallc2233c52010-01-15 08:34:02 +00002661 SS, /*ObjCImpDecl*/ DeclPtrTy());
John McCallaa81e162009-12-01 22:10:20 +00002662
2663 if (Result.isInvalid()) {
2664 Owned(Base);
2665 return ExprError();
2666 }
2667
2668 if (Result.get())
2669 return move(Result);
John McCall129e2df2009-11-30 22:42:35 +00002670 }
2671
John McCallaa81e162009-12-01 22:10:20 +00002672 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
John McCallc2233c52010-01-15 08:34:02 +00002673 OpLoc, IsArrow, SS, FirstQualifierInScope,
2674 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002675}
2676
2677Sema::OwningExprResult
John McCallaa81e162009-12-01 22:10:20 +00002678Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2679 SourceLocation OpLoc, bool IsArrow,
2680 const CXXScopeSpec &SS,
John McCallc2233c52010-01-15 08:34:02 +00002681 NamedDecl *FirstQualifierInScope,
John McCall129e2df2009-11-30 22:42:35 +00002682 LookupResult &R,
2683 const TemplateArgumentListInfo *TemplateArgs) {
2684 Expr *BaseExpr = Base.takeAs<Expr>();
John McCallaa81e162009-12-01 22:10:20 +00002685 QualType BaseType = BaseExprType;
John McCall129e2df2009-11-30 22:42:35 +00002686 if (IsArrow) {
2687 assert(BaseType->isPointerType());
2688 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2689 }
2690
2691 NestedNameSpecifier *Qualifier =
2692 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2693 DeclarationName MemberName = R.getLookupName();
2694 SourceLocation MemberLoc = R.getNameLoc();
2695
2696 if (R.isAmbiguous())
Douglas Gregorfe85ced2009-08-06 03:17:00 +00002697 return ExprError();
2698
John McCall129e2df2009-11-30 22:42:35 +00002699 if (R.empty()) {
2700 // Rederive where we looked up.
2701 DeclContext *DC = (SS.isSet()
2702 ? computeDeclContext(SS, false)
2703 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman2ef13e52009-08-10 23:49:36 +00002704
John McCall129e2df2009-11-30 22:42:35 +00002705 Diag(R.getNameLoc(), diag::err_no_member)
John McCallaa81e162009-12-01 22:10:20 +00002706 << MemberName << DC
2707 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall129e2df2009-11-30 22:42:35 +00002708 return ExprError();
2709 }
2710
John McCallc2233c52010-01-15 08:34:02 +00002711 // Diagnose lookups that find only declarations from a non-base
2712 // type. This is possible for either qualified lookups (which may
2713 // have been qualified with an unrelated type) or implicit member
2714 // expressions (which were found with unqualified lookup and thus
2715 // may have come from an enclosing scope). Note that it's okay for
2716 // lookup to find declarations from a non-base type as long as those
2717 // aren't the ones picked by overload resolution.
2718 if ((SS.isSet() || !BaseExpr ||
2719 (isa<CXXThisExpr>(BaseExpr) &&
2720 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
2721 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall129e2df2009-11-30 22:42:35 +00002722 return ExprError();
2723
2724 // Construct an unresolved result if we in fact got an unresolved
2725 // result.
2726 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCallaa81e162009-12-01 22:10:20 +00002727 bool Dependent =
John McCall410a3f32009-12-19 02:05:44 +00002728 BaseExprType->isDependentType() ||
John McCallaa81e162009-12-01 22:10:20 +00002729 R.isUnresolvableResult() ||
John McCall7bb12da2010-02-02 06:20:04 +00002730 OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00002731
John McCallc373d482010-01-27 01:50:18 +00002732 // Suppress any lookup-related diagnostics; we'll do these when we
2733 // pick a member.
2734 R.suppressDiagnostics();
2735
John McCall129e2df2009-11-30 22:42:35 +00002736 UnresolvedMemberExpr *MemExpr
2737 = UnresolvedMemberExpr::Create(Context, Dependent,
2738 R.isUnresolvableResult(),
John McCallaa81e162009-12-01 22:10:20 +00002739 BaseExpr, BaseExprType,
2740 IsArrow, OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002741 Qualifier, SS.getRange(),
2742 MemberName, MemberLoc,
2743 TemplateArgs);
John McCallc373d482010-01-27 01:50:18 +00002744 MemExpr->addDecls(R.begin(), R.end());
John McCall129e2df2009-11-30 22:42:35 +00002745
2746 return Owned(MemExpr);
2747 }
2748
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002749 assert(R.isSingleResult());
John McCall6bb80172010-03-30 21:47:33 +00002750 NamedDecl *FoundDecl = *R.begin();
John McCall129e2df2009-11-30 22:42:35 +00002751 NamedDecl *MemberDecl = R.getFoundDecl();
2752
2753 // FIXME: diagnose the presence of template arguments now.
2754
2755 // If the decl being referenced had an error, return an error for this
2756 // sub-expr without emitting another error, in order to avoid cascading
2757 // error cases.
2758 if (MemberDecl->isInvalidDecl())
2759 return ExprError();
2760
John McCallaa81e162009-12-01 22:10:20 +00002761 // Handle the implicit-member-access case.
2762 if (!BaseExpr) {
2763 // If this is not an instance member, convert to a non-member access.
2764 if (!IsInstanceMember(MemberDecl))
2765 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2766
Douglas Gregor828a1972010-01-07 23:12:05 +00002767 SourceLocation Loc = R.getNameLoc();
2768 if (SS.getRange().isValid())
2769 Loc = SS.getRange().getBegin();
2770 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
John McCallaa81e162009-12-01 22:10:20 +00002771 }
2772
John McCall129e2df2009-11-30 22:42:35 +00002773 bool ShouldCheckUse = true;
2774 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2775 // Don't diagnose the use of a virtual member function unless it's
2776 // explicitly qualified.
2777 if (MD->isVirtual() && !SS.isSet())
2778 ShouldCheckUse = false;
2779 }
2780
2781 // Check the use of this member.
2782 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2783 Owned(BaseExpr);
2784 return ExprError();
2785 }
2786
2787 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2788 // We may have found a field within an anonymous union or struct
2789 // (C++ [class.union]).
Eli Friedman16c53782009-12-04 07:18:51 +00002790 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2791 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall129e2df2009-11-30 22:42:35 +00002792 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2793 BaseExpr, OpLoc);
2794
2795 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2796 QualType MemberType = FD->getType();
2797 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2798 MemberType = Ref->getPointeeType();
2799 else {
2800 Qualifiers BaseQuals = BaseType.getQualifiers();
2801 BaseQuals.removeObjCGCAttr();
2802 if (FD->isMutable()) BaseQuals.removeConst();
2803
2804 Qualifiers MemberQuals
2805 = Context.getCanonicalType(MemberType).getQualifiers();
2806
2807 Qualifiers Combined = BaseQuals + MemberQuals;
2808 if (Combined != MemberQuals)
2809 MemberType = Context.getQualifiedType(MemberType, Combined);
2810 }
2811
2812 MarkDeclarationReferenced(MemberLoc, FD);
John McCall6bb80172010-03-30 21:47:33 +00002813 if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
John McCall129e2df2009-11-30 22:42:35 +00002814 return ExprError();
2815 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002816 FD, FoundDecl, MemberLoc, MemberType));
John McCall129e2df2009-11-30 22:42:35 +00002817 }
2818
2819 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2820 MarkDeclarationReferenced(MemberLoc, Var);
2821 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002822 Var, FoundDecl, MemberLoc,
John McCall129e2df2009-11-30 22:42:35 +00002823 Var->getType().getNonReferenceType()));
2824 }
2825
2826 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2827 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2828 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002829 MemberFn, FoundDecl, MemberLoc,
John McCall129e2df2009-11-30 22:42:35 +00002830 MemberFn->getType()));
2831 }
2832
2833 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2834 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2835 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
John McCall6bb80172010-03-30 21:47:33 +00002836 Enum, FoundDecl, MemberLoc, Enum->getType()));
John McCall129e2df2009-11-30 22:42:35 +00002837 }
2838
2839 Owned(BaseExpr);
2840
2841 if (isa<TypeDecl>(MemberDecl))
2842 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2843 << MemberName << int(IsArrow));
2844
2845 // We found a declaration kind that we didn't expect. This is a
2846 // generic error message that tells the user that she can't refer
2847 // to this member with '.' or '->'.
2848 return ExprError(Diag(MemberLoc,
2849 diag::err_typecheck_member_reference_unknown)
2850 << MemberName << int(IsArrow));
2851}
2852
2853/// Look up the given member of the given non-type-dependent
2854/// expression. This can return in one of two ways:
2855/// * If it returns a sentinel null-but-valid result, the caller will
2856/// assume that lookup was performed and the results written into
2857/// the provided structure. It will take over from there.
2858/// * Otherwise, the returned expression will be produced in place of
2859/// an ordinary member expression.
2860///
2861/// The ObjCImpDecl bit is a gross hack that will need to be properly
2862/// fixed for ObjC++.
2863Sema::OwningExprResult
2864Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
John McCall812c1542009-12-07 22:46:59 +00002865 bool &IsArrow, SourceLocation OpLoc,
John McCall129e2df2009-11-30 22:42:35 +00002866 const CXXScopeSpec &SS,
John McCall129e2df2009-11-30 22:42:35 +00002867 DeclPtrTy ObjCImpDecl) {
Douglas Gregora71d8192009-09-04 17:36:40 +00002868 assert(BaseExpr && "no base expression");
Mike Stump1eb44332009-09-09 15:08:12 +00002869
Steve Naroff3cc4af82007-12-16 21:42:28 +00002870 // Perform default conversions.
2871 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl0eb23302009-01-19 00:08:26 +00002872
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002873 QualType BaseType = BaseExpr->getType();
John McCall129e2df2009-11-30 22:42:35 +00002874 assert(!BaseType->isDependentType());
2875
2876 DeclarationName MemberName = R.getLookupName();
2877 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002878
2879 // If the user is trying to apply -> or . to a function pointer
John McCall129e2df2009-11-30 22:42:35 +00002880 // type, it's probably because they forgot parentheses to call that
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002881 // function. Suggest the addition of those parentheses, build the
2882 // call, and continue on.
2883 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2884 if (const FunctionProtoType *Fun
2885 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2886 QualType ResultTy = Fun->getResultType();
2887 if (Fun->getNumArgs() == 0 &&
John McCall129e2df2009-11-30 22:42:35 +00002888 ((!IsArrow && ResultTy->isRecordType()) ||
2889 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002890 ResultTy->getAs<PointerType>()->getPointeeType()
2891 ->isRecordType()))) {
2892 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2893 Diag(Loc, diag::err_member_reference_needs_call)
2894 << QualType(Fun, 0)
Douglas Gregord0ebe082010-03-31 15:31:50 +00002895 << FixItHint::CreateInsertion(Loc, "()");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002896
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002897 OwningExprResult NewBase
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002898 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002899 MultiExprArg(*this, 0, 0), 0, Loc);
2900 if (NewBase.isInvalid())
John McCall129e2df2009-11-30 22:42:35 +00002901 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002902
Douglas Gregor3f0b5fd2009-11-06 06:30:47 +00002903 BaseExpr = NewBase.takeAs<Expr>();
2904 DefaultFunctionArrayConversion(BaseExpr);
2905 BaseType = BaseExpr->getType();
2906 }
2907 }
2908 }
2909
David Chisnall0f436562009-08-17 16:35:33 +00002910 // If this is an Objective-C pseudo-builtin and a definition is provided then
2911 // use that.
2912 if (BaseType->isObjCIdType()) {
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002913 if (IsArrow) {
2914 // Handle the following exceptional case PObj->isa.
2915 if (const ObjCObjectPointerType *OPT =
2916 BaseType->getAs<ObjCObjectPointerType>()) {
2917 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2918 MemberName.getAsIdentifierInfo()->isStr("isa"))
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00002919 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2920 Context.getObjCClassType()));
Fariborz Jahanian6d910f02009-12-07 20:09:25 +00002921 }
2922 }
David Chisnall0f436562009-08-17 16:35:33 +00002923 // We have an 'id' type. Rather than fall through, we check if this
2924 // is a reference to 'isa'.
2925 if (BaseType != Context.ObjCIdRedefinitionType) {
2926 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002927 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall0f436562009-08-17 16:35:33 +00002928 }
David Chisnall0f436562009-08-17 16:35:33 +00002929 }
John McCall129e2df2009-11-30 22:42:35 +00002930
Fariborz Jahanian369a3bd2009-11-25 23:07:42 +00002931 // If this is an Objective-C pseudo-builtin and a definition is provided then
2932 // use that.
2933 if (Context.isObjCSelType(BaseType)) {
2934 // We have an 'SEL' type. Rather than fall through, we check if this
2935 // is a reference to 'sel_id'.
2936 if (BaseType != Context.ObjCSelRedefinitionType) {
2937 BaseType = Context.ObjCSelRedefinitionType;
2938 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2939 }
2940 }
John McCall129e2df2009-11-30 22:42:35 +00002941
Steve Naroffdfa6aae2007-07-26 03:11:44 +00002942 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl0eb23302009-01-19 00:08:26 +00002943
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002944 // Handle properties on ObjC 'Class' types.
John McCall129e2df2009-11-30 22:42:35 +00002945 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002946 // Also must look for a getter name which uses property syntax.
2947 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2948 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2949 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2950 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2951 ObjCMethodDecl *Getter;
2952 // FIXME: need to also look locally in the implementation.
2953 if ((Getter = IFace->lookupClassMethod(Sel))) {
2954 // Check the use of this method.
2955 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2956 return ExprError();
2957 }
2958 // If we found a getter then this may be a valid dot-reference, we
2959 // will look for the matching setter, in case it is needed.
2960 Selector SetterSel =
2961 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2962 PP.getSelectorTable(), Member);
2963 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2964 if (!Setter) {
2965 // If this reference is in an @implementation, also check for 'private'
2966 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00002967 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002968 }
2969 // Look through local category implementations associated with the class.
2970 if (!Setter)
2971 Setter = IFace->getCategoryClassMethod(SetterSel);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002972
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002973 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2974 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002975
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002976 if (Getter || Setter) {
2977 QualType PType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002978
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002979 if (Getter)
2980 PType = Getter->getResultType();
2981 else
2982 // Get the expression type from Setter's incoming parameter.
2983 PType = (*(Setter->param_end() -1))->getType();
2984 // FIXME: we must check that the setter has property type.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002985 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002986 PType,
2987 Setter, MemberLoc, BaseExpr));
2988 }
2989 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2990 << MemberName << BaseType);
2991 }
2992 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00002993
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002994 if (BaseType->isObjCClassType() &&
2995 BaseType != Context.ObjCClassRedefinitionType) {
2996 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman73c39ab2009-10-20 08:27:19 +00002997 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahanianb2ef1be2009-09-22 16:48:37 +00002998 }
Mike Stump1eb44332009-09-09 15:08:12 +00002999
John McCall129e2df2009-11-30 22:42:35 +00003000 if (IsArrow) {
3001 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroffdfa6aae2007-07-26 03:11:44 +00003002 BaseType = PT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00003003 else if (BaseType->isObjCObjectPointerType())
3004 ;
John McCall812c1542009-12-07 22:46:59 +00003005 else if (BaseType->isRecordType()) {
3006 // Recover from arrow accesses to records, e.g.:
3007 // struct MyRecord foo;
3008 // foo->bar
3009 // This is actually well-formed in C++ if MyRecord has an
3010 // overloaded operator->, but that should have been dealt with
3011 // by now.
3012 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3013 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregord0ebe082010-03-31 15:31:50 +00003014 << FixItHint::CreateReplacement(OpLoc, ".");
John McCall812c1542009-12-07 22:46:59 +00003015 IsArrow = false;
3016 } else {
John McCall129e2df2009-11-30 22:42:35 +00003017 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3018 << BaseType << BaseExpr->getSourceRange();
3019 return ExprError();
Anders Carlsson4ef27702009-05-16 20:31:20 +00003020 }
John McCall812c1542009-12-07 22:46:59 +00003021 } else {
3022 // Recover from dot accesses to pointers, e.g.:
3023 // type *foo;
3024 // foo.bar
3025 // This is actually well-formed in two cases:
3026 // - 'type' is an Objective C type
3027 // - 'bar' is a pseudo-destructor name which happens to refer to
3028 // the appropriate pointer type
3029 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3030 const PointerType *PT = BaseType->getAs<PointerType>();
3031 if (PT && PT->getPointeeType()->isRecordType()) {
3032 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3033 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
Douglas Gregord0ebe082010-03-31 15:31:50 +00003034 << FixItHint::CreateReplacement(OpLoc, "->");
John McCall812c1542009-12-07 22:46:59 +00003035 BaseType = PT->getPointeeType();
3036 IsArrow = true;
3037 }
3038 }
John McCall129e2df2009-11-30 22:42:35 +00003039 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003040
John McCall129e2df2009-11-30 22:42:35 +00003041 // Handle field access to simple records. This also handles access
3042 // to fields of the ObjC 'id' struct.
Ted Kremenek6217b802009-07-29 21:53:49 +00003043 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCallaa81e162009-12-01 22:10:20 +00003044 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3045 RTy, OpLoc, SS))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003046 return ExprError();
John McCall129e2df2009-11-30 22:42:35 +00003047 return Owned((Expr*) 0);
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003048 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003049
Chris Lattnera38e6b12008-07-21 04:59:05 +00003050 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3051 // (*Obj).ivar.
John McCall129e2df2009-11-30 22:42:35 +00003052 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3053 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall183700f2009-09-21 23:43:11 +00003054 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00003055 const ObjCInterfaceType *IFaceT =
John McCall183700f2009-09-21 23:43:11 +00003056 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffc70e8d92009-07-16 00:25:06 +00003057 if (IFaceT) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003058 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3059
Steve Naroffc70e8d92009-07-16 00:25:06 +00003060 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
3061 ObjCInterfaceDecl *ClassDeclared;
Anders Carlsson8f28f992009-08-26 18:25:21 +00003062 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump1eb44332009-09-09 15:08:12 +00003063
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003064 if (!IV) {
3065 // Attempt to correct for typos in ivar names.
3066 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3067 LookupMemberName);
3068 if (CorrectTypo(Res, 0, 0, IDecl) &&
3069 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003070 Diag(R.getNameLoc(),
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003071 diag::err_typecheck_member_reference_ivar_suggest)
3072 << IDecl->getDeclName() << MemberName << IV->getDeclName()
Douglas Gregord0ebe082010-03-31 15:31:50 +00003073 << FixItHint::CreateReplacement(R.getNameLoc(),
3074 IV->getNameAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003075 Diag(IV->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003076 << IV->getDeclName();
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003077 }
3078 }
3079
Steve Naroffc70e8d92009-07-16 00:25:06 +00003080 if (IV) {
3081 // If the decl being referenced had an error, return an error for this
3082 // sub-expr without emitting another error, in order to avoid cascading
3083 // error cases.
3084 if (IV->isInvalidDecl())
3085 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003086
Steve Naroffc70e8d92009-07-16 00:25:06 +00003087 // Check whether we can reference this field.
3088 if (DiagnoseUseOfDecl(IV, MemberLoc))
3089 return ExprError();
3090 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3091 IV->getAccessControl() != ObjCIvarDecl::Package) {
3092 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3093 if (ObjCMethodDecl *MD = getCurMethodDecl())
3094 ClassOfMethodDecl = MD->getClassInterface();
3095 else if (ObjCImpDecl && getCurFunctionDecl()) {
3096 // Case of a c-function declared inside an objc implementation.
3097 // FIXME: For a c-style function nested inside an objc implementation
3098 // class, there is no implementation context available, so we pass
3099 // down the context as argument to this routine. Ideally, this context
3100 // need be passed down in the AST node and somehow calculated from the
3101 // AST for a function decl.
3102 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump1eb44332009-09-09 15:08:12 +00003103 if (ObjCImplementationDecl *IMPD =
Steve Naroffc70e8d92009-07-16 00:25:06 +00003104 dyn_cast<ObjCImplementationDecl>(ImplDecl))
3105 ClassOfMethodDecl = IMPD->getClassInterface();
3106 else if (ObjCCategoryImplDecl* CatImplClass =
3107 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
3108 ClassOfMethodDecl = CatImplClass->getClassInterface();
3109 }
Mike Stump1eb44332009-09-09 15:08:12 +00003110
3111 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3112 if (ClassDeclared != IDecl ||
Steve Naroffc70e8d92009-07-16 00:25:06 +00003113 ClassOfMethodDecl != ClassDeclared)
Mike Stump1eb44332009-09-09 15:08:12 +00003114 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003115 << IV->getDeclName();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003116 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3117 // @protected
Mike Stump1eb44332009-09-09 15:08:12 +00003118 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffc70e8d92009-07-16 00:25:06 +00003119 << IV->getDeclName();
Steve Naroffb06d8752009-03-04 18:34:24 +00003120 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003121
3122 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3123 MemberLoc, BaseExpr,
John McCall129e2df2009-11-30 22:42:35 +00003124 IsArrow));
Fariborz Jahanian935fd762009-03-03 01:21:12 +00003125 }
Steve Naroffc70e8d92009-07-16 00:25:06 +00003126 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003127 << IDecl->getDeclName() << MemberName
Steve Naroffc70e8d92009-07-16 00:25:06 +00003128 << BaseExpr->getSourceRange());
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +00003129 }
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003130 }
Steve Naroffde2e22d2009-07-15 18:40:39 +00003131 // Handle properties on 'id' and qualified "id".
John McCall129e2df2009-11-30 22:42:35 +00003132 if (!IsArrow && (BaseType->isObjCIdType() ||
3133 BaseType->isObjCQualifiedIdType())) {
John McCall183700f2009-09-21 23:43:11 +00003134 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003135 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Steve Naroff14108da2009-07-10 23:34:53 +00003137 // Check protocols on qualified interfaces.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003138 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff14108da2009-07-10 23:34:53 +00003139 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3140 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3141 // Check the use of this declaration
3142 if (DiagnoseUseOfDecl(PD, MemberLoc))
3143 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003144
Steve Naroff14108da2009-07-10 23:34:53 +00003145 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3146 MemberLoc, BaseExpr));
3147 }
3148 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3149 // Check the use of this method.
3150 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3151 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003152
Ted Kremenekeb3b3242010-02-11 22:41:21 +00003153 return Owned(new (Context) ObjCMessageExpr(Context, BaseExpr, Sel,
Mike Stump1eb44332009-09-09 15:08:12 +00003154 OMD->getResultType(),
3155 OMD, OpLoc, MemberLoc,
Steve Naroff14108da2009-07-10 23:34:53 +00003156 NULL, 0));
3157 }
3158 }
Sebastian Redl0eb23302009-01-19 00:08:26 +00003159
Steve Naroff14108da2009-07-10 23:34:53 +00003160 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003161 << MemberName << BaseType);
Steve Naroff14108da2009-07-10 23:34:53 +00003162 }
Chris Lattnera38e6b12008-07-21 04:59:05 +00003163 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3164 // pointer to a (potentially qualified) interface type.
Steve Naroff14108da2009-07-10 23:34:53 +00003165 const ObjCObjectPointerType *OPT;
John McCall129e2df2009-11-30 22:42:35 +00003166 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff14108da2009-07-10 23:34:53 +00003167 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
3168 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003169 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump1eb44332009-09-09 15:08:12 +00003170
Daniel Dunbar2307d312008-09-03 01:05:41 +00003171 // Search for a declared property first.
Anders Carlsson8f28f992009-08-26 18:25:21 +00003172 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003173 // Check whether we can reference this property.
3174 if (DiagnoseUseOfDecl(PD, MemberLoc))
3175 return ExprError();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00003176 QualType ResTy = PD->getType();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003177 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003178 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianc001e892009-05-08 20:20:55 +00003179 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
3180 ResTy = Getter->getResultType();
Fariborz Jahanian4c2743f2009-05-08 19:36:34 +00003181 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner7eba82e2009-02-16 18:35:08 +00003182 MemberLoc, BaseExpr));
3183 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00003184 // Check protocols on qualified interfaces.
Steve Naroff67ef8ea2009-07-20 17:56:53 +00003185 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3186 E = OPT->qual_end(); I != E; ++I)
Anders Carlsson8f28f992009-08-26 18:25:21 +00003187 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003188 // Check whether we can reference this property.
3189 if (DiagnoseUseOfDecl(PD, MemberLoc))
3190 return ExprError();
Chris Lattner7eba82e2009-02-16 18:35:08 +00003191
Steve Naroff6ece14c2009-01-21 00:14:39 +00003192 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner7eba82e2009-02-16 18:35:08 +00003193 MemberLoc, BaseExpr));
3194 }
Daniel Dunbar2307d312008-09-03 01:05:41 +00003195 // If that failed, look for an "implicit" property by seeing if the nullary
3196 // selector is implemented.
3197
3198 // FIXME: The logic for looking up nullary and unary selectors should be
3199 // shared with the code in ActOnInstanceMessage.
3200
Anders Carlsson8f28f992009-08-26 18:25:21 +00003201 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003202 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003203
Daniel Dunbar2307d312008-09-03 01:05:41 +00003204 // If this reference is in an @implementation, check for 'private' methods.
3205 if (!Getter)
Steve Naroffd789d3d2009-10-01 23:46:04 +00003206 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00003207
Steve Naroff7692ed62008-10-22 19:16:27 +00003208 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00003209 if (!Getter)
3210 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar2307d312008-09-03 01:05:41 +00003211 if (Getter) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003212 // Check if we can reference this property.
3213 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3214 return ExprError();
Steve Naroff1ca66942009-03-11 13:48:17 +00003215 }
3216 // If we found a getter then this may be a valid dot-reference, we
3217 // will look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00003218 Selector SetterSel =
3219 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlsson8f28f992009-08-26 18:25:21 +00003220 PP.getSelectorTable(), Member);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003221 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00003222 if (!Setter) {
3223 // If this reference is in an @implementation, also check for 'private'
3224 // methods.
Steve Naroffd789d3d2009-10-01 23:46:04 +00003225 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1ca66942009-03-11 13:48:17 +00003226 }
3227 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00003228 if (!Setter)
3229 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl0eb23302009-01-19 00:08:26 +00003230
Steve Naroff1ca66942009-03-11 13:48:17 +00003231 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3232 return ExprError();
3233
Fariborz Jahaniandd0cb902010-01-19 17:48:02 +00003234 if (Getter) {
Steve Naroff1ca66942009-03-11 13:48:17 +00003235 QualType PType;
Fariborz Jahaniandd0cb902010-01-19 17:48:02 +00003236 PType = Getter->getResultType();
Fariborz Jahanian09105f52009-08-20 17:02:02 +00003237 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1ca66942009-03-11 13:48:17 +00003238 Setter, MemberLoc, BaseExpr));
3239 }
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003240
3241 // Attempt to correct for typos in property names.
3242 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3243 LookupOrdinaryName);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003244 if (CorrectTypo(Res, 0, 0, IFace, false, OPT) &&
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003245 Res.getAsSingle<ObjCPropertyDecl>()) {
3246 Diag(R.getNameLoc(), diag::err_property_not_found_suggest)
3247 << MemberName << BaseType << Res.getLookupName()
Douglas Gregord0ebe082010-03-31 15:31:50 +00003248 << FixItHint::CreateReplacement(R.getNameLoc(),
3249 Res.getLookupName().getAsString());
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003250 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
3251 Diag(Property->getLocation(), diag::note_previous_decl)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003252 << Property->getDeclName();
Douglas Gregor67dd1d42010-01-07 00:17:44 +00003253
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003254 return LookupMemberExpr(Res, BaseExpr, IsArrow, OpLoc, SS,
John McCallc2233c52010-01-15 08:34:02 +00003255 ObjCImpDecl);
Douglas Gregorf06cdae2010-01-03 18:01:57 +00003256 }
Fariborz Jahanian354095c2010-02-19 18:30:30 +00003257 Diag(MemberLoc, diag::err_property_not_found)
3258 << MemberName << BaseType;
3259 if (Setter && !Getter)
3260 Diag(Setter->getLocation(), diag::note_getter_unavailable)
3261 << MemberName << BaseExpr->getSourceRange();
3262 return ExprError();
Fariborz Jahanian232220c2007-11-12 22:29:28 +00003263 }
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Steve Narofff242b1b2009-07-24 17:54:45 +00003265 // Handle the following exceptional case (*Obj).isa.
John McCall129e2df2009-11-30 22:42:35 +00003266 if (!IsArrow &&
Steve Narofff242b1b2009-07-24 17:54:45 +00003267 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlsson8f28f992009-08-26 18:25:21 +00003268 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Narofff242b1b2009-07-24 17:54:45 +00003269 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
Fariborz Jahanian83dc3252009-12-09 19:05:56 +00003270 Context.getObjCClassType()));
Steve Narofff242b1b2009-07-24 17:54:45 +00003271
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003272 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner73525de2009-02-16 21:11:58 +00003273 if (BaseType->isExtVectorType()) {
Anders Carlsson8f28f992009-08-26 18:25:21 +00003274 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003275 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3276 if (ret.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003277 return ExprError();
Anders Carlsson8f28f992009-08-26 18:25:21 +00003278 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003279 MemberLoc));
Chris Lattnerfb173ec2008-07-21 04:28:12 +00003280 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003281
Douglas Gregor214f31a2009-03-27 06:00:30 +00003282 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3283 << BaseType << BaseExpr->getSourceRange();
3284
Douglas Gregor214f31a2009-03-27 06:00:30 +00003285 return ExprError();
Reid Spencer5f016e22007-07-11 17:01:13 +00003286}
3287
John McCall129e2df2009-11-30 22:42:35 +00003288/// The main callback when the parser finds something like
3289/// expression . [nested-name-specifier] identifier
3290/// expression -> [nested-name-specifier] identifier
3291/// where 'identifier' encompasses a fairly broad spectrum of
3292/// possibilities, including destructor and operator references.
3293///
3294/// \param OpKind either tok::arrow or tok::period
3295/// \param HasTrailingLParen whether the next token is '(', which
3296/// is used to diagnose mis-uses of special members that can
3297/// only be called
3298/// \param ObjCImpDecl the current ObjC @implementation decl;
3299/// this is an ugly hack around the fact that ObjC @implementations
3300/// aren't properly put in the context chain
3301Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3302 SourceLocation OpLoc,
3303 tok::TokenKind OpKind,
3304 const CXXScopeSpec &SS,
3305 UnqualifiedId &Id,
3306 DeclPtrTy ObjCImpDecl,
3307 bool HasTrailingLParen) {
3308 if (SS.isSet() && SS.isInvalid())
3309 return ExprError();
3310
3311 TemplateArgumentListInfo TemplateArgsBuffer;
3312
3313 // Decompose the name into its component parts.
3314 DeclarationName Name;
3315 SourceLocation NameLoc;
3316 const TemplateArgumentListInfo *TemplateArgs;
3317 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3318 Name, NameLoc, TemplateArgs);
3319
3320 bool IsArrow = (OpKind == tok::arrow);
3321
3322 NamedDecl *FirstQualifierInScope
3323 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3324 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3325
3326 // This is a postfix expression, so get rid of ParenListExprs.
3327 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3328
3329 Expr *Base = BaseArg.takeAs<Expr>();
3330 OwningExprResult Result(*this);
Douglas Gregor48026d22010-01-11 18:40:55 +00003331 if (Base->getType()->isDependentType() || Name.isDependentName()) {
John McCallaa81e162009-12-01 22:10:20 +00003332 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall129e2df2009-11-30 22:42:35 +00003333 IsArrow, OpLoc,
3334 SS, FirstQualifierInScope,
3335 Name, NameLoc,
3336 TemplateArgs);
3337 } else {
3338 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3339 if (TemplateArgs) {
3340 // Re-use the lookup done for the template name.
3341 DecomposeTemplateName(R, Id);
3342 } else {
3343 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
John McCallc2233c52010-01-15 08:34:02 +00003344 SS, ObjCImpDecl);
John McCall129e2df2009-11-30 22:42:35 +00003345
3346 if (Result.isInvalid()) {
3347 Owned(Base);
3348 return ExprError();
3349 }
3350
3351 if (Result.get()) {
3352 // The only way a reference to a destructor can be used is to
3353 // immediately call it, which falls into this case. If the
3354 // next token is not a '(', produce a diagnostic and build the
3355 // call now.
3356 if (!HasTrailingLParen &&
3357 Id.getKind() == UnqualifiedId::IK_DestructorName)
Douglas Gregor77549082010-02-24 21:29:12 +00003358 return DiagnoseDtorReference(NameLoc, move(Result));
John McCall129e2df2009-11-30 22:42:35 +00003359
3360 return move(Result);
3361 }
3362 }
3363
John McCallaa81e162009-12-01 22:10:20 +00003364 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
John McCallc2233c52010-01-15 08:34:02 +00003365 OpLoc, IsArrow, SS, FirstQualifierInScope,
3366 R, TemplateArgs);
John McCall129e2df2009-11-30 22:42:35 +00003367 }
3368
3369 return move(Result);
Anders Carlsson8f28f992009-08-26 18:25:21 +00003370}
3371
Anders Carlsson56c5e332009-08-25 03:49:14 +00003372Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3373 FunctionDecl *FD,
3374 ParmVarDecl *Param) {
3375 if (Param->hasUnparsedDefaultArg()) {
3376 Diag (CallLoc,
3377 diag::err_use_of_default_argument_to_function_declared_later) <<
3378 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump1eb44332009-09-09 15:08:12 +00003379 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson56c5e332009-08-25 03:49:14 +00003380 diag::note_default_argument_declared_here);
3381 } else {
3382 if (Param->hasUninstantiatedDefaultArg()) {
3383 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3384
3385 // Instantiate the expression.
Douglas Gregor525f96c2010-02-05 07:33:43 +00003386 MultiLevelTemplateArgumentList ArgList
3387 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson25cae7f2009-09-05 05:14:19 +00003388
Mike Stump1eb44332009-09-09 15:08:12 +00003389 InstantiatingTemplate Inst(*this, CallLoc, Param,
3390 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregord6350ae2009-08-28 20:31:08 +00003391 ArgList.getInnermost().flat_size());
Anders Carlsson56c5e332009-08-25 03:49:14 +00003392
John McCallce3ff2b2009-08-25 22:02:44 +00003393 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump1eb44332009-09-09 15:08:12 +00003394 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003395 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003396
Douglas Gregor65222e82009-12-23 18:19:08 +00003397 // Check the expression as an initializer for the parameter.
3398 InitializedEntity Entity
3399 = InitializedEntity::InitializeParameter(Param);
3400 InitializationKind Kind
3401 = InitializationKind::CreateCopy(Param->getLocation(),
3402 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3403 Expr *ResultE = Result.takeAs<Expr>();
3404
3405 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003406 Result = InitSeq.Perform(*this, Entity, Kind,
Douglas Gregor65222e82009-12-23 18:19:08 +00003407 MultiExprArg(*this, (void**)&ResultE, 1));
3408 if (Result.isInvalid())
Anders Carlsson56c5e332009-08-25 03:49:14 +00003409 return ExprError();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003410
Douglas Gregor65222e82009-12-23 18:19:08 +00003411 // Build the default argument expression.
Douglas Gregor036aed12009-12-23 23:03:06 +00003412 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
Douglas Gregor65222e82009-12-23 18:19:08 +00003413 Result.takeAs<Expr>()));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003414 }
Mike Stump1eb44332009-09-09 15:08:12 +00003415
Anders Carlsson56c5e332009-08-25 03:49:14 +00003416 // If the default expression creates temporaries, we need to
3417 // push them to the current stack of expression temporaries so they'll
3418 // be properly destroyed.
Douglas Gregor65222e82009-12-23 18:19:08 +00003419 // FIXME: We should really be rebuilding the default argument with new
3420 // bound temporaries; see the comment in PR5810.
Anders Carlsson337cba42009-12-15 19:16:31 +00003421 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3422 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003423 }
3424
3425 // We already type-checked the argument, so we know it works.
Douglas Gregor036aed12009-12-23 23:03:06 +00003426 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson56c5e332009-08-25 03:49:14 +00003427}
3428
Douglas Gregor88a35142008-12-22 05:46:06 +00003429/// ConvertArgumentsForCall - Converts the arguments specified in
3430/// Args/NumArgs to the parameter types of the function FDecl with
3431/// function prototype Proto. Call is the call expression itself, and
3432/// Fn is the function expression. For a C++ member function, this
3433/// routine does not attempt to convert the object argument. Returns
3434/// true if the call is ill-formed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003435bool
3436Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor88a35142008-12-22 05:46:06 +00003437 FunctionDecl *FDecl,
Douglas Gregor72564e72009-02-26 23:50:07 +00003438 const FunctionProtoType *Proto,
Douglas Gregor88a35142008-12-22 05:46:06 +00003439 Expr **Args, unsigned NumArgs,
3440 SourceLocation RParenLoc) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003441 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor88a35142008-12-22 05:46:06 +00003442 // assignment, to the types of the corresponding parameter, ...
3443 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003444 bool Invalid = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003445
Douglas Gregor88a35142008-12-22 05:46:06 +00003446 // If too few arguments are available (and we don't have default
3447 // arguments for the remaining parameters), don't make the call.
3448 if (NumArgs < NumArgsInProto) {
3449 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3450 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3451 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek8189cde2009-02-07 01:47:29 +00003452 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor88a35142008-12-22 05:46:06 +00003453 }
3454
3455 // If too many are passed and not variadic, error on the extras and drop
3456 // them.
3457 if (NumArgs > NumArgsInProto) {
3458 if (!Proto->isVariadic()) {
3459 Diag(Args[NumArgsInProto]->getLocStart(),
3460 diag::err_typecheck_call_too_many_args)
3461 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3462 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3463 Args[NumArgs-1]->getLocEnd());
3464 // This deletes the extra arguments.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003465 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003466 return true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003467 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003468 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003469 llvm::SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003470 VariadicCallType CallType =
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003471 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3472 if (Fn->getType()->isBlockPointerType())
3473 CallType = VariadicBlock; // Block
3474 else if (isa<MemberExpr>(Fn))
3475 CallType = VariadicMethod;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003476 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian2fe168f2009-11-24 21:37:28 +00003477 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003478 if (Invalid)
3479 return true;
3480 unsigned TotalNumArgs = AllArgs.size();
3481 for (unsigned i = 0; i < TotalNumArgs; ++i)
3482 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003483
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003484 return false;
3485}
Mike Stumpeed9cac2009-02-19 03:04:26 +00003486
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003487bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3488 FunctionDecl *FDecl,
3489 const FunctionProtoType *Proto,
3490 unsigned FirstProtoArg,
3491 Expr **Args, unsigned NumArgs,
3492 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003493 VariadicCallType CallType) {
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003494 unsigned NumArgsInProto = Proto->getNumArgs();
3495 unsigned NumArgsToCheck = NumArgs;
3496 bool Invalid = false;
3497 if (NumArgs != NumArgsInProto)
3498 // Use default arguments for missing arguments
3499 NumArgsToCheck = NumArgsInProto;
3500 unsigned ArgIx = 0;
Douglas Gregor88a35142008-12-22 05:46:06 +00003501 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003502 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003503 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003504
Douglas Gregor88a35142008-12-22 05:46:06 +00003505 Expr *Arg;
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003506 if (ArgIx < NumArgs) {
3507 Arg = Args[ArgIx++];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003508
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003509 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3510 ProtoArgType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003511 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003512 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003513 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003514
Douglas Gregora188ff22009-12-22 16:09:06 +00003515 // Pass the argument
3516 ParmVarDecl *Param = 0;
3517 if (FDecl && i < FDecl->getNumParams())
3518 Param = FDecl->getParamDecl(i);
Douglas Gregoraa037312009-12-22 07:24:36 +00003519
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003520
Douglas Gregora188ff22009-12-22 16:09:06 +00003521 InitializedEntity Entity =
3522 Param? InitializedEntity::InitializeParameter(Param)
3523 : InitializedEntity::InitializeParameter(ProtoArgType);
3524 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3525 SourceLocation(),
3526 Owned(Arg));
3527 if (ArgE.isInvalid())
3528 return true;
3529
3530 Arg = ArgE.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003531 } else {
Anders Carlssoned961f92009-08-25 02:29:20 +00003532 ParmVarDecl *Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003533
Mike Stump1eb44332009-09-09 15:08:12 +00003534 OwningExprResult ArgExpr =
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003535 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson56c5e332009-08-25 03:49:14 +00003536 if (ArgExpr.isInvalid())
3537 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003538
Anders Carlsson56c5e332009-08-25 03:49:14 +00003539 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson5e300d12009-06-12 16:51:40 +00003540 }
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003541 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003542 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003543
Douglas Gregor88a35142008-12-22 05:46:06 +00003544 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian4cd1c702009-11-24 19:27:49 +00003545 if (CallType != VariadicDoesNotApply) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003546 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003547 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003548 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00003549 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian048f52a2009-11-24 18:29:37 +00003550 AllArgs.push_back(Arg);
Douglas Gregor88a35142008-12-22 05:46:06 +00003551 }
3552 }
Douglas Gregor3fd56d72009-01-23 21:30:56 +00003553 return Invalid;
Douglas Gregor88a35142008-12-22 05:46:06 +00003554}
3555
Steve Narofff69936d2007-09-16 03:34:24 +00003556/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Reid Spencer5f016e22007-07-11 17:01:13 +00003557/// This provides the location of the left/right parens and a list of comma
3558/// locations.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003559Action::OwningExprResult
3560Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3561 MultiExprArg args,
Douglas Gregor88a35142008-12-22 05:46:06 +00003562 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl0eb23302009-01-19 00:08:26 +00003563 unsigned NumArgs = args.size();
Nate Begeman2ef13e52009-08-10 23:49:36 +00003564
3565 // Since this might be a postfix expression, get rid of ParenListExprs.
3566 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump1eb44332009-09-09 15:08:12 +00003567
Anders Carlssonf1b1d592009-05-01 19:30:39 +00003568 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl0eb23302009-01-19 00:08:26 +00003569 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner74c469f2007-07-21 03:03:59 +00003570 assert(Fn && "no function call expression");
Mike Stump1eb44332009-09-09 15:08:12 +00003571
Douglas Gregor88a35142008-12-22 05:46:06 +00003572 if (getLangOptions().CPlusPlus) {
Douglas Gregora71d8192009-09-04 17:36:40 +00003573 // If this is a pseudo-destructor expression, build the call immediately.
3574 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3575 if (NumArgs > 0) {
3576 // Pseudo-destructor calls should not have any arguments.
3577 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregord0ebe082010-03-31 15:31:50 +00003578 << FixItHint::CreateRemoval(
Douglas Gregora71d8192009-09-04 17:36:40 +00003579 SourceRange(Args[0]->getLocStart(),
3580 Args[NumArgs-1]->getLocEnd()));
Mike Stump1eb44332009-09-09 15:08:12 +00003581
Douglas Gregora71d8192009-09-04 17:36:40 +00003582 for (unsigned I = 0; I != NumArgs; ++I)
3583 Args[I]->Destroy(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003584
Douglas Gregora71d8192009-09-04 17:36:40 +00003585 NumArgs = 0;
3586 }
Mike Stump1eb44332009-09-09 15:08:12 +00003587
Douglas Gregora71d8192009-09-04 17:36:40 +00003588 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3589 RParenLoc));
3590 }
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Douglas Gregor17330012009-02-04 15:01:18 +00003592 // Determine whether this is a dependent call inside a C++ template,
Mike Stumpeed9cac2009-02-19 03:04:26 +00003593 // in which case we won't do any semantic analysis now.
Mike Stump390b4cc2009-05-16 07:39:55 +00003594 // FIXME: Will need to cache the results of name lookup (including ADL) in
3595 // Fn.
Douglas Gregor17330012009-02-04 15:01:18 +00003596 bool Dependent = false;
3597 if (Fn->isTypeDependent())
3598 Dependent = true;
3599 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3600 Dependent = true;
3601
3602 if (Dependent)
Ted Kremenek668bf912009-02-09 20:51:47 +00003603 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor17330012009-02-04 15:01:18 +00003604 Context.DependentTy, RParenLoc));
3605
3606 // Determine whether this is a call to an object (C++ [over.call.object]).
3607 if (Fn->getType()->isRecordType())
3608 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3609 CommaLocs, RParenLoc));
3610
John McCall129e2df2009-11-30 22:42:35 +00003611 Expr *NakedFn = Fn->IgnoreParens();
3612
3613 // Determine whether this is a call to an unresolved member function.
3614 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3615 // If lookup was unresolved but not dependent (i.e. didn't find
3616 // an unresolved using declaration), it has to be an overloaded
3617 // function set, which means it must contain either multiple
3618 // declarations (all methods or method templates) or a single
3619 // method template.
3620 assert((MemE->getNumDecls() > 1) ||
3621 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor958aeb02009-12-01 03:34:29 +00003622 (void)MemE;
John McCall129e2df2009-11-30 22:42:35 +00003623
John McCallaa81e162009-12-01 22:10:20 +00003624 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3625 CommaLocs, RParenLoc);
John McCall129e2df2009-11-30 22:42:35 +00003626 }
3627
Douglas Gregorfa047642009-02-04 00:32:51 +00003628 // Determine whether this is a call to a member function.
John McCall129e2df2009-11-30 22:42:35 +00003629 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003630 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall129e2df2009-11-30 22:42:35 +00003631 if (isa<CXXMethodDecl>(MemDecl))
John McCallaa81e162009-12-01 22:10:20 +00003632 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3633 CommaLocs, RParenLoc);
Douglas Gregore53060f2009-06-25 22:08:12 +00003634 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003635
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003636 // Determine whether this is a call to a pointer-to-member function.
John McCall129e2df2009-11-30 22:42:35 +00003637 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003638 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3639 BO->getOpcode() == BinaryOperator::PtrMemI) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003640 if (const FunctionProtoType *FPT =
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003641 dyn_cast<FunctionProtoType>(BO->getType())) {
3642 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003643
3644 ExprOwningPtr<CXXMemberCallExpr>
3645 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003646 NumArgs, ResultTy,
3647 RParenLoc));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003648
3649 if (CheckCallReturnType(FPT->getResultType(),
3650 BO->getRHS()->getSourceRange().getBegin(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003651 TheCall.get(), 0))
3652 return ExprError();
Anders Carlsson8d6d90d2009-10-15 00:41:48 +00003653
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003654 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003655 RParenLoc))
3656 return ExprError();
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003657
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003658 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3659 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003660 return ExprError(Diag(Fn->getLocStart(),
Fariborz Jahanian5de24502009-10-28 16:49:46 +00003661 diag::err_typecheck_call_not_function)
3662 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson83ccfc32009-10-03 17:40:22 +00003663 }
3664 }
Douglas Gregor88a35142008-12-22 05:46:06 +00003665 }
3666
Douglas Gregorfa047642009-02-04 00:32:51 +00003667 // If we're directly calling a function, get the appropriate declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003668 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003669 // lookup and whether there were any explicitly-specified template arguments.
Mike Stumpeed9cac2009-02-19 03:04:26 +00003670
Eli Friedmanefa42f72009-12-26 03:35:45 +00003671 Expr *NakedFn = Fn->IgnoreParens();
John McCall3b4294e2009-12-16 12:17:52 +00003672 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3673 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3674 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3675 CommaLocs, RParenLoc);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003676 }
Chris Lattner04421082008-04-08 04:40:51 +00003677
John McCall3b4294e2009-12-16 12:17:52 +00003678 NamedDecl *NDecl = 0;
3679 if (isa<DeclRefExpr>(NakedFn))
3680 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3681
John McCallaa81e162009-12-01 22:10:20 +00003682 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3683}
3684
John McCall3b4294e2009-12-16 12:17:52 +00003685/// BuildResolvedCallExpr - Build a call to a resolved expression,
3686/// i.e. an expression not of \p OverloadTy. The expression should
John McCallaa81e162009-12-01 22:10:20 +00003687/// unary-convert to an expression of function-pointer or
3688/// block-pointer type.
3689///
3690/// \param NDecl the declaration being called, if available
3691Sema::OwningExprResult
3692Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3693 SourceLocation LParenLoc,
3694 Expr **Args, unsigned NumArgs,
3695 SourceLocation RParenLoc) {
3696 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3697
Chris Lattner04421082008-04-08 04:40:51 +00003698 // Promote the function operand.
3699 UsualUnaryConversions(Fn);
3700
Chris Lattner925e60d2007-12-28 05:29:59 +00003701 // Make the call expr early, before semantic checks. This guarantees cleanup
3702 // of arguments and function on error.
Ted Kremenek668bf912009-02-09 20:51:47 +00003703 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3704 Args, NumArgs,
3705 Context.BoolTy,
3706 RParenLoc));
Sebastian Redl0eb23302009-01-19 00:08:26 +00003707
Steve Naroffdd972f22008-09-05 22:11:13 +00003708 const FunctionType *FuncT;
3709 if (!Fn->getType()->isBlockPointerType()) {
3710 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3711 // have type pointer to function".
Ted Kremenek6217b802009-07-29 21:53:49 +00003712 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003713 if (PT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003714 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3715 << Fn->getType() << Fn->getSourceRange());
John McCall183700f2009-09-21 23:43:11 +00003716 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003717 } else { // This is a block call.
Ted Kremenek6217b802009-07-29 21:53:49 +00003718 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall183700f2009-09-21 23:43:11 +00003719 getAs<FunctionType>();
Steve Naroffdd972f22008-09-05 22:11:13 +00003720 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003721 if (FuncT == 0)
Sebastian Redl0eb23302009-01-19 00:08:26 +00003722 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3723 << Fn->getType() << Fn->getSourceRange());
3724
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003725 // Check for a valid return type
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003726 if (CheckCallReturnType(FuncT->getResultType(),
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003727 Fn->getSourceRange().getBegin(), TheCall.get(),
3728 FDecl))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003729 return ExprError();
3730
Chris Lattner925e60d2007-12-28 05:29:59 +00003731 // We know the result type of the call, set it.
Douglas Gregor15da57e2008-10-29 02:00:59 +00003732 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl0eb23302009-01-19 00:08:26 +00003733
Douglas Gregor72564e72009-02-26 23:50:07 +00003734 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00003735 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00003736 RParenLoc))
Sebastian Redl0eb23302009-01-19 00:08:26 +00003737 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003738 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003739 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl0eb23302009-01-19 00:08:26 +00003740
Douglas Gregor74734d52009-04-02 15:37:10 +00003741 if (FDecl) {
3742 // Check if we have too few/too many template arguments, based
3743 // on our knowledge of the function definition.
3744 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00003745 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003746 const FunctionProtoType *Proto =
John McCall183700f2009-09-21 23:43:11 +00003747 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanbc4e29f2009-06-01 09:24:59 +00003748 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3749 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3750 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3751 }
3752 }
Douglas Gregor74734d52009-04-02 15:37:10 +00003753 }
3754
Steve Naroffb291ab62007-08-28 23:30:39 +00003755 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner925e60d2007-12-28 05:29:59 +00003756 for (unsigned i = 0; i != NumArgs; i++) {
3757 Expr *Arg = Args[i];
3758 DefaultArgumentPromotion(Arg);
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003759 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3760 Arg->getType(),
Anders Carlssonb7906612009-08-26 23:45:07 +00003761 PDiag(diag::err_call_incomplete_argument)
3762 << Arg->getSourceRange()))
Eli Friedmane7c6f7a2009-03-22 22:00:50 +00003763 return ExprError();
Chris Lattner925e60d2007-12-28 05:29:59 +00003764 TheCall->setArg(i, Arg);
Steve Naroffb291ab62007-08-28 23:30:39 +00003765 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003766 }
Chris Lattner925e60d2007-12-28 05:29:59 +00003767
Douglas Gregor88a35142008-12-22 05:46:06 +00003768 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3769 if (!Method->isStatic())
Sebastian Redl0eb23302009-01-19 00:08:26 +00003770 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3771 << Fn->getSourceRange());
Douglas Gregor88a35142008-12-22 05:46:06 +00003772
Fariborz Jahaniandaf04152009-05-15 20:33:25 +00003773 // Check for sentinels
3774 if (NDecl)
3775 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003776
Chris Lattner59907c42007-08-10 20:18:51 +00003777 // Do special checking on direct calls to functions.
Anders Carlssond406bf02009-08-16 01:56:34 +00003778 if (FDecl) {
3779 if (CheckFunctionCall(FDecl, TheCall.get()))
3780 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00003781
Douglas Gregor7814e6d2009-09-12 00:22:50 +00003782 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssond406bf02009-08-16 01:56:34 +00003783 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3784 } else if (NDecl) {
3785 if (CheckBlockCall(NDecl, TheCall.get()))
3786 return ExprError();
3787 }
Chris Lattner59907c42007-08-10 20:18:51 +00003788
Anders Carlssonec74c592009-08-16 03:06:32 +00003789 return MaybeBindToTemporary(TheCall.take());
Reid Spencer5f016e22007-07-11 17:01:13 +00003790}
3791
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003792Action::OwningExprResult
3793Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3794 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Narofff69936d2007-09-16 03:34:24 +00003795 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroffaff1edd2007-07-19 21:32:11 +00003796 // FIXME: put back this assert when initializers are worked out.
Steve Narofff69936d2007-09-16 03:34:24 +00003797 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCall42f56b52010-01-18 19:35:47 +00003798
3799 TypeSourceInfo *TInfo;
3800 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3801 if (!TInfo)
3802 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3803
3804 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3805}
3806
3807Action::OwningExprResult
3808Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3809 SourceLocation RParenLoc, ExprArg InitExpr) {
3810 QualType literalType = TInfo->getType();
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003811 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlssond35c8322007-12-05 07:24:19 +00003812
Eli Friedman6223c222008-05-20 05:22:08 +00003813 if (literalType->isArrayType()) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00003814 if (literalType->isVariableArrayType())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003815 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3816 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor690dc7f2009-05-21 23:48:18 +00003817 } else if (!literalType->isDependentType() &&
3818 RequireCompleteType(LParenLoc, literalType,
Anders Carlssonb7906612009-08-26 23:45:07 +00003819 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00003820 << SourceRange(LParenLoc,
Anders Carlssonb7906612009-08-26 23:45:07 +00003821 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003822 return ExprError();
Eli Friedman6223c222008-05-20 05:22:08 +00003823
Douglas Gregor99a2e602009-12-16 01:38:02 +00003824 InitializedEntity Entity
Douglas Gregord6542d82009-12-22 15:35:07 +00003825 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor99a2e602009-12-16 01:38:02 +00003826 InitializationKind Kind
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003827 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
Douglas Gregor99a2e602009-12-16 01:38:02 +00003828 /*IsCStyleCast=*/true);
Eli Friedman08544622009-12-22 02:35:53 +00003829 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3830 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3831 MultiExprArg(*this, (void**)&literalExpr, 1),
3832 &literalType);
3833 if (Result.isInvalid())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003834 return ExprError();
Eli Friedman08544622009-12-22 02:35:53 +00003835 InitExpr.release();
3836 literalExpr = static_cast<Expr*>(Result.get());
Steve Naroffe9b12192008-01-14 18:19:28 +00003837
Chris Lattner371f2582008-12-04 23:50:19 +00003838 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffe9b12192008-01-14 18:19:28 +00003839 if (isFileScope) { // 6.5.2.5p3
Steve Naroffd0091aa2008-01-10 22:15:12 +00003840 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003841 return ExprError();
Steve Naroffd0091aa2008-01-10 22:15:12 +00003842 }
Eli Friedman08544622009-12-22 02:35:53 +00003843
3844 Result.release();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003845
John McCall1d7d8d62010-01-19 22:33:45 +00003846 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Steve Naroff6ece14c2009-01-21 00:14:39 +00003847 literalExpr, isFileScope));
Steve Naroff4aa88f82007-07-19 01:06:55 +00003848}
3849
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003850Action::OwningExprResult
3851Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003852 SourceLocation RBraceLoc) {
3853 unsigned NumInit = initlist.size();
3854 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson66b5a8a2007-08-31 04:56:16 +00003855
Steve Naroff08d92e42007-09-15 18:49:24 +00003856 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stumpeed9cac2009-02-19 03:04:26 +00003857 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003858
Ted Kremenekba7bc552010-02-19 01:50:18 +00003859 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
3860 RBraceLoc);
Chris Lattnerf0467b32008-04-02 04:24:33 +00003861 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00003862 return Owned(E);
Steve Naroff4aa88f82007-07-19 01:06:55 +00003863}
3864
Anders Carlsson82debc72009-10-18 18:12:03 +00003865static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3866 QualType SrcTy, QualType DestTy) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003867 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson82debc72009-10-18 18:12:03 +00003868 return CastExpr::CK_NoOp;
3869
3870 if (SrcTy->hasPointerRepresentation()) {
3871 if (DestTy->hasPointerRepresentation())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003872 return DestTy->isObjCObjectPointerType() ?
3873 CastExpr::CK_AnyPointerToObjCPointerCast :
Fariborz Jahaniana7fa7cd2009-12-15 21:34:52 +00003874 CastExpr::CK_BitCast;
Anders Carlsson82debc72009-10-18 18:12:03 +00003875 if (DestTy->isIntegerType())
3876 return CastExpr::CK_PointerToIntegral;
3877 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003878
Anders Carlsson82debc72009-10-18 18:12:03 +00003879 if (SrcTy->isIntegerType()) {
3880 if (DestTy->isIntegerType())
3881 return CastExpr::CK_IntegralCast;
3882 if (DestTy->hasPointerRepresentation())
3883 return CastExpr::CK_IntegralToPointer;
3884 if (DestTy->isRealFloatingType())
3885 return CastExpr::CK_IntegralToFloating;
3886 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003887
Anders Carlsson82debc72009-10-18 18:12:03 +00003888 if (SrcTy->isRealFloatingType()) {
3889 if (DestTy->isRealFloatingType())
3890 return CastExpr::CK_FloatingCast;
3891 if (DestTy->isIntegerType())
3892 return CastExpr::CK_FloatingToIntegral;
3893 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003894
Anders Carlsson82debc72009-10-18 18:12:03 +00003895 // FIXME: Assert here.
3896 // assert(false && "Unhandled cast combination!");
3897 return CastExpr::CK_Unknown;
3898}
3899
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003900/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlef0cb8e2009-07-29 13:50:23 +00003901bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump1eb44332009-09-09 15:08:12 +00003902 CastExpr::CastKind& Kind,
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003903 CXXMethodDecl *& ConversionDecl,
3904 bool FunctionalStyle) {
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003905 if (getLangOptions().CPlusPlus)
Fariborz Jahaniane9f42082009-08-26 18:55:36 +00003906 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3907 ConversionDecl);
Sebastian Redl9cc11e72009-07-25 15:41:38 +00003908
Douglas Gregora873dfc2010-02-03 00:27:59 +00003909 DefaultFunctionArrayLvalueConversion(castExpr);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003910
3911 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3912 // type needs to be scalar.
3913 if (castType->isVoidType()) {
3914 // Cast to void allows any expr type.
Anders Carlssonebeaf202009-10-16 02:35:04 +00003915 Kind = CastExpr::CK_ToVoid;
3916 return false;
3917 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003918
Anders Carlssonebeaf202009-10-16 02:35:04 +00003919 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregora4923eb2009-11-16 21:35:15 +00003920 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003921 (castType->isStructureType() || castType->isUnionType())) {
3922 // GCC struct/union extension: allow cast to self.
Eli Friedmanb1d796d2009-03-23 00:24:07 +00003923 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003924 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3925 << castType << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003926 Kind = CastExpr::CK_NoOp;
Anders Carlssonc3516322009-10-16 02:48:28 +00003927 return false;
3928 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003929
Anders Carlssonc3516322009-10-16 02:48:28 +00003930 if (castType->isUnionType()) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003931 // GCC cast to union extension
Ted Kremenek6217b802009-07-29 21:53:49 +00003932 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003933 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003934 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003935 Field != FieldEnd; ++Field) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003936 if (Context.hasSameUnqualifiedType(Field->getType(),
Douglas Gregora4923eb2009-11-16 21:35:15 +00003937 castExpr->getType())) {
Seo Sanghyeoneff2cd52009-01-15 04:51:39 +00003938 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3939 << castExpr->getSourceRange();
3940 break;
3941 }
3942 }
3943 if (Field == FieldEnd)
3944 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3945 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson4d8673b2009-08-07 23:22:37 +00003946 Kind = CastExpr::CK_ToUnion;
Anders Carlssonc3516322009-10-16 02:48:28 +00003947 return false;
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003948 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003949
Anders Carlssonc3516322009-10-16 02:48:28 +00003950 // Reject any other conversions to non-scalar types.
3951 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3952 << castType << castExpr->getSourceRange();
3953 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003954
3955 if (!castExpr->getType()->isScalarType() &&
Anders Carlssonc3516322009-10-16 02:48:28 +00003956 !castExpr->getType()->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003957 return Diag(castExpr->getLocStart(),
3958 diag::err_typecheck_expect_scalar_operand)
Chris Lattnerd1625842008-11-24 06:25:27 +00003959 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonc3516322009-10-16 02:48:28 +00003960 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003961
3962 if (castType->isExtVectorType())
Anders Carlsson16a89042009-10-16 05:23:41 +00003963 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003964
Anders Carlssonc3516322009-10-16 02:48:28 +00003965 if (castType->isVectorType())
3966 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3967 if (castExpr->getType()->isVectorType())
3968 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3969
3970 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffa0c3e9c2009-04-08 23:52:26 +00003971 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003972
Anders Carlsson16a89042009-10-16 05:23:41 +00003973 if (isa<ObjCSelectorExpr>(castExpr))
3974 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00003975
Anders Carlssonc3516322009-10-16 02:48:28 +00003976 if (!castType->isArithmeticType()) {
Eli Friedman41826bb2009-05-01 02:23:58 +00003977 QualType castExprType = castExpr->getType();
3978 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3979 return Diag(castExpr->getLocStart(),
3980 diag::err_cast_pointer_from_non_pointer_int)
3981 << castExprType << castExpr->getSourceRange();
3982 } else if (!castExpr->getType()->isArithmeticType()) {
3983 if (!castType->isIntegralType() && castType->isArithmeticType())
3984 return Diag(castExpr->getLocStart(),
3985 diag::err_cast_pointer_to_non_pointer_int)
3986 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003987 }
Anders Carlsson82debc72009-10-18 18:12:03 +00003988
3989 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis6c2dc4d2008-08-16 20:27:34 +00003990 return false;
3991}
3992
Anders Carlssonc3516322009-10-16 02:48:28 +00003993bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3994 CastExpr::CastKind &Kind) {
Anders Carlssona64db8f2007-11-27 05:51:55 +00003995 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00003996
Anders Carlssona64db8f2007-11-27 05:51:55 +00003997 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner98be4942008-03-05 18:54:05 +00003998 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssona64db8f2007-11-27 05:51:55 +00003999 return Diag(R.getBegin(),
Mike Stumpeed9cac2009-02-19 03:04:26 +00004000 Ty->isVectorType() ?
Anders Carlssona64db8f2007-11-27 05:51:55 +00004001 diag::err_invalid_conversion_between_vectors :
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004002 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattnerd1625842008-11-24 06:25:27 +00004003 << VectorTy << Ty << R;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004004 } else
4005 return Diag(R.getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004006 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattnerd1625842008-11-24 06:25:27 +00004007 << VectorTy << Ty << R;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004008
Anders Carlssonc3516322009-10-16 02:48:28 +00004009 Kind = CastExpr::CK_BitCast;
Anders Carlssona64db8f2007-11-27 05:51:55 +00004010 return false;
4011}
4012
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004013bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
Anders Carlsson16a89042009-10-16 05:23:41 +00004014 CastExpr::CastKind &Kind) {
Nate Begeman58d29a42009-06-26 00:50:28 +00004015 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004016
Anders Carlsson16a89042009-10-16 05:23:41 +00004017 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004018
Nate Begeman9b10da62009-06-27 22:05:55 +00004019 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4020 // an ExtVectorType.
Nate Begeman58d29a42009-06-26 00:50:28 +00004021 if (SrcTy->isVectorType()) {
4022 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4023 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4024 << DestTy << SrcTy << R;
Anders Carlsson16a89042009-10-16 05:23:41 +00004025 Kind = CastExpr::CK_BitCast;
Nate Begeman58d29a42009-06-26 00:50:28 +00004026 return false;
4027 }
4028
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004029 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begeman58d29a42009-06-26 00:50:28 +00004030 // conversion will take place first from scalar to elt type, and then
4031 // splat from elt type to vector.
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004032 if (SrcTy->isPointerType())
4033 return Diag(R.getBegin(),
4034 diag::err_invalid_conversion_between_vector_and_scalar)
4035 << DestTy << SrcTy << R;
Eli Friedman73c39ab2009-10-20 08:27:19 +00004036
4037 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4038 ImpCastExprToType(CastExpr, DestElemTy,
4039 getScalarCastKind(Context, SrcTy, DestElemTy));
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004040
Anders Carlsson16a89042009-10-16 05:23:41 +00004041 Kind = CastExpr::CK_VectorSplat;
Nate Begeman58d29a42009-06-26 00:50:28 +00004042 return false;
4043}
4044
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004045Action::OwningExprResult
Nate Begeman2ef13e52009-08-10 23:49:36 +00004046Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004047 SourceLocation RParenLoc, ExprArg Op) {
4048 assert((Ty != 0) && (Op.get() != 0) &&
4049 "ActOnCastExpr(): missing type or expr");
Steve Naroff16beff82007-07-16 23:25:18 +00004050
John McCall9d125032010-01-15 18:39:57 +00004051 TypeSourceInfo *castTInfo;
4052 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4053 if (!castTInfo)
John McCall42f56b52010-01-18 19:35:47 +00004054 castTInfo = Context.getTrivialTypeSourceInfo(castType);
Mike Stump1eb44332009-09-09 15:08:12 +00004055
Nate Begeman2ef13e52009-08-10 23:49:36 +00004056 // If the Expr being casted is a ParenListExpr, handle it specially.
John McCallb042fdf2010-01-15 18:56:44 +00004057 Expr *castExpr = (Expr *)Op.get();
Nate Begeman2ef13e52009-08-10 23:49:36 +00004058 if (isa<ParenListExpr>(castExpr))
John McCall42f56b52010-01-18 19:35:47 +00004059 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
4060 castTInfo);
John McCallb042fdf2010-01-15 18:56:44 +00004061
4062 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
4063}
4064
4065Action::OwningExprResult
4066Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
4067 SourceLocation RParenLoc, ExprArg Op) {
4068 Expr *castExpr = static_cast<Expr*>(Op.get());
4069
Anders Carlsson0aebc812009-09-09 21:33:21 +00004070 CXXMethodDecl *Method = 0;
John McCallb042fdf2010-01-15 18:56:44 +00004071 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
4072 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
Anders Carlsson0aebc812009-09-09 21:33:21 +00004073 Kind, Method))
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004074 return ExprError();
Anders Carlsson0aebc812009-09-09 21:33:21 +00004075
4076 if (Method) {
John McCallb042fdf2010-01-15 18:56:44 +00004077 // FIXME: preserve type source info here
4078 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, Ty->getType(),
4079 Kind, Method, move(Op));
Daniel Dunbar7e88a602009-09-17 06:31:17 +00004080
Anders Carlsson0aebc812009-09-09 21:33:21 +00004081 if (CastArg.isInvalid())
4082 return ExprError();
Daniel Dunbar7e88a602009-09-17 06:31:17 +00004083
Anders Carlsson0aebc812009-09-09 21:33:21 +00004084 castExpr = CastArg.takeAs<Expr>();
4085 } else {
4086 Op.release();
Fariborz Jahanian31976592009-08-29 19:15:16 +00004087 }
Mike Stump1eb44332009-09-09 15:08:12 +00004088
John McCallb042fdf2010-01-15 18:56:44 +00004089 return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
4090 Kind, castExpr, Ty,
Anders Carlssoncdb61972009-08-07 22:21:05 +00004091 LParenLoc, RParenLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00004092}
4093
Nate Begeman2ef13e52009-08-10 23:49:36 +00004094/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4095/// of comma binary operators.
4096Action::OwningExprResult
4097Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
4098 Expr *expr = EA.takeAs<Expr>();
4099 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4100 if (!E)
4101 return Owned(expr);
Mike Stump1eb44332009-09-09 15:08:12 +00004102
Nate Begeman2ef13e52009-08-10 23:49:36 +00004103 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump1eb44332009-09-09 15:08:12 +00004104
Nate Begeman2ef13e52009-08-10 23:49:36 +00004105 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4106 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
4107 Owned(E->getExpr(i)));
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Nate Begeman2ef13e52009-08-10 23:49:36 +00004109 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
4110}
4111
4112Action::OwningExprResult
4113Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4114 SourceLocation RParenLoc, ExprArg Op,
John McCall42f56b52010-01-18 19:35:47 +00004115 TypeSourceInfo *TInfo) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004116 ParenListExpr *PE = (ParenListExpr *)Op.get();
John McCall42f56b52010-01-18 19:35:47 +00004117 QualType Ty = TInfo->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004118
4119 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman2ef13e52009-08-10 23:49:36 +00004120 // then handle it as such.
4121 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4122 if (PE->getNumExprs() == 0) {
4123 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4124 return ExprError();
4125 }
4126
4127 llvm::SmallVector<Expr *, 8> initExprs;
4128 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4129 initExprs.push_back(PE->getExpr(i));
4130
4131 // FIXME: This means that pretty-printing the final AST will produce curly
4132 // braces instead of the original commas.
4133 Op.release();
Ted Kremenekba7bc552010-02-19 01:50:18 +00004134 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman2ef13e52009-08-10 23:49:36 +00004135 initExprs.size(), RParenLoc);
4136 E->setType(Ty);
John McCall42f56b52010-01-18 19:35:47 +00004137 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004138 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004139 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman2ef13e52009-08-10 23:49:36 +00004140 // sequence of BinOp comma operators.
4141 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
John McCall42f56b52010-01-18 19:35:47 +00004142 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
Nate Begeman2ef13e52009-08-10 23:49:36 +00004143 }
4144}
4145
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004146Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman2ef13e52009-08-10 23:49:36 +00004147 SourceLocation R,
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004148 MultiExprArg Val,
4149 TypeTy *TypeOfCast) {
Nate Begeman2ef13e52009-08-10 23:49:36 +00004150 unsigned nexprs = Val.size();
4151 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanianf88f7ab2009-11-25 01:26:41 +00004152 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4153 Expr *expr;
4154 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4155 expr = new (Context) ParenExpr(L, R, exprs[0]);
4156 else
4157 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman2ef13e52009-08-10 23:49:36 +00004158 return Owned(expr);
4159}
4160
Sebastian Redl28507842009-02-26 14:39:58 +00004161/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4162/// In that case, lhs = cond.
Chris Lattnera119a3b2009-02-18 04:38:20 +00004163/// C99 6.5.15
4164QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4165 SourceLocation QuestionLoc) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004166 // C++ is sufficiently different to merit its own checker.
4167 if (getLangOptions().CPlusPlus)
4168 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4169
John McCalld1b47bf2010-03-11 19:43:18 +00004170 CheckSignCompare(LHS, RHS, QuestionLoc);
John McCallb13c87f2009-11-05 09:23:39 +00004171
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004172 UsualUnaryConversions(Cond);
4173 UsualUnaryConversions(LHS);
4174 UsualUnaryConversions(RHS);
4175 QualType CondTy = Cond->getType();
4176 QualType LHSTy = LHS->getType();
4177 QualType RHSTy = RHS->getType();
Steve Naroffc80b4ee2007-07-16 21:54:35 +00004178
Reid Spencer5f016e22007-07-11 17:01:13 +00004179 // first, check the condition.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004180 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4181 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4182 << CondTy;
4183 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004184 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004185
Chris Lattner70d67a92008-01-06 22:42:25 +00004186 // Now check the two expressions.
Nate Begeman2ef13e52009-08-10 23:49:36 +00004187 if (LHSTy->isVectorType() || RHSTy->isVectorType())
4188 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor898574e2008-12-05 23:32:09 +00004189
Chris Lattner70d67a92008-01-06 22:42:25 +00004190 // If both operands have arithmetic type, do the usual arithmetic conversions
4191 // to find a common type: C99 6.5.15p3,5.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004192 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4193 UsualArithmeticConversions(LHS, RHS);
4194 return LHS->getType();
Steve Naroffa4332e22007-07-17 00:58:39 +00004195 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004196
Chris Lattner70d67a92008-01-06 22:42:25 +00004197 // If both operands are the same structure or union type, the result is that
4198 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004199 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4200 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattnera21ddb32007-11-26 01:40:58 +00004201 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stumpeed9cac2009-02-19 03:04:26 +00004202 // "If both the operands have structure or union type, the result has
Chris Lattner70d67a92008-01-06 22:42:25 +00004203 // that type." This implies that CV qualifiers are dropped.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004204 return LHSTy.getUnqualifiedType();
Eli Friedmanb1d796d2009-03-23 00:24:07 +00004205 // FIXME: Type of conditional expression must be complete in C mode.
Reid Spencer5f016e22007-07-11 17:01:13 +00004206 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004207
Chris Lattner70d67a92008-01-06 22:42:25 +00004208 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffe701c0a2008-05-12 21:44:38 +00004209 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004210 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4211 if (!LHSTy->isVoidType())
4212 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4213 << RHS->getSourceRange();
4214 if (!RHSTy->isVoidType())
4215 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4216 << LHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004217 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4218 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman0e724012008-06-04 19:47:51 +00004219 return Context.VoidTy;
Steve Naroffe701c0a2008-05-12 21:44:38 +00004220 }
Steve Naroffb6d54e52008-01-08 01:11:38 +00004221 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4222 // the type of the other operand."
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004223 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004224 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004225 // promote the null to a pointer.
4226 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004227 return LHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004228 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00004229 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregorce940492009-09-25 04:25:58 +00004230 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004231 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004232 return RHSTy;
Steve Naroffb6d54e52008-01-08 01:11:38 +00004233 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004234
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004235 // All objective-c pointer type analysis is done here.
4236 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4237 QuestionLoc);
4238 if (!compositeType.isNull())
4239 return compositeType;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004240
4241
Steve Naroff7154a772009-07-01 14:36:47 +00004242 // Handle block pointer types.
4243 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4244 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4245 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4246 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004247 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4248 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004249 return destType;
4250 }
4251 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004252 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroff7154a772009-07-01 14:36:47 +00004253 return QualType();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004254 }
Steve Naroff7154a772009-07-01 14:36:47 +00004255 // We have 2 block pointer types.
4256 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4257 // Two identical block pointer types are always compatible.
Mike Stumpdd3e1662009-05-07 03:14:14 +00004258 return LHSTy;
4259 }
Steve Naroff7154a772009-07-01 14:36:47 +00004260 // The block pointer types aren't identical, continue checking.
Ted Kremenek6217b802009-07-29 21:53:49 +00004261 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4262 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004263
Steve Naroff7154a772009-07-01 14:36:47 +00004264 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4265 rhptee.getUnqualifiedType())) {
Mike Stumpdd3e1662009-05-07 03:14:14 +00004266 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004267 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Mike Stumpdd3e1662009-05-07 03:14:14 +00004268 // In this situation, we assume void* type. No especially good
4269 // reason, but this is what gcc does, and we do have to pick
4270 // to get a consistent AST.
4271 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004272 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4273 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stumpdd3e1662009-05-07 03:14:14 +00004274 return incompatTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004275 }
Steve Naroff7154a772009-07-01 14:36:47 +00004276 // The block pointer types are compatible.
Eli Friedman73c39ab2009-10-20 08:27:19 +00004277 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4278 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff91588042009-04-08 17:05:15 +00004279 return LHSTy;
4280 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004281
Steve Naroff7154a772009-07-01 14:36:47 +00004282 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4283 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4284 // get the "pointed to" types
Ted Kremenek6217b802009-07-29 21:53:49 +00004285 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4286 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff7154a772009-07-01 14:36:47 +00004287
4288 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4289 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4290 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall0953e762009-09-24 19:53:00 +00004291 QualType destPointee
4292 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004293 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004294 // Add qualifiers if necessary.
4295 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4296 // Promote to void*.
4297 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004298 return destType;
4299 }
4300 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall0953e762009-09-24 19:53:00 +00004301 QualType destPointee
4302 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff7154a772009-07-01 14:36:47 +00004303 QualType destType = Context.getPointerType(destPointee);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004304 // Add qualifiers if necessary.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004305 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004306 // Promote to void*.
Eli Friedman16fea9b2009-11-17 01:22:05 +00004307 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004308 return destType;
4309 }
4310
4311 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4312 // Two identical pointer types are always compatible.
4313 return LHSTy;
4314 }
4315 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4316 rhptee.getUnqualifiedType())) {
4317 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4318 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4319 // In this situation, we assume void* type. No especially good
4320 // reason, but this is what gcc does, and we do have to pick
4321 // to get a consistent AST.
4322 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman73c39ab2009-10-20 08:27:19 +00004323 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4324 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004325 return incompatTy;
4326 }
4327 // The pointer types are compatible.
4328 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4329 // differently qualified versions of compatible types, the result type is
4330 // a pointer to an appropriately qualified version of the *composite*
4331 // type.
4332 // FIXME: Need to calculate the composite type.
4333 // FIXME: Need to add qualifiers
Eli Friedman73c39ab2009-10-20 08:27:19 +00004334 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4335 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff7154a772009-07-01 14:36:47 +00004336 return LHSTy;
4337 }
Mike Stump1eb44332009-09-09 15:08:12 +00004338
Steve Naroff7154a772009-07-01 14:36:47 +00004339 // GCC compatibility: soften pointer/integer mismatch.
4340 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4341 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4342 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004343 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004344 return RHSTy;
4345 }
4346 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4347 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4348 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00004349 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff7154a772009-07-01 14:36:47 +00004350 return LHSTy;
4351 }
Daniel Dunbar5e155f02008-09-11 23:12:46 +00004352
Chris Lattner70d67a92008-01-06 22:42:25 +00004353 // Otherwise, the operands are not compatible.
Chris Lattnerefdc39d2009-02-18 04:28:32 +00004354 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4355 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00004356 return QualType();
4357}
4358
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004359/// FindCompositeObjCPointerType - Helper method to find composite type of
4360/// two objective-c pointer types of the two input expressions.
4361QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4362 SourceLocation QuestionLoc) {
4363 QualType LHSTy = LHS->getType();
4364 QualType RHSTy = RHS->getType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004365
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004366 // Handle things like Class and struct objc_class*. Here we case the result
4367 // to the pseudo-builtin, because that will be implicitly cast back to the
4368 // redefinition type if an attempt is made to access its fields.
4369 if (LHSTy->isObjCClassType() &&
4370 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4371 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4372 return LHSTy;
4373 }
4374 if (RHSTy->isObjCClassType() &&
4375 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4376 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4377 return RHSTy;
4378 }
4379 // And the same for struct objc_object* / id
4380 if (LHSTy->isObjCIdType() &&
4381 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4382 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4383 return LHSTy;
4384 }
4385 if (RHSTy->isObjCIdType() &&
4386 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4387 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4388 return RHSTy;
4389 }
4390 // And the same for struct objc_selector* / SEL
4391 if (Context.isObjCSelType(LHSTy) &&
4392 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4393 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4394 return LHSTy;
4395 }
4396 if (Context.isObjCSelType(RHSTy) &&
4397 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4398 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4399 return RHSTy;
4400 }
4401 // Check constraints for Objective-C object pointers types.
4402 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004403
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004404 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4405 // Two identical object pointer types are always compatible.
4406 return LHSTy;
4407 }
4408 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4409 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4410 QualType compositeType = LHSTy;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004411
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004412 // If both operands are interfaces and either operand can be
4413 // assigned to the other, use that type as the composite
4414 // type. This allows
4415 // xxx ? (A*) a : (B*) b
4416 // where B is a subclass of A.
4417 //
4418 // Additionally, as for assignment, if either type is 'id'
4419 // allow silent coercion. Finally, if the types are
4420 // incompatible then make sure to use 'id' as the composite
4421 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004422
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004423 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4424 // It could return the composite type.
4425 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4426 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4427 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4428 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4429 } else if ((LHSTy->isObjCQualifiedIdType() ||
4430 RHSTy->isObjCQualifiedIdType()) &&
4431 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4432 // Need to handle "id<xx>" explicitly.
4433 // GCC allows qualified id and any Objective-C type to devolve to
4434 // id. Currently localizing to here until clear this should be
4435 // part of ObjCQualifiedIdTypesAreCompatible.
4436 compositeType = Context.getObjCIdType();
4437 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4438 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004439 } else if (!(compositeType =
Fariborz Jahanianeebc4752009-12-10 19:47:41 +00004440 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4441 ;
4442 else {
4443 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4444 << LHSTy << RHSTy
4445 << LHS->getSourceRange() << RHS->getSourceRange();
4446 QualType incompatTy = Context.getObjCIdType();
4447 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4448 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4449 return incompatTy;
4450 }
4451 // The object pointer types are compatible.
4452 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4453 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4454 return compositeType;
4455 }
4456 // Check Objective-C object pointer types and 'void *'
4457 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4458 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4459 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4460 QualType destPointee
4461 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4462 QualType destType = Context.getPointerType(destPointee);
4463 // Add qualifiers if necessary.
4464 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4465 // Promote to void*.
4466 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4467 return destType;
4468 }
4469 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4470 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4471 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4472 QualType destPointee
4473 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4474 QualType destType = Context.getPointerType(destPointee);
4475 // Add qualifiers if necessary.
4476 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4477 // Promote to void*.
4478 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4479 return destType;
4480 }
4481 return QualType();
4482}
4483
Steve Narofff69936d2007-09-16 03:34:24 +00004484/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Reid Spencer5f016e22007-07-11 17:01:13 +00004485/// in the case of a the GNU conditional expr extension.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004486Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4487 SourceLocation ColonLoc,
4488 ExprArg Cond, ExprArg LHS,
4489 ExprArg RHS) {
4490 Expr *CondExpr = (Expr *) Cond.get();
4491 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattnera21ddb32007-11-26 01:40:58 +00004492
4493 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4494 // was the condition.
4495 bool isLHSNull = LHSExpr == 0;
4496 if (isLHSNull)
4497 LHSExpr = CondExpr;
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004498
4499 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner26824902007-07-16 21:39:03 +00004500 RHSExpr, QuestionLoc);
Reid Spencer5f016e22007-07-11 17:01:13 +00004501 if (result.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00004502 return ExprError();
4503
4504 Cond.release();
4505 LHS.release();
4506 RHS.release();
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004507 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Naroff6ece14c2009-01-21 00:14:39 +00004508 isLHSNull ? 0 : LHSExpr,
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00004509 ColonLoc, RHSExpr, result));
Reid Spencer5f016e22007-07-11 17:01:13 +00004510}
4511
Reid Spencer5f016e22007-07-11 17:01:13 +00004512// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stumpeed9cac2009-02-19 03:04:26 +00004513// being closely modeled after the C99 spec:-). The odd characteristic of this
Reid Spencer5f016e22007-07-11 17:01:13 +00004514// routine is it effectively iqnores the qualifiers on the top level pointee.
4515// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4516// FIXME: add a couple examples in this comment.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004517Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004518Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4519 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004520
David Chisnall0f436562009-08-17 16:35:33 +00004521 if ((lhsType->isObjCClassType() &&
4522 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4523 (rhsType->isObjCClassType() &&
4524 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4525 return Compatible;
4526 }
4527
Reid Spencer5f016e22007-07-11 17:01:13 +00004528 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004529 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4530 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004531
Reid Spencer5f016e22007-07-11 17:01:13 +00004532 // make sure we operate on the canonical type
Chris Lattnerb77792e2008-07-26 22:17:49 +00004533 lhptee = Context.getCanonicalType(lhptee);
4534 rhptee = Context.getCanonicalType(rhptee);
Reid Spencer5f016e22007-07-11 17:01:13 +00004535
Chris Lattner5cf216b2008-01-04 18:04:52 +00004536 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004537
4538 // C99 6.5.16.1p1: This following citation is common to constraints
4539 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4540 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianf11284a2009-02-17 18:27:45 +00004541 // FIXME: Handle ExtQualType
Douglas Gregor98cd5992008-10-21 23:43:52 +00004542 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner5cf216b2008-01-04 18:04:52 +00004543 ConvTy = CompatiblePointerDiscardsQualifiers;
Reid Spencer5f016e22007-07-11 17:01:13 +00004544
Mike Stumpeed9cac2009-02-19 03:04:26 +00004545 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4546 // incomplete type and the other is a pointer to a qualified or unqualified
Reid Spencer5f016e22007-07-11 17:01:13 +00004547 // version of void...
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004548 if (lhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004549 if (rhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004550 return ConvTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004551
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004552 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004553 assert(rhptee->isFunctionType());
4554 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004555 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004556
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004557 if (rhptee->isVoidType()) {
Chris Lattnerd805bec2008-04-02 06:59:01 +00004558 if (lhptee->isIncompleteOrObjectType())
Chris Lattner5cf216b2008-01-04 18:04:52 +00004559 return ConvTy;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004560
4561 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerd805bec2008-04-02 06:59:01 +00004562 assert(lhptee->isFunctionType());
4563 return FunctionVoidPointer;
Chris Lattnerbfe639e2008-01-03 22:56:36 +00004564 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004565 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Reid Spencer5f016e22007-07-11 17:01:13 +00004566 // unqualified versions of compatible types, ...
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004567 lhptee = lhptee.getUnqualifiedType();
4568 rhptee = rhptee.getUnqualifiedType();
4569 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4570 // Check if the pointee types are compatible ignoring the sign.
4571 // We explicitly check for char so that we catch "char" vs
4572 // "unsigned char" on systems where "char" is unsigned.
Chris Lattner6a2b9262009-10-17 20:33:28 +00004573 if (lhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004574 lhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004575 else if (lhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004576 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004577
Chris Lattner6a2b9262009-10-17 20:33:28 +00004578 if (rhptee->isCharType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004579 rhptee = Context.UnsignedCharTy;
Chris Lattner6a2b9262009-10-17 20:33:28 +00004580 else if (rhptee->isSignedIntegerType())
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004581 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattner6a2b9262009-10-17 20:33:28 +00004582
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004583 if (lhptee == rhptee) {
4584 // Types are compatible ignoring the sign. Qualifier incompatibility
4585 // takes priority over sign incompatibility because the sign
4586 // warning can be disabled.
4587 if (ConvTy != Compatible)
4588 return ConvTy;
4589 return IncompatiblePointerSign;
4590 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004591
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004592 // If we are a multi-level pointer, it's possible that our issue is simply
4593 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4594 // the eventual target type is the same and the pointers have the same
4595 // level of indirection, this must be the issue.
4596 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4597 do {
4598 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4599 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004600
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004601 lhptee = Context.getCanonicalType(lhptee);
4602 rhptee = Context.getCanonicalType(rhptee);
4603 } while (lhptee->isPointerType() && rhptee->isPointerType());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004604
Douglas Gregora4923eb2009-11-16 21:35:15 +00004605 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Sean Huntc9132b62009-11-08 07:46:34 +00004606 return IncompatibleNestedPointerQualifiers;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00004607 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004608
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004609 // General pointer incompatibility takes priority over qualifiers.
Mike Stump1eb44332009-09-09 15:08:12 +00004610 return IncompatiblePointer;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00004611 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00004612 return ConvTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00004613}
4614
Steve Naroff1c7d0672008-09-04 15:10:53 +00004615/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4616/// block pointer types are compatible or whether a block and normal pointer
4617/// are compatible. It is more restrict than comparing two function pointer
4618// types.
Mike Stumpeed9cac2009-02-19 03:04:26 +00004619Sema::AssignConvertType
4620Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff1c7d0672008-09-04 15:10:53 +00004621 QualType rhsType) {
4622 QualType lhptee, rhptee;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004623
Steve Naroff1c7d0672008-09-04 15:10:53 +00004624 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenek6217b802009-07-29 21:53:49 +00004625 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4626 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004627
Steve Naroff1c7d0672008-09-04 15:10:53 +00004628 // make sure we operate on the canonical type
4629 lhptee = Context.getCanonicalType(lhptee);
4630 rhptee = Context.getCanonicalType(rhptee);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004631
Steve Naroff1c7d0672008-09-04 15:10:53 +00004632 AssignConvertType ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004633
Steve Naroff1c7d0672008-09-04 15:10:53 +00004634 // For blocks we enforce that qualifiers are identical.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004635 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff1c7d0672008-09-04 15:10:53 +00004636 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004637
Fariborz Jahanian132f2a22010-03-17 00:20:01 +00004638 if (!getLangOptions().CPlusPlus) {
4639 if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4640 return IncompatibleBlockPointer;
4641 }
4642 else if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stumpeed9cac2009-02-19 03:04:26 +00004643 return IncompatibleBlockPointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004644 return ConvTy;
4645}
4646
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004647/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4648/// for assignment compatibility.
4649Sema::AssignConvertType
4650Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004651 if (lhsType->isObjCBuiltinType()) {
4652 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004653 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4654 !rhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004655 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004656 return Compatible;
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004657 }
4658 if (rhsType->isObjCBuiltinType()) {
4659 // Class is not compatible with ObjC object pointers.
Fariborz Jahanian528adb12010-03-24 21:00:27 +00004660 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4661 !lhsType->isObjCQualifiedClassType())
Fariborz Jahaniand4c60902010-03-19 18:06:10 +00004662 return IncompatiblePointer;
4663 return Compatible;
4664 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004665 QualType lhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004666 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004667 QualType rhptee =
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004668 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4669 // make sure we operate on the canonical type
4670 lhptee = Context.getCanonicalType(lhptee);
4671 rhptee = Context.getCanonicalType(rhptee);
4672 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4673 return CompatiblePointerDiscardsQualifiers;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004674
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004675 if (Context.typesAreCompatible(lhsType, rhsType))
4676 return Compatible;
4677 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4678 return IncompatibleObjCQualifiedId;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004679 return IncompatiblePointer;
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004680}
4681
Mike Stumpeed9cac2009-02-19 03:04:26 +00004682/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4683/// has code to accommodate several GCC extensions when type checking
Reid Spencer5f016e22007-07-11 17:01:13 +00004684/// pointers. Here are some objectionable examples that GCC considers warnings:
4685///
4686/// int a, *pint;
4687/// short *pshort;
4688/// struct foo *pfoo;
4689///
4690/// pint = pshort; // warning: assignment from incompatible pointer type
4691/// a = pint; // warning: assignment makes integer from pointer without a cast
4692/// pint = a; // warning: assignment makes pointer from integer without a cast
4693/// pint = pfoo; // warning: assignment from incompatible pointer type
4694///
4695/// As a result, the code for dealing with pointers is more complex than the
Mike Stumpeed9cac2009-02-19 03:04:26 +00004696/// C99 spec dictates.
Reid Spencer5f016e22007-07-11 17:01:13 +00004697///
Chris Lattner5cf216b2008-01-04 18:04:52 +00004698Sema::AssignConvertType
Reid Spencer5f016e22007-07-11 17:01:13 +00004699Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnerfc144e22008-01-04 23:18:45 +00004700 // Get canonical types. We're not formatting these types, just comparing
4701 // them.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004702 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4703 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004704
4705 if (lhsType == rhsType)
Chris Lattnerd2656dd2008-01-07 17:51:46 +00004706 return Compatible; // Common case: fast path an exact match.
Steve Naroff700204c2007-07-24 21:46:40 +00004707
David Chisnall0f436562009-08-17 16:35:33 +00004708 if ((lhsType->isObjCClassType() &&
4709 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4710 (rhsType->isObjCClassType() &&
4711 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4712 return Compatible;
4713 }
4714
Douglas Gregor9d293df2008-10-28 00:22:11 +00004715 // If the left-hand side is a reference type, then we are in a
4716 // (rare!) case where we've allowed the use of references in C,
4717 // e.g., as a parameter type in a built-in function. In this case,
4718 // just make sure that the type referenced is compatible with the
4719 // right-hand side type. The caller is responsible for adjusting
4720 // lhsType so that the resulting expression does not have reference
4721 // type.
Ted Kremenek6217b802009-07-29 21:53:49 +00004722 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor9d293df2008-10-28 00:22:11 +00004723 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson793680e2007-10-12 23:56:29 +00004724 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004725 return Incompatible;
Fariborz Jahanian411f3732007-12-19 17:45:58 +00004726 }
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00004727 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4728 // to the same ExtVector type.
4729 if (lhsType->isExtVectorType()) {
4730 if (rhsType->isExtVectorType())
4731 return lhsType == rhsType ? Compatible : Incompatible;
4732 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4733 return Compatible;
4734 }
Mike Stump1eb44332009-09-09 15:08:12 +00004735
Nate Begemanbe2341d2008-07-14 18:02:46 +00004736 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004737 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stumpeed9cac2009-02-19 03:04:26 +00004738 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanbe2341d2008-07-14 18:02:46 +00004739 // no bits are changed but the result type is different.
Chris Lattnere8b3e962008-01-04 23:32:24 +00004740 if (getLangOptions().LaxVectorConversions &&
4741 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00004742 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00004743 return IncompatibleVectors;
Chris Lattnere8b3e962008-01-04 23:32:24 +00004744 }
4745 return Incompatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004746 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004747
Chris Lattnere8b3e962008-01-04 23:32:24 +00004748 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Reid Spencer5f016e22007-07-11 17:01:13 +00004749 return Compatible;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004750
Chris Lattner78eca282008-04-07 06:49:41 +00004751 if (isa<PointerType>(lhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004752 if (rhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004753 return IntToPointer;
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004754
Chris Lattner78eca282008-04-07 06:49:41 +00004755 if (isa<PointerType>(rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004756 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004757
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004758 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004759 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004760 if (lhsType->isVoidPointerType()) // an exception to the rule.
4761 return Compatible;
4762 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004763 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004764 if (rhsType->getAs<BlockPointerType>()) {
4765 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004766 return Compatible;
Steve Naroffb4406862008-09-29 18:10:17 +00004767
4768 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004769 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004770 return Compatible;
4771 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00004772 return Incompatible;
4773 }
4774
4775 if (isa<BlockPointerType>(lhsType)) {
4776 if (rhsType->isIntegerType())
Eli Friedmand8f4f432009-02-25 04:20:42 +00004777 return IntToBlockPointer;
Mike Stumpeed9cac2009-02-19 03:04:26 +00004778
Steve Naroffb4406862008-09-29 18:10:17 +00004779 // Treat block pointers as objects.
Steve Naroff14108da2009-07-10 23:34:53 +00004780 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffb4406862008-09-29 18:10:17 +00004781 return Compatible;
4782
Steve Naroff1c7d0672008-09-04 15:10:53 +00004783 if (rhsType->isBlockPointerType())
4784 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004785
Ted Kremenek6217b802009-07-29 21:53:49 +00004786 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff1c7d0672008-09-04 15:10:53 +00004787 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004788 return Compatible;
Steve Naroff1c7d0672008-09-04 15:10:53 +00004789 }
Chris Lattnerfc144e22008-01-04 23:18:45 +00004790 return Incompatible;
4791 }
4792
Steve Naroff14108da2009-07-10 23:34:53 +00004793 if (isa<ObjCObjectPointerType>(lhsType)) {
4794 if (rhsType->isIntegerType())
4795 return IntToPointer;
Mike Stump1eb44332009-09-09 15:08:12 +00004796
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004797 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004798 if (isa<PointerType>(rhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004799 if (rhsType->isVoidPointerType()) // an exception to the rule.
4800 return Compatible;
4801 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004802 }
4803 if (rhsType->isObjCObjectPointerType()) {
Fariborz Jahanian52efc3f2009-12-08 18:24:49 +00004804 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
Steve Naroff14108da2009-07-10 23:34:53 +00004805 }
Ted Kremenek6217b802009-07-29 21:53:49 +00004806 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00004807 if (RHSPT->getPointeeType()->isVoidType())
4808 return Compatible;
4809 }
4810 // Treat block pointers as objects.
4811 if (rhsType->isBlockPointerType())
4812 return Compatible;
4813 return Incompatible;
4814 }
Chris Lattner78eca282008-04-07 06:49:41 +00004815 if (isa<PointerType>(rhsType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00004816 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004817 if (lhsType == Context.BoolTy)
4818 return Compatible;
4819
4820 if (lhsType->isIntegerType())
Chris Lattnerb7b61152008-01-04 18:22:42 +00004821 return PointerToInt;
Reid Spencer5f016e22007-07-11 17:01:13 +00004822
Mike Stumpeed9cac2009-02-19 03:04:26 +00004823 if (isa<PointerType>(lhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004824 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stumpeed9cac2009-02-19 03:04:26 +00004825
4826 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004827 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor63a94902008-11-27 00:44:28 +00004828 return Compatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004829 return Incompatible;
Chris Lattnerfc144e22008-01-04 23:18:45 +00004830 }
Steve Naroff14108da2009-07-10 23:34:53 +00004831 if (isa<ObjCObjectPointerType>(rhsType)) {
4832 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4833 if (lhsType == Context.BoolTy)
4834 return Compatible;
4835
4836 if (lhsType->isIntegerType())
4837 return PointerToInt;
4838
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004839 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff14108da2009-07-10 23:34:53 +00004840 if (isa<PointerType>(lhsType)) {
Steve Naroff67ef8ea2009-07-20 17:56:53 +00004841 if (lhsType->isVoidPointerType()) // an exception to the rule.
4842 return Compatible;
4843 return IncompatiblePointer;
Steve Naroff14108da2009-07-10 23:34:53 +00004844 }
4845 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenek6217b802009-07-29 21:53:49 +00004846 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff14108da2009-07-10 23:34:53 +00004847 return Compatible;
4848 return Incompatible;
4849 }
Eli Friedmanf8f873d2008-05-30 18:07:22 +00004850
Chris Lattnerfc144e22008-01-04 23:18:45 +00004851 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner78eca282008-04-07 06:49:41 +00004852 if (Context.typesAreCompatible(lhsType, rhsType))
Reid Spencer5f016e22007-07-11 17:01:13 +00004853 return Compatible;
Reid Spencer5f016e22007-07-11 17:01:13 +00004854 }
4855 return Incompatible;
4856}
4857
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004858/// \brief Constructs a transparent union from an expression that is
4859/// used to initialize the transparent union.
Mike Stump1eb44332009-09-09 15:08:12 +00004860static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004861 QualType UnionType, FieldDecl *Field) {
4862 // Build an initializer list that designates the appropriate member
4863 // of the transparent union.
Ted Kremenekba7bc552010-02-19 01:50:18 +00004864 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4865 &E, 1,
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004866 SourceLocation());
4867 Initializer->setType(UnionType);
4868 Initializer->setInitializedFieldInUnion(Field);
4869
4870 // Build a compound literal constructing a value of the transparent
4871 // union type from this initializer list.
John McCall42f56b52010-01-18 19:35:47 +00004872 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John McCall1d7d8d62010-01-19 22:33:45 +00004873 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
John McCall42f56b52010-01-18 19:35:47 +00004874 Initializer, false);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004875}
4876
4877Sema::AssignConvertType
4878Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4879 QualType FromType = rExpr->getType();
4880
Mike Stump1eb44332009-09-09 15:08:12 +00004881 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004882 // transparent_union GCC extension.
4883 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004884 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004885 return Incompatible;
4886
4887 // The field to initialize within the transparent union.
4888 RecordDecl *UD = UT->getDecl();
4889 FieldDecl *InitField = 0;
4890 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004891 for (RecordDecl::field_iterator it = UD->field_begin(),
4892 itend = UD->field_end();
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004893 it != itend; ++it) {
4894 if (it->getType()->isPointerType()) {
4895 // If the transparent union contains a pointer type, we allow:
4896 // 1) void pointer
4897 // 2) null pointer constant
4898 if (FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +00004899 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004900 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004901 InitField = *it;
4902 break;
4903 }
Mike Stump1eb44332009-09-09 15:08:12 +00004904
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004905 if (rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004906 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004907 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004908 InitField = *it;
4909 break;
4910 }
4911 }
4912
4913 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4914 == Compatible) {
4915 InitField = *it;
4916 break;
4917 }
4918 }
4919
4920 if (!InitField)
4921 return Incompatible;
4922
4923 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4924 return Compatible;
4925}
4926
Chris Lattner5cf216b2008-01-04 18:04:52 +00004927Sema::AssignConvertType
Steve Naroff90045e82007-07-13 23:32:42 +00004928Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00004929 if (getLangOptions().CPlusPlus) {
4930 if (!lhsType->isRecordType()) {
4931 // C++ 5.17p3: If the left operand is not of class type, the
4932 // expression is implicitly converted (C++ 4) to the
4933 // cv-unqualified type of the left operand.
Douglas Gregor45920e82008-12-19 17:40:08 +00004934 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
Douglas Gregor68647482009-12-16 03:45:30 +00004935 AA_Assigning))
Douglas Gregor98cd5992008-10-21 23:43:52 +00004936 return Incompatible;
Chris Lattner2c4463f2009-04-12 09:02:39 +00004937 return Compatible;
Douglas Gregor98cd5992008-10-21 23:43:52 +00004938 }
4939
4940 // FIXME: Currently, we fall through and treat C++ classes like C
4941 // structures.
4942 }
4943
Steve Naroff529a4ad2007-11-27 17:58:44 +00004944 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4945 // a null pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00004946 if ((lhsType->isPointerType() ||
4947 lhsType->isObjCObjectPointerType() ||
Mike Stumpeed9cac2009-02-19 03:04:26 +00004948 lhsType->isBlockPointerType())
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00004949 && rExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00004950 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00004951 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff529a4ad2007-11-27 17:58:44 +00004952 return Compatible;
4953 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00004954
Chris Lattner943140e2007-10-16 02:55:40 +00004955 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroff90045e82007-07-13 23:32:42 +00004956 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregor02a24ee2009-11-03 16:56:39 +00004957 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroff90045e82007-07-13 23:32:42 +00004958 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner943140e2007-10-16 02:55:40 +00004959 //
Mike Stumpeed9cac2009-02-19 03:04:26 +00004960 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner943140e2007-10-16 02:55:40 +00004961 if (!lhsType->isReferenceType())
Douglas Gregora873dfc2010-02-03 00:27:59 +00004962 DefaultFunctionArrayLvalueConversion(rExpr);
Steve Narofff1120de2007-08-24 22:33:52 +00004963
Chris Lattner5cf216b2008-01-04 18:04:52 +00004964 Sema::AssignConvertType result =
4965 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00004966
Steve Narofff1120de2007-08-24 22:33:52 +00004967 // C99 6.5.16.1p2: The value of the right operand is converted to the
4968 // type of the assignment expression.
Douglas Gregor9d293df2008-10-28 00:22:11 +00004969 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4970 // so that we can use references in built-in functions even in C.
4971 // The getNonReferenceType() call makes sure that the resulting expression
4972 // does not have reference type.
Douglas Gregor0c74e8a2009-04-29 22:16:16 +00004973 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman73c39ab2009-10-20 08:27:19 +00004974 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4975 CastExpr::CK_Unknown);
Steve Narofff1120de2007-08-24 22:33:52 +00004976 return result;
Steve Naroff90045e82007-07-13 23:32:42 +00004977}
4978
Chris Lattner29a1cfb2008-11-18 01:30:42 +00004979QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004980 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner22caddc2008-11-23 09:13:29 +00004981 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00004982 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerca5eede2007-12-12 05:47:28 +00004983 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00004984}
4985
Chris Lattner7ef655a2010-01-12 21:23:57 +00004986QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Mike Stumpeed9cac2009-02-19 03:04:26 +00004987 // For conversion purposes, we ignore any qualifiers.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004988 // For example, "const float" and "float" are equivalent.
Chris Lattnerb77792e2008-07-26 22:17:49 +00004989 QualType lhsType =
4990 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4991 QualType rhsType =
4992 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00004993
Nate Begemanbe2341d2008-07-14 18:02:46 +00004994 // If the vector types are identical, return.
Nate Begeman1330b0e2008-04-04 01:30:25 +00004995 if (lhsType == rhsType)
Reid Spencer5f016e22007-07-11 17:01:13 +00004996 return lhsType;
Nate Begeman4119d1a2007-12-30 02:59:45 +00004997
Nate Begemanbe2341d2008-07-14 18:02:46 +00004998 // Handle the case of a vector & extvector type of the same size and element
4999 // type. It would be nice if we only had one vector type someday.
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005000 if (getLangOptions().LaxVectorConversions) {
5001 // FIXME: Should we warn here?
John McCall183700f2009-09-21 23:43:11 +00005002 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
5003 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begemanbe2341d2008-07-14 18:02:46 +00005004 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005005 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanbe2341d2008-07-14 18:02:46 +00005006 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00005007 }
5008 }
5009 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005010
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005011 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5012 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5013 bool swapped = false;
5014 if (rhsType->isExtVectorType()) {
5015 swapped = true;
5016 std::swap(rex, lex);
5017 std::swap(rhsType, lhsType);
5018 }
Mike Stump1eb44332009-09-09 15:08:12 +00005019
Nate Begemandde25982009-06-28 19:12:57 +00005020 // Handle the case of an ext vector and scalar.
John McCall183700f2009-09-21 23:43:11 +00005021 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005022 QualType EltTy = LV->getElementType();
5023 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
5024 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005025 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005026 if (swapped) std::swap(rex, lex);
5027 return lhsType;
5028 }
5029 }
5030 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5031 rhsType->isRealFloatingType()) {
5032 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005033 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begeman1bd1f6e2009-06-28 02:36:38 +00005034 if (swapped) std::swap(rex, lex);
5035 return lhsType;
5036 }
Nate Begeman4119d1a2007-12-30 02:59:45 +00005037 }
5038 }
Mike Stump1eb44332009-09-09 15:08:12 +00005039
Nate Begemandde25982009-06-28 19:12:57 +00005040 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005041 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattnerd1625842008-11-24 06:25:27 +00005042 << lex->getType() << rex->getType()
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005043 << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005044 return QualType();
Sebastian Redl22460502009-02-07 00:15:38 +00005045}
5046
Chris Lattner7ef655a2010-01-12 21:23:57 +00005047QualType Sema::CheckMultiplyDivideOperands(
5048 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
Daniel Dunbar69d1d002009-01-05 22:42:10 +00005049 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005050 return CheckVectorOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005051
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005052 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005053
Chris Lattner7ef655a2010-01-12 21:23:57 +00005054 if (!lex->getType()->isArithmeticType() ||
5055 !rex->getType()->isArithmeticType())
5056 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005057
Chris Lattner7ef655a2010-01-12 21:23:57 +00005058 // Check for division by zero.
5059 if (isDiv &&
5060 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005061 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
Chris Lattnercb329c52010-01-12 21:30:55 +00005062 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005063
Chris Lattner7ef655a2010-01-12 21:23:57 +00005064 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005065}
5066
Chris Lattner7ef655a2010-01-12 21:23:57 +00005067QualType Sema::CheckRemainderOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005068 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar523aa602009-01-05 22:55:36 +00005069 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5070 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
5071 return CheckVectorOperands(Loc, lex, rex);
5072 return InvalidOperands(Loc, lex, rex);
5073 }
Steve Naroff90045e82007-07-13 23:32:42 +00005074
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005075 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005076
Chris Lattner7ef655a2010-01-12 21:23:57 +00005077 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5078 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005079
Chris Lattner7ef655a2010-01-12 21:23:57 +00005080 // Check for remainder by zero.
5081 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
Chris Lattnercb329c52010-01-12 21:30:55 +00005082 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5083 << rex->getSourceRange());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005084
Chris Lattner7ef655a2010-01-12 21:23:57 +00005085 return compType;
Reid Spencer5f016e22007-07-11 17:01:13 +00005086}
5087
Chris Lattner7ef655a2010-01-12 21:23:57 +00005088QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump1eb44332009-09-09 15:08:12 +00005089 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005090 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5091 QualType compType = CheckVectorOperands(Loc, lex, rex);
5092 if (CompLHSTy) *CompLHSTy = compType;
5093 return compType;
5094 }
Steve Naroff49b45262007-07-13 16:58:59 +00005095
Eli Friedmanab3a8522009-03-28 01:22:36 +00005096 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand72d16e2008-05-18 18:08:51 +00005097
Reid Spencer5f016e22007-07-11 17:01:13 +00005098 // handle the common case first (both operands are arithmetic).
Eli Friedmanab3a8522009-03-28 01:22:36 +00005099 if (lex->getType()->isArithmeticType() &&
5100 rex->getType()->isArithmeticType()) {
5101 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005102 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005103 }
Reid Spencer5f016e22007-07-11 17:01:13 +00005104
Eli Friedmand72d16e2008-05-18 18:08:51 +00005105 // Put any potential pointer into PExp
5106 Expr* PExp = lex, *IExp = rex;
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005107 if (IExp->getType()->isAnyPointerType())
Eli Friedmand72d16e2008-05-18 18:08:51 +00005108 std::swap(PExp, IExp);
5109
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005110 if (PExp->getType()->isAnyPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00005111
Eli Friedmand72d16e2008-05-18 18:08:51 +00005112 if (IExp->getType()->isIntegerType()) {
Steve Naroff760e3c42009-07-13 21:20:41 +00005113 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005114
Chris Lattnerb5f15622009-04-24 23:50:08 +00005115 // Check for arithmetic on pointers to incomplete types.
5116 if (PointeeTy->isVoidType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005117 if (getLangOptions().CPlusPlus) {
5118 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00005119 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005120 return QualType();
Eli Friedmand72d16e2008-05-18 18:08:51 +00005121 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005122
5123 // GNU extension: arithmetic on pointer to void
5124 Diag(Loc, diag::ext_gnu_void_ptr)
5125 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerb5f15622009-04-24 23:50:08 +00005126 } else if (PointeeTy->isFunctionType()) {
Douglas Gregore7450f52009-03-24 19:52:54 +00005127 if (getLangOptions().CPlusPlus) {
5128 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5129 << lex->getType() << lex->getSourceRange();
5130 return QualType();
5131 }
5132
5133 // GNU extension: arithmetic on pointer to function
5134 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5135 << lex->getType() << lex->getSourceRange();
Steve Naroff9deaeca2009-07-13 21:32:29 +00005136 } else {
Steve Naroff760e3c42009-07-13 21:20:41 +00005137 // Check if we require a complete type.
Mike Stump1eb44332009-09-09 15:08:12 +00005138 if (((PExp->getType()->isPointerType() &&
Steve Naroff9deaeca2009-07-13 21:32:29 +00005139 !PExp->getType()->isDependentType()) ||
Steve Naroff760e3c42009-07-13 21:20:41 +00005140 PExp->getType()->isObjCObjectPointerType()) &&
5141 RequireCompleteType(Loc, PointeeTy,
Mike Stump1eb44332009-09-09 15:08:12 +00005142 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5143 << PExp->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005144 << PExp->getType()))
Steve Naroff760e3c42009-07-13 21:20:41 +00005145 return QualType();
5146 }
Chris Lattnerb5f15622009-04-24 23:50:08 +00005147 // Diagnose bad cases where we step over interface counts.
5148 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5149 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5150 << PointeeTy << PExp->getSourceRange();
5151 return QualType();
5152 }
Mike Stump1eb44332009-09-09 15:08:12 +00005153
Eli Friedmanab3a8522009-03-28 01:22:36 +00005154 if (CompLHSTy) {
Eli Friedman04e83572009-08-20 04:21:42 +00005155 QualType LHSTy = Context.isPromotableBitField(lex);
5156 if (LHSTy.isNull()) {
5157 LHSTy = lex->getType();
5158 if (LHSTy->isPromotableIntegerType())
5159 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005160 }
Eli Friedmanab3a8522009-03-28 01:22:36 +00005161 *CompLHSTy = LHSTy;
5162 }
Eli Friedmand72d16e2008-05-18 18:08:51 +00005163 return PExp->getType();
5164 }
5165 }
5166
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005167 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005168}
5169
Chris Lattnereca7be62008-04-07 05:30:13 +00005170// C99 6.5.6
5171QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedmanab3a8522009-03-28 01:22:36 +00005172 SourceLocation Loc, QualType* CompLHSTy) {
5173 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5174 QualType compType = CheckVectorOperands(Loc, lex, rex);
5175 if (CompLHSTy) *CompLHSTy = compType;
5176 return compType;
5177 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005178
Eli Friedmanab3a8522009-03-28 01:22:36 +00005179 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005180
Chris Lattner6e4ab612007-12-09 21:53:25 +00005181 // Enforce type constraints: C99 6.5.6p3.
Mike Stumpeed9cac2009-02-19 03:04:26 +00005182
Chris Lattner6e4ab612007-12-09 21:53:25 +00005183 // Handle the common case first (both operands are arithmetic).
Mike Stumpaf199f32009-05-07 18:43:07 +00005184 if (lex->getType()->isArithmeticType()
5185 && rex->getType()->isArithmeticType()) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00005186 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005187 return compType;
Eli Friedmanab3a8522009-03-28 01:22:36 +00005188 }
Mike Stump1eb44332009-09-09 15:08:12 +00005189
Chris Lattner6e4ab612007-12-09 21:53:25 +00005190 // Either ptr - int or ptr - ptr.
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005191 if (lex->getType()->isAnyPointerType()) {
Steve Naroff430ee5a2009-07-13 17:19:15 +00005192 QualType lpointee = lex->getType()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005193
Douglas Gregore7450f52009-03-24 19:52:54 +00005194 // The LHS must be an completely-defined object type.
Douglas Gregorc983b862009-01-23 00:36:41 +00005195
Douglas Gregore7450f52009-03-24 19:52:54 +00005196 bool ComplainAboutVoid = false;
5197 Expr *ComplainAboutFunc = 0;
5198 if (lpointee->isVoidType()) {
5199 if (getLangOptions().CPlusPlus) {
5200 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5201 << lex->getSourceRange() << rex->getSourceRange();
5202 return QualType();
5203 }
5204
5205 // GNU C extension: arithmetic on pointer to void
5206 ComplainAboutVoid = true;
5207 } else if (lpointee->isFunctionType()) {
5208 if (getLangOptions().CPlusPlus) {
5209 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005210 << lex->getType() << lex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005211 return QualType();
5212 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005213
5214 // GNU C extension: arithmetic on pointer to function
5215 ComplainAboutFunc = lex;
5216 } else if (!lpointee->isDependentType() &&
Mike Stump1eb44332009-09-09 15:08:12 +00005217 RequireCompleteType(Loc, lpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005218 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump1eb44332009-09-09 15:08:12 +00005219 << lex->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005220 << lex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005221 return QualType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005222
Chris Lattnerb5f15622009-04-24 23:50:08 +00005223 // Diagnose bad cases where we step over interface counts.
5224 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5225 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5226 << lpointee << lex->getSourceRange();
5227 return QualType();
5228 }
Mike Stump1eb44332009-09-09 15:08:12 +00005229
Chris Lattner6e4ab612007-12-09 21:53:25 +00005230 // The result type of a pointer-int computation is the pointer type.
Douglas Gregore7450f52009-03-24 19:52:54 +00005231 if (rex->getType()->isIntegerType()) {
5232 if (ComplainAboutVoid)
5233 Diag(Loc, diag::ext_gnu_void_ptr)
5234 << lex->getSourceRange() << rex->getSourceRange();
5235 if (ComplainAboutFunc)
5236 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005237 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005238 << ComplainAboutFunc->getSourceRange();
5239
Eli Friedmanab3a8522009-03-28 01:22:36 +00005240 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005241 return lex->getType();
Douglas Gregore7450f52009-03-24 19:52:54 +00005242 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005243
Chris Lattner6e4ab612007-12-09 21:53:25 +00005244 // Handle pointer-pointer subtractions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005245 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman8e54ad02008-02-08 01:19:44 +00005246 QualType rpointee = RHSPTy->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005247
Douglas Gregore7450f52009-03-24 19:52:54 +00005248 // RHS must be a completely-type object type.
5249 // Handle the GNU void* extension.
5250 if (rpointee->isVoidType()) {
5251 if (getLangOptions().CPlusPlus) {
5252 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5253 << lex->getSourceRange() << rex->getSourceRange();
5254 return QualType();
5255 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005256
Douglas Gregore7450f52009-03-24 19:52:54 +00005257 ComplainAboutVoid = true;
5258 } else if (rpointee->isFunctionType()) {
5259 if (getLangOptions().CPlusPlus) {
5260 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattnerd1625842008-11-24 06:25:27 +00005261 << rex->getType() << rex->getSourceRange();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005262 return QualType();
5263 }
Douglas Gregore7450f52009-03-24 19:52:54 +00005264
5265 // GNU extension: arithmetic on pointer to function
5266 if (!ComplainAboutFunc)
5267 ComplainAboutFunc = rex;
5268 } else if (!rpointee->isDependentType() &&
5269 RequireCompleteType(Loc, rpointee,
Anders Carlssond497ba72009-08-26 22:59:12 +00005270 PDiag(diag::err_typecheck_sub_ptr_object)
5271 << rex->getSourceRange()
5272 << rex->getType()))
Douglas Gregore7450f52009-03-24 19:52:54 +00005273 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005274
Eli Friedman88d936b2009-05-16 13:54:38 +00005275 if (getLangOptions().CPlusPlus) {
5276 // Pointee types must be the same: C++ [expr.add]
5277 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5278 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5279 << lex->getType() << rex->getType()
5280 << lex->getSourceRange() << rex->getSourceRange();
5281 return QualType();
5282 }
5283 } else {
5284 // Pointee types must be compatible C99 6.5.6p3
5285 if (!Context.typesAreCompatible(
5286 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5287 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5288 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5289 << lex->getType() << rex->getType()
5290 << lex->getSourceRange() << rex->getSourceRange();
5291 return QualType();
5292 }
Chris Lattner6e4ab612007-12-09 21:53:25 +00005293 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005294
Douglas Gregore7450f52009-03-24 19:52:54 +00005295 if (ComplainAboutVoid)
5296 Diag(Loc, diag::ext_gnu_void_ptr)
5297 << lex->getSourceRange() << rex->getSourceRange();
5298 if (ComplainAboutFunc)
5299 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump1eb44332009-09-09 15:08:12 +00005300 << ComplainAboutFunc->getType()
Douglas Gregore7450f52009-03-24 19:52:54 +00005301 << ComplainAboutFunc->getSourceRange();
Eli Friedmanab3a8522009-03-28 01:22:36 +00005302
5303 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner6e4ab612007-12-09 21:53:25 +00005304 return Context.getPointerDiffType();
5305 }
5306 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005307
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005308 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005309}
5310
Chris Lattnereca7be62008-04-07 05:30:13 +00005311// C99 6.5.7
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005312QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnereca7be62008-04-07 05:30:13 +00005313 bool isCompAssign) {
Chris Lattnerca5eede2007-12-12 05:47:28 +00005314 // C99 6.5.7p2: Each of the operands shall have integer type.
5315 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005316 return InvalidOperands(Loc, lex, rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005317
Nate Begeman2207d792009-10-25 02:26:48 +00005318 // Vector shifts promote their scalar inputs to vector type.
5319 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5320 return CheckVectorOperands(Loc, lex, rex);
5321
Chris Lattnerca5eede2007-12-12 05:47:28 +00005322 // Shifts don't perform usual arithmetic conversions, they just do integer
5323 // promotions on each operand. C99 6.5.7p3
Eli Friedman04e83572009-08-20 04:21:42 +00005324 QualType LHSTy = Context.isPromotableBitField(lex);
5325 if (LHSTy.isNull()) {
5326 LHSTy = lex->getType();
5327 if (LHSTy->isPromotableIntegerType())
5328 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregor2d833e32009-05-02 00:36:19 +00005329 }
Chris Lattner1dcf2c82007-12-13 07:28:16 +00005330 if (!isCompAssign)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005331 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedmanab3a8522009-03-28 01:22:36 +00005332
Chris Lattnerca5eede2007-12-12 05:47:28 +00005333 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005334
Ryan Flynnd0439682009-08-07 16:20:20 +00005335 // Sanity-check shift operands
5336 llvm::APSInt Right;
5337 // Check right/shifter operand
Daniel Dunbar3f180c62009-09-17 06:31:27 +00005338 if (!rex->isValueDependent() &&
5339 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn8045c732009-08-08 19:18:23 +00005340 if (Right.isNegative())
Ryan Flynnd0439682009-08-07 16:20:20 +00005341 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5342 else {
5343 llvm::APInt LeftBits(Right.getBitWidth(),
5344 Context.getTypeSize(lex->getType()));
5345 if (Right.uge(LeftBits))
5346 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5347 }
5348 }
5349
Chris Lattnerca5eede2007-12-12 05:47:28 +00005350 // "The type of the result is that of the promoted left operand."
Eli Friedmanab3a8522009-03-28 01:22:36 +00005351 return LHSTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005352}
5353
Douglas Gregor0c6db942009-05-04 06:07:12 +00005354// C99 6.5.8, C++ [expr.rel]
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005355QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregora86b8322009-04-06 18:45:53 +00005356 unsigned OpaqueOpc, bool isRelational) {
5357 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5358
Chris Lattner02dd4b12009-12-05 05:40:13 +00005359 // Handle vector comparisons separately.
Nate Begemanbe2341d2008-07-14 18:02:46 +00005360 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005361 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005362
John McCalld1b47bf2010-03-11 19:43:18 +00005363 CheckSignCompare(lex, rex, Loc, &Opc);
John McCall45aa4552009-11-05 00:40:04 +00005364
Chris Lattnera5937dd2007-08-26 01:18:55 +00005365 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff30bf7712007-08-10 18:26:40 +00005366 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5367 UsualArithmeticConversions(lex, rex);
5368 else {
5369 UsualUnaryConversions(lex);
5370 UsualUnaryConversions(rex);
5371 }
Steve Naroffc80b4ee2007-07-16 21:54:35 +00005372 QualType lType = lex->getType();
5373 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005374
Mike Stumpaf199f32009-05-07 18:43:07 +00005375 if (!lType->isFloatingType()
5376 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner55660a72009-03-08 19:39:53 +00005377 // For non-floating point types, check for self-comparisons of the form
5378 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5379 // often indicate logic errors in the program.
Mike Stump1eb44332009-09-09 15:08:12 +00005380 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenek9ecede72009-03-20 19:57:37 +00005381 // from macro expansions, and are usually quite deliberate.
Chris Lattner55660a72009-03-08 19:39:53 +00005382 Expr *LHSStripped = lex->IgnoreParens();
5383 Expr *RHSStripped = rex->IgnoreParens();
5384 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5385 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekb82dcd82009-03-20 18:35:45 +00005386 if (DRL->getDecl() == DRR->getDecl() &&
5387 !isa<EnumConstantDecl>(DRL->getDecl()))
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005388 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Mike Stump1eb44332009-09-09 15:08:12 +00005389
Chris Lattner55660a72009-03-08 19:39:53 +00005390 if (isa<CastExpr>(LHSStripped))
5391 LHSStripped = LHSStripped->IgnoreParenCasts();
5392 if (isa<CastExpr>(RHSStripped))
5393 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00005394
Chris Lattner55660a72009-03-08 19:39:53 +00005395 // Warn about comparisons against a string constant (unless the other
5396 // operand is null), the user probably wants strcmp.
Douglas Gregora86b8322009-04-06 18:45:53 +00005397 Expr *literalString = 0;
5398 Expr *literalStringStripped = 0;
Chris Lattner55660a72009-03-08 19:39:53 +00005399 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005400 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005401 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005402 literalString = lex;
5403 literalStringStripped = LHSStripped;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00005404 } else if ((isa<StringLiteral>(RHSStripped) ||
5405 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005406 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005407 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregora86b8322009-04-06 18:45:53 +00005408 literalString = rex;
5409 literalStringStripped = RHSStripped;
5410 }
5411
5412 if (literalString) {
5413 std::string resultComparison;
5414 switch (Opc) {
5415 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5416 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5417 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5418 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5419 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5420 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5421 default: assert(false && "Invalid comparison operator");
5422 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005423
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005424 DiagRuntimeBehavior(Loc,
5425 PDiag(diag::warn_stringcompare)
5426 << isa<ObjCEncodeExpr>(literalStringStripped)
5427 << literalString->getSourceRange()
Douglas Gregord0ebe082010-03-31 15:31:50 +00005428 << FixItHint::CreateReplacement(SourceRange(Loc), ", ")
5429 << FixItHint::CreateInsertion(lex->getLocStart(), "strcmp(")
5430 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(rex->getLocEnd()),
5431 resultComparison));
Douglas Gregora86b8322009-04-06 18:45:53 +00005432 }
Ted Kremenek3ca0bf22007-10-29 16:58:49 +00005433 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005434
Douglas Gregor447b69e2008-11-19 03:25:36 +00005435 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005436 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregor447b69e2008-11-19 03:25:36 +00005437
Chris Lattnera5937dd2007-08-26 01:18:55 +00005438 if (isRelational) {
5439 if (lType->isRealType() && rType->isRealType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005440 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005441 } else {
Ted Kremenek72cb1ae2007-10-29 17:13:39 +00005442 // Check for comparisons of floating point operands using != and ==.
Chris Lattner02dd4b12009-12-05 05:40:13 +00005443 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005444 CheckFloatComparison(Loc,lex,rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005445
Chris Lattnera5937dd2007-08-26 01:18:55 +00005446 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor447b69e2008-11-19 03:25:36 +00005447 return ResultTy;
Chris Lattnera5937dd2007-08-26 01:18:55 +00005448 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005449
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005450 bool LHSIsNull = lex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005451 Expr::NPC_ValueDependentIsNull);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005452 bool RHSIsNull = rex->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00005453 Expr::NPC_ValueDependentIsNull);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005454
Chris Lattnera5937dd2007-08-26 01:18:55 +00005455 // All of the following pointer related warnings are GCC extensions, except
5456 // when handling null pointer constants. One day, we can consider making them
5457 // errors (when -pedantic-errors is enabled).
Steve Naroff77878cc2007-08-27 04:08:11 +00005458 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattnerbc896f52008-04-03 05:07:25 +00005459 QualType LCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005460 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattnerbc896f52008-04-03 05:07:25 +00005461 QualType RCanPointeeTy =
Ted Kremenek6217b802009-07-29 21:53:49 +00005462 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00005463
Douglas Gregor0c6db942009-05-04 06:07:12 +00005464 if (getLangOptions().CPlusPlus) {
Eli Friedman3075e762009-08-23 00:27:47 +00005465 if (LCanPointeeTy == RCanPointeeTy)
5466 return ResultTy;
Fariborz Jahanian51874dd2009-12-21 18:19:17 +00005467 if (!isRelational &&
5468 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5469 // Valid unless comparison between non-null pointer and function pointer
5470 // This is a gcc extension compatibility comparison.
5471 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5472 && !LHSIsNull && !RHSIsNull) {
5473 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5474 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5475 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5476 return ResultTy;
5477 }
5478 }
Douglas Gregor0c6db942009-05-04 06:07:12 +00005479 // C++ [expr.rel]p2:
5480 // [...] Pointer conversions (4.10) and qualification
5481 // conversions (4.4) are performed on pointer operands (or on
5482 // a pointer operand and a null pointer constant) to bring
5483 // them to their composite pointer type. [...]
5484 //
Douglas Gregor20b3e992009-08-24 17:42:35 +00005485 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor0c6db942009-05-04 06:07:12 +00005486 // comparisons of pointers.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005487 bool NonStandardCompositeType = false;
5488 QualType T = FindCompositePointerType(lex, rex,
5489 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005490 if (T.isNull()) {
5491 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5492 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5493 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005494 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005495 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005496 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005497 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005498 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor0c6db942009-05-04 06:07:12 +00005499 }
5500
Eli Friedman73c39ab2009-10-20 08:27:19 +00005501 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5502 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor0c6db942009-05-04 06:07:12 +00005503 return ResultTy;
5504 }
Eli Friedman3075e762009-08-23 00:27:47 +00005505 // C99 6.5.9p2 and C99 6.5.8p2
5506 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5507 RCanPointeeTy.getUnqualifiedType())) {
5508 // Valid unless a relational comparison of function pointers
5509 if (isRelational && LCanPointeeTy->isFunctionType()) {
5510 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5511 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5512 }
5513 } else if (!isRelational &&
5514 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5515 // Valid unless comparison between non-null pointer and function pointer
5516 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5517 && !LHSIsNull && !RHSIsNull) {
5518 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5519 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5520 }
5521 } else {
5522 // Invalid
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005523 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005524 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00005525 }
Eli Friedman3075e762009-08-23 00:27:47 +00005526 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman73c39ab2009-10-20 08:27:19 +00005527 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005528 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005529 }
Mike Stump1eb44332009-09-09 15:08:12 +00005530
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005531 if (getLangOptions().CPlusPlus) {
Mike Stump1eb44332009-09-09 15:08:12 +00005532 // Comparison of pointers with null pointer constants and equality
Douglas Gregor20b3e992009-08-24 17:42:35 +00005533 // comparisons of member pointers to null pointer constants.
Mike Stump1eb44332009-09-09 15:08:12 +00005534 if (RHSIsNull &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005535 (lType->isPointerType() ||
5536 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005537 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005538 return ResultTy;
5539 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005540 if (LHSIsNull &&
5541 (rType->isPointerType() ||
5542 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson26ba8502009-08-24 18:03:14 +00005543 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005544 return ResultTy;
5545 }
Douglas Gregor20b3e992009-08-24 17:42:35 +00005546
5547 // Comparison of member pointers.
Mike Stump1eb44332009-09-09 15:08:12 +00005548 if (!isRelational &&
Douglas Gregor20b3e992009-08-24 17:42:35 +00005549 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5550 // C++ [expr.eq]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005551 // In addition, pointers to members can be compared, or a pointer to
5552 // member and a null pointer constant. Pointer to member conversions
5553 // (4.11) and qualification conversions (4.4) are performed to bring
5554 // them to a common type. If one operand is a null pointer constant,
5555 // the common type is the type of the other operand. Otherwise, the
5556 // common type is a pointer to member type similar (4.4) to the type
5557 // of one of the operands, with a cv-qualification signature (4.4)
5558 // that is the union of the cv-qualification signatures of the operand
Douglas Gregor20b3e992009-08-24 17:42:35 +00005559 // types.
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005560 bool NonStandardCompositeType = false;
5561 QualType T = FindCompositePointerType(lex, rex,
5562 isSFINAEContext()? 0 : &NonStandardCompositeType);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005563 if (T.isNull()) {
5564 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005565 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005566 return QualType();
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005567 } else if (NonStandardCompositeType) {
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005568 Diag(Loc,
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005569 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005570 << lType << rType << T
Douglas Gregorb2cb1cb2010-02-25 22:29:57 +00005571 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor20b3e992009-08-24 17:42:35 +00005572 }
Mike Stump1eb44332009-09-09 15:08:12 +00005573
Eli Friedman73c39ab2009-10-20 08:27:19 +00005574 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5575 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor20b3e992009-08-24 17:42:35 +00005576 return ResultTy;
5577 }
Mike Stump1eb44332009-09-09 15:08:12 +00005578
Douglas Gregor20b3e992009-08-24 17:42:35 +00005579 // Comparison of nullptr_t with itself.
Sebastian Redl6e8ed162009-05-10 18:38:11 +00005580 if (lType->isNullPtrType() && rType->isNullPtrType())
5581 return ResultTy;
5582 }
Mike Stump1eb44332009-09-09 15:08:12 +00005583
Steve Naroff1c7d0672008-09-04 15:10:53 +00005584 // Handle block pointer types.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005585 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005586 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5587 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005588
Steve Naroff1c7d0672008-09-04 15:10:53 +00005589 if (!LHSIsNull && !RHSIsNull &&
Eli Friedman26784c12009-06-08 05:08:54 +00005590 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005591 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattnerd1625842008-11-24 06:25:27 +00005592 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1c7d0672008-09-04 15:10:53 +00005593 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005594 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005595 return ResultTy;
Steve Naroff1c7d0672008-09-04 15:10:53 +00005596 }
Steve Naroff59f53942008-09-28 01:11:11 +00005597 // Allow block pointers to be compared with null pointer constants.
Mike Stumpdd3e1662009-05-07 03:14:14 +00005598 if (!isRelational
5599 && ((lType->isBlockPointerType() && rType->isPointerType())
5600 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroff59f53942008-09-28 01:11:11 +00005601 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005602 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005603 ->getPointeeType()->isVoidType())
Ted Kremenek6217b802009-07-29 21:53:49 +00005604 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpdd3e1662009-05-07 03:14:14 +00005605 ->getPointeeType()->isVoidType())))
5606 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5607 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff59f53942008-09-28 01:11:11 +00005608 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005609 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005610 return ResultTy;
Steve Naroff59f53942008-09-28 01:11:11 +00005611 }
Steve Naroff1c7d0672008-09-04 15:10:53 +00005612
Steve Naroff14108da2009-07-10 23:34:53 +00005613 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroffa5ad8632008-10-27 10:33:19 +00005614 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenek6217b802009-07-29 21:53:49 +00005615 const PointerType *LPT = lType->getAs<PointerType>();
5616 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005617 bool LPtrToVoid = LPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005618 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005619 bool RPtrToVoid = RPT ?
Steve Naroffa8069f12008-11-17 19:49:16 +00005620 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005621
Steve Naroffa8069f12008-11-17 19:49:16 +00005622 if (!LPtrToVoid && !RPtrToVoid &&
5623 !Context.typesAreCompatible(lType, rType)) {
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00005624 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattnerd1625842008-11-24 06:25:27 +00005625 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffa5ad8632008-10-27 10:33:19 +00005626 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005627 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005628 return ResultTy;
Steve Naroff87f3b932008-10-20 18:19:10 +00005629 }
Steve Naroff14108da2009-07-10 23:34:53 +00005630 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005631 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff14108da2009-07-10 23:34:53 +00005632 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5633 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman73c39ab2009-10-20 08:27:19 +00005634 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005635 return ResultTy;
Steve Naroff20373222008-06-03 14:04:54 +00005636 }
Fariborz Jahanian7359f042007-12-20 01:06:58 +00005637 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005638 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005639 unsigned DiagID = 0;
5640 if (RHSIsNull) {
5641 if (isRelational)
5642 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5643 } else if (isRelational)
5644 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5645 else
5646 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005647
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005648 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005649 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005650 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005651 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005652 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005653 return ResultTy;
Steve Naroffe77fd3c2007-08-16 21:48:38 +00005654 }
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005655 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005656 unsigned DiagID = 0;
5657 if (LHSIsNull) {
5658 if (isRelational)
5659 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5660 } else if (isRelational)
5661 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5662 else
5663 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump1eb44332009-09-09 15:08:12 +00005664
Chris Lattner06c0f5b2009-08-23 00:03:44 +00005665 if (DiagID) {
Chris Lattner6365e3e2009-08-22 18:58:31 +00005666 Diag(Loc, DiagID)
Chris Lattner149f1382009-06-30 06:24:05 +00005667 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner6365e3e2009-08-22 18:58:31 +00005668 }
Eli Friedman73c39ab2009-10-20 08:27:19 +00005669 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005670 return ResultTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005671 }
Steve Naroff39218df2008-09-04 16:56:14 +00005672 // Handle block pointers.
Mike Stumpaf199f32009-05-07 18:43:07 +00005673 if (!isRelational && RHSIsNull
5674 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005675 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005676 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005677 }
Mike Stumpaf199f32009-05-07 18:43:07 +00005678 if (!isRelational && LHSIsNull
5679 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +00005680 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregor447b69e2008-11-19 03:25:36 +00005681 return ResultTy;
Steve Naroff39218df2008-09-04 16:56:14 +00005682 }
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005683 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005684}
5685
Nate Begemanbe2341d2008-07-14 18:02:46 +00005686/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stumpeed9cac2009-02-19 03:04:26 +00005687/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005688/// like a scalar comparison, a vector comparison produces a vector of integer
5689/// types.
5690QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005691 SourceLocation Loc,
Nate Begemanbe2341d2008-07-14 18:02:46 +00005692 bool isRelational) {
5693 // Check to make sure we're operating on vectors of the same type and width,
5694 // Allowing one side to be a scalar of element type.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005695 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005696 if (vType.isNull())
5697 return vType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005698
Nate Begemanbe2341d2008-07-14 18:02:46 +00005699 QualType lType = lex->getType();
5700 QualType rType = rex->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005701
Nate Begemanbe2341d2008-07-14 18:02:46 +00005702 // For non-floating point types, check for self-comparisons of the form
5703 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5704 // often indicate logic errors in the program.
5705 if (!lType->isFloatingType()) {
5706 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5707 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5708 if (DRL->getDecl() == DRR->getDecl())
Douglas Gregord1e4d9b2010-01-12 23:18:54 +00005709 DiagRuntimeBehavior(Loc, PDiag(diag::warn_selfcomparison));
Nate Begemanbe2341d2008-07-14 18:02:46 +00005710 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005711
Nate Begemanbe2341d2008-07-14 18:02:46 +00005712 // Check for comparisons of floating point operands using != and ==.
5713 if (!isRelational && lType->isFloatingType()) {
5714 assert (rType->isFloatingType());
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005715 CheckFloatComparison(Loc,lex,rex);
Nate Begemanbe2341d2008-07-14 18:02:46 +00005716 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00005717
Nate Begemanbe2341d2008-07-14 18:02:46 +00005718 // Return the type for the comparison, which is the same as vector type for
5719 // integer vectors, or an integer type of identical size and number of
5720 // elements for floating point vectors.
5721 if (lType->isIntegerType())
5722 return lType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005723
John McCall183700f2009-09-21 23:43:11 +00005724 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begemanbe2341d2008-07-14 18:02:46 +00005725 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman59b5da62009-01-18 03:20:47 +00005726 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanbe2341d2008-07-14 18:02:46 +00005727 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattnerd013aa12009-03-31 07:46:52 +00005728 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman59b5da62009-01-18 03:20:47 +00005729 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5730
Mike Stumpeed9cac2009-02-19 03:04:26 +00005731 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman59b5da62009-01-18 03:20:47 +00005732 "Unhandled vector element size in vector compare");
Nate Begemanbe2341d2008-07-14 18:02:46 +00005733 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5734}
5735
Reid Spencer5f016e22007-07-11 17:01:13 +00005736inline QualType Sema::CheckBitwiseOperands(
Mike Stump1eb44332009-09-09 15:08:12 +00005737 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff3e5e5562007-07-16 22:23:01 +00005738 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005739 return CheckVectorOperands(Loc, lex, rex);
Steve Naroff90045e82007-07-13 23:32:42 +00005740
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005741 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005742
Steve Naroffa4332e22007-07-17 00:58:39 +00005743 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff9f5fa9b2007-08-24 19:07:16 +00005744 return compType;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005745 return InvalidOperands(Loc, lex, rex);
Reid Spencer5f016e22007-07-11 17:01:13 +00005746}
5747
5748inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump1eb44332009-09-09 15:08:12 +00005749 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005750 if (!Context.getLangOptions().CPlusPlus) {
5751 UsualUnaryConversions(lex);
5752 UsualUnaryConversions(rex);
Mike Stumpeed9cac2009-02-19 03:04:26 +00005753
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005754 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5755 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005756
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005757 return Context.IntTy;
Anders Carlsson04905012009-10-16 01:44:21 +00005758 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005759
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005760 // C++ [expr.log.and]p1
5761 // C++ [expr.log.or]p1
5762 // The operands are both implicitly converted to type bool (clause 4).
5763 StandardConversionSequence LHS;
5764 if (!IsStandardConversion(lex, Context.BoolTy,
5765 /*InOverloadResolution=*/false, LHS))
5766 return InvalidOperands(Loc, lex, rex);
Anders Carlsson04905012009-10-16 01:44:21 +00005767
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005768 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005769 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005770 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005771
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005772 StandardConversionSequence RHS;
5773 if (!IsStandardConversion(rex, Context.BoolTy,
5774 /*InOverloadResolution=*/false, RHS))
5775 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005776
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005777 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
Douglas Gregor68647482009-12-16 03:45:30 +00005778 AA_Passing, /*IgnoreBaseAccess=*/false))
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005779 return InvalidOperands(Loc, lex, rex);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00005780
Anders Carlssona4c98cd2009-11-23 21:47:44 +00005781 // C++ [expr.log.and]p2
5782 // C++ [expr.log.or]p2
5783 // The result is a bool.
5784 return Context.BoolTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00005785}
5786
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005787/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5788/// is a read-only property; return true if so. A readonly property expression
5789/// depends on various declarations and thus must be treated specially.
5790///
Mike Stump1eb44332009-09-09 15:08:12 +00005791static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005792 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5793 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5794 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5795 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005796 if (const ObjCObjectPointerType *OPT =
Steve Naroff14108da2009-07-10 23:34:53 +00005797 BaseType->getAsObjCInterfacePointerType())
5798 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5799 if (S.isPropertyReadonly(PDecl, IFace))
5800 return true;
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005801 }
5802 }
5803 return false;
5804}
5805
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005806/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5807/// emit an error and return true. If so, return false.
5808static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005809 SourceLocation OrigLoc = Loc;
Mike Stump1eb44332009-09-09 15:08:12 +00005810 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005811 &Loc);
Fariborz Jahaniand1fa6442009-01-12 19:55:42 +00005812 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5813 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005814 if (IsLV == Expr::MLV_Valid)
5815 return false;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005816
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005817 unsigned Diag = 0;
5818 bool NeedType = false;
5819 switch (IsLV) { // C99 6.5.16p2
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005820 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005821 case Expr::MLV_ArrayType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005822 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5823 NeedType = true;
5824 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005825 case Expr::MLV_NotObjectType:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005826 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5827 NeedType = true;
5828 break;
Chris Lattnerca354fa2008-11-17 19:51:54 +00005829 case Expr::MLV_LValueCast:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005830 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5831 break;
Douglas Gregore873fb72010-02-16 21:39:57 +00005832 case Expr::MLV_Valid:
5833 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner5cf216b2008-01-04 18:04:52 +00005834 case Expr::MLV_InvalidExpression:
Douglas Gregore873fb72010-02-16 21:39:57 +00005835 case Expr::MLV_MemberFunction:
5836 case Expr::MLV_ClassTemporary:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005837 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5838 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00005839 case Expr::MLV_IncompleteType:
5840 case Expr::MLV_IncompleteVoidType:
Douglas Gregor86447ec2009-03-09 16:13:40 +00005841 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005842 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssonb7906612009-08-26 23:45:07 +00005843 << E->getSourceRange());
Chris Lattner5cf216b2008-01-04 18:04:52 +00005844 case Expr::MLV_DuplicateVectorComponents:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005845 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5846 break;
Steve Naroff4f6a7d72008-09-26 14:41:28 +00005847 case Expr::MLV_NotBlockQualified:
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005848 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5849 break;
Fariborz Jahanian5daf5702008-11-22 18:39:36 +00005850 case Expr::MLV_ReadonlyProperty:
5851 Diag = diag::error_readonly_property_assignment;
5852 break;
Fariborz Jahanianba8d2d62008-11-22 20:25:50 +00005853 case Expr::MLV_NoSetterProperty:
5854 Diag = diag::error_nosetter_property_assignment;
5855 break;
Fariborz Jahanian2514a302009-12-15 23:59:41 +00005856 case Expr::MLV_SubObjCPropertySetting:
5857 Diag = diag::error_no_subobject_property_setting;
5858 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00005859 }
Steve Naroffd1861fd2007-07-31 12:34:36 +00005860
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005861 SourceRange Assign;
5862 if (Loc != OrigLoc)
5863 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005864 if (NeedType)
Daniel Dunbar44e35f72009-04-15 00:08:05 +00005865 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005866 else
Mike Stump1eb44332009-09-09 15:08:12 +00005867 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005868 return true;
5869}
5870
5871
5872
5873// C99 6.5.16.1
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005874QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5875 SourceLocation Loc,
5876 QualType CompoundType) {
5877 // Verify that LHS is a modifiable lvalue, and emit error if not.
5878 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattnerf67bd9f2008-11-18 01:22:49 +00005879 return QualType();
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005880
5881 QualType LHSType = LHS->getType();
5882 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005883
Chris Lattner5cf216b2008-01-04 18:04:52 +00005884 AssignConvertType ConvTy;
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005885 if (CompoundType.isNull()) {
Chris Lattner2c156472008-08-21 18:04:13 +00005886 // Simple assignment "x = y".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005887 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005888 // Special case of NSObject attributes on c-style pointer types.
5889 if (ConvTy == IncompatiblePointer &&
5890 ((Context.isObjCNSObjectType(LHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005891 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005892 (Context.isObjCNSObjectType(RHSType) &&
Steve Narofff4954562009-07-16 15:41:00 +00005893 LHSType->isObjCObjectPointerType())))
Fariborz Jahanianfa23c1d2009-01-13 23:34:40 +00005894 ConvTy = Compatible;
Mike Stumpeed9cac2009-02-19 03:04:26 +00005895
Chris Lattner2c156472008-08-21 18:04:13 +00005896 // If the RHS is a unary plus or minus, check to see if they = and + are
5897 // right next to each other. If so, the user may have typo'd "x =+ 4"
5898 // instead of "x += 4".
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005899 Expr *RHSCheck = RHS;
Chris Lattner2c156472008-08-21 18:04:13 +00005900 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5901 RHSCheck = ICE->getSubExpr();
5902 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5903 if ((UO->getOpcode() == UnaryOperator::Plus ||
5904 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005905 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner2c156472008-08-21 18:04:13 +00005906 // Only if the two operators are exactly adjacent.
Chris Lattner399bd1b2009-03-08 06:51:10 +00005907 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5908 // And there is a space or other character before the subexpr of the
5909 // unary +/-. We don't want to warn on "x=-1".
Chris Lattner3e872092009-03-09 07:11:10 +00005910 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5911 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00005912 Diag(Loc, diag::warn_not_compound_assign)
5913 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5914 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner399bd1b2009-03-08 06:51:10 +00005915 }
Chris Lattner2c156472008-08-21 18:04:13 +00005916 }
5917 } else {
5918 // Compound assignment "x += y"
Eli Friedman623712b2009-05-16 05:56:02 +00005919 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner2c156472008-08-21 18:04:13 +00005920 }
Chris Lattner5cf216b2008-01-04 18:04:52 +00005921
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005922 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
Douglas Gregor68647482009-12-16 03:45:30 +00005923 RHS, AA_Assigning))
Chris Lattner5cf216b2008-01-04 18:04:52 +00005924 return QualType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00005925
Reid Spencer5f016e22007-07-11 17:01:13 +00005926 // C99 6.5.16p3: The type of an assignment expression is the type of the
5927 // left operand unless the left operand has qualified type, in which case
Mike Stumpeed9cac2009-02-19 03:04:26 +00005928 // it is the unqualified version of the type of the left operand.
Reid Spencer5f016e22007-07-11 17:01:13 +00005929 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5930 // is converted to the type of the assignment expression (above).
Chris Lattner73d0d4f2007-08-30 17:45:32 +00005931 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor2d833e32009-05-02 00:36:19 +00005932 // operand.
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005933 return LHSType.getUnqualifiedType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005934}
5935
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005936// C99 6.5.17
5937QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner53fcaa92008-07-25 20:54:07 +00005938 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Douglas Gregora873dfc2010-02-03 00:27:59 +00005939 // C++ does not perform this conversion (C++ [expr.comma]p1).
5940 if (!getLangOptions().CPlusPlus)
5941 DefaultFunctionArrayLvalueConversion(RHS);
Eli Friedmanb1d796d2009-03-23 00:24:07 +00005942
5943 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5944 // incomplete in C++).
5945
Chris Lattner29a1cfb2008-11-18 01:30:42 +00005946 return RHS->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00005947}
5948
Steve Naroff49b45262007-07-13 16:58:59 +00005949/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5950/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005951QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5952 bool isInc) {
Sebastian Redl28507842009-02-26 14:39:58 +00005953 if (Op->isTypeDependent())
5954 return Context.DependentTy;
5955
Chris Lattner3528d352008-11-21 07:05:48 +00005956 QualType ResType = Op->getType();
5957 assert(!ResType.isNull() && "no type for increment/decrement expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00005958
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00005959 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5960 // Decrement of bool is not allowed.
5961 if (!isInc) {
5962 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5963 return QualType();
5964 }
5965 // Increment of bool sets it to true, but is deprecated.
5966 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5967 } else if (ResType->isRealType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00005968 // OK!
Steve Naroff58f9f2c2009-07-14 18:25:06 +00005969 } else if (ResType->isAnyPointerType()) {
5970 QualType PointeeTy = ResType->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00005971
Chris Lattner3528d352008-11-21 07:05:48 +00005972 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff14108da2009-07-10 23:34:53 +00005973 if (PointeeTy->isVoidType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005974 if (getLangOptions().CPlusPlus) {
5975 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5976 << Op->getSourceRange();
5977 return QualType();
5978 }
5979
5980 // Pointer to void is a GNU extension in C.
Chris Lattner3528d352008-11-21 07:05:48 +00005981 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005982 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorc983b862009-01-23 00:36:41 +00005983 if (getLangOptions().CPlusPlus) {
5984 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5985 << Op->getType() << Op->getSourceRange();
5986 return QualType();
5987 }
5988
5989 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattnerd1625842008-11-24 06:25:27 +00005990 << ResType << Op->getSourceRange();
Steve Naroff14108da2009-07-10 23:34:53 +00005991 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlssond497ba72009-08-26 22:59:12 +00005992 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump1eb44332009-09-09 15:08:12 +00005993 << Op->getSourceRange()
Anders Carlssond497ba72009-08-26 22:59:12 +00005994 << ResType))
Douglas Gregor4ec339f2009-01-19 19:26:10 +00005995 return QualType();
Fariborz Jahanian9f8a04f2009-07-16 17:59:14 +00005996 // Diagnose bad cases where we step over interface counts.
5997 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5998 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5999 << PointeeTy << Op->getSourceRange();
6000 return QualType();
6001 }
Eli Friedman5b088a12010-01-03 00:20:48 +00006002 } else if (ResType->isAnyComplexType()) {
Chris Lattner3528d352008-11-21 07:05:48 +00006003 // C99 does not support ++/-- on complex types, we allow as an extension.
6004 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006005 << ResType << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00006006 } else {
6007 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Douglas Gregor5cc07df2009-12-15 16:44:32 +00006008 << ResType << int(isInc) << Op->getSourceRange();
Chris Lattner3528d352008-11-21 07:05:48 +00006009 return QualType();
Reid Spencer5f016e22007-07-11 17:01:13 +00006010 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006011 // At this point, we know we have a real, complex or pointer type.
Steve Naroffdd10e022007-08-23 21:37:33 +00006012 // Now make sure the operand is a modifiable lvalue.
Chris Lattner3528d352008-11-21 07:05:48 +00006013 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Reid Spencer5f016e22007-07-11 17:01:13 +00006014 return QualType();
Chris Lattner3528d352008-11-21 07:05:48 +00006015 return ResType;
Reid Spencer5f016e22007-07-11 17:01:13 +00006016}
6017
Anders Carlsson369dee42008-02-01 07:15:58 +00006018/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Reid Spencer5f016e22007-07-11 17:01:13 +00006019/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006020/// where the declaration is needed for type checking. We only need to
6021/// handle cases when the expression references a function designator
6022/// or is an lvalue. Here are some examples:
6023/// - &(x) => x
6024/// - &*****f => f for f a function designator.
6025/// - &s.xx => s
6026/// - &s.zz[1].yy -> s, if zz is an array
6027/// - *(x + 1) -> x, if x is an array
6028/// - &"123"[2] -> 0
6029/// - & __real__ x -> x
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006030static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattnerf0467b32008-04-02 04:24:33 +00006031 switch (E->getStmtClass()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006032 case Stmt::DeclRefExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00006033 return cast<DeclRefExpr>(E)->getDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00006034 case Stmt::MemberExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00006035 // If this is an arrow operator, the address is an offset from
6036 // the base's value, so the object the base refers to is
6037 // irrelevant.
Chris Lattnerf0467b32008-04-02 04:24:33 +00006038 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnerf82228f2007-11-16 17:46:48 +00006039 return 0;
Eli Friedman23d58ce2009-04-20 08:23:18 +00006040 // Otherwise, the expression refers to a part of the base
Chris Lattnerf0467b32008-04-02 04:24:33 +00006041 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson369dee42008-02-01 07:15:58 +00006042 case Stmt::ArraySubscriptExprClass: {
Mike Stump390b4cc2009-05-16 07:39:55 +00006043 // FIXME: This code shouldn't be necessary! We should catch the implicit
6044 // promotion of register arrays earlier.
Eli Friedman23d58ce2009-04-20 08:23:18 +00006045 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
6046 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
6047 if (ICE->getSubExpr()->getType()->isArrayType())
6048 return getPrimaryDecl(ICE->getSubExpr());
6049 }
6050 return 0;
Anders Carlsson369dee42008-02-01 07:15:58 +00006051 }
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006052 case Stmt::UnaryOperatorClass: {
6053 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006054
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006055 switch(UO->getOpcode()) {
Daniel Dunbar1e76ce62008-08-04 20:02:37 +00006056 case UnaryOperator::Real:
6057 case UnaryOperator::Imag:
6058 case UnaryOperator::Extension:
6059 return getPrimaryDecl(UO->getSubExpr());
6060 default:
6061 return 0;
6062 }
6063 }
Reid Spencer5f016e22007-07-11 17:01:13 +00006064 case Stmt::ParenExprClass:
Chris Lattnerf0467b32008-04-02 04:24:33 +00006065 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf82228f2007-11-16 17:46:48 +00006066 case Stmt::ImplicitCastExprClass:
Eli Friedman23d58ce2009-04-20 08:23:18 +00006067 // If the result of an implicit cast is an l-value, we care about
6068 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattnerf0467b32008-04-02 04:24:33 +00006069 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Reid Spencer5f016e22007-07-11 17:01:13 +00006070 default:
6071 return 0;
6072 }
6073}
6074
6075/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stumpeed9cac2009-02-19 03:04:26 +00006076/// designator or an lvalue designating an object. If it is an lvalue, the
Reid Spencer5f016e22007-07-11 17:01:13 +00006077/// object cannot be declared with storage class register or be a bit field.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006078/// Note: The usual conversions are *not* applied to the operand of the &
Reid Spencer5f016e22007-07-11 17:01:13 +00006079/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006080/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor904eed32008-11-10 20:40:00 +00006081/// we allow the '&' but retain the overloaded-function type.
Reid Spencer5f016e22007-07-11 17:01:13 +00006082QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00006083 // Make sure to ignore parentheses in subsequent checks
6084 op = op->IgnoreParens();
6085
Douglas Gregor9103bb22008-12-17 22:52:20 +00006086 if (op->isTypeDependent())
6087 return Context.DependentTy;
6088
Steve Naroff08f19672008-01-13 17:10:08 +00006089 if (getLangOptions().C99) {
6090 // Implement C99-only parts of addressof rules.
6091 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
6092 if (uOp->getOpcode() == UnaryOperator::Deref)
6093 // Per C99 6.5.3.2, the address of a deref always returns a valid result
6094 // (assuming the deref expression is valid).
6095 return uOp->getSubExpr()->getType();
6096 }
6097 // Technically, there should be a check for array subscript
6098 // expressions here, but the result of one is always an lvalue anyway.
6099 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006100 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner28be73f2008-07-26 21:30:36 +00006101 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes6b6609f2008-12-16 22:59:47 +00006102
Sebastian Redle27d87f2010-01-11 15:56:56 +00006103 MemberExpr *ME = dyn_cast<MemberExpr>(op);
6104 if (lval == Expr::LV_MemberFunction && ME &&
6105 isa<CXXMethodDecl>(ME->getMemberDecl())) {
6106 ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
6107 // &f where f is a member of the current object, or &o.f, or &p->f
6108 // All these are not allowed, and we need to catch them before the dcl
6109 // branch of the if, below.
6110 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
6111 << dcl;
6112 // FIXME: Improve this diagnostic and provide a fixit.
6113
6114 // Now recover by acting as if the function had been accessed qualified.
6115 return Context.getMemberPointerType(op->getType(),
6116 Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
6117 .getTypePtr());
Douglas Gregore873fb72010-02-16 21:39:57 +00006118 } else if (lval == Expr::LV_ClassTemporary) {
6119 Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6120 : diag::ext_typecheck_addrof_class_temporary)
6121 << op->getType() << op->getSourceRange();
6122 if (isSFINAEContext())
6123 return QualType();
Sebastian Redle27d87f2010-01-11 15:56:56 +00006124 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedman441cf102009-05-16 23:27:50 +00006125 // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006126 // The operand must be either an l-value or a function designator
Eli Friedman441cf102009-05-16 23:27:50 +00006127 if (!op->getType()->isFunctionType()) {
Chris Lattnerf82228f2007-11-16 17:46:48 +00006128 // FIXME: emit more specific diag...
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006129 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6130 << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006131 return QualType();
6132 }
Douglas Gregor33bbbc52009-05-02 02:18:30 +00006133 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman23d58ce2009-04-20 08:23:18 +00006134 // The operand cannot be a bit-field
6135 Diag(OpLoc, diag::err_typecheck_address_of)
6136 << "bit-field" << op->getSourceRange();
Douglas Gregor86f19402008-12-20 23:49:58 +00006137 return QualType();
Anders Carlsson09380262010-01-31 17:18:49 +00006138 } else if (op->refersToVectorElement()) {
Eli Friedman23d58ce2009-04-20 08:23:18 +00006139 // The operand cannot be an element of a vector
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006140 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemanb104b1f2009-02-15 22:45:20 +00006141 << "vector element" << op->getSourceRange();
Steve Naroffbcb2b612008-02-29 23:30:25 +00006142 return QualType();
Fariborz Jahanian0337f212009-07-07 18:50:52 +00006143 } else if (isa<ObjCPropertyRefExpr>(op)) {
6144 // cannot take address of a property expression.
6145 Diag(OpLoc, diag::err_typecheck_address_of)
6146 << "property expression" << op->getSourceRange();
6147 return QualType();
Anders Carlsson1d524c32009-09-14 23:15:26 +00006148 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6149 // FIXME: Can LHS ever be null here?
Anders Carlsson474e1022009-09-15 16:03:44 +00006150 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6151 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCallba135432009-11-21 08:51:07 +00006152 } else if (isa<UnresolvedLookupExpr>(op)) {
6153 return Context.OverloadTy;
Steve Naroffbcb2b612008-02-29 23:30:25 +00006154 } else if (dcl) { // C99 6.5.3.2p1
Mike Stumpeed9cac2009-02-19 03:04:26 +00006155 // We have an lvalue with a decl. Make sure the decl is not declared
Reid Spencer5f016e22007-07-11 17:01:13 +00006156 // with the register storage-class specifier.
6157 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
6158 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006159 Diag(OpLoc, diag::err_typecheck_address_of)
6160 << "register variable" << op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006161 return QualType();
6162 }
John McCallba135432009-11-21 08:51:07 +00006163 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006164 return Context.OverloadTy;
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006165 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor29882052008-12-10 21:26:49 +00006166 // Okay: we can take the address of a field.
Sebastian Redlebc07d52009-02-03 20:19:35 +00006167 // Could be a pointer to member, though, if there is an explicit
6168 // scope qualifier for the class.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006169 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redlebc07d52009-02-03 20:19:35 +00006170 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006171 if (Ctx && Ctx->isRecord()) {
6172 if (FD->getType()->isReferenceType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006173 Diag(OpLoc,
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006174 diag::err_cannot_form_pointer_to_member_of_reference_type)
6175 << FD->getDeclName() << FD->getType();
6176 return QualType();
6177 }
Mike Stump1eb44332009-09-09 15:08:12 +00006178
Sebastian Redlebc07d52009-02-03 20:19:35 +00006179 return Context.getMemberPointerType(op->getType(),
6180 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlssonf9e48bd2009-07-08 21:45:58 +00006181 }
Sebastian Redlebc07d52009-02-03 20:19:35 +00006182 }
Anders Carlsson196f7d02009-05-16 21:43:42 +00006183 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes6fea8d22008-12-16 22:58:26 +00006184 // Okay: we can take the address of a function.
Sebastian Redl33b399a2009-02-04 21:23:32 +00006185 // As above.
Douglas Gregora2813ce2009-10-23 18:54:35 +00006186 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6187 MD->isInstance())
Anders Carlsson196f7d02009-05-16 21:43:42 +00006188 return Context.getMemberPointerType(op->getType(),
6189 Context.getTypeDeclType(MD->getParent()).getTypePtr());
6190 } else if (!isa<FunctionDecl>(dcl))
Reid Spencer5f016e22007-07-11 17:01:13 +00006191 assert(0 && "Unknown/unexpected decl type");
Reid Spencer5f016e22007-07-11 17:01:13 +00006192 }
Sebastian Redl33b399a2009-02-04 21:23:32 +00006193
Eli Friedman441cf102009-05-16 23:27:50 +00006194 if (lval == Expr::LV_IncompleteVoidType) {
6195 // Taking the address of a void variable is technically illegal, but we
6196 // allow it in cases which are otherwise valid.
6197 // Example: "extern void x; void* y = &x;".
6198 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6199 }
6200
Reid Spencer5f016e22007-07-11 17:01:13 +00006201 // If the operand has type "type", the result has type "pointer to type".
6202 return Context.getPointerType(op->getType());
6203}
6204
Chris Lattner22caddc2008-11-23 09:13:29 +00006205QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl28507842009-02-26 14:39:58 +00006206 if (Op->isTypeDependent())
6207 return Context.DependentTy;
6208
Chris Lattner22caddc2008-11-23 09:13:29 +00006209 UsualUnaryConversions(Op);
6210 QualType Ty = Op->getType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006211
Chris Lattner22caddc2008-11-23 09:13:29 +00006212 // Note that per both C89 and C99, this is always legal, even if ptype is an
6213 // incomplete type or void. It would be possible to warn about dereferencing
6214 // a void pointer, but it's completely well-defined, and such a warning is
6215 // unlikely to catch any mistakes.
Ted Kremenek6217b802009-07-29 21:53:49 +00006216 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff08f19672008-01-13 17:10:08 +00006217 return PT->getPointeeType();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006218
John McCall183700f2009-09-21 23:43:11 +00006219 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanian16b10372009-09-03 00:43:07 +00006220 return OPT->getPointeeType();
Steve Naroff14108da2009-07-10 23:34:53 +00006221
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006222 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner22caddc2008-11-23 09:13:29 +00006223 << Ty << Op->getSourceRange();
Reid Spencer5f016e22007-07-11 17:01:13 +00006224 return QualType();
6225}
6226
6227static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6228 tok::TokenKind Kind) {
6229 BinaryOperator::Opcode Opc;
6230 switch (Kind) {
6231 default: assert(0 && "Unknown binop!");
Sebastian Redl22460502009-02-07 00:15:38 +00006232 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
6233 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006234 case tok::star: Opc = BinaryOperator::Mul; break;
6235 case tok::slash: Opc = BinaryOperator::Div; break;
6236 case tok::percent: Opc = BinaryOperator::Rem; break;
6237 case tok::plus: Opc = BinaryOperator::Add; break;
6238 case tok::minus: Opc = BinaryOperator::Sub; break;
6239 case tok::lessless: Opc = BinaryOperator::Shl; break;
6240 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
6241 case tok::lessequal: Opc = BinaryOperator::LE; break;
6242 case tok::less: Opc = BinaryOperator::LT; break;
6243 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6244 case tok::greater: Opc = BinaryOperator::GT; break;
6245 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6246 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6247 case tok::amp: Opc = BinaryOperator::And; break;
6248 case tok::caret: Opc = BinaryOperator::Xor; break;
6249 case tok::pipe: Opc = BinaryOperator::Or; break;
6250 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6251 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6252 case tok::equal: Opc = BinaryOperator::Assign; break;
6253 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6254 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6255 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6256 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6257 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6258 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6259 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6260 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6261 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6262 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6263 case tok::comma: Opc = BinaryOperator::Comma; break;
6264 }
6265 return Opc;
6266}
6267
6268static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6269 tok::TokenKind Kind) {
6270 UnaryOperator::Opcode Opc;
6271 switch (Kind) {
6272 default: assert(0 && "Unknown unary op!");
6273 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6274 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6275 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6276 case tok::star: Opc = UnaryOperator::Deref; break;
6277 case tok::plus: Opc = UnaryOperator::Plus; break;
6278 case tok::minus: Opc = UnaryOperator::Minus; break;
6279 case tok::tilde: Opc = UnaryOperator::Not; break;
6280 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006281 case tok::kw___real: Opc = UnaryOperator::Real; break;
6282 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6283 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6284 }
6285 return Opc;
6286}
6287
Douglas Gregoreaebc752008-11-06 23:29:22 +00006288/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6289/// operator @p Opc at location @c TokLoc. This routine only supports
6290/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006291Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6292 unsigned Op,
6293 Expr *lhs, Expr *rhs) {
Eli Friedmanab3a8522009-03-28 01:22:36 +00006294 QualType ResultTy; // Result type of the binary operator.
Douglas Gregoreaebc752008-11-06 23:29:22 +00006295 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedmanab3a8522009-03-28 01:22:36 +00006296 // The following two variables are used for compound assignment operators
6297 QualType CompLHSTy; // Type of LHS after promotions for computation
6298 QualType CompResultTy; // Type of computation result
Douglas Gregoreaebc752008-11-06 23:29:22 +00006299
6300 switch (Opc) {
Douglas Gregoreaebc752008-11-06 23:29:22 +00006301 case BinaryOperator::Assign:
6302 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6303 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006304 case BinaryOperator::PtrMemD:
6305 case BinaryOperator::PtrMemI:
6306 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6307 Opc == BinaryOperator::PtrMemI);
6308 break;
6309 case BinaryOperator::Mul:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006310 case BinaryOperator::Div:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006311 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6312 Opc == BinaryOperator::Div);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006313 break;
6314 case BinaryOperator::Rem:
6315 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6316 break;
6317 case BinaryOperator::Add:
6318 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6319 break;
6320 case BinaryOperator::Sub:
6321 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6322 break;
Sebastian Redl22460502009-02-07 00:15:38 +00006323 case BinaryOperator::Shl:
Douglas Gregoreaebc752008-11-06 23:29:22 +00006324 case BinaryOperator::Shr:
6325 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6326 break;
6327 case BinaryOperator::LE:
6328 case BinaryOperator::LT:
6329 case BinaryOperator::GE:
6330 case BinaryOperator::GT:
Douglas Gregora86b8322009-04-06 18:45:53 +00006331 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006332 break;
6333 case BinaryOperator::EQ:
6334 case BinaryOperator::NE:
Douglas Gregora86b8322009-04-06 18:45:53 +00006335 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006336 break;
6337 case BinaryOperator::And:
6338 case BinaryOperator::Xor:
6339 case BinaryOperator::Or:
6340 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6341 break;
6342 case BinaryOperator::LAnd:
6343 case BinaryOperator::LOr:
6344 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6345 break;
6346 case BinaryOperator::MulAssign:
6347 case BinaryOperator::DivAssign:
Chris Lattner7ef655a2010-01-12 21:23:57 +00006348 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6349 Opc == BinaryOperator::DivAssign);
Eli Friedmanab3a8522009-03-28 01:22:36 +00006350 CompLHSTy = CompResultTy;
6351 if (!CompResultTy.isNull())
6352 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006353 break;
6354 case BinaryOperator::RemAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006355 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6356 CompLHSTy = CompResultTy;
6357 if (!CompResultTy.isNull())
6358 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006359 break;
6360 case BinaryOperator::AddAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006361 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6362 if (!CompResultTy.isNull())
6363 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006364 break;
6365 case BinaryOperator::SubAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006366 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6367 if (!CompResultTy.isNull())
6368 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006369 break;
6370 case BinaryOperator::ShlAssign:
6371 case BinaryOperator::ShrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006372 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6373 CompLHSTy = CompResultTy;
6374 if (!CompResultTy.isNull())
6375 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006376 break;
6377 case BinaryOperator::AndAssign:
6378 case BinaryOperator::XorAssign:
6379 case BinaryOperator::OrAssign:
Eli Friedmanab3a8522009-03-28 01:22:36 +00006380 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6381 CompLHSTy = CompResultTy;
6382 if (!CompResultTy.isNull())
6383 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregoreaebc752008-11-06 23:29:22 +00006384 break;
6385 case BinaryOperator::Comma:
6386 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6387 break;
6388 }
6389 if (ResultTy.isNull())
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006390 return ExprError();
Eli Friedmanab3a8522009-03-28 01:22:36 +00006391 if (CompResultTy.isNull())
Steve Naroff6ece14c2009-01-21 00:14:39 +00006392 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6393 else
6394 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedmanab3a8522009-03-28 01:22:36 +00006395 CompLHSTy, CompResultTy,
6396 OpLoc));
Douglas Gregoreaebc752008-11-06 23:29:22 +00006397}
6398
Sebastian Redlaee3c932009-10-27 12:10:02 +00006399/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6400/// ParenRange in parentheses.
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006401static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6402 const PartialDiagnostic &PD,
Douglas Gregor827feec2010-01-08 00:20:23 +00006403 SourceRange ParenRange,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006404 const PartialDiagnostic &SecondPD,
6405 SourceRange SecondParenRange) {
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006406 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6407 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6408 // We can't display the parentheses, so just dig the
6409 // warning/error and return.
6410 Self.Diag(Loc, PD);
6411 return;
6412 }
6413
6414 Self.Diag(Loc, PD)
Douglas Gregord0ebe082010-03-31 15:31:50 +00006415 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6416 << FixItHint::CreateInsertion(EndLoc, ")");
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006417
Douglas Gregor827feec2010-01-08 00:20:23 +00006418 if (!SecondPD.getDiagID())
6419 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006420
Douglas Gregor827feec2010-01-08 00:20:23 +00006421 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6422 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6423 // We can't display the parentheses, so just dig the
6424 // warning/error and return.
6425 Self.Diag(Loc, SecondPD);
6426 return;
6427 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006428
Douglas Gregor827feec2010-01-08 00:20:23 +00006429 Self.Diag(Loc, SecondPD)
Douglas Gregord0ebe082010-03-31 15:31:50 +00006430 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6431 << FixItHint::CreateInsertion(EndLoc, ")");
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006432}
6433
Sebastian Redlaee3c932009-10-27 12:10:02 +00006434/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6435/// operators are mixed in a way that suggests that the programmer forgot that
6436/// comparison operators have higher precedence. The most typical example of
6437/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006438static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6439 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006440 typedef BinaryOperator BinOp;
6441 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6442 rhsopc = static_cast<BinOp::Opcode>(-1);
6443 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006444 lhsopc = BO->getOpcode();
Sebastian Redlaee3c932009-10-27 12:10:02 +00006445 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006446 rhsopc = BO->getOpcode();
6447
6448 // Subs are not binary operators.
6449 if (lhsopc == -1 && rhsopc == -1)
6450 return;
6451
6452 // Bitwise operations are sometimes used as eager logical ops.
6453 // Don't diagnose this.
Sebastian Redlaee3c932009-10-27 12:10:02 +00006454 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6455 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006456 return;
6457
Sebastian Redlaee3c932009-10-27 12:10:02 +00006458 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006459 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006460 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006461 << SourceRange(lhs->getLocStart(), OpLoc)
6462 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
Douglas Gregor827feec2010-01-08 00:20:23 +00006463 lhs->getSourceRange(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006464 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006465 << BinOp::getOpcodeStr(Opc),
Sebastian Redlaee3c932009-10-27 12:10:02 +00006466 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6467 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl6b169ac2009-10-26 17:01:32 +00006468 SuggestParentheses(Self, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006469 Self.PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redlaee3c932009-10-27 12:10:02 +00006470 << SourceRange(OpLoc, rhs->getLocEnd())
6471 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
Douglas Gregor827feec2010-01-08 00:20:23 +00006472 rhs->getSourceRange(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006473 Self.PDiag(diag::note_precedence_bitwise_first)
Douglas Gregor827feec2010-01-08 00:20:23 +00006474 << BinOp::getOpcodeStr(Opc),
Sebastian Redlaee3c932009-10-27 12:10:02 +00006475 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006476}
6477
6478/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6479/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6480/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6481static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6482 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redlaee3c932009-10-27 12:10:02 +00006483 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006484 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6485}
6486
Reid Spencer5f016e22007-07-11 17:01:13 +00006487// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006488Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6489 tok::TokenKind Kind,
6490 ExprArg LHS, ExprArg RHS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006491 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssone9146f22009-05-01 19:49:17 +00006492 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Reid Spencer5f016e22007-07-11 17:01:13 +00006493
Steve Narofff69936d2007-09-16 03:34:24 +00006494 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6495 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Reid Spencer5f016e22007-07-11 17:01:13 +00006496
Sebastian Redl9e1d29b2009-10-26 15:24:15 +00006497 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6498 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6499
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006500 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6501}
6502
6503Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6504 BinaryOperator::Opcode Opc,
6505 Expr *lhs, Expr *rhs) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006506 if (getLangOptions().CPlusPlus &&
Mike Stump1eb44332009-09-09 15:08:12 +00006507 (lhs->getType()->isOverloadableType() ||
Douglas Gregor063daf62009-03-13 18:40:31 +00006508 rhs->getType()->isOverloadableType())) {
6509 // Find all of the overloaded operators visible from this
6510 // point. We perform both an operator-name lookup from the local
6511 // scope and an argument-dependent lookup based on the types of
6512 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006513 UnresolvedSet<16> Functions;
Douglas Gregor063daf62009-03-13 18:40:31 +00006514 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006515 if (S && OverOp != OO_None)
6516 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6517 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006518
Douglas Gregor063daf62009-03-13 18:40:31 +00006519 // Build the (potentially-overloaded, potentially-dependent)
6520 // binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006521 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb8a6aca2009-01-19 22:31:54 +00006522 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006523
Douglas Gregoreaebc752008-11-06 23:29:22 +00006524 // Build a built-in binary operation.
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006525 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Reid Spencer5f016e22007-07-11 17:01:13 +00006526}
6527
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006528Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006529 unsigned OpcIn,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006530 ExprArg InputArg) {
6531 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor74253732008-11-19 15:42:04 +00006532
Mike Stump390b4cc2009-05-16 07:39:55 +00006533 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006534 Expr *Input = (Expr *)InputArg.get();
Reid Spencer5f016e22007-07-11 17:01:13 +00006535 QualType resultType;
6536 switch (Opc) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006537 case UnaryOperator::OffsetOf:
6538 assert(false && "Invalid unary operator");
6539 break;
6540
Reid Spencer5f016e22007-07-11 17:01:13 +00006541 case UnaryOperator::PreInc:
6542 case UnaryOperator::PreDec:
Eli Friedmande99a452009-07-22 22:25:00 +00006543 case UnaryOperator::PostInc:
6544 case UnaryOperator::PostDec:
Sebastian Redle6d5a4a2008-12-20 09:35:34 +00006545 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedmande99a452009-07-22 22:25:00 +00006546 Opc == UnaryOperator::PreInc ||
6547 Opc == UnaryOperator::PostInc);
Reid Spencer5f016e22007-07-11 17:01:13 +00006548 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006549 case UnaryOperator::AddrOf:
Reid Spencer5f016e22007-07-11 17:01:13 +00006550 resultType = CheckAddressOfOperand(Input, OpLoc);
6551 break;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006552 case UnaryOperator::Deref:
Douglas Gregora873dfc2010-02-03 00:27:59 +00006553 DefaultFunctionArrayLvalueConversion(Input);
Reid Spencer5f016e22007-07-11 17:01:13 +00006554 resultType = CheckIndirectionOperand(Input, OpLoc);
6555 break;
6556 case UnaryOperator::Plus:
6557 case UnaryOperator::Minus:
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006558 UsualUnaryConversions(Input);
6559 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006560 if (resultType->isDependentType())
6561 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006562 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6563 break;
6564 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6565 resultType->isEnumeralType())
6566 break;
6567 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6568 Opc == UnaryOperator::Plus &&
6569 resultType->isPointerType())
6570 break;
6571
Sebastian Redl0eb23302009-01-19 00:08:26 +00006572 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6573 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006574 case UnaryOperator::Not: // bitwise complement
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006575 UsualUnaryConversions(Input);
6576 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006577 if (resultType->isDependentType())
6578 break;
Chris Lattner02a65142008-07-25 23:52:49 +00006579 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6580 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6581 // C99 does not support '~' for complex conjugation.
Chris Lattnerd3a94e22008-11-20 06:06:08 +00006582 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattnerd1625842008-11-24 06:25:27 +00006583 << resultType << Input->getSourceRange();
Chris Lattner02a65142008-07-25 23:52:49 +00006584 else if (!resultType->isIntegerType())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006585 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6586 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006587 break;
6588 case UnaryOperator::LNot: // logical negation
6589 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Douglas Gregora873dfc2010-02-03 00:27:59 +00006590 DefaultFunctionArrayLvalueConversion(Input);
Steve Naroffc80b4ee2007-07-16 21:54:35 +00006591 resultType = Input->getType();
Sebastian Redl28507842009-02-26 14:39:58 +00006592 if (resultType->isDependentType())
6593 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006594 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl0eb23302009-01-19 00:08:26 +00006595 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6596 << resultType << Input->getSourceRange());
Reid Spencer5f016e22007-07-11 17:01:13 +00006597 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl0eb23302009-01-19 00:08:26 +00006598 // In C++, it's bool. C++ 5.3.1p8
6599 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00006600 break;
Chris Lattnerdbb36972007-08-24 21:16:53 +00006601 case UnaryOperator::Real:
Chris Lattnerdbb36972007-08-24 21:16:53 +00006602 case UnaryOperator::Imag:
Chris Lattnerba27e2a2009-02-17 08:12:06 +00006603 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattnerdbb36972007-08-24 21:16:53 +00006604 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00006605 case UnaryOperator::Extension:
Reid Spencer5f016e22007-07-11 17:01:13 +00006606 resultType = Input->getType();
6607 break;
6608 }
6609 if (resultType.isNull())
Sebastian Redl0eb23302009-01-19 00:08:26 +00006610 return ExprError();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006611
6612 InputArg.release();
Steve Naroff6ece14c2009-01-21 00:14:39 +00006613 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Reid Spencer5f016e22007-07-11 17:01:13 +00006614}
6615
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006616Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6617 UnaryOperator::Opcode Opc,
6618 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006619 Expr *Input = (Expr*)input.get();
Anders Carlssona8a1e3d2009-11-14 21:26:41 +00006620 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6621 Opc != UnaryOperator::Extension) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006622 // Find all of the overloaded operators visible from this
6623 // point. We perform both an operator-name lookup from the local
6624 // scope and an argument-dependent lookup based on the types of
6625 // the arguments.
John McCall6e266892010-01-26 03:27:55 +00006626 UnresolvedSet<16> Functions;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006627 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall6e266892010-01-26 03:27:55 +00006628 if (S && OverOp != OO_None)
6629 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6630 Functions);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006631
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006632 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6633 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006634
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006635 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6636}
6637
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006638// Unary Operators. 'Tok' is the token for the operator.
6639Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6640 tok::TokenKind Op, ExprArg input) {
6641 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6642}
6643
Steve Naroff1b273c42007-09-16 14:56:35 +00006644/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redlf53597f2009-03-15 17:47:39 +00006645Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6646 SourceLocation LabLoc,
6647 IdentifierInfo *LabelII) {
Reid Spencer5f016e22007-07-11 17:01:13 +00006648 // Look up the record for this label identifier.
Chris Lattnerea29a3a2009-04-18 20:01:55 +00006649 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stumpeed9cac2009-02-19 03:04:26 +00006650
Daniel Dunbar0ffb1252008-08-04 16:51:22 +00006651 // If we haven't seen this label yet, create a forward reference. It
6652 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffcaaacec2009-03-13 15:38:40 +00006653 if (LabelDecl == 0)
Steve Naroff6ece14c2009-01-21 00:14:39 +00006654 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006655
Reid Spencer5f016e22007-07-11 17:01:13 +00006656 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redlf53597f2009-03-15 17:47:39 +00006657 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6658 Context.getPointerType(Context.VoidTy)));
Reid Spencer5f016e22007-07-11 17:01:13 +00006659}
6660
Sebastian Redlf53597f2009-03-15 17:47:39 +00006661Sema::OwningExprResult
6662Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6663 SourceLocation RPLoc) { // "({..})"
6664 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006665 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6666 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6667
Douglas Gregordd8f5692010-03-10 04:54:39 +00006668 bool isFileScope
6669 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattner4a049f02009-04-25 19:11:05 +00006670 if (isFileScope)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006671 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmandca2b732009-01-24 23:09:00 +00006672
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006673 // FIXME: there are a variety of strange constraints to enforce here, for
6674 // example, it is not possible to goto into a stmt expression apparently.
6675 // More semantic analysis is needed.
Mike Stumpeed9cac2009-02-19 03:04:26 +00006676
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006677 // If there are sub stmts in the compound stmt, take the type of the last one
6678 // as the type of the stmtexpr.
6679 QualType Ty = Context.VoidTy;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006680
Chris Lattner611b2ec2008-07-26 19:51:01 +00006681 if (!Compound->body_empty()) {
6682 Stmt *LastStmt = Compound->body_back();
6683 // If LastStmt is a label, skip down through into the body.
6684 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6685 LastStmt = Label->getSubStmt();
Mike Stumpeed9cac2009-02-19 03:04:26 +00006686
Chris Lattner611b2ec2008-07-26 19:51:01 +00006687 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006688 Ty = LastExpr->getType();
Chris Lattner611b2ec2008-07-26 19:51:01 +00006689 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006690
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006691 // FIXME: Check that expression type is complete/non-abstract; statement
6692 // expressions are not lvalues.
6693
Sebastian Redlf53597f2009-03-15 17:47:39 +00006694 substmt.release();
6695 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattnerab18c4c2007-07-24 16:58:17 +00006696}
Steve Naroffd34e9152007-08-01 22:05:33 +00006697
Sebastian Redlf53597f2009-03-15 17:47:39 +00006698Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6699 SourceLocation BuiltinLoc,
6700 SourceLocation TypeLoc,
6701 TypeTy *argty,
6702 OffsetOfComponent *CompPtr,
6703 unsigned NumComponents,
6704 SourceLocation RPLoc) {
6705 // FIXME: This function leaks all expressions in the offset components on
6706 // error.
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006707 // FIXME: Preserve type source info.
6708 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006709 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006710
Sebastian Redl28507842009-02-26 14:39:58 +00006711 bool Dependent = ArgTy->isDependentType();
6712
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006713 // We must have at least one component that refers to the type, and the first
6714 // one is known to be a field designator. Verify that the ArgTy represents
6715 // a struct/union/class.
Sebastian Redl28507842009-02-26 14:39:58 +00006716 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006717 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006718
Eli Friedmanb1d796d2009-03-23 00:24:07 +00006719 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6720 // with an incomplete type would be illegal.
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00006721
Eli Friedman35183ac2009-02-27 06:44:11 +00006722 // Otherwise, create a null pointer as the base, and iteratively process
6723 // the offsetof designators.
6724 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6725 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006726 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman35183ac2009-02-27 06:44:11 +00006727 ArgTy, SourceLocation());
Eli Friedman1d242592009-01-26 01:33:06 +00006728
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006729 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6730 // GCC extension, diagnose them.
Eli Friedman35183ac2009-02-27 06:44:11 +00006731 // FIXME: This diagnostic isn't actually visible because the location is in
6732 // a system header!
Chris Lattner9e2b75c2007-08-31 21:49:13 +00006733 if (NumComponents != 1)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00006734 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6735 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006736
Sebastian Redl28507842009-02-26 14:39:58 +00006737 if (!Dependent) {
Eli Friedmanc0d600c2009-05-03 21:22:18 +00006738 bool DidWarnAboutNonPOD = false;
Mike Stump1eb44332009-09-09 15:08:12 +00006739
John McCalld00f2002009-11-04 03:03:43 +00006740 if (RequireCompleteType(TypeLoc, Res->getType(),
6741 diag::err_offsetof_incomplete_type))
6742 return ExprError();
6743
Sebastian Redl28507842009-02-26 14:39:58 +00006744 // FIXME: Dependent case loses a lot of information here. And probably
6745 // leaks like a sieve.
6746 for (unsigned i = 0; i != NumComponents; ++i) {
6747 const OffsetOfComponent &OC = CompPtr[i];
6748 if (OC.isBrackets) {
6749 // Offset of an array sub-field. TODO: Should we allow vector elements?
6750 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6751 if (!AT) {
6752 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006753 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6754 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006755 }
6756
6757 // FIXME: C++: Verify that operator[] isn't overloaded.
6758
Eli Friedman35183ac2009-02-27 06:44:11 +00006759 // Promote the array so it looks more like a normal array subscript
6760 // expression.
Douglas Gregora873dfc2010-02-03 00:27:59 +00006761 DefaultFunctionArrayLvalueConversion(Res);
Eli Friedman35183ac2009-02-27 06:44:11 +00006762
Sebastian Redl28507842009-02-26 14:39:58 +00006763 // C99 6.5.2.1p1
6764 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006765 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006766 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redlf53597f2009-03-15 17:47:39 +00006767 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner338395d2009-04-25 22:50:55 +00006768 diag::err_typecheck_subscript_not_integer)
Sebastian Redlf53597f2009-03-15 17:47:39 +00006769 << Idx->getSourceRange());
Sebastian Redl28507842009-02-26 14:39:58 +00006770
6771 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6772 OC.LocEnd);
6773 continue;
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006774 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006775
Ted Kremenek6217b802009-07-29 21:53:49 +00006776 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl28507842009-02-26 14:39:58 +00006777 if (!RC) {
6778 Res->Destroy(Context);
Sebastian Redlf53597f2009-03-15 17:47:39 +00006779 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6780 << Res->getType());
Sebastian Redl28507842009-02-26 14:39:58 +00006781 }
Chris Lattner704fe352007-08-30 17:59:59 +00006782
Sebastian Redl28507842009-02-26 14:39:58 +00006783 // Get the decl corresponding to this.
6784 RecordDecl *RD = RC->getDecl();
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006785 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00006786 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6787 DiagRuntimeBehavior(BuiltinLoc,
6788 PDiag(diag::warn_offsetof_non_pod_type)
6789 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6790 << Res->getType()))
6791 DidWarnAboutNonPOD = true;
Anders Carlsson6d7f1492009-05-01 23:20:30 +00006792 }
Mike Stump1eb44332009-09-09 15:08:12 +00006793
John McCalla24dc2e2009-11-17 02:14:36 +00006794 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6795 LookupQualifiedName(R, RD);
John McCallf36e02d2009-10-09 21:13:30 +00006796
John McCall1bcee0a2009-12-02 08:25:40 +00006797 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redlf53597f2009-03-15 17:47:39 +00006798 // FIXME: Leaks Res
Sebastian Redl28507842009-02-26 14:39:58 +00006799 if (!MemberDecl)
Douglas Gregor3f093272009-10-13 21:16:44 +00006800 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6801 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stumpeed9cac2009-02-19 03:04:26 +00006802
Sebastian Redl28507842009-02-26 14:39:58 +00006803 // FIXME: C++: Verify that MemberDecl isn't a static field.
6804 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedmane9356962009-04-26 20:50:44 +00006805 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonf1b1d592009-05-01 19:30:39 +00006806 Res = BuildAnonymousStructUnionMemberReference(
John McCall09b6d0e2009-11-11 03:23:23 +00006807 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedmane9356962009-04-26 20:50:44 +00006808 } else {
John McCall6bb80172010-03-30 21:47:33 +00006809 PerformObjectMemberConversion(Res, /*Qualifier=*/0,
6810 *R.begin(), MemberDecl);
Eli Friedmane9356962009-04-26 20:50:44 +00006811 // MemberDecl->getType() doesn't get the right qualifiers, but it
6812 // doesn't matter here.
6813 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6814 MemberDecl->getType().getNonReferenceType());
6815 }
Sebastian Redl28507842009-02-26 14:39:58 +00006816 }
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006817 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00006818
Sebastian Redlf53597f2009-03-15 17:47:39 +00006819 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6820 Context.getSizeType(), BuiltinLoc));
Chris Lattner73d0d4f2007-08-30 17:45:32 +00006821}
6822
6823
Sebastian Redlf53597f2009-03-15 17:47:39 +00006824Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6825 TypeTy *arg1,TypeTy *arg2,
6826 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00006827 // FIXME: Preserve type source info.
6828 QualType argT1 = GetTypeFromParser(arg1);
6829 QualType argT2 = GetTypeFromParser(arg2);
Mike Stumpeed9cac2009-02-19 03:04:26 +00006830
Steve Naroffd34e9152007-08-01 22:05:33 +00006831 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stumpeed9cac2009-02-19 03:04:26 +00006832
Douglas Gregorc12a9c52009-05-19 22:28:02 +00006833 if (getLangOptions().CPlusPlus) {
6834 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6835 << SourceRange(BuiltinLoc, RPLoc);
6836 return ExprError();
6837 }
6838
Sebastian Redlf53597f2009-03-15 17:47:39 +00006839 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6840 argT1, argT2, RPLoc));
Steve Naroffd34e9152007-08-01 22:05:33 +00006841}
6842
Sebastian Redlf53597f2009-03-15 17:47:39 +00006843Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6844 ExprArg cond,
6845 ExprArg expr1, ExprArg expr2,
6846 SourceLocation RPLoc) {
6847 Expr *CondExpr = static_cast<Expr*>(cond.get());
6848 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6849 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stumpeed9cac2009-02-19 03:04:26 +00006850
Steve Naroffd04fdd52007-08-03 21:21:27 +00006851 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6852
Sebastian Redl28507842009-02-26 14:39:58 +00006853 QualType resType;
Douglas Gregorce940492009-09-25 04:25:58 +00006854 bool ValueDependent = false;
Douglas Gregorc9ecc572009-05-19 22:43:30 +00006855 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl28507842009-02-26 14:39:58 +00006856 resType = Context.DependentTy;
Douglas Gregorce940492009-09-25 04:25:58 +00006857 ValueDependent = true;
Sebastian Redl28507842009-02-26 14:39:58 +00006858 } else {
6859 // The conditional expression is required to be a constant expression.
6860 llvm::APSInt condEval(32);
6861 SourceLocation ExpLoc;
6862 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redlf53597f2009-03-15 17:47:39 +00006863 return ExprError(Diag(ExpLoc,
6864 diag::err_typecheck_choose_expr_requires_constant)
6865 << CondExpr->getSourceRange());
Steve Naroffd04fdd52007-08-03 21:21:27 +00006866
Sebastian Redl28507842009-02-26 14:39:58 +00006867 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6868 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregorce940492009-09-25 04:25:58 +00006869 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6870 : RHSExpr->isValueDependent();
Sebastian Redl28507842009-02-26 14:39:58 +00006871 }
6872
Sebastian Redlf53597f2009-03-15 17:47:39 +00006873 cond.release(); expr1.release(); expr2.release();
6874 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregorce940492009-09-25 04:25:58 +00006875 resType, RPLoc,
6876 resType->isDependentType(),
6877 ValueDependent));
Steve Naroffd04fdd52007-08-03 21:21:27 +00006878}
6879
Steve Naroff4eb206b2008-09-03 18:15:37 +00006880//===----------------------------------------------------------------------===//
6881// Clang Extensions.
6882//===----------------------------------------------------------------------===//
6883
6884/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff090276f2008-10-10 01:28:17 +00006885void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006886 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
6887 PushBlockScope(BlockScope, Block);
6888 CurContext->addDecl(Block);
6889 PushDeclContext(BlockScope, Block);
Steve Naroff090276f2008-10-10 01:28:17 +00006890}
6891
Mike Stump98eb8a72009-02-04 22:31:32 +00006892void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpaf199f32009-05-07 18:43:07 +00006893 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00006894 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00006895
Mike Stump98eb8a72009-02-04 22:31:32 +00006896 if (ParamInfo.getNumTypeObjects() == 0
6897 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006898 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump98eb8a72009-02-04 22:31:32 +00006899 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6900
Mike Stump4eeab842009-04-28 01:10:27 +00006901 if (T->isArrayType()) {
6902 Diag(ParamInfo.getSourceRange().getBegin(),
6903 diag::err_block_returns_array);
6904 return;
6905 }
6906
Mike Stump98eb8a72009-02-04 22:31:32 +00006907 // The parameter list is optional, if there was none, assume ().
6908 if (!T->isFunctionType())
Rafael Espindola264ba482010-03-30 20:24:48 +00006909 T = Context.getFunctionType(T, 0, 0, false, 0, false, false, 0, 0,
6910 FunctionType::ExtInfo());
Mike Stump98eb8a72009-02-04 22:31:32 +00006911
6912 CurBlock->hasPrototype = true;
6913 CurBlock->isVariadic = false;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006914 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006915 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006916 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006917 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006918 // FIXME: remove the attribute.
6919 }
John McCall183700f2009-09-21 23:43:11 +00006920 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006921
Chris Lattner9097af12009-04-11 19:27:54 +00006922 // Do not allow returning a objc interface by-value.
6923 if (RetTy->isObjCInterfaceType()) {
6924 Diag(ParamInfo.getSourceRange().getBegin(),
6925 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6926 return;
6927 }
Douglas Gregora873dfc2010-02-03 00:27:59 +00006928
6929 CurBlock->ReturnType = RetTy;
Mike Stump98eb8a72009-02-04 22:31:32 +00006930 return;
6931 }
6932
Steve Naroff4eb206b2008-09-03 18:15:37 +00006933 // Analyze arguments to block.
6934 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6935 "Not a function declarator!");
6936 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006937
Steve Naroff090276f2008-10-10 01:28:17 +00006938 CurBlock->hasPrototype = FTI.hasPrototype;
6939 CurBlock->isVariadic = true;
Mike Stumpeed9cac2009-02-19 03:04:26 +00006940
Steve Naroff4eb206b2008-09-03 18:15:37 +00006941 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6942 // no arguments, not a function that takes a single void argument.
6943 if (FTI.hasPrototype &&
6944 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattnerb28317a2009-03-28 19:18:32 +00006945 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6946 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00006947 // empty arg list, don't push any params.
Steve Naroff090276f2008-10-10 01:28:17 +00006948 CurBlock->isVariadic = false;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006949 } else if (FTI.hasPrototype) {
Fariborz Jahanian9a66c302010-02-12 21:53:14 +00006950 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
6951 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
6952 if (Param->getIdentifier() == 0 &&
6953 !Param->isImplicit() &&
6954 !Param->isInvalidDecl() &&
6955 !getLangOptions().CPlusPlus)
6956 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6957 CurBlock->Params.push_back(Param);
6958 }
Steve Naroff090276f2008-10-10 01:28:17 +00006959 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff4eb206b2008-09-03 18:15:37 +00006960 }
Douglas Gregor838db382010-02-11 01:19:42 +00006961 CurBlock->TheDecl->setParams(CurBlock->Params.data(),
Chris Lattner9097af12009-04-11 19:27:54 +00006962 CurBlock->Params.size());
Fariborz Jahaniand66f22d2009-05-19 17:08:59 +00006963 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00006964 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCall053f4bd2010-03-22 09:20:08 +00006965
6966 bool ShouldCheckShadow =
6967 Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
6968
Steve Naroff090276f2008-10-10 01:28:17 +00006969 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCall7a9813c2010-01-22 00:28:27 +00006970 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
6971 (*AI)->setOwningFunction(CurBlock->TheDecl);
6972
Steve Naroff090276f2008-10-10 01:28:17 +00006973 // If this has an identifier, add it to the scope stack.
John McCall053f4bd2010-03-22 09:20:08 +00006974 if ((*AI)->getIdentifier()) {
6975 if (ShouldCheckShadow)
6976 CheckShadow(CurBlock->TheScope, *AI);
6977
Steve Naroff090276f2008-10-10 01:28:17 +00006978 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCall053f4bd2010-03-22 09:20:08 +00006979 }
John McCall7a9813c2010-01-22 00:28:27 +00006980 }
Chris Lattner9097af12009-04-11 19:27:54 +00006981
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006982 // Check for a valid sentinel attribute on this block.
Mike Stump1eb44332009-09-09 15:08:12 +00006983 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00006984 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00006985 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian3bba33d2009-05-15 21:18:04 +00006986 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian2f7c3922009-05-14 20:53:39 +00006987 // FIXME: remove the attribute.
6988 }
Mike Stump1eb44332009-09-09 15:08:12 +00006989
Chris Lattner9097af12009-04-11 19:27:54 +00006990 // Analyze the return type.
6991 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall183700f2009-09-21 23:43:11 +00006992 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006993
Chris Lattner9097af12009-04-11 19:27:54 +00006994 // Do not allow returning a objc interface by-value.
6995 if (RetTy->isObjCInterfaceType()) {
6996 Diag(ParamInfo.getSourceRange().getBegin(),
6997 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6998 } else if (!RetTy->isDependentType())
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00006999 CurBlock->ReturnType = RetTy;
Steve Naroff4eb206b2008-09-03 18:15:37 +00007000}
7001
7002/// ActOnBlockError - If there is an error parsing a block, this callback
7003/// is invoked to pop the information about the block from the action impl.
7004void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
Steve Naroff4eb206b2008-09-03 18:15:37 +00007005 // Pop off CurBlock, handle nested blocks.
Chris Lattner5c59e2b2009-04-21 22:38:46 +00007006 PopDeclContext();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007007 PopFunctionOrBlockScope();
Steve Naroff4eb206b2008-09-03 18:15:37 +00007008 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff4eb206b2008-09-03 18:15:37 +00007009}
7010
7011/// ActOnBlockStmtExpr - This is called when the body of a block statement
7012/// literal was successfully completed. ^(int x){...}
Sebastian Redlf53597f2009-03-15 17:47:39 +00007013Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
7014 StmtArg body, Scope *CurScope) {
Chris Lattner9af55002009-03-27 04:18:06 +00007015 // If blocks are disabled, emit an error.
7016 if (!LangOpts.Blocks)
7017 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump1eb44332009-09-09 15:08:12 +00007018
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007019 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Steve Naroff4eb206b2008-09-03 18:15:37 +00007020
Steve Naroff090276f2008-10-10 01:28:17 +00007021 PopDeclContext();
7022
Steve Naroff4eb206b2008-09-03 18:15:37 +00007023 QualType RetTy = Context.VoidTy;
Fariborz Jahanian7d5c74e2009-06-19 23:37:08 +00007024 if (!BSI->ReturnType.isNull())
7025 RetTy = BSI->ReturnType;
Mike Stumpeed9cac2009-02-19 03:04:26 +00007026
Steve Naroff4eb206b2008-09-03 18:15:37 +00007027 llvm::SmallVector<QualType, 8> ArgTypes;
7028 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
7029 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stumpeed9cac2009-02-19 03:04:26 +00007030
Mike Stump56925862009-07-28 22:04:01 +00007031 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff4eb206b2008-09-03 18:15:37 +00007032 QualType BlockTy;
7033 if (!BSI->hasPrototype)
Mike Stump56925862009-07-28 22:04:01 +00007034 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00007035 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
Steve Naroff4eb206b2008-09-03 18:15:37 +00007036 else
Jay Foadbeaaccd2009-05-21 09:52:38 +00007037 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump56925862009-07-28 22:04:01 +00007038 BSI->isVariadic, 0, false, false, 0, 0,
Rafael Espindola425ef722010-03-30 22:15:11 +00007039 FunctionType::ExtInfo(NoReturn, 0, CC_Default));
Mike Stumpeed9cac2009-02-19 03:04:26 +00007040
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007041 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregore0762c92009-06-19 23:52:42 +00007042 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff4eb206b2008-09-03 18:15:37 +00007043 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007044
Chris Lattner17a78302009-04-19 05:28:12 +00007045 // If needed, diagnose invalid gotos and switches in the block.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007046 if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
Chris Lattner17a78302009-04-19 05:28:12 +00007047 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
Mike Stump1eb44332009-09-09 15:08:12 +00007048
Anders Carlssone9146f22009-05-01 19:49:17 +00007049 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stumpa3899eb2010-01-19 23:08:01 +00007050
7051 bool Good = true;
7052 // Check goto/label use.
7053 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
7054 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
7055 LabelStmt *L = I->second;
7056
7057 // Verify that we have no forward references left. If so, there was a goto
7058 // or address of a label taken, but no definition of it.
7059 if (L->getSubStmt() != 0)
7060 continue;
7061
7062 // Emit error.
7063 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
7064 Good = false;
7065 }
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007066 if (!Good) {
7067 PopFunctionOrBlockScope();
Mike Stumpa3899eb2010-01-19 23:08:01 +00007068 return ExprError();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007069 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007070
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007071 // Issue any analysis-based warnings.
Ted Kremenekd064fdc2010-03-23 00:13:23 +00007072 const sema::AnalysisBasedWarnings::Policy &WP =
7073 AnalysisWarnings.getDefaultPolicy();
7074 AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
Ted Kremenekdbdbaaf2010-03-20 21:06:02 +00007075
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007076 Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
7077 BSI->hasBlockDeclRefExprs);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007078 PopFunctionOrBlockScope();
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00007079 return Owned(Result);
Steve Naroff4eb206b2008-09-03 18:15:37 +00007080}
7081
Sebastian Redlf53597f2009-03-15 17:47:39 +00007082Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
7083 ExprArg expr, TypeTy *type,
7084 SourceLocation RPLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +00007085 QualType T = GetTypeFromParser(type);
Chris Lattner0d20b8a2009-04-05 15:49:53 +00007086 Expr *E = static_cast<Expr*>(expr.get());
7087 Expr *OrigExpr = E;
Mike Stump1eb44332009-09-09 15:08:12 +00007088
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007089 InitBuiltinVaListType();
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007090
7091 // Get the va_list type
7092 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman5c091ba2009-05-16 12:46:54 +00007093 if (VaListType->isArrayType()) {
7094 // Deal with implicit array decay; for example, on x86-64,
7095 // va_list is an array, but it's supposed to decay to
7096 // a pointer for va_arg.
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007097 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman5c091ba2009-05-16 12:46:54 +00007098 // Make sure the input expression also decays appropriately.
7099 UsualUnaryConversions(E);
7100 } else {
7101 // Otherwise, the va_list argument must be an l-value because
7102 // it is modified by va_arg.
Mike Stump1eb44332009-09-09 15:08:12 +00007103 if (!E->isTypeDependent() &&
Douglas Gregordd027302009-05-19 23:10:31 +00007104 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman5c091ba2009-05-16 12:46:54 +00007105 return ExprError();
7106 }
Eli Friedmanc34bcde2008-08-09 23:32:40 +00007107
Douglas Gregordd027302009-05-19 23:10:31 +00007108 if (!E->isTypeDependent() &&
7109 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redlf53597f2009-03-15 17:47:39 +00007110 return ExprError(Diag(E->getLocStart(),
7111 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner0d20b8a2009-04-05 15:49:53 +00007112 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner9dc8f192009-04-05 00:59:53 +00007113 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007114
Eli Friedmanb1d796d2009-03-23 00:24:07 +00007115 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007116 // FIXME: Warn if a non-POD type is passed in.
Mike Stumpeed9cac2009-02-19 03:04:26 +00007117
Sebastian Redlf53597f2009-03-15 17:47:39 +00007118 expr.release();
7119 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
7120 RPLoc));
Anders Carlsson7c50aca2007-10-15 20:28:48 +00007121}
7122
Sebastian Redlf53597f2009-03-15 17:47:39 +00007123Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007124 // The type of __null will be int or long, depending on the size of
7125 // pointers on the target.
7126 QualType Ty;
7127 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7128 Ty = Context.IntTy;
7129 else
7130 Ty = Context.LongTy;
7131
Sebastian Redlf53597f2009-03-15 17:47:39 +00007132 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor2d8b2732008-11-29 04:51:27 +00007133}
7134
Douglas Gregord0ebe082010-03-31 15:31:50 +00007135static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
7136 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007137 if (!SemaRef.getLangOptions().ObjC1)
7138 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007139
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007140 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7141 if (!PT)
7142 return;
7143
7144 // Check if the destination is of type 'id'.
7145 if (!PT->isObjCIdType()) {
7146 // Check if the destination is the 'NSString' interface.
7147 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7148 if (!ID || !ID->getIdentifier()->isStr("NSString"))
7149 return;
7150 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007151
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007152 // Strip off any parens and casts.
7153 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7154 if (!SL || SL->isWide())
7155 return;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007156
Douglas Gregord0ebe082010-03-31 15:31:50 +00007157 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007158}
7159
Chris Lattner5cf216b2008-01-04 18:04:52 +00007160bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7161 SourceLocation Loc,
7162 QualType DstType, QualType SrcType,
Douglas Gregor68647482009-12-16 03:45:30 +00007163 Expr *SrcExpr, AssignmentAction Action) {
Chris Lattner5cf216b2008-01-04 18:04:52 +00007164 // Decode the result (notice that AST's are still created for extensions).
7165 bool isInvalid = false;
7166 unsigned DiagKind;
Douglas Gregord0ebe082010-03-31 15:31:50 +00007167 FixItHint Hint;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007168
Chris Lattner5cf216b2008-01-04 18:04:52 +00007169 switch (ConvTy) {
7170 default: assert(0 && "Unknown conversion type");
7171 case Compatible: return false;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007172 case PointerToInt:
Chris Lattner5cf216b2008-01-04 18:04:52 +00007173 DiagKind = diag::ext_typecheck_convert_pointer_int;
7174 break;
Chris Lattnerb7b61152008-01-04 18:22:42 +00007175 case IntToPointer:
7176 DiagKind = diag::ext_typecheck_convert_int_pointer;
7177 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007178 case IncompatiblePointer:
Douglas Gregord0ebe082010-03-31 15:31:50 +00007179 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner5cf216b2008-01-04 18:04:52 +00007180 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7181 break;
Eli Friedmanf05c05d2009-03-22 23:59:44 +00007182 case IncompatiblePointerSign:
7183 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7184 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007185 case FunctionVoidPointer:
7186 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7187 break;
7188 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor77a52232008-09-12 00:47:35 +00007189 // If the qualifiers lost were because we were applying the
7190 // (deprecated) C++ conversion from a string literal to a char*
7191 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
7192 // Ideally, this check would be performed in
7193 // CheckPointerTypesForAssignment. However, that would require a
7194 // bit of refactoring (so that the second argument is an
7195 // expression, rather than a type), which should be done as part
7196 // of a larger effort to fix CheckPointerTypesForAssignment for
7197 // C++ semantics.
7198 if (getLangOptions().CPlusPlus &&
7199 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7200 return false;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007201 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7202 break;
Sean Huntc9132b62009-11-08 07:46:34 +00007203 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanian3451e922009-11-09 22:16:37 +00007204 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahanian36a862f2009-11-07 20:20:40 +00007205 break;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007206 case IntToBlockPointer:
7207 DiagKind = diag::err_int_to_block_pointer;
7208 break;
7209 case IncompatibleBlockPointer:
Mike Stump25efa102009-04-21 22:51:42 +00007210 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff1c7d0672008-09-04 15:10:53 +00007211 break;
Steve Naroff39579072008-10-14 22:18:38 +00007212 case IncompatibleObjCQualifiedId:
Mike Stumpeed9cac2009-02-19 03:04:26 +00007213 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff39579072008-10-14 22:18:38 +00007214 // it can give a more specific diagnostic.
7215 DiagKind = diag::warn_incompatible_qualified_id;
7216 break;
Anders Carlssonb0f90cc2009-01-30 23:17:46 +00007217 case IncompatibleVectors:
7218 DiagKind = diag::warn_incompatible_vectors;
7219 break;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007220 case Incompatible:
7221 DiagKind = diag::err_typecheck_convert_incompatible;
7222 isInvalid = true;
7223 break;
7224 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007225
Douglas Gregor68647482009-12-16 03:45:30 +00007226 Diag(Loc, DiagKind) << DstType << SrcType << Action
Anders Carlssonb76cd3d2009-11-10 04:46:30 +00007227 << SrcExpr->getSourceRange() << Hint;
Chris Lattner5cf216b2008-01-04 18:04:52 +00007228 return isInvalid;
7229}
Anders Carlssone21555e2008-11-30 19:50:32 +00007230
Chris Lattner3bf68932009-04-25 21:59:05 +00007231bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007232 llvm::APSInt ICEResult;
7233 if (E->isIntegerConstantExpr(ICEResult, Context)) {
7234 if (Result)
7235 *Result = ICEResult;
7236 return false;
7237 }
7238
Anders Carlssone21555e2008-11-30 19:50:32 +00007239 Expr::EvalResult EvalResult;
7240
Mike Stumpeed9cac2009-02-19 03:04:26 +00007241 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone21555e2008-11-30 19:50:32 +00007242 EvalResult.HasSideEffects) {
7243 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7244
7245 if (EvalResult.Diag) {
7246 // We only show the note if it's not the usual "invalid subexpression"
7247 // or if it's actually in a subexpression.
7248 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7249 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7250 Diag(EvalResult.DiagLoc, EvalResult.Diag);
7251 }
Mike Stumpeed9cac2009-02-19 03:04:26 +00007252
Anders Carlssone21555e2008-11-30 19:50:32 +00007253 return true;
7254 }
7255
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007256 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7257 E->getSourceRange();
Anders Carlssone21555e2008-11-30 19:50:32 +00007258
Eli Friedman3b5ccca2009-04-25 22:26:58 +00007259 if (EvalResult.Diag &&
7260 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7261 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stumpeed9cac2009-02-19 03:04:26 +00007262
Anders Carlssone21555e2008-11-30 19:50:32 +00007263 if (Result)
7264 *Result = EvalResult.Val.getInt();
7265 return false;
7266}
Douglas Gregore0762c92009-06-19 23:52:42 +00007267
Douglas Gregor2afce722009-11-26 00:44:06 +00007268void
Mike Stump1eb44332009-09-09 15:08:12 +00007269Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor2afce722009-11-26 00:44:06 +00007270 ExprEvalContexts.push_back(
7271 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregorac7610d2009-06-22 20:57:11 +00007272}
7273
Mike Stump1eb44332009-09-09 15:08:12 +00007274void
Douglas Gregor2afce722009-11-26 00:44:06 +00007275Sema::PopExpressionEvaluationContext() {
7276 // Pop the current expression evaluation context off the stack.
7277 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7278 ExprEvalContexts.pop_back();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007279
Douglas Gregor06d33692009-12-12 07:57:52 +00007280 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7281 if (Rec.PotentiallyReferenced) {
7282 // Mark any remaining declarations in the current position of the stack
7283 // as "referenced". If they were not meant to be referenced, semantic
7284 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007285 for (PotentiallyReferencedDecls::iterator
Douglas Gregor06d33692009-12-12 07:57:52 +00007286 I = Rec.PotentiallyReferenced->begin(),
7287 IEnd = Rec.PotentiallyReferenced->end();
7288 I != IEnd; ++I)
7289 MarkDeclarationReferenced(I->first, I->second);
7290 }
7291
7292 if (Rec.PotentiallyDiagnosed) {
7293 // Emit any pending diagnostics.
7294 for (PotentiallyEmittedDiagnostics::iterator
7295 I = Rec.PotentiallyDiagnosed->begin(),
7296 IEnd = Rec.PotentiallyDiagnosed->end();
7297 I != IEnd; ++I)
7298 Diag(I->first, I->second);
7299 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007300 }
Douglas Gregor2afce722009-11-26 00:44:06 +00007301
7302 // When are coming out of an unevaluated context, clear out any
7303 // temporaries that we may have created as part of the evaluation of
7304 // the expression in that context: they aren't relevant because they
7305 // will never be constructed.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007306 if (Rec.Context == Unevaluated &&
Douglas Gregor2afce722009-11-26 00:44:06 +00007307 ExprTemporaries.size() > Rec.NumTemporaries)
7308 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7309 ExprTemporaries.end());
7310
7311 // Destroy the popped expression evaluation record.
7312 Rec.Destroy();
Douglas Gregorac7610d2009-06-22 20:57:11 +00007313}
Douglas Gregore0762c92009-06-19 23:52:42 +00007314
7315/// \brief Note that the given declaration was referenced in the source code.
7316///
7317/// This routine should be invoke whenever a given declaration is referenced
7318/// in the source code, and where that reference occurred. If this declaration
7319/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7320/// C99 6.9p3), then the declaration will be marked as used.
7321///
7322/// \param Loc the location where the declaration was referenced.
7323///
7324/// \param D the declaration that has been referenced by the source code.
7325void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7326 assert(D && "No declaration?");
Mike Stump1eb44332009-09-09 15:08:12 +00007327
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007328 if (D->isUsed())
7329 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007330
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007331 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7332 // template or not. The reason for this is that unevaluated expressions
7333 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7334 // -Wunused-parameters)
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007335 if (isa<ParmVarDecl>(D) ||
Douglas Gregorb5352cf2009-10-08 21:35:42 +00007336 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregore0762c92009-06-19 23:52:42 +00007337 D->setUsed(true);
Mike Stump1eb44332009-09-09 15:08:12 +00007338
Douglas Gregore0762c92009-06-19 23:52:42 +00007339 // Do not mark anything as "used" within a dependent context; wait for
7340 // an instantiation.
7341 if (CurContext->isDependentContext())
7342 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007343
Douglas Gregor2afce722009-11-26 00:44:06 +00007344 switch (ExprEvalContexts.back().Context) {
Douglas Gregorac7610d2009-06-22 20:57:11 +00007345 case Unevaluated:
7346 // We are in an expression that is not potentially evaluated; do nothing.
7347 return;
Mike Stump1eb44332009-09-09 15:08:12 +00007348
Douglas Gregorac7610d2009-06-22 20:57:11 +00007349 case PotentiallyEvaluated:
7350 // We are in a potentially-evaluated expression, so this declaration is
7351 // "used"; handle this below.
7352 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007353
Douglas Gregorac7610d2009-06-22 20:57:11 +00007354 case PotentiallyPotentiallyEvaluated:
7355 // We are in an expression that may be potentially evaluated; queue this
7356 // declaration reference until we know whether the expression is
7357 // potentially evaluated.
Douglas Gregor2afce722009-11-26 00:44:06 +00007358 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregorac7610d2009-06-22 20:57:11 +00007359 return;
7360 }
Mike Stump1eb44332009-09-09 15:08:12 +00007361
Douglas Gregore0762c92009-06-19 23:52:42 +00007362 // Note that this declaration has been used.
Fariborz Jahanianb7f4cc02009-06-22 17:30:33 +00007363 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007364 unsigned TypeQuals;
Fariborz Jahanian05a5c452009-06-22 20:37:23 +00007365 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7366 if (!Constructor->isUsed())
7367 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007368 } else if (Constructor->isImplicit() &&
Douglas Gregor9e9199d2009-12-22 00:34:07 +00007369 Constructor->isCopyConstructor(TypeQuals)) {
Fariborz Jahanian485f0872009-06-22 23:34:40 +00007370 if (!Constructor->isUsed())
7371 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7372 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007373
Anders Carlssond6a637f2009-12-07 08:24:59 +00007374 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian8d2b3562009-06-26 23:49:16 +00007375 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7376 if (Destructor->isImplicit() && !Destructor->isUsed())
7377 DefineImplicitDestructor(Loc, Destructor);
Mike Stump1eb44332009-09-09 15:08:12 +00007378
Fariborz Jahanianc75bc2d2009-06-25 21:45:19 +00007379 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7380 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7381 MethodDecl->getOverloadedOperator() == OO_Equal) {
7382 if (!MethodDecl->isUsed())
7383 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7384 }
7385 }
Fariborz Jahanianf5ed9e02009-06-24 22:09:44 +00007386 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007387 // Implicit instantiation of function templates and member functions of
Douglas Gregor1637be72009-06-26 00:10:03 +00007388 // class templates.
Douglas Gregor3b846b62009-10-27 20:53:28 +00007389 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007390 bool AlreadyInstantiated = false;
7391 if (FunctionTemplateSpecializationInfo *SpecInfo
7392 = Function->getTemplateSpecializationInfo()) {
7393 if (SpecInfo->getPointOfInstantiation().isInvalid())
7394 SpecInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007395 else if (SpecInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007396 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007397 AlreadyInstantiated = true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007398 } else if (MemberSpecializationInfo *MSInfo
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007399 = Function->getMemberSpecializationInfo()) {
7400 if (MSInfo->getPointOfInstantiation().isInvalid())
7401 MSInfo->setPointOfInstantiation(Loc);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007402 else if (MSInfo->getTemplateSpecializationKind()
Douglas Gregor3b846b62009-10-27 20:53:28 +00007403 == TSK_ImplicitInstantiation)
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007404 AlreadyInstantiated = true;
7405 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007406
Douglas Gregor60406be2010-01-16 22:29:39 +00007407 if (!AlreadyInstantiated) {
7408 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7409 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7410 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7411 Loc));
7412 else
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007413 PendingImplicitInstantiations.push_back(std::make_pair(Function,
Douglas Gregor60406be2010-01-16 22:29:39 +00007414 Loc));
7415 }
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007416 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007417
Douglas Gregore0762c92009-06-19 23:52:42 +00007418 // FIXME: keep track of references to static functions
Douglas Gregore0762c92009-06-19 23:52:42 +00007419 Function->setUsed(true);
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007420
Douglas Gregore0762c92009-06-19 23:52:42 +00007421 return;
Douglas Gregord7f37bf2009-06-22 23:06:13 +00007422 }
Mike Stump1eb44332009-09-09 15:08:12 +00007423
Douglas Gregore0762c92009-06-19 23:52:42 +00007424 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00007425 // Implicit instantiation of static data members of class templates.
Mike Stump1eb44332009-09-09 15:08:12 +00007426 if (Var->isStaticDataMember() &&
Douglas Gregorb3ae4fc2009-10-12 20:18:28 +00007427 Var->getInstantiatedFromStaticDataMember()) {
7428 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7429 assert(MSInfo && "Missing member specialization information?");
7430 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7431 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7432 MSInfo->setPointOfInstantiation(Loc);
7433 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7434 }
7435 }
Mike Stump1eb44332009-09-09 15:08:12 +00007436
Douglas Gregore0762c92009-06-19 23:52:42 +00007437 // FIXME: keep track of references to static data?
Douglas Gregor7caa6822009-07-24 20:34:43 +00007438
Douglas Gregore0762c92009-06-19 23:52:42 +00007439 D->setUsed(true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00007440 return;
Sam Weinigcce6ebc2009-09-11 03:29:30 +00007441 }
Douglas Gregore0762c92009-06-19 23:52:42 +00007442}
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007443
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007444/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7445/// of the program being compiled.
7446///
7447/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007448/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007449/// possibility that the code will actually be executable. Code in sizeof()
7450/// expressions, code used only during overload resolution, etc., are not
7451/// potentially evaluated. This routine will suppress such diagnostics or,
7452/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007453/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007454/// later.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007455///
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007456/// This routine should be used for all diagnostics that describe the run-time
7457/// behavior of a program, such as passing a non-POD value through an ellipsis.
7458/// Failure to do so will likely result in spurious diagnostics or failures
7459/// during overload resolution or within sizeof/alignof/typeof/typeid.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007460bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007461 const PartialDiagnostic &PD) {
7462 switch (ExprEvalContexts.back().Context ) {
7463 case Unevaluated:
7464 // The argument will never be evaluated, so don't complain.
7465 break;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007466
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007467 case PotentiallyEvaluated:
7468 Diag(Loc, PD);
7469 return true;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007470
Douglas Gregor1c7c3fb2009-12-22 01:01:55 +00007471 case PotentiallyPotentiallyEvaluated:
7472 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7473 break;
7474 }
7475
7476 return false;
7477}
7478
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007479bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7480 CallExpr *CE, FunctionDecl *FD) {
7481 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7482 return false;
7483
7484 PartialDiagnostic Note =
7485 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7486 << FD->getDeclName() : PDiag();
7487 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007488
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007489 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007490 FD ?
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007491 PDiag(diag::err_call_function_incomplete_return)
7492 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007493 PDiag(diag::err_call_incomplete_return)
Anders Carlsson8c8d9192009-10-09 23:51:55 +00007494 << CE->getSourceRange(),
7495 std::make_pair(NoteLoc, Note)))
7496 return true;
7497
7498 return false;
7499}
7500
John McCall5a881bb2009-10-12 21:59:07 +00007501// Diagnose the common s/=/==/ typo. Note that adding parentheses
7502// will prevent this condition from triggering, which is what we want.
7503void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7504 SourceLocation Loc;
7505
John McCalla52ef082009-11-11 02:41:58 +00007506 unsigned diagnostic = diag::warn_condition_is_assignment;
7507
John McCall5a881bb2009-10-12 21:59:07 +00007508 if (isa<BinaryOperator>(E)) {
7509 BinaryOperator *Op = cast<BinaryOperator>(E);
7510 if (Op->getOpcode() != BinaryOperator::Assign)
7511 return;
7512
John McCallc8d8ac52009-11-12 00:06:05 +00007513 // Greylist some idioms by putting them into a warning subcategory.
7514 if (ObjCMessageExpr *ME
7515 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7516 Selector Sel = ME->getSelector();
7517
John McCallc8d8ac52009-11-12 00:06:05 +00007518 // self = [<foo> init...]
7519 if (isSelfExpr(Op->getLHS())
7520 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7521 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7522
7523 // <foo> = [<bar> nextObject]
7524 else if (Sel.isUnarySelector() &&
7525 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7526 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7527 }
John McCalla52ef082009-11-11 02:41:58 +00007528
John McCall5a881bb2009-10-12 21:59:07 +00007529 Loc = Op->getOperatorLoc();
7530 } else if (isa<CXXOperatorCallExpr>(E)) {
7531 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7532 if (Op->getOperator() != OO_Equal)
7533 return;
7534
7535 Loc = Op->getOperatorLoc();
7536 } else {
7537 // Not an assignment.
7538 return;
7539 }
7540
John McCall5a881bb2009-10-12 21:59:07 +00007541 SourceLocation Open = E->getSourceRange().getBegin();
John McCall2d152152009-10-12 22:25:59 +00007542 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +00007543
John McCalla52ef082009-11-11 02:41:58 +00007544 Diag(Loc, diagnostic)
John McCall5a881bb2009-10-12 21:59:07 +00007545 << E->getSourceRange()
Douglas Gregord0ebe082010-03-31 15:31:50 +00007546 << FixItHint::CreateInsertion(Open, "(")
7547 << FixItHint::CreateInsertion(Close, ")");
Douglas Gregor827feec2010-01-08 00:20:23 +00007548 Diag(Loc, diag::note_condition_assign_to_comparison)
Douglas Gregord0ebe082010-03-31 15:31:50 +00007549 << FixItHint::CreateReplacement(Loc, "==");
John McCall5a881bb2009-10-12 21:59:07 +00007550}
7551
7552bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7553 DiagnoseAssignmentAsCondition(E);
7554
7555 if (!E->isTypeDependent()) {
Douglas Gregora873dfc2010-02-03 00:27:59 +00007556 DefaultFunctionArrayLvalueConversion(E);
John McCall5a881bb2009-10-12 21:59:07 +00007557
7558 QualType T = E->getType();
7559
7560 if (getLangOptions().CPlusPlus) {
7561 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7562 return true;
7563 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7564 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7565 << T << E->getSourceRange();
7566 return true;
7567 }
7568 }
7569
7570 return false;
7571}