rename test
[clang.git] / lib / Sema / SemaExpr.cpp
blob2b1b8b29054f95554556206f1021bab995fe1779
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/AnalysisBasedWarnings.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Designator.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Template.h"
39 using namespace clang;
40 using namespace sema;
43 /// \brief Determine whether the use of this declaration is valid, and
44 /// emit any corresponding diagnostics.
45 ///
46 /// This routine diagnoses various problems with referencing
47 /// declarations that can occur when using a declaration. For example,
48 /// it might warn if a deprecated or unavailable declaration is being
49 /// used, or produce an error (and return true) if a C++0x deleted
50 /// function is being used.
51 ///
52 /// If IgnoreDeprecated is set to true, this should not warn about deprecated
53 /// decls.
54 ///
55 /// \returns true if there was an error (this declaration cannot be
56 /// referenced), false otherwise.
57 ///
58 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
59 bool UnknownObjCClass) {
60 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
70 // Clear out the list of suppressed diagnostics, so that we don't emit
71 // them again for this specialization. However, we don't remove this
72 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
78 // See if the decl is deprecated.
79 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
80 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
82 // See if the decl is unavailable
83 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
84 if (UA->getMessage().empty()) {
85 if (!UnknownObjCClass)
86 Diag(Loc, diag::err_unavailable) << D->getDeclName();
87 else
88 Diag(Loc, diag::warn_unavailable_fwdclass_message)
89 << D->getDeclName();
91 else
92 Diag(Loc, diag::err_unavailable_message)
93 << D->getDeclName() << UA->getMessage();
94 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
97 // See if this is a deleted function.
98 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
99 if (FD->isDeleted()) {
100 Diag(Loc, diag::err_deleted_function_use);
101 Diag(D->getLocation(), diag::note_unavailable_here) << true;
102 return true;
106 // Warn if this is used but marked unused.
107 if (D->hasAttr<UnusedAttr>())
108 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
110 return false;
113 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
114 /// (and other functions in future), which have been declared with sentinel
115 /// attribute. It warns if call does not have the sentinel argument.
117 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
118 Expr **Args, unsigned NumArgs) {
119 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
120 if (!attr)
121 return;
123 // FIXME: In C++0x, if any of the arguments are parameter pack
124 // expansions, we can't check for the sentinel now.
125 int sentinelPos = attr->getSentinel();
126 int nullPos = attr->getNullPos();
128 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
129 // base class. Then we won't be needing two versions of the same code.
130 unsigned int i = 0;
131 bool warnNotEnoughArgs = false;
132 int isMethod = 0;
133 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
134 // skip over named parameters.
135 ObjCMethodDecl::param_iterator P, E = MD->param_end();
136 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
137 if (nullPos)
138 --nullPos;
139 else
140 ++i;
142 warnNotEnoughArgs = (P != E || i >= NumArgs);
143 isMethod = 1;
144 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
145 // skip over named parameters.
146 ObjCMethodDecl::param_iterator P, E = FD->param_end();
147 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
148 if (nullPos)
149 --nullPos;
150 else
151 ++i;
153 warnNotEnoughArgs = (P != E || i >= NumArgs);
154 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
155 // block or function pointer call.
156 QualType Ty = V->getType();
157 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
158 const FunctionType *FT = Ty->isFunctionPointerType()
159 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
160 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
161 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
162 unsigned NumArgsInProto = Proto->getNumArgs();
163 unsigned k;
164 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
165 if (nullPos)
166 --nullPos;
167 else
168 ++i;
170 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
172 if (Ty->isBlockPointerType())
173 isMethod = 2;
174 } else
175 return;
176 } else
177 return;
179 if (warnNotEnoughArgs) {
180 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
181 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
182 return;
184 int sentinel = i;
185 while (sentinelPos > 0 && i < NumArgs-1) {
186 --sentinelPos;
187 ++i;
189 if (sentinelPos > 0) {
190 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
191 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
192 return;
194 while (i < NumArgs-1) {
195 ++i;
196 ++sentinel;
198 Expr *sentinelExpr = Args[sentinel];
199 if (!sentinelExpr) return;
200 if (sentinelExpr->isTypeDependent()) return;
201 if (sentinelExpr->isValueDependent()) return;
203 // nullptr_t is always treated as null.
204 if (sentinelExpr->getType()->isNullPtrType()) return;
206 if (sentinelExpr->getType()->isAnyPointerType() &&
207 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
208 Expr::NPC_ValueDependentIsNull))
209 return;
211 // Unfortunately, __null has type 'int'.
212 if (isa<GNUNullExpr>(sentinelExpr)) return;
214 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
215 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
218 SourceRange Sema::getExprRange(ExprTy *E) const {
219 Expr *Ex = (Expr *)E;
220 return Ex? Ex->getSourceRange() : SourceRange();
223 //===----------------------------------------------------------------------===//
224 // Standard Promotions and Conversions
225 //===----------------------------------------------------------------------===//
227 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
228 void Sema::DefaultFunctionArrayConversion(Expr *&E) {
229 QualType Ty = E->getType();
230 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
232 if (Ty->isFunctionType())
233 ImpCastExprToType(E, Context.getPointerType(Ty),
234 CK_FunctionToPointerDecay);
235 else if (Ty->isArrayType()) {
236 // In C90 mode, arrays only promote to pointers if the array expression is
237 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
238 // type 'array of type' is converted to an expression that has type 'pointer
239 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
240 // that has type 'array of type' ...". The relevant change is "an lvalue"
241 // (C90) to "an expression" (C99).
243 // C++ 4.2p1:
244 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
245 // T" can be converted to an rvalue of type "pointer to T".
247 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
248 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
249 CK_ArrayToPointerDecay);
253 void Sema::DefaultLvalueConversion(Expr *&E) {
254 // C++ [conv.lval]p1:
255 // A glvalue of a non-function, non-array type T can be
256 // converted to a prvalue.
257 if (!E->isGLValue()) return;
259 QualType T = E->getType();
260 assert(!T.isNull() && "r-value conversion on typeless expression?");
262 // Create a load out of an ObjCProperty l-value, if necessary.
263 if (E->getObjectKind() == OK_ObjCProperty) {
264 ConvertPropertyForRValue(E);
265 if (!E->isGLValue())
266 return;
269 // We don't want to throw lvalue-to-rvalue casts on top of
270 // expressions of certain types in C++.
271 if (getLangOptions().CPlusPlus &&
272 (E->getType() == Context.OverloadTy ||
273 T->isDependentType() ||
274 T->isRecordType()))
275 return;
277 // The C standard is actually really unclear on this point, and
278 // DR106 tells us what the result should be but not why. It's
279 // generally best to say that void types just doesn't undergo
280 // lvalue-to-rvalue at all. Note that expressions of unqualified
281 // 'void' type are never l-values, but qualified void can be.
282 if (T->isVoidType())
283 return;
285 // C++ [conv.lval]p1:
286 // [...] If T is a non-class type, the type of the prvalue is the
287 // cv-unqualified version of T. Otherwise, the type of the
288 // rvalue is T.
290 // C99 6.3.2.1p2:
291 // If the lvalue has qualified type, the value has the unqualified
292 // version of the type of the lvalue; otherwise, the value has the
293 // type of the lvalue.
294 if (T.hasQualifiers())
295 T = T.getUnqualifiedType();
297 if (const ArraySubscriptExpr *ae = dyn_cast<ArraySubscriptExpr>(E))
298 CheckArrayAccess(ae);
300 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
301 E, 0, VK_RValue);
304 void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
305 DefaultFunctionArrayConversion(E);
306 DefaultLvalueConversion(E);
310 /// UsualUnaryConversions - Performs various conversions that are common to most
311 /// operators (C99 6.3). The conversions of array and function types are
312 /// sometimes surpressed. For example, the array->pointer conversion doesn't
313 /// apply if the array is an argument to the sizeof or address (&) operators.
314 /// In these instances, this routine should *not* be called.
315 Expr *Sema::UsualUnaryConversions(Expr *&E) {
316 // First, convert to an r-value.
317 DefaultFunctionArrayLvalueConversion(E);
319 QualType Ty = E->getType();
320 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
322 // Try to perform integral promotions if the object has a theoretically
323 // promotable type.
324 if (Ty->isIntegralOrUnscopedEnumerationType()) {
325 // C99 6.3.1.1p2:
327 // The following may be used in an expression wherever an int or
328 // unsigned int may be used:
329 // - an object or expression with an integer type whose integer
330 // conversion rank is less than or equal to the rank of int
331 // and unsigned int.
332 // - A bit-field of type _Bool, int, signed int, or unsigned int.
334 // If an int can represent all values of the original type, the
335 // value is converted to an int; otherwise, it is converted to an
336 // unsigned int. These are called the integer promotions. All
337 // other types are unchanged by the integer promotions.
339 QualType PTy = Context.isPromotableBitField(E);
340 if (!PTy.isNull()) {
341 ImpCastExprToType(E, PTy, CK_IntegralCast);
342 return E;
344 if (Ty->isPromotableIntegerType()) {
345 QualType PT = Context.getPromotedIntegerType(Ty);
346 ImpCastExprToType(E, PT, CK_IntegralCast);
347 return E;
351 return E;
354 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
355 /// do not have a prototype. Arguments that have type float are promoted to
356 /// double. All other argument types are converted by UsualUnaryConversions().
357 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
358 QualType Ty = Expr->getType();
359 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
361 UsualUnaryConversions(Expr);
363 // If this is a 'float' (CVR qualified or typedef) promote to double.
364 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
365 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
368 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
369 /// will warn if the resulting type is not a POD type, and rejects ObjC
370 /// interfaces passed by value. This returns true if the argument type is
371 /// completely illegal.
372 bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
373 FunctionDecl *FDecl) {
374 DefaultArgumentPromotion(Expr);
376 // __builtin_va_start takes the second argument as a "varargs" argument, but
377 // it doesn't actually do anything with it. It doesn't need to be non-pod
378 // etc.
379 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
380 return false;
382 if (Expr->getType()->isObjCObjectType() &&
383 DiagRuntimeBehavior(Expr->getLocStart(),
384 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
385 << Expr->getType() << CT))
386 return true;
388 if (!Expr->getType()->isPODType() &&
389 DiagRuntimeBehavior(Expr->getLocStart(),
390 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
391 << Expr->getType() << CT))
392 return true;
394 return false;
397 /// UsualArithmeticConversions - Performs various conversions that are common to
398 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
399 /// routine returns the first non-arithmetic type found. The client is
400 /// responsible for emitting appropriate error diagnostics.
401 /// FIXME: verify the conversion rules for "complex int" are consistent with
402 /// GCC.
403 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
404 bool isCompAssign) {
405 if (!isCompAssign)
406 UsualUnaryConversions(lhsExpr);
408 UsualUnaryConversions(rhsExpr);
410 // For conversion purposes, we ignore any qualifiers.
411 // For example, "const float" and "float" are equivalent.
412 QualType lhs =
413 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
414 QualType rhs =
415 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
417 // If both types are identical, no conversion is needed.
418 if (lhs == rhs)
419 return lhs;
421 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
422 // The caller can deal with this (e.g. pointer + int).
423 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
424 return lhs;
426 // Apply unary and bitfield promotions to the LHS's type.
427 QualType lhs_unpromoted = lhs;
428 if (lhs->isPromotableIntegerType())
429 lhs = Context.getPromotedIntegerType(lhs);
430 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
431 if (!LHSBitfieldPromoteTy.isNull())
432 lhs = LHSBitfieldPromoteTy;
433 if (lhs != lhs_unpromoted && !isCompAssign)
434 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
436 // If both types are identical, no conversion is needed.
437 if (lhs == rhs)
438 return lhs;
440 // At this point, we have two different arithmetic types.
442 // Handle complex types first (C99 6.3.1.8p1).
443 bool LHSComplexFloat = lhs->isComplexType();
444 bool RHSComplexFloat = rhs->isComplexType();
445 if (LHSComplexFloat || RHSComplexFloat) {
446 // if we have an integer operand, the result is the complex type.
448 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
449 if (rhs->isIntegerType()) {
450 QualType fp = cast<ComplexType>(lhs)->getElementType();
451 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
452 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
453 } else {
454 assert(rhs->isComplexIntegerType());
455 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
457 return lhs;
460 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
461 if (!isCompAssign) {
462 // int -> float -> _Complex float
463 if (lhs->isIntegerType()) {
464 QualType fp = cast<ComplexType>(rhs)->getElementType();
465 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
466 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
467 } else {
468 assert(lhs->isComplexIntegerType());
469 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
472 return rhs;
475 // This handles complex/complex, complex/float, or float/complex.
476 // When both operands are complex, the shorter operand is converted to the
477 // type of the longer, and that is the type of the result. This corresponds
478 // to what is done when combining two real floating-point operands.
479 // The fun begins when size promotion occur across type domains.
480 // From H&S 6.3.4: When one operand is complex and the other is a real
481 // floating-point type, the less precise type is converted, within it's
482 // real or complex domain, to the precision of the other type. For example,
483 // when combining a "long double" with a "double _Complex", the
484 // "double _Complex" is promoted to "long double _Complex".
485 int order = Context.getFloatingTypeOrder(lhs, rhs);
487 // If both are complex, just cast to the more precise type.
488 if (LHSComplexFloat && RHSComplexFloat) {
489 if (order > 0) {
490 // _Complex float -> _Complex double
491 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
492 return lhs;
494 } else if (order < 0) {
495 // _Complex float -> _Complex double
496 if (!isCompAssign)
497 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
498 return rhs;
500 return lhs;
503 // If just the LHS is complex, the RHS needs to be converted,
504 // and the LHS might need to be promoted.
505 if (LHSComplexFloat) {
506 if (order > 0) { // LHS is wider
507 // float -> _Complex double
508 QualType fp = cast<ComplexType>(lhs)->getElementType();
509 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
510 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
511 return lhs;
514 // RHS is at least as wide. Find its corresponding complex type.
515 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
517 // double -> _Complex double
518 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
520 // _Complex float -> _Complex double
521 if (!isCompAssign && order < 0)
522 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
524 return result;
527 // Just the RHS is complex, so the LHS needs to be converted
528 // and the RHS might need to be promoted.
529 assert(RHSComplexFloat);
531 if (order < 0) { // RHS is wider
532 // float -> _Complex double
533 if (!isCompAssign) {
534 QualType fp = cast<ComplexType>(rhs)->getElementType();
535 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
536 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
538 return rhs;
541 // LHS is at least as wide. Find its corresponding complex type.
542 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
544 // double -> _Complex double
545 if (!isCompAssign)
546 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
548 // _Complex float -> _Complex double
549 if (order > 0)
550 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
552 return result;
555 // Now handle "real" floating types (i.e. float, double, long double).
556 bool LHSFloat = lhs->isRealFloatingType();
557 bool RHSFloat = rhs->isRealFloatingType();
558 if (LHSFloat || RHSFloat) {
559 // If we have two real floating types, convert the smaller operand
560 // to the bigger result.
561 if (LHSFloat && RHSFloat) {
562 int order = Context.getFloatingTypeOrder(lhs, rhs);
563 if (order > 0) {
564 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
565 return lhs;
568 assert(order < 0 && "illegal float comparison");
569 if (!isCompAssign)
570 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
571 return rhs;
574 // If we have an integer operand, the result is the real floating type.
575 if (LHSFloat) {
576 if (rhs->isIntegerType()) {
577 // Convert rhs to the lhs floating point type.
578 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
579 return lhs;
582 // Convert both sides to the appropriate complex float.
583 assert(rhs->isComplexIntegerType());
584 QualType result = Context.getComplexType(lhs);
586 // _Complex int -> _Complex float
587 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
589 // float -> _Complex float
590 if (!isCompAssign)
591 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
593 return result;
596 assert(RHSFloat);
597 if (lhs->isIntegerType()) {
598 // Convert lhs to the rhs floating point type.
599 if (!isCompAssign)
600 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
601 return rhs;
604 // Convert both sides to the appropriate complex float.
605 assert(lhs->isComplexIntegerType());
606 QualType result = Context.getComplexType(rhs);
608 // _Complex int -> _Complex float
609 if (!isCompAssign)
610 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
612 // float -> _Complex float
613 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
615 return result;
618 // Handle GCC complex int extension.
619 // FIXME: if the operands are (int, _Complex long), we currently
620 // don't promote the complex. Also, signedness?
621 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
622 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
623 if (lhsComplexInt && rhsComplexInt) {
624 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
625 rhsComplexInt->getElementType());
626 assert(order && "inequal types with equal element ordering");
627 if (order > 0) {
628 // _Complex int -> _Complex long
629 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
630 return lhs;
633 if (!isCompAssign)
634 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
635 return rhs;
636 } else if (lhsComplexInt) {
637 // int -> _Complex int
638 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
639 return lhs;
640 } else if (rhsComplexInt) {
641 // int -> _Complex int
642 if (!isCompAssign)
643 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
644 return rhs;
647 // Finally, we have two differing integer types.
648 // The rules for this case are in C99 6.3.1.8
649 int compare = Context.getIntegerTypeOrder(lhs, rhs);
650 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
651 rhsSigned = rhs->hasSignedIntegerRepresentation();
652 if (lhsSigned == rhsSigned) {
653 // Same signedness; use the higher-ranked type
654 if (compare >= 0) {
655 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
656 return lhs;
657 } else if (!isCompAssign)
658 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
659 return rhs;
660 } else if (compare != (lhsSigned ? 1 : -1)) {
661 // The unsigned type has greater than or equal rank to the
662 // signed type, so use the unsigned type
663 if (rhsSigned) {
664 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
665 return lhs;
666 } else if (!isCompAssign)
667 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
668 return rhs;
669 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
670 // The two types are different widths; if we are here, that
671 // means the signed type is larger than the unsigned type, so
672 // use the signed type.
673 if (lhsSigned) {
674 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
675 return lhs;
676 } else if (!isCompAssign)
677 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
678 return rhs;
679 } else {
680 // The signed type is higher-ranked than the unsigned type,
681 // but isn't actually any bigger (like unsigned int and long
682 // on most 32-bit systems). Use the unsigned type corresponding
683 // to the signed type.
684 QualType result =
685 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
686 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
687 if (!isCompAssign)
688 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
689 return result;
693 //===----------------------------------------------------------------------===//
694 // Semantic Analysis for various Expression Types
695 //===----------------------------------------------------------------------===//
698 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
699 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
700 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
701 /// multiple tokens. However, the common case is that StringToks points to one
702 /// string.
704 ExprResult
705 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
706 assert(NumStringToks && "Must have at least one string!");
708 StringLiteralParser Literal(StringToks, NumStringToks, PP);
709 if (Literal.hadError)
710 return ExprError();
712 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
713 for (unsigned i = 0; i != NumStringToks; ++i)
714 StringTokLocs.push_back(StringToks[i].getLocation());
716 QualType StrTy = Context.CharTy;
717 if (Literal.AnyWide) StrTy = Context.getWCharType();
718 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
720 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
721 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
722 StrTy.addConst();
724 // Get an array type for the string, according to C99 6.4.5. This includes
725 // the nul terminator character as well as the string length for pascal
726 // strings.
727 StrTy = Context.getConstantArrayType(StrTy,
728 llvm::APInt(32, Literal.GetNumStringChars()+1),
729 ArrayType::Normal, 0);
731 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
732 return Owned(StringLiteral::Create(Context, Literal.GetString(),
733 Literal.GetStringLength(),
734 Literal.AnyWide, StrTy,
735 &StringTokLocs[0],
736 StringTokLocs.size()));
739 enum CaptureResult {
740 /// No capture is required.
741 CR_NoCapture,
743 /// A capture is required.
744 CR_Capture,
746 /// A by-ref capture is required.
747 CR_CaptureByRef,
749 /// An error occurred when trying to capture the given variable.
750 CR_Error
753 /// Diagnose an uncapturable value reference.
755 /// \param var - the variable referenced
756 /// \param DC - the context which we couldn't capture through
757 static CaptureResult
758 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
759 VarDecl *var, DeclContext *DC) {
760 switch (S.ExprEvalContexts.back().Context) {
761 case Sema::Unevaluated:
762 // The argument will never be evaluated, so don't complain.
763 return CR_NoCapture;
765 case Sema::PotentiallyEvaluated:
766 case Sema::PotentiallyEvaluatedIfUsed:
767 break;
769 case Sema::PotentiallyPotentiallyEvaluated:
770 // FIXME: delay these!
771 break;
774 // Don't diagnose about capture if we're not actually in code right
775 // now; in general, there are more appropriate places that will
776 // diagnose this.
777 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
779 // This particular madness can happen in ill-formed default
780 // arguments; claim it's okay and let downstream code handle it.
781 if (isa<ParmVarDecl>(var) &&
782 S.CurContext == var->getDeclContext()->getParent())
783 return CR_NoCapture;
785 DeclarationName functionName;
786 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
787 functionName = fn->getDeclName();
788 // FIXME: variable from enclosing block that we couldn't capture from!
790 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
791 << var->getIdentifier() << functionName;
792 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
793 << var->getIdentifier();
795 return CR_Error;
798 /// There is a well-formed capture at a particular scope level;
799 /// propagate it through all the nested blocks.
800 static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
801 const BlockDecl::Capture &capture) {
802 VarDecl *var = capture.getVariable();
804 // Update all the inner blocks with the capture information.
805 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
806 i != e; ++i) {
807 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
808 innerBlock->Captures.push_back(
809 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
810 /*nested*/ true, capture.getCopyExpr()));
811 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
814 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
817 /// shouldCaptureValueReference - Determine if a reference to the
818 /// given value in the current context requires a variable capture.
820 /// This also keeps the captures set in the BlockScopeInfo records
821 /// up-to-date.
822 static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
823 ValueDecl *value) {
824 // Only variables ever require capture.
825 VarDecl *var = dyn_cast<VarDecl>(value);
826 if (!var) return CR_NoCapture;
828 // Fast path: variables from the current context never require capture.
829 DeclContext *DC = S.CurContext;
830 if (var->getDeclContext() == DC) return CR_NoCapture;
832 // Only variables with local storage require capture.
833 // FIXME: What about 'const' variables in C++?
834 if (!var->hasLocalStorage()) return CR_NoCapture;
836 // Otherwise, we need to capture.
838 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
839 do {
840 // Only blocks (and eventually C++0x closures) can capture; other
841 // scopes don't work.
842 if (!isa<BlockDecl>(DC))
843 return diagnoseUncapturableValueReference(S, loc, var, DC);
845 BlockScopeInfo *blockScope =
846 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
847 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
849 // Check whether we've already captured it in this block. If so,
850 // we're done.
851 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
852 return propagateCapture(S, functionScopesIndex,
853 blockScope->Captures[indexPlus1 - 1]);
855 functionScopesIndex--;
856 DC = cast<BlockDecl>(DC)->getDeclContext();
857 } while (var->getDeclContext() != DC);
859 // Okay, we descended all the way to the block that defines the variable.
860 // Actually try to capture it.
861 QualType type = var->getType();
863 // Prohibit variably-modified types.
864 if (type->isVariablyModifiedType()) {
865 S.Diag(loc, diag::err_ref_vm_type);
866 S.Diag(var->getLocation(), diag::note_declared_at);
867 return CR_Error;
870 // Prohibit arrays, even in __block variables, but not references to
871 // them.
872 if (type->isArrayType()) {
873 S.Diag(loc, diag::err_ref_array_type);
874 S.Diag(var->getLocation(), diag::note_declared_at);
875 return CR_Error;
878 S.MarkDeclarationReferenced(loc, var);
880 // The BlocksAttr indicates the variable is bound by-reference.
881 bool byRef = var->hasAttr<BlocksAttr>();
883 // Build a copy expression.
884 Expr *copyExpr = 0;
885 if (!byRef && S.getLangOptions().CPlusPlus &&
886 !type->isDependentType() && type->isStructureOrClassType()) {
887 // According to the blocks spec, the capture of a variable from
888 // the stack requires a const copy constructor. This is not true
889 // of the copy/move done to move a __block variable to the heap.
890 type.addConst();
892 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
893 ExprResult result =
894 S.PerformCopyInitialization(
895 InitializedEntity::InitializeBlock(var->getLocation(),
896 type, false),
897 loc, S.Owned(declRef));
899 // Build a full-expression copy expression if initialization
900 // succeeded and used a non-trivial constructor. Recover from
901 // errors by pretending that the copy isn't necessary.
902 if (!result.isInvalid() &&
903 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
904 result = S.MaybeCreateExprWithCleanups(result);
905 copyExpr = result.take();
909 // We're currently at the declarer; go back to the closure.
910 functionScopesIndex++;
911 BlockScopeInfo *blockScope =
912 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
914 // Build a valid capture in this scope.
915 blockScope->Captures.push_back(
916 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
917 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
919 // Propagate that to inner captures if necessary.
920 return propagateCapture(S, functionScopesIndex,
921 blockScope->Captures.back());
924 static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
925 const DeclarationNameInfo &NameInfo,
926 bool byRef) {
927 assert(isa<VarDecl>(vd) && "capturing non-variable");
929 VarDecl *var = cast<VarDecl>(vd);
930 assert(var->hasLocalStorage() && "capturing non-local");
931 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
933 QualType exprType = var->getType().getNonReferenceType();
935 BlockDeclRefExpr *BDRE;
936 if (!byRef) {
937 // The variable will be bound by copy; make it const within the
938 // closure, but record that this was done in the expression.
939 bool constAdded = !exprType.isConstQualified();
940 exprType.addConst();
942 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
943 NameInfo.getLoc(), false,
944 constAdded);
945 } else {
946 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
947 NameInfo.getLoc(), true);
950 return S.Owned(BDRE);
953 ExprResult
954 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
955 SourceLocation Loc,
956 const CXXScopeSpec *SS) {
957 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
958 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
961 /// BuildDeclRefExpr - Build an expression that references a
962 /// declaration that does not require a closure capture.
963 ExprResult
964 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
965 const DeclarationNameInfo &NameInfo,
966 const CXXScopeSpec *SS) {
967 if (Ty == Context.UndeducedAutoTy) {
968 Diag(NameInfo.getLoc(),
969 diag::err_auto_variable_cannot_appear_in_own_initializer)
970 << D->getDeclName();
971 return ExprError();
974 MarkDeclarationReferenced(NameInfo.getLoc(), D);
976 Expr *E = DeclRefExpr::Create(Context,
977 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
978 SS? SS->getRange() : SourceRange(),
979 D, NameInfo, Ty, VK);
981 // Just in case we're building an illegal pointer-to-member.
982 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
983 E->setObjectKind(OK_BitField);
985 return Owned(E);
988 static ExprResult
989 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
990 const CXXScopeSpec &SS, FieldDecl *Field,
991 DeclAccessPair FoundDecl,
992 const DeclarationNameInfo &MemberNameInfo);
994 ExprResult
995 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
996 SourceLocation loc,
997 IndirectFieldDecl *indirectField,
998 Expr *baseObjectExpr,
999 SourceLocation opLoc) {
1000 // First, build the expression that refers to the base object.
1002 bool baseObjectIsPointer = false;
1003 Qualifiers baseQuals;
1005 // Case 1: the base of the indirect field is not a field.
1006 VarDecl *baseVariable = indirectField->getVarDecl();
1007 if (baseVariable) {
1008 assert(baseVariable->getType()->isRecordType());
1010 // In principle we could have a member access expression that
1011 // accesses an anonymous struct/union that's a static member of
1012 // the base object's class. However, under the current standard,
1013 // static data members cannot be anonymous structs or unions.
1014 // Supporting this is as easy as building a MemberExpr here.
1015 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1017 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1019 ExprResult result =
1020 BuildDeclarationNameExpr(SS, baseNameInfo, baseVariable);
1021 if (result.isInvalid()) return ExprError();
1023 baseObjectExpr = result.take();
1024 baseObjectIsPointer = false;
1025 baseQuals = baseObjectExpr->getType().getQualifiers();
1027 // Case 2: the base of the indirect field is a field and the user
1028 // wrote a member expression.
1029 } else if (baseObjectExpr) {
1030 // The caller provided the base object expression. Determine
1031 // whether its a pointer and whether it adds any qualifiers to the
1032 // anonymous struct/union fields we're looking into.
1033 QualType objectType = baseObjectExpr->getType();
1035 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1036 baseObjectIsPointer = true;
1037 objectType = ptr->getPointeeType();
1038 } else {
1039 baseObjectIsPointer = false;
1041 baseQuals = objectType.getQualifiers();
1043 // Case 3: the base of the indirect field is a field and we should
1044 // build an implicit member access.
1045 } else {
1046 // We've found a member of an anonymous struct/union that is
1047 // inside a non-anonymous struct/union, so in a well-formed
1048 // program our base object expression is "this".
1049 CXXMethodDecl *method = tryCaptureCXXThis();
1050 if (!method) {
1051 Diag(loc, diag::err_invalid_member_use_in_static_method)
1052 << indirectField->getDeclName();
1053 return ExprError();
1056 // Our base object expression is "this".
1057 baseObjectExpr =
1058 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1059 /*isImplicit=*/ true);
1060 baseObjectIsPointer = true;
1061 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
1064 // Build the implicit member references to the field of the
1065 // anonymous struct/union.
1066 Expr *result = baseObjectExpr;
1067 IndirectFieldDecl::chain_iterator
1068 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
1070 // Build the first member access in the chain with full information.
1071 if (!baseVariable) {
1072 FieldDecl *field = cast<FieldDecl>(*FI);
1074 // FIXME: use the real found-decl info!
1075 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1077 // Make a nameInfo that properly uses the anonymous name.
1078 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1080 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
1081 SS, field, foundDecl,
1082 memberNameInfo).take();
1083 baseObjectIsPointer = false;
1085 // FIXME: check qualified member access
1088 // In all cases, we should now skip the first declaration in the chain.
1089 ++FI;
1091 for (; FI != FEnd; FI++) {
1092 FieldDecl *field = cast<FieldDecl>(*FI);
1094 // FIXME: these are somewhat meaningless
1095 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1096 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1097 CXXScopeSpec memberSS;
1099 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
1100 memberSS, field, foundDecl, memberNameInfo)
1101 .take();
1104 return Owned(result);
1107 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1108 /// possibly a list of template arguments.
1110 /// If this produces template arguments, it is permitted to call
1111 /// DecomposeTemplateName.
1113 /// This actually loses a lot of source location information for
1114 /// non-standard name kinds; we should consider preserving that in
1115 /// some way.
1116 static void DecomposeUnqualifiedId(Sema &SemaRef,
1117 const UnqualifiedId &Id,
1118 TemplateArgumentListInfo &Buffer,
1119 DeclarationNameInfo &NameInfo,
1120 const TemplateArgumentListInfo *&TemplateArgs) {
1121 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1122 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1123 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1125 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1126 Id.TemplateId->getTemplateArgs(),
1127 Id.TemplateId->NumArgs);
1128 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1129 TemplateArgsPtr.release();
1131 TemplateName TName = Id.TemplateId->Template.get();
1132 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1133 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
1134 TemplateArgs = &Buffer;
1135 } else {
1136 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
1137 TemplateArgs = 0;
1141 /// Determines if the given class is provably not derived from all of
1142 /// the prospective base classes.
1143 static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1144 CXXRecordDecl *Record,
1145 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
1146 if (Bases.count(Record->getCanonicalDecl()))
1147 return false;
1149 RecordDecl *RD = Record->getDefinition();
1150 if (!RD) return false;
1151 Record = cast<CXXRecordDecl>(RD);
1153 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1154 E = Record->bases_end(); I != E; ++I) {
1155 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1156 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1157 if (!BaseRT) return false;
1159 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
1160 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1161 return false;
1164 return true;
1167 enum IMAKind {
1168 /// The reference is definitely not an instance member access.
1169 IMA_Static,
1171 /// The reference may be an implicit instance member access.
1172 IMA_Mixed,
1174 /// The reference may be to an instance member, but it is invalid if
1175 /// so, because the context is not an instance method.
1176 IMA_Mixed_StaticContext,
1178 /// The reference may be to an instance member, but it is invalid if
1179 /// so, because the context is from an unrelated class.
1180 IMA_Mixed_Unrelated,
1182 /// The reference is definitely an implicit instance member access.
1183 IMA_Instance,
1185 /// The reference may be to an unresolved using declaration.
1186 IMA_Unresolved,
1188 /// The reference may be to an unresolved using declaration and the
1189 /// context is not an instance method.
1190 IMA_Unresolved_StaticContext,
1192 /// All possible referrents are instance members and the current
1193 /// context is not an instance method.
1194 IMA_Error_StaticContext,
1196 /// All possible referrents are instance members of an unrelated
1197 /// class.
1198 IMA_Error_Unrelated
1201 /// The given lookup names class member(s) and is not being used for
1202 /// an address-of-member expression. Classify the type of access
1203 /// according to whether it's possible that this reference names an
1204 /// instance member. This is best-effort; it is okay to
1205 /// conservatively answer "yes", in which case some errors will simply
1206 /// not be caught until template-instantiation.
1207 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1208 const LookupResult &R) {
1209 assert(!R.empty() && (*R.begin())->isCXXClassMember());
1211 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
1212 bool isStaticContext =
1213 (!isa<CXXMethodDecl>(DC) ||
1214 cast<CXXMethodDecl>(DC)->isStatic());
1216 if (R.isUnresolvableResult())
1217 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1219 // Collect all the declaring classes of instance members we find.
1220 bool hasNonInstance = false;
1221 bool hasField = false;
1222 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1223 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1224 NamedDecl *D = *I;
1226 if (D->isCXXInstanceMember()) {
1227 if (dyn_cast<FieldDecl>(D))
1228 hasField = true;
1230 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
1231 Classes.insert(R->getCanonicalDecl());
1233 else
1234 hasNonInstance = true;
1237 // If we didn't find any instance members, it can't be an implicit
1238 // member reference.
1239 if (Classes.empty())
1240 return IMA_Static;
1242 // If the current context is not an instance method, it can't be
1243 // an implicit member reference.
1244 if (isStaticContext) {
1245 if (hasNonInstance)
1246 return IMA_Mixed_StaticContext;
1248 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1249 // C++0x [expr.prim.general]p10:
1250 // An id-expression that denotes a non-static data member or non-static
1251 // member function of a class can only be used:
1252 // (...)
1253 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1254 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1255 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1256 if (isUnevaluatedExpression)
1257 return IMA_Mixed_StaticContext;
1260 return IMA_Error_StaticContext;
1263 // If we can prove that the current context is unrelated to all the
1264 // declaring classes, it can't be an implicit member reference (in
1265 // which case it's an error if any of those members are selected).
1266 if (IsProvablyNotDerivedFrom(SemaRef,
1267 cast<CXXMethodDecl>(DC)->getParent(),
1268 Classes))
1269 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1271 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1274 /// Diagnose a reference to a field with no object available.
1275 static void DiagnoseInstanceReference(Sema &SemaRef,
1276 const CXXScopeSpec &SS,
1277 NamedDecl *rep,
1278 const DeclarationNameInfo &nameInfo) {
1279 SourceLocation Loc = nameInfo.getLoc();
1280 SourceRange Range(Loc);
1281 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1283 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
1284 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1285 if (MD->isStatic()) {
1286 // "invalid use of member 'x' in static member function"
1287 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1288 << Range << nameInfo.getName();
1289 return;
1293 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1294 << nameInfo.getName() << Range;
1295 return;
1298 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
1301 /// Diagnose an empty lookup.
1303 /// \return false if new lookup candidates were found
1304 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1305 CorrectTypoContext CTC) {
1306 DeclarationName Name = R.getLookupName();
1308 unsigned diagnostic = diag::err_undeclared_var_use;
1309 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1310 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1311 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1312 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1313 diagnostic = diag::err_undeclared_use;
1314 diagnostic_suggest = diag::err_undeclared_use_suggest;
1317 // If the original lookup was an unqualified lookup, fake an
1318 // unqualified lookup. This is useful when (for example) the
1319 // original lookup would not have found something because it was a
1320 // dependent name.
1321 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1322 DC; DC = DC->getParent()) {
1323 if (isa<CXXRecordDecl>(DC)) {
1324 LookupQualifiedName(R, DC);
1326 if (!R.empty()) {
1327 // Don't give errors about ambiguities in this lookup.
1328 R.suppressDiagnostics();
1330 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1331 bool isInstance = CurMethod &&
1332 CurMethod->isInstance() &&
1333 DC == CurMethod->getParent();
1335 // Give a code modification hint to insert 'this->'.
1336 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1337 // Actually quite difficult!
1338 if (isInstance) {
1339 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1340 CallsUndergoingInstantiation.back()->getCallee());
1341 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
1342 CurMethod->getInstantiatedFromMemberFunction());
1343 if (DepMethod) {
1344 Diag(R.getNameLoc(), diagnostic) << Name
1345 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1346 QualType DepThisType = DepMethod->getThisType(Context);
1347 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1348 R.getNameLoc(), DepThisType, false);
1349 TemplateArgumentListInfo TList;
1350 if (ULE->hasExplicitTemplateArgs())
1351 ULE->copyTemplateArgumentsInto(TList);
1352 CXXDependentScopeMemberExpr *DepExpr =
1353 CXXDependentScopeMemberExpr::Create(
1354 Context, DepThis, DepThisType, true, SourceLocation(),
1355 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1356 R.getLookupNameInfo(), &TList);
1357 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1358 } else {
1359 // FIXME: we should be able to handle this case too. It is correct
1360 // to add this-> here. This is a workaround for PR7947.
1361 Diag(R.getNameLoc(), diagnostic) << Name;
1363 } else {
1364 Diag(R.getNameLoc(), diagnostic) << Name;
1367 // Do we really want to note all of these?
1368 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1369 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1371 // Tell the callee to try to recover.
1372 return false;
1375 R.clear();
1379 // We didn't find anything, so try to correct for a typo.
1380 DeclarationName Corrected;
1381 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
1382 if (!R.empty()) {
1383 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1384 if (SS.isEmpty())
1385 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1386 << FixItHint::CreateReplacement(R.getNameLoc(),
1387 R.getLookupName().getAsString());
1388 else
1389 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1390 << Name << computeDeclContext(SS, false) << R.getLookupName()
1391 << SS.getRange()
1392 << FixItHint::CreateReplacement(R.getNameLoc(),
1393 R.getLookupName().getAsString());
1394 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1395 Diag(ND->getLocation(), diag::note_previous_decl)
1396 << ND->getDeclName();
1398 // Tell the callee to try to recover.
1399 return false;
1402 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1403 // FIXME: If we ended up with a typo for a type name or
1404 // Objective-C class name, we're in trouble because the parser
1405 // is in the wrong place to recover. Suggest the typo
1406 // correction, but don't make it a fix-it since we're not going
1407 // to recover well anyway.
1408 if (SS.isEmpty())
1409 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1410 else
1411 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1412 << Name << computeDeclContext(SS, false) << R.getLookupName()
1413 << SS.getRange();
1415 // Don't try to recover; it won't work.
1416 return true;
1418 } else {
1419 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1420 // because we aren't able to recover.
1421 if (SS.isEmpty())
1422 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
1423 else
1424 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1425 << Name << computeDeclContext(SS, false) << Corrected
1426 << SS.getRange();
1427 return true;
1429 R.clear();
1432 // Emit a special diagnostic for failed member lookups.
1433 // FIXME: computing the declaration context might fail here (?)
1434 if (!SS.isEmpty()) {
1435 Diag(R.getNameLoc(), diag::err_no_member)
1436 << Name << computeDeclContext(SS, false)
1437 << SS.getRange();
1438 return true;
1441 // Give up, we can't recover.
1442 Diag(R.getNameLoc(), diagnostic) << Name;
1443 return true;
1446 ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1447 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1448 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1449 if (!IDecl)
1450 return 0;
1451 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1452 if (!ClassImpDecl)
1453 return 0;
1454 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
1455 if (!property)
1456 return 0;
1457 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1458 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1459 PIDecl->getPropertyIvarDecl())
1460 return 0;
1461 return property;
1464 bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1465 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1466 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1467 if (!IDecl)
1468 return false;
1469 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1470 if (!ClassImpDecl)
1471 return false;
1472 if (ObjCPropertyImplDecl *PIDecl
1473 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1474 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1475 PIDecl->getPropertyIvarDecl())
1476 return false;
1478 return true;
1481 static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
1482 LookupResult &Lookup,
1483 IdentifierInfo *II,
1484 SourceLocation NameLoc) {
1485 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1486 bool LookForIvars;
1487 if (Lookup.empty())
1488 LookForIvars = true;
1489 else if (CurMeth->isClassMethod())
1490 LookForIvars = false;
1491 else
1492 LookForIvars = (Lookup.isSingleResult() &&
1493 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1494 (Lookup.getAsSingle<VarDecl>() != 0));
1495 if (!LookForIvars)
1496 return 0;
1498 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1499 if (!IDecl)
1500 return 0;
1501 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1502 if (!ClassImpDecl)
1503 return 0;
1504 bool DynamicImplSeen = false;
1505 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1506 if (!property)
1507 return 0;
1508 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
1509 DynamicImplSeen =
1510 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1511 // property implementation has a designated ivar. No need to assume a new
1512 // one.
1513 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1514 return 0;
1516 if (!DynamicImplSeen) {
1517 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1518 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
1519 NameLoc,
1520 II, PropType, /*Dinfo=*/0,
1521 ObjCIvarDecl::Private,
1522 (Expr *)0, true);
1523 ClassImpDecl->addDecl(Ivar);
1524 IDecl->makeDeclVisibleInContext(Ivar, false);
1525 property->setPropertyIvarDecl(Ivar);
1526 return Ivar;
1528 return 0;
1531 ExprResult Sema::ActOnIdExpression(Scope *S,
1532 CXXScopeSpec &SS,
1533 UnqualifiedId &Id,
1534 bool HasTrailingLParen,
1535 bool isAddressOfOperand) {
1536 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1537 "cannot be direct & operand and have a trailing lparen");
1539 if (SS.isInvalid())
1540 return ExprError();
1542 TemplateArgumentListInfo TemplateArgsBuffer;
1544 // Decompose the UnqualifiedId into the following data.
1545 DeclarationNameInfo NameInfo;
1546 const TemplateArgumentListInfo *TemplateArgs;
1547 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1549 DeclarationName Name = NameInfo.getName();
1550 IdentifierInfo *II = Name.getAsIdentifierInfo();
1551 SourceLocation NameLoc = NameInfo.getLoc();
1553 // C++ [temp.dep.expr]p3:
1554 // An id-expression is type-dependent if it contains:
1555 // -- an identifier that was declared with a dependent type,
1556 // (note: handled after lookup)
1557 // -- a template-id that is dependent,
1558 // (note: handled in BuildTemplateIdExpr)
1559 // -- a conversion-function-id that specifies a dependent type,
1560 // -- a nested-name-specifier that contains a class-name that
1561 // names a dependent type.
1562 // Determine whether this is a member of an unknown specialization;
1563 // we need to handle these differently.
1564 bool DependentID = false;
1565 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1566 Name.getCXXNameType()->isDependentType()) {
1567 DependentID = true;
1568 } else if (SS.isSet()) {
1569 if (DeclContext *DC = computeDeclContext(SS, false)) {
1570 if (RequireCompleteDeclContext(SS, DC))
1571 return ExprError();
1572 } else {
1573 DependentID = true;
1577 if (DependentID)
1578 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1579 TemplateArgs);
1581 bool IvarLookupFollowUp = false;
1582 // Perform the required lookup.
1583 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1584 if (TemplateArgs) {
1585 // Lookup the template name again to correctly establish the context in
1586 // which it was found. This is really unfortunate as we already did the
1587 // lookup to determine that it was a template name in the first place. If
1588 // this becomes a performance hit, we can work harder to preserve those
1589 // results until we get here but it's likely not worth it.
1590 bool MemberOfUnknownSpecialization;
1591 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1592 MemberOfUnknownSpecialization);
1594 if (MemberOfUnknownSpecialization ||
1595 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1596 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1597 TemplateArgs);
1598 } else {
1599 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1600 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1602 // If the result might be in a dependent base class, this is a dependent
1603 // id-expression.
1604 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1605 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1606 TemplateArgs);
1608 // If this reference is in an Objective-C method, then we need to do
1609 // some special Objective-C lookup, too.
1610 if (IvarLookupFollowUp) {
1611 ExprResult E(LookupInObjCMethod(R, S, II, true));
1612 if (E.isInvalid())
1613 return ExprError();
1615 if (Expr *Ex = E.takeAs<Expr>())
1616 return Owned(Ex);
1618 // Synthesize ivars lazily.
1619 if (getLangOptions().ObjCDefaultSynthProperties &&
1620 getLangOptions().ObjCNonFragileABI2) {
1621 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1622 if (const ObjCPropertyDecl *Property =
1623 canSynthesizeProvisionalIvar(II)) {
1624 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1625 Diag(Property->getLocation(), diag::note_property_declare);
1627 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1628 isAddressOfOperand);
1631 // for further use, this must be set to false if in class method.
1632 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
1636 if (R.isAmbiguous())
1637 return ExprError();
1639 // Determine whether this name might be a candidate for
1640 // argument-dependent lookup.
1641 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1643 if (R.empty() && !ADL) {
1644 // Otherwise, this could be an implicitly declared function reference (legal
1645 // in C90, extension in C99, forbidden in C++).
1646 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1647 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1648 if (D) R.addDecl(D);
1651 // If this name wasn't predeclared and if this is not a function
1652 // call, diagnose the problem.
1653 if (R.empty()) {
1654 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1655 return ExprError();
1657 assert(!R.empty() &&
1658 "DiagnoseEmptyLookup returned false but added no results");
1660 // If we found an Objective-C instance variable, let
1661 // LookupInObjCMethod build the appropriate expression to
1662 // reference the ivar.
1663 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1664 R.clear();
1665 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1666 assert(E.isInvalid() || E.get());
1667 return move(E);
1672 // This is guaranteed from this point on.
1673 assert(!R.empty() || ADL);
1675 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
1676 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
1677 !(getLangOptions().ObjCDefaultSynthProperties &&
1678 getLangOptions().ObjCNonFragileABI2) &&
1679 Var->isFileVarDecl()) {
1680 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
1681 if (Property) {
1682 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1683 Diag(Property->getLocation(), diag::note_property_declare);
1684 Diag(Var->getLocation(), diag::note_global_declared_at);
1689 // Check whether this might be a C++ implicit instance member access.
1690 // C++ [class.mfct.non-static]p3:
1691 // When an id-expression that is not part of a class member access
1692 // syntax and not used to form a pointer to member is used in the
1693 // body of a non-static member function of class X, if name lookup
1694 // resolves the name in the id-expression to a non-static non-type
1695 // member of some class C, the id-expression is transformed into a
1696 // class member access expression using (*this) as the
1697 // postfix-expression to the left of the . operator.
1699 // But we don't actually need to do this for '&' operands if R
1700 // resolved to a function or overloaded function set, because the
1701 // expression is ill-formed if it actually works out to be a
1702 // non-static member function:
1704 // C++ [expr.ref]p4:
1705 // Otherwise, if E1.E2 refers to a non-static member function. . .
1706 // [t]he expression can be used only as the left-hand operand of a
1707 // member function call.
1709 // There are other safeguards against such uses, but it's important
1710 // to get this right here so that we don't end up making a
1711 // spuriously dependent expression if we're inside a dependent
1712 // instance method.
1713 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1714 bool MightBeImplicitMember;
1715 if (!isAddressOfOperand)
1716 MightBeImplicitMember = true;
1717 else if (!SS.isEmpty())
1718 MightBeImplicitMember = false;
1719 else if (R.isOverloadedResult())
1720 MightBeImplicitMember = false;
1721 else if (R.isUnresolvableResult())
1722 MightBeImplicitMember = true;
1723 else
1724 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1725 isa<IndirectFieldDecl>(R.getFoundDecl());
1727 if (MightBeImplicitMember)
1728 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1731 if (TemplateArgs)
1732 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1734 return BuildDeclarationNameExpr(SS, R, ADL);
1737 /// Builds an expression which might be an implicit member expression.
1738 ExprResult
1739 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1740 LookupResult &R,
1741 const TemplateArgumentListInfo *TemplateArgs) {
1742 switch (ClassifyImplicitMemberAccess(*this, R)) {
1743 case IMA_Instance:
1744 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1746 case IMA_Mixed:
1747 case IMA_Mixed_Unrelated:
1748 case IMA_Unresolved:
1749 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1751 case IMA_Static:
1752 case IMA_Mixed_StaticContext:
1753 case IMA_Unresolved_StaticContext:
1754 if (TemplateArgs)
1755 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1756 return BuildDeclarationNameExpr(SS, R, false);
1758 case IMA_Error_StaticContext:
1759 case IMA_Error_Unrelated:
1760 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1761 R.getLookupNameInfo());
1762 return ExprError();
1765 llvm_unreachable("unexpected instance member access kind");
1766 return ExprError();
1769 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1770 /// declaration name, generally during template instantiation.
1771 /// There's a large number of things which don't need to be done along
1772 /// this path.
1773 ExprResult
1774 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1775 const DeclarationNameInfo &NameInfo) {
1776 DeclContext *DC;
1777 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1778 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
1780 if (RequireCompleteDeclContext(SS, DC))
1781 return ExprError();
1783 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1784 LookupQualifiedName(R, DC);
1786 if (R.isAmbiguous())
1787 return ExprError();
1789 if (R.empty()) {
1790 Diag(NameInfo.getLoc(), diag::err_no_member)
1791 << NameInfo.getName() << DC << SS.getRange();
1792 return ExprError();
1795 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1798 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1799 /// detected that we're currently inside an ObjC method. Perform some
1800 /// additional lookup.
1802 /// Ideally, most of this would be done by lookup, but there's
1803 /// actually quite a lot of extra work involved.
1805 /// Returns a null sentinel to indicate trivial success.
1806 ExprResult
1807 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1808 IdentifierInfo *II, bool AllowBuiltinCreation) {
1809 SourceLocation Loc = Lookup.getNameLoc();
1810 ObjCMethodDecl *CurMethod = getCurMethodDecl();
1812 // There are two cases to handle here. 1) scoped lookup could have failed,
1813 // in which case we should look for an ivar. 2) scoped lookup could have
1814 // found a decl, but that decl is outside the current instance method (i.e.
1815 // a global variable). In these two cases, we do a lookup for an ivar with
1816 // this name, if the lookup sucedes, we replace it our current decl.
1818 // If we're in a class method, we don't normally want to look for
1819 // ivars. But if we don't find anything else, and there's an
1820 // ivar, that's an error.
1821 bool IsClassMethod = CurMethod->isClassMethod();
1823 bool LookForIvars;
1824 if (Lookup.empty())
1825 LookForIvars = true;
1826 else if (IsClassMethod)
1827 LookForIvars = false;
1828 else
1829 LookForIvars = (Lookup.isSingleResult() &&
1830 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1831 ObjCInterfaceDecl *IFace = 0;
1832 if (LookForIvars) {
1833 IFace = CurMethod->getClassInterface();
1834 ObjCInterfaceDecl *ClassDeclared;
1835 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1836 // Diagnose using an ivar in a class method.
1837 if (IsClassMethod)
1838 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1839 << IV->getDeclName());
1841 // If we're referencing an invalid decl, just return this as a silent
1842 // error node. The error diagnostic was already emitted on the decl.
1843 if (IV->isInvalidDecl())
1844 return ExprError();
1846 // Check if referencing a field with __attribute__((deprecated)).
1847 if (DiagnoseUseOfDecl(IV, Loc))
1848 return ExprError();
1850 // Diagnose the use of an ivar outside of the declaring class.
1851 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1852 ClassDeclared != IFace)
1853 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1855 // FIXME: This should use a new expr for a direct reference, don't
1856 // turn this into Self->ivar, just return a BareIVarExpr or something.
1857 IdentifierInfo &II = Context.Idents.get("self");
1858 UnqualifiedId SelfName;
1859 SelfName.setIdentifier(&II, SourceLocation());
1860 CXXScopeSpec SelfScopeSpec;
1861 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1862 SelfName, false, false);
1863 if (SelfExpr.isInvalid())
1864 return ExprError();
1866 Expr *SelfE = SelfExpr.take();
1867 DefaultLvalueConversion(SelfE);
1869 MarkDeclarationReferenced(Loc, IV);
1870 return Owned(new (Context)
1871 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1872 SelfE, true, true));
1874 } else if (CurMethod->isInstanceMethod()) {
1875 // We should warn if a local variable hides an ivar.
1876 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
1877 ObjCInterfaceDecl *ClassDeclared;
1878 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1879 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1880 IFace == ClassDeclared)
1881 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1885 if (Lookup.empty() && II && AllowBuiltinCreation) {
1886 // FIXME. Consolidate this with similar code in LookupName.
1887 if (unsigned BuiltinID = II->getBuiltinID()) {
1888 if (!(getLangOptions().CPlusPlus &&
1889 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1890 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1891 S, Lookup.isForRedeclaration(),
1892 Lookup.getNameLoc());
1893 if (D) Lookup.addDecl(D);
1897 // Sentinel value saying that we didn't do anything special.
1898 return Owned((Expr*) 0);
1901 /// \brief Cast a base object to a member's actual type.
1903 /// Logically this happens in three phases:
1905 /// * First we cast from the base type to the naming class.
1906 /// The naming class is the class into which we were looking
1907 /// when we found the member; it's the qualifier type if a
1908 /// qualifier was provided, and otherwise it's the base type.
1910 /// * Next we cast from the naming class to the declaring class.
1911 /// If the member we found was brought into a class's scope by
1912 /// a using declaration, this is that class; otherwise it's
1913 /// the class declaring the member.
1915 /// * Finally we cast from the declaring class to the "true"
1916 /// declaring class of the member. This conversion does not
1917 /// obey access control.
1918 bool
1919 Sema::PerformObjectMemberConversion(Expr *&From,
1920 NestedNameSpecifier *Qualifier,
1921 NamedDecl *FoundDecl,
1922 NamedDecl *Member) {
1923 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1924 if (!RD)
1925 return false;
1927 QualType DestRecordType;
1928 QualType DestType;
1929 QualType FromRecordType;
1930 QualType FromType = From->getType();
1931 bool PointerConversions = false;
1932 if (isa<FieldDecl>(Member)) {
1933 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
1935 if (FromType->getAs<PointerType>()) {
1936 DestType = Context.getPointerType(DestRecordType);
1937 FromRecordType = FromType->getPointeeType();
1938 PointerConversions = true;
1939 } else {
1940 DestType = DestRecordType;
1941 FromRecordType = FromType;
1943 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1944 if (Method->isStatic())
1945 return false;
1947 DestType = Method->getThisType(Context);
1948 DestRecordType = DestType->getPointeeType();
1950 if (FromType->getAs<PointerType>()) {
1951 FromRecordType = FromType->getPointeeType();
1952 PointerConversions = true;
1953 } else {
1954 FromRecordType = FromType;
1955 DestType = DestRecordType;
1957 } else {
1958 // No conversion necessary.
1959 return false;
1962 if (DestType->isDependentType() || FromType->isDependentType())
1963 return false;
1965 // If the unqualified types are the same, no conversion is necessary.
1966 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1967 return false;
1969 SourceRange FromRange = From->getSourceRange();
1970 SourceLocation FromLoc = FromRange.getBegin();
1972 ExprValueKind VK = CastCategory(From);
1974 // C++ [class.member.lookup]p8:
1975 // [...] Ambiguities can often be resolved by qualifying a name with its
1976 // class name.
1978 // If the member was a qualified name and the qualified referred to a
1979 // specific base subobject type, we'll cast to that intermediate type
1980 // first and then to the object in which the member is declared. That allows
1981 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1983 // class Base { public: int x; };
1984 // class Derived1 : public Base { };
1985 // class Derived2 : public Base { };
1986 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1988 // void VeryDerived::f() {
1989 // x = 17; // error: ambiguous base subobjects
1990 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1991 // }
1992 if (Qualifier) {
1993 QualType QType = QualType(Qualifier->getAsType(), 0);
1994 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1995 assert(QType->isRecordType() && "lookup done with non-record type");
1997 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1999 // In C++98, the qualifier type doesn't actually have to be a base
2000 // type of the object type, in which case we just ignore it.
2001 // Otherwise build the appropriate casts.
2002 if (IsDerivedFrom(FromRecordType, QRecordType)) {
2003 CXXCastPath BasePath;
2004 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2005 FromLoc, FromRange, &BasePath))
2006 return true;
2008 if (PointerConversions)
2009 QType = Context.getPointerType(QType);
2010 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2011 VK, &BasePath);
2013 FromType = QType;
2014 FromRecordType = QRecordType;
2016 // If the qualifier type was the same as the destination type,
2017 // we're done.
2018 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2019 return false;
2023 bool IgnoreAccess = false;
2025 // If we actually found the member through a using declaration, cast
2026 // down to the using declaration's type.
2028 // Pointer equality is fine here because only one declaration of a
2029 // class ever has member declarations.
2030 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2031 assert(isa<UsingShadowDecl>(FoundDecl));
2032 QualType URecordType = Context.getTypeDeclType(
2033 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2035 // We only need to do this if the naming-class to declaring-class
2036 // conversion is non-trivial.
2037 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2038 assert(IsDerivedFrom(FromRecordType, URecordType));
2039 CXXCastPath BasePath;
2040 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2041 FromLoc, FromRange, &BasePath))
2042 return true;
2044 QualType UType = URecordType;
2045 if (PointerConversions)
2046 UType = Context.getPointerType(UType);
2047 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2048 VK, &BasePath);
2049 FromType = UType;
2050 FromRecordType = URecordType;
2053 // We don't do access control for the conversion from the
2054 // declaring class to the true declaring class.
2055 IgnoreAccess = true;
2058 CXXCastPath BasePath;
2059 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2060 FromLoc, FromRange, &BasePath,
2061 IgnoreAccess))
2062 return true;
2064 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2065 VK, &BasePath);
2066 return false;
2069 /// \brief Build a MemberExpr AST node.
2070 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
2071 const CXXScopeSpec &SS, ValueDecl *Member,
2072 DeclAccessPair FoundDecl,
2073 const DeclarationNameInfo &MemberNameInfo,
2074 QualType Ty,
2075 ExprValueKind VK, ExprObjectKind OK,
2076 const TemplateArgumentListInfo *TemplateArgs = 0) {
2077 NestedNameSpecifier *Qualifier = 0;
2078 SourceRange QualifierRange;
2079 if (SS.isSet()) {
2080 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
2081 QualifierRange = SS.getRange();
2084 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
2085 Member, FoundDecl, MemberNameInfo,
2086 TemplateArgs, Ty, VK, OK);
2089 static ExprResult
2090 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2091 const CXXScopeSpec &SS, FieldDecl *Field,
2092 DeclAccessPair FoundDecl,
2093 const DeclarationNameInfo &MemberNameInfo) {
2094 // x.a is an l-value if 'a' has a reference type. Otherwise:
2095 // x.a is an l-value/x-value/pr-value if the base is (and note
2096 // that *x is always an l-value), except that if the base isn't
2097 // an ordinary object then we must have an rvalue.
2098 ExprValueKind VK = VK_LValue;
2099 ExprObjectKind OK = OK_Ordinary;
2100 if (!IsArrow) {
2101 if (BaseExpr->getObjectKind() == OK_Ordinary)
2102 VK = BaseExpr->getValueKind();
2103 else
2104 VK = VK_RValue;
2106 if (VK != VK_RValue && Field->isBitField())
2107 OK = OK_BitField;
2109 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2110 QualType MemberType = Field->getType();
2111 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2112 MemberType = Ref->getPointeeType();
2113 VK = VK_LValue;
2114 } else {
2115 QualType BaseType = BaseExpr->getType();
2116 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2118 Qualifiers BaseQuals = BaseType.getQualifiers();
2120 // GC attributes are never picked up by members.
2121 BaseQuals.removeObjCGCAttr();
2123 // CVR attributes from the base are picked up by members,
2124 // except that 'mutable' members don't pick up 'const'.
2125 if (Field->isMutable()) BaseQuals.removeConst();
2127 Qualifiers MemberQuals
2128 = S.Context.getCanonicalType(MemberType).getQualifiers();
2130 // TR 18037 does not allow fields to be declared with address spaces.
2131 assert(!MemberQuals.hasAddressSpace());
2133 Qualifiers Combined = BaseQuals + MemberQuals;
2134 if (Combined != MemberQuals)
2135 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2138 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2139 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2140 FoundDecl, Field))
2141 return ExprError();
2142 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2143 Field, FoundDecl, MemberNameInfo,
2144 MemberType, VK, OK));
2147 /// Builds an implicit member access expression. The current context
2148 /// is known to be an instance method, and the given unqualified lookup
2149 /// set is known to contain only instance members, at least one of which
2150 /// is from an appropriate type.
2151 ExprResult
2152 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2153 LookupResult &R,
2154 const TemplateArgumentListInfo *TemplateArgs,
2155 bool IsKnownInstance) {
2156 assert(!R.empty() && !R.isAmbiguous());
2158 SourceLocation loc = R.getNameLoc();
2160 // We may have found a field within an anonymous union or struct
2161 // (C++ [class.union]).
2162 // FIXME: template-ids inside anonymous structs?
2163 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2164 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
2166 // If this is known to be an instance access, go ahead and build an
2167 // implicit 'this' expression now.
2168 // 'this' expression now.
2169 CXXMethodDecl *method = tryCaptureCXXThis();
2170 assert(method && "didn't correctly pre-flight capture of 'this'");
2172 QualType thisType = method->getThisType(Context);
2173 Expr *baseExpr = 0; // null signifies implicit access
2174 if (IsKnownInstance) {
2175 SourceLocation Loc = R.getNameLoc();
2176 if (SS.getRange().isValid())
2177 Loc = SS.getRange().getBegin();
2178 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
2181 return BuildMemberReferenceExpr(baseExpr, thisType,
2182 /*OpLoc*/ SourceLocation(),
2183 /*IsArrow*/ true,
2185 /*FirstQualifierInScope*/ 0,
2186 R, TemplateArgs);
2189 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2190 const LookupResult &R,
2191 bool HasTrailingLParen) {
2192 // Only when used directly as the postfix-expression of a call.
2193 if (!HasTrailingLParen)
2194 return false;
2196 // Never if a scope specifier was provided.
2197 if (SS.isSet())
2198 return false;
2200 // Only in C++ or ObjC++.
2201 if (!getLangOptions().CPlusPlus)
2202 return false;
2204 // Turn off ADL when we find certain kinds of declarations during
2205 // normal lookup:
2206 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2207 NamedDecl *D = *I;
2209 // C++0x [basic.lookup.argdep]p3:
2210 // -- a declaration of a class member
2211 // Since using decls preserve this property, we check this on the
2212 // original decl.
2213 if (D->isCXXClassMember())
2214 return false;
2216 // C++0x [basic.lookup.argdep]p3:
2217 // -- a block-scope function declaration that is not a
2218 // using-declaration
2219 // NOTE: we also trigger this for function templates (in fact, we
2220 // don't check the decl type at all, since all other decl types
2221 // turn off ADL anyway).
2222 if (isa<UsingShadowDecl>(D))
2223 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2224 else if (D->getDeclContext()->isFunctionOrMethod())
2225 return false;
2227 // C++0x [basic.lookup.argdep]p3:
2228 // -- a declaration that is neither a function or a function
2229 // template
2230 // And also for builtin functions.
2231 if (isa<FunctionDecl>(D)) {
2232 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2234 // But also builtin functions.
2235 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2236 return false;
2237 } else if (!isa<FunctionTemplateDecl>(D))
2238 return false;
2241 return true;
2245 /// Diagnoses obvious problems with the use of the given declaration
2246 /// as an expression. This is only actually called for lookups that
2247 /// were not overloaded, and it doesn't promise that the declaration
2248 /// will in fact be used.
2249 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2250 if (isa<TypedefDecl>(D)) {
2251 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2252 return true;
2255 if (isa<ObjCInterfaceDecl>(D)) {
2256 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2257 return true;
2260 if (isa<NamespaceDecl>(D)) {
2261 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2262 return true;
2265 return false;
2268 ExprResult
2269 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2270 LookupResult &R,
2271 bool NeedsADL) {
2272 // If this is a single, fully-resolved result and we don't need ADL,
2273 // just build an ordinary singleton decl ref.
2274 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2275 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2276 R.getFoundDecl());
2278 // We only need to check the declaration if there's exactly one
2279 // result, because in the overloaded case the results can only be
2280 // functions and function templates.
2281 if (R.isSingleResult() &&
2282 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2283 return ExprError();
2285 // Otherwise, just build an unresolved lookup expression. Suppress
2286 // any lookup-related diagnostics; we'll hash these out later, when
2287 // we've picked a target.
2288 R.suppressDiagnostics();
2290 UnresolvedLookupExpr *ULE
2291 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2292 (NestedNameSpecifier*) SS.getScopeRep(),
2293 SS.getRange(), R.getLookupNameInfo(),
2294 NeedsADL, R.isOverloadedResult(),
2295 R.begin(), R.end());
2297 return Owned(ULE);
2300 /// \brief Complete semantic analysis for a reference to the given declaration.
2301 ExprResult
2302 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2303 const DeclarationNameInfo &NameInfo,
2304 NamedDecl *D) {
2305 assert(D && "Cannot refer to a NULL declaration");
2306 assert(!isa<FunctionTemplateDecl>(D) &&
2307 "Cannot refer unambiguously to a function template");
2309 SourceLocation Loc = NameInfo.getLoc();
2310 if (CheckDeclInExpr(*this, Loc, D))
2311 return ExprError();
2313 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2314 // Specifically diagnose references to class templates that are missing
2315 // a template argument list.
2316 Diag(Loc, diag::err_template_decl_ref)
2317 << Template << SS.getRange();
2318 Diag(Template->getLocation(), diag::note_template_decl_here);
2319 return ExprError();
2322 // Make sure that we're referring to a value.
2323 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2324 if (!VD) {
2325 Diag(Loc, diag::err_ref_non_value)
2326 << D << SS.getRange();
2327 Diag(D->getLocation(), diag::note_declared_at);
2328 return ExprError();
2331 // Check whether this declaration can be used. Note that we suppress
2332 // this check when we're going to perform argument-dependent lookup
2333 // on this function name, because this might not be the function
2334 // that overload resolution actually selects.
2335 if (DiagnoseUseOfDecl(VD, Loc))
2336 return ExprError();
2338 // Only create DeclRefExpr's for valid Decl's.
2339 if (VD->isInvalidDecl())
2340 return ExprError();
2342 // Handle members of anonymous structs and unions. If we got here,
2343 // and the reference is to a class member indirect field, then this
2344 // must be the subject of a pointer-to-member expression.
2345 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2346 if (!indirectField->isCXXClassMember())
2347 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2348 indirectField);
2350 // If the identifier reference is inside a block, and it refers to a value
2351 // that is outside the block, create a BlockDeclRefExpr instead of a
2352 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2353 // the block is formed.
2355 // We do not do this for things like enum constants, global variables, etc,
2356 // as they do not get snapshotted.
2358 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
2359 case CR_Error:
2360 return ExprError();
2362 case CR_Capture:
2363 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2364 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2366 case CR_CaptureByRef:
2367 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2368 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
2370 case CR_NoCapture: {
2371 // If this reference is not in a block or if the referenced
2372 // variable is within the block, create a normal DeclRefExpr.
2374 QualType type = VD->getType();
2375 ExprValueKind valueKind = VK_RValue;
2377 switch (D->getKind()) {
2378 // Ignore all the non-ValueDecl kinds.
2379 #define ABSTRACT_DECL(kind)
2380 #define VALUE(type, base)
2381 #define DECL(type, base) \
2382 case Decl::type:
2383 #include "clang/AST/DeclNodes.inc"
2384 llvm_unreachable("invalid value decl kind");
2385 return ExprError();
2387 // These shouldn't make it here.
2388 case Decl::ObjCAtDefsField:
2389 case Decl::ObjCIvar:
2390 llvm_unreachable("forming non-member reference to ivar?");
2391 return ExprError();
2393 // Enum constants are always r-values and never references.
2394 // Unresolved using declarations are dependent.
2395 case Decl::EnumConstant:
2396 case Decl::UnresolvedUsingValue:
2397 valueKind = VK_RValue;
2398 break;
2400 // Fields and indirect fields that got here must be for
2401 // pointer-to-member expressions; we just call them l-values for
2402 // internal consistency, because this subexpression doesn't really
2403 // exist in the high-level semantics.
2404 case Decl::Field:
2405 case Decl::IndirectField:
2406 assert(getLangOptions().CPlusPlus &&
2407 "building reference to field in C?");
2409 // These can't have reference type in well-formed programs, but
2410 // for internal consistency we do this anyway.
2411 type = type.getNonReferenceType();
2412 valueKind = VK_LValue;
2413 break;
2415 // Non-type template parameters are either l-values or r-values
2416 // depending on the type.
2417 case Decl::NonTypeTemplateParm: {
2418 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2419 type = reftype->getPointeeType();
2420 valueKind = VK_LValue; // even if the parameter is an r-value reference
2421 break;
2424 // For non-references, we need to strip qualifiers just in case
2425 // the template parameter was declared as 'const int' or whatever.
2426 valueKind = VK_RValue;
2427 type = type.getUnqualifiedType();
2428 break;
2431 case Decl::Var:
2432 // In C, "extern void blah;" is valid and is an r-value.
2433 if (!getLangOptions().CPlusPlus &&
2434 !type.hasQualifiers() &&
2435 type->isVoidType()) {
2436 valueKind = VK_RValue;
2437 break;
2439 // fallthrough
2441 case Decl::ImplicitParam:
2442 case Decl::ParmVar:
2443 // These are always l-values.
2444 valueKind = VK_LValue;
2445 type = type.getNonReferenceType();
2446 break;
2448 case Decl::Function: {
2449 // Functions are l-values in C++.
2450 if (getLangOptions().CPlusPlus) {
2451 valueKind = VK_LValue;
2452 break;
2455 // C99 DR 316 says that, if a function type comes from a
2456 // function definition (without a prototype), that type is only
2457 // used for checking compatibility. Therefore, when referencing
2458 // the function, we pretend that we don't have the full function
2459 // type.
2460 if (!cast<FunctionDecl>(VD)->hasPrototype())
2461 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2462 type = Context.getFunctionNoProtoType(proto->getResultType(),
2463 proto->getExtInfo());
2465 // Functions are r-values in C.
2466 valueKind = VK_RValue;
2467 break;
2470 case Decl::CXXMethod:
2471 // C++ methods are l-values if static, r-values if non-static.
2472 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2473 valueKind = VK_LValue;
2474 break;
2476 // fallthrough
2478 case Decl::CXXConversion:
2479 case Decl::CXXDestructor:
2480 case Decl::CXXConstructor:
2481 valueKind = VK_RValue;
2482 break;
2485 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2490 llvm_unreachable("unknown capture result");
2491 return ExprError();
2494 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
2495 tok::TokenKind Kind) {
2496 PredefinedExpr::IdentType IT;
2498 switch (Kind) {
2499 default: assert(0 && "Unknown simple primary expr!");
2500 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2501 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2502 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2505 // Pre-defined identifiers are of type char[x], where x is the length of the
2506 // string.
2508 Decl *currentDecl = getCurFunctionOrMethodDecl();
2509 if (!currentDecl && getCurBlock())
2510 currentDecl = getCurBlock()->TheDecl;
2511 if (!currentDecl) {
2512 Diag(Loc, diag::ext_predef_outside_function);
2513 currentDecl = Context.getTranslationUnitDecl();
2516 QualType ResTy;
2517 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2518 ResTy = Context.DependentTy;
2519 } else {
2520 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2522 llvm::APInt LengthI(32, Length + 1);
2523 ResTy = Context.CharTy.withConst();
2524 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2526 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2529 ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
2530 llvm::SmallString<16> CharBuffer;
2531 bool Invalid = false;
2532 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2533 if (Invalid)
2534 return ExprError();
2536 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2537 PP);
2538 if (Literal.hadError())
2539 return ExprError();
2541 QualType Ty;
2542 if (!getLangOptions().CPlusPlus)
2543 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2544 else if (Literal.isWide())
2545 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
2546 else if (Literal.isMultiChar())
2547 Ty = Context.IntTy; // 'wxyz' -> int in C++.
2548 else
2549 Ty = Context.CharTy; // 'x' -> char in C++
2551 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2552 Literal.isWide(),
2553 Ty, Tok.getLocation()));
2556 ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
2557 // Fast path for a single digit (which is quite common). A single digit
2558 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2559 if (Tok.getLength() == 1) {
2560 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2561 unsigned IntSize = Context.Target.getIntWidth();
2562 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
2563 Context.IntTy, Tok.getLocation()));
2566 llvm::SmallString<512> IntegerBuffer;
2567 // Add padding so that NumericLiteralParser can overread by one character.
2568 IntegerBuffer.resize(Tok.getLength()+1);
2569 const char *ThisTokBegin = &IntegerBuffer[0];
2571 // Get the spelling of the token, which eliminates trigraphs, etc.
2572 bool Invalid = false;
2573 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2574 if (Invalid)
2575 return ExprError();
2577 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2578 Tok.getLocation(), PP);
2579 if (Literal.hadError)
2580 return ExprError();
2582 Expr *Res;
2584 if (Literal.isFloatingLiteral()) {
2585 QualType Ty;
2586 if (Literal.isFloat)
2587 Ty = Context.FloatTy;
2588 else if (!Literal.isLong)
2589 Ty = Context.DoubleTy;
2590 else
2591 Ty = Context.LongDoubleTy;
2593 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2595 using llvm::APFloat;
2596 APFloat Val(Format);
2598 APFloat::opStatus result = Literal.GetFloatValue(Val);
2600 // Overflow is always an error, but underflow is only an error if
2601 // we underflowed to zero (APFloat reports denormals as underflow).
2602 if ((result & APFloat::opOverflow) ||
2603 ((result & APFloat::opUnderflow) && Val.isZero())) {
2604 unsigned diagnostic;
2605 llvm::SmallString<20> buffer;
2606 if (result & APFloat::opOverflow) {
2607 diagnostic = diag::warn_float_overflow;
2608 APFloat::getLargest(Format).toString(buffer);
2609 } else {
2610 diagnostic = diag::warn_float_underflow;
2611 APFloat::getSmallest(Format).toString(buffer);
2614 Diag(Tok.getLocation(), diagnostic)
2615 << Ty
2616 << llvm::StringRef(buffer.data(), buffer.size());
2619 bool isExact = (result == APFloat::opOK);
2620 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
2622 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2623 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2625 } else if (!Literal.isIntegerLiteral()) {
2626 return ExprError();
2627 } else {
2628 QualType Ty;
2630 // long long is a C99 feature.
2631 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
2632 Literal.isLongLong)
2633 Diag(Tok.getLocation(), diag::ext_longlong);
2635 // Get the value in the widest-possible width.
2636 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
2638 if (Literal.GetIntegerValue(ResultVal)) {
2639 // If this value didn't fit into uintmax_t, warn and force to ull.
2640 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2641 Ty = Context.UnsignedLongLongTy;
2642 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2643 "long long is not intmax_t?");
2644 } else {
2645 // If this value fits into a ULL, try to figure out what else it fits into
2646 // according to the rules of C99 6.4.4.1p5.
2648 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2649 // be an unsigned int.
2650 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2652 // Check from smallest to largest, picking the smallest type we can.
2653 unsigned Width = 0;
2654 if (!Literal.isLong && !Literal.isLongLong) {
2655 // Are int/unsigned possibilities?
2656 unsigned IntSize = Context.Target.getIntWidth();
2658 // Does it fit in a unsigned int?
2659 if (ResultVal.isIntN(IntSize)) {
2660 // Does it fit in a signed int?
2661 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2662 Ty = Context.IntTy;
2663 else if (AllowUnsigned)
2664 Ty = Context.UnsignedIntTy;
2665 Width = IntSize;
2669 // Are long/unsigned long possibilities?
2670 if (Ty.isNull() && !Literal.isLongLong) {
2671 unsigned LongSize = Context.Target.getLongWidth();
2673 // Does it fit in a unsigned long?
2674 if (ResultVal.isIntN(LongSize)) {
2675 // Does it fit in a signed long?
2676 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2677 Ty = Context.LongTy;
2678 else if (AllowUnsigned)
2679 Ty = Context.UnsignedLongTy;
2680 Width = LongSize;
2684 // Finally, check long long if needed.
2685 if (Ty.isNull()) {
2686 unsigned LongLongSize = Context.Target.getLongLongWidth();
2688 // Does it fit in a unsigned long long?
2689 if (ResultVal.isIntN(LongLongSize)) {
2690 // Does it fit in a signed long long?
2691 // To be compatible with MSVC, hex integer literals ending with the
2692 // LL or i64 suffix are always signed in Microsoft mode.
2693 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2694 (getLangOptions().Microsoft && Literal.isLongLong)))
2695 Ty = Context.LongLongTy;
2696 else if (AllowUnsigned)
2697 Ty = Context.UnsignedLongLongTy;
2698 Width = LongLongSize;
2702 // If we still couldn't decide a type, we probably have something that
2703 // does not fit in a signed long long, but has no U suffix.
2704 if (Ty.isNull()) {
2705 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2706 Ty = Context.UnsignedLongLongTy;
2707 Width = Context.Target.getLongLongWidth();
2710 if (ResultVal.getBitWidth() != Width)
2711 ResultVal = ResultVal.trunc(Width);
2713 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2716 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2717 if (Literal.isImaginary)
2718 Res = new (Context) ImaginaryLiteral(Res,
2719 Context.getComplexType(Res->getType()));
2721 return Owned(Res);
2724 ExprResult Sema::ActOnParenExpr(SourceLocation L,
2725 SourceLocation R, Expr *E) {
2726 assert((E != 0) && "ActOnParenExpr() missing expr");
2727 return Owned(new (Context) ParenExpr(L, R, E));
2730 /// The UsualUnaryConversions() function is *not* called by this routine.
2731 /// See C99 6.3.2.1p[2-4] for more details.
2732 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
2733 SourceLocation OpLoc,
2734 SourceRange ExprRange,
2735 bool isSizeof) {
2736 if (exprType->isDependentType())
2737 return false;
2739 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2740 // the result is the size of the referenced type."
2741 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2742 // result shall be the alignment of the referenced type."
2743 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2744 exprType = Ref->getPointeeType();
2746 // C99 6.5.3.4p1:
2747 if (exprType->isFunctionType()) {
2748 // alignof(function) is allowed as an extension.
2749 if (isSizeof)
2750 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2751 return false;
2754 // Allow sizeof(void)/alignof(void) as an extension.
2755 if (exprType->isVoidType()) {
2756 Diag(OpLoc, diag::ext_sizeof_void_type)
2757 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
2758 return false;
2761 if (RequireCompleteType(OpLoc, exprType,
2762 PDiag(diag::err_sizeof_alignof_incomplete_type)
2763 << int(!isSizeof) << ExprRange))
2764 return true;
2766 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2767 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
2768 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
2769 << exprType << isSizeof << ExprRange;
2770 return true;
2773 return false;
2776 static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2777 SourceRange ExprRange) {
2778 E = E->IgnoreParens();
2780 // alignof decl is always ok.
2781 if (isa<DeclRefExpr>(E))
2782 return false;
2784 // Cannot know anything else if the expression is dependent.
2785 if (E->isTypeDependent())
2786 return false;
2788 if (E->getBitField()) {
2789 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2790 return true;
2793 // Alignment of a field access is always okay, so long as it isn't a
2794 // bit-field.
2795 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2796 if (isa<FieldDecl>(ME->getMemberDecl()))
2797 return false;
2799 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2802 /// \brief Build a sizeof or alignof expression given a type operand.
2803 ExprResult
2804 Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
2805 SourceLocation OpLoc,
2806 bool isSizeOf, SourceRange R) {
2807 if (!TInfo)
2808 return ExprError();
2810 QualType T = TInfo->getType();
2812 if (!T->isDependentType() &&
2813 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2814 return ExprError();
2816 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2817 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
2818 Context.getSizeType(), OpLoc,
2819 R.getEnd()));
2822 /// \brief Build a sizeof or alignof expression given an expression
2823 /// operand.
2824 ExprResult
2825 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
2826 bool isSizeOf, SourceRange R) {
2827 // Verify that the operand is valid.
2828 bool isInvalid = false;
2829 if (E->isTypeDependent()) {
2830 // Delay type-checking for type-dependent expressions.
2831 } else if (!isSizeOf) {
2832 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
2833 } else if (E->getBitField()) { // C99 6.5.3.4p1.
2834 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2835 isInvalid = true;
2836 } else if (E->getType()->isPlaceholderType()) {
2837 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2838 if (PE.isInvalid()) return ExprError();
2839 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
2840 } else {
2841 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2844 if (isInvalid)
2845 return ExprError();
2847 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2848 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2849 Context.getSizeType(), OpLoc,
2850 R.getEnd()));
2853 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2854 /// the same for @c alignof and @c __alignof
2855 /// Note that the ArgRange is invalid if isType is false.
2856 ExprResult
2857 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2858 void *TyOrEx, const SourceRange &ArgRange) {
2859 // If error parsing type, ignore.
2860 if (TyOrEx == 0) return ExprError();
2862 if (isType) {
2863 TypeSourceInfo *TInfo;
2864 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
2865 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
2868 Expr *ArgEx = (Expr *)TyOrEx;
2869 ExprResult Result
2870 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2872 return move(Result);
2875 static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2876 bool isReal) {
2877 if (V->isTypeDependent())
2878 return S.Context.DependentTy;
2880 // _Real and _Imag are only l-values for normal l-values.
2881 if (V->getObjectKind() != OK_Ordinary)
2882 S.DefaultLvalueConversion(V);
2884 // These operators return the element type of a complex type.
2885 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
2886 return CT->getElementType();
2888 // Otherwise they pass through real integer and floating point types here.
2889 if (V->getType()->isArithmeticType())
2890 return V->getType();
2892 // Test for placeholders.
2893 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
2894 if (PR.isInvalid()) return QualType();
2895 if (PR.take() != V) {
2896 V = PR.take();
2897 return CheckRealImagOperand(S, V, Loc, isReal);
2900 // Reject anything else.
2901 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2902 << (isReal ? "__real" : "__imag");
2903 return QualType();
2908 ExprResult
2909 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2910 tok::TokenKind Kind, Expr *Input) {
2911 UnaryOperatorKind Opc;
2912 switch (Kind) {
2913 default: assert(0 && "Unknown unary op!");
2914 case tok::plusplus: Opc = UO_PostInc; break;
2915 case tok::minusminus: Opc = UO_PostDec; break;
2918 return BuildUnaryOp(S, OpLoc, Opc, Input);
2921 /// Expressions of certain arbitrary types are forbidden by C from
2922 /// having l-value type. These are:
2923 /// - 'void', but not qualified void
2924 /// - function types
2926 /// The exact rule here is C99 6.3.2.1:
2927 /// An lvalue is an expression with an object type or an incomplete
2928 /// type other than void.
2929 static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2930 return ((T->isVoidType() && !T.hasQualifiers()) ||
2931 T->isFunctionType());
2934 ExprResult
2935 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2936 Expr *Idx, SourceLocation RLoc) {
2937 // Since this might be a postfix expression, get rid of ParenListExprs.
2938 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
2939 if (Result.isInvalid()) return ExprError();
2940 Base = Result.take();
2942 Expr *LHSExp = Base, *RHSExp = Idx;
2944 if (getLangOptions().CPlusPlus &&
2945 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2946 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2947 Context.DependentTy,
2948 VK_LValue, OK_Ordinary,
2949 RLoc));
2952 if (getLangOptions().CPlusPlus &&
2953 (LHSExp->getType()->isRecordType() ||
2954 LHSExp->getType()->isEnumeralType() ||
2955 RHSExp->getType()->isRecordType() ||
2956 RHSExp->getType()->isEnumeralType())) {
2957 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
2960 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
2964 ExprResult
2965 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2966 Expr *Idx, SourceLocation RLoc) {
2967 Expr *LHSExp = Base;
2968 Expr *RHSExp = Idx;
2970 // Perform default conversions.
2971 if (!LHSExp->getType()->getAs<VectorType>())
2972 DefaultFunctionArrayLvalueConversion(LHSExp);
2973 DefaultFunctionArrayLvalueConversion(RHSExp);
2975 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
2976 ExprValueKind VK = VK_LValue;
2977 ExprObjectKind OK = OK_Ordinary;
2979 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
2980 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
2981 // in the subscript position. As a result, we need to derive the array base
2982 // and index from the expression types.
2983 Expr *BaseExpr, *IndexExpr;
2984 QualType ResultType;
2985 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2986 BaseExpr = LHSExp;
2987 IndexExpr = RHSExp;
2988 ResultType = Context.DependentTy;
2989 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
2990 BaseExpr = LHSExp;
2991 IndexExpr = RHSExp;
2992 ResultType = PTy->getPointeeType();
2993 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
2994 // Handle the uncommon case of "123[Ptr]".
2995 BaseExpr = RHSExp;
2996 IndexExpr = LHSExp;
2997 ResultType = PTy->getPointeeType();
2998 } else if (const ObjCObjectPointerType *PTy =
2999 LHSTy->getAs<ObjCObjectPointerType>()) {
3000 BaseExpr = LHSExp;
3001 IndexExpr = RHSExp;
3002 ResultType = PTy->getPointeeType();
3003 } else if (const ObjCObjectPointerType *PTy =
3004 RHSTy->getAs<ObjCObjectPointerType>()) {
3005 // Handle the uncommon case of "123[Ptr]".
3006 BaseExpr = RHSExp;
3007 IndexExpr = LHSExp;
3008 ResultType = PTy->getPointeeType();
3009 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3010 BaseExpr = LHSExp; // vectors: V[123]
3011 IndexExpr = RHSExp;
3012 VK = LHSExp->getValueKind();
3013 if (VK != VK_RValue)
3014 OK = OK_VectorComponent;
3016 // FIXME: need to deal with const...
3017 ResultType = VTy->getElementType();
3018 } else if (LHSTy->isArrayType()) {
3019 // If we see an array that wasn't promoted by
3020 // DefaultFunctionArrayLvalueConversion, it must be an array that
3021 // wasn't promoted because of the C90 rule that doesn't
3022 // allow promoting non-lvalue arrays. Warn, then
3023 // force the promotion here.
3024 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3025 LHSExp->getSourceRange();
3026 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3027 CK_ArrayToPointerDecay);
3028 LHSTy = LHSExp->getType();
3030 BaseExpr = LHSExp;
3031 IndexExpr = RHSExp;
3032 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3033 } else if (RHSTy->isArrayType()) {
3034 // Same as previous, except for 123[f().a] case
3035 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3036 RHSExp->getSourceRange();
3037 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3038 CK_ArrayToPointerDecay);
3039 RHSTy = RHSExp->getType();
3041 BaseExpr = RHSExp;
3042 IndexExpr = LHSExp;
3043 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3044 } else {
3045 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3046 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3048 // C99 6.5.2.1p1
3049 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3050 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3051 << IndexExpr->getSourceRange());
3053 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3054 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3055 && !IndexExpr->isTypeDependent())
3056 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3058 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3059 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3060 // type. Note that Functions are not objects, and that (in C99 parlance)
3061 // incomplete types are not object types.
3062 if (ResultType->isFunctionType()) {
3063 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3064 << ResultType << BaseExpr->getSourceRange();
3065 return ExprError();
3068 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3069 // GNU extension: subscripting on pointer to void
3070 Diag(LLoc, diag::ext_gnu_void_ptr)
3071 << BaseExpr->getSourceRange();
3073 // C forbids expressions of unqualified void type from being l-values.
3074 // See IsCForbiddenLValueType.
3075 if (!ResultType.hasQualifiers()) VK = VK_RValue;
3076 } else if (!ResultType->isDependentType() &&
3077 RequireCompleteType(LLoc, ResultType,
3078 PDiag(diag::err_subscript_incomplete_type)
3079 << BaseExpr->getSourceRange()))
3080 return ExprError();
3082 // Diagnose bad cases where we step over interface counts.
3083 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
3084 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3085 << ResultType << BaseExpr->getSourceRange();
3086 return ExprError();
3089 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3090 !IsCForbiddenLValueType(Context, ResultType));
3092 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3093 ResultType, VK, OK, RLoc));
3096 /// Check an ext-vector component access expression.
3098 /// VK should be set in advance to the value kind of the base
3099 /// expression.
3100 static QualType
3101 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3102 SourceLocation OpLoc, const IdentifierInfo *CompName,
3103 SourceLocation CompLoc) {
3104 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3105 // see FIXME there.
3107 // FIXME: This logic can be greatly simplified by splitting it along
3108 // halving/not halving and reworking the component checking.
3109 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
3111 // The vector accessor can't exceed the number of elements.
3112 const char *compStr = CompName->getNameStart();
3114 // This flag determines whether or not the component is one of the four
3115 // special names that indicate a subset of exactly half the elements are
3116 // to be selected.
3117 bool HalvingSwizzle = false;
3119 // This flag determines whether or not CompName has an 's' char prefix,
3120 // indicating that it is a string of hex values to be used as vector indices.
3121 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
3123 bool HasRepeated = false;
3124 bool HasIndex[16] = {};
3126 int Idx;
3128 // Check that we've found one of the special components, or that the component
3129 // names must come from the same set.
3130 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
3131 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3132 HalvingSwizzle = true;
3133 } else if (!HexSwizzle &&
3134 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3135 do {
3136 if (HasIndex[Idx]) HasRepeated = true;
3137 HasIndex[Idx] = true;
3138 compStr++;
3139 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3140 } else {
3141 if (HexSwizzle) compStr++;
3142 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3143 if (HasIndex[Idx]) HasRepeated = true;
3144 HasIndex[Idx] = true;
3145 compStr++;
3149 if (!HalvingSwizzle && *compStr) {
3150 // We didn't get to the end of the string. This means the component names
3151 // didn't come from the same set *or* we encountered an illegal name.
3152 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
3153 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
3154 return QualType();
3157 // Ensure no component accessor exceeds the width of the vector type it
3158 // operates on.
3159 if (!HalvingSwizzle) {
3160 compStr = CompName->getNameStart();
3162 if (HexSwizzle)
3163 compStr++;
3165 while (*compStr) {
3166 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
3167 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
3168 << baseType << SourceRange(CompLoc);
3169 return QualType();
3174 // The component accessor looks fine - now we need to compute the actual type.
3175 // The vector type is implied by the component accessor. For example,
3176 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
3177 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
3178 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
3179 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
3180 : CompName->getLength();
3181 if (HexSwizzle)
3182 CompSize--;
3184 if (CompSize == 1)
3185 return vecType->getElementType();
3187 if (HasRepeated) VK = VK_RValue;
3189 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
3190 // Now look up the TypeDefDecl from the vector type. Without this,
3191 // diagostics look bad. We want extended vector types to appear built-in.
3192 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3193 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3194 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
3196 return VT; // should never get here (a typedef type should always be found).
3199 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
3200 IdentifierInfo *Member,
3201 const Selector &Sel,
3202 ASTContext &Context) {
3203 if (Member)
3204 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3205 return PD;
3206 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
3207 return OMD;
3209 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3210 E = PDecl->protocol_end(); I != E; ++I) {
3211 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3212 Context))
3213 return D;
3215 return 0;
3218 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3219 IdentifierInfo *Member,
3220 const Selector &Sel,
3221 ASTContext &Context) {
3222 // Check protocols on qualified interfaces.
3223 Decl *GDecl = 0;
3224 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3225 E = QIdTy->qual_end(); I != E; ++I) {
3226 if (Member)
3227 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3228 GDecl = PD;
3229 break;
3231 // Also must look for a getter or setter name which uses property syntax.
3232 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
3233 GDecl = OMD;
3234 break;
3237 if (!GDecl) {
3238 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3239 E = QIdTy->qual_end(); I != E; ++I) {
3240 // Search in the protocol-qualifier list of current protocol.
3241 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3242 Context);
3243 if (GDecl)
3244 return GDecl;
3247 return GDecl;
3250 ExprResult
3251 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
3252 bool IsArrow, SourceLocation OpLoc,
3253 const CXXScopeSpec &SS,
3254 NamedDecl *FirstQualifierInScope,
3255 const DeclarationNameInfo &NameInfo,
3256 const TemplateArgumentListInfo *TemplateArgs) {
3257 // Even in dependent contexts, try to diagnose base expressions with
3258 // obviously wrong types, e.g.:
3260 // T* t;
3261 // t.f;
3263 // In Obj-C++, however, the above expression is valid, since it could be
3264 // accessing the 'f' property if T is an Obj-C interface. The extra check
3265 // allows this, while still reporting an error if T is a struct pointer.
3266 if (!IsArrow) {
3267 const PointerType *PT = BaseType->getAs<PointerType>();
3268 if (PT && (!getLangOptions().ObjC1 ||
3269 PT->getPointeeType()->isRecordType())) {
3270 assert(BaseExpr && "cannot happen with implicit member accesses");
3271 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
3272 << BaseType << BaseExpr->getSourceRange();
3273 return ExprError();
3277 assert(BaseType->isDependentType() ||
3278 NameInfo.getName().isDependentName() ||
3279 isDependentScopeSpecifier(SS));
3281 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3282 // must have pointer type, and the accessed type is the pointee.
3283 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
3284 IsArrow, OpLoc,
3285 SS.getScopeRep(),
3286 SS.getRange(),
3287 FirstQualifierInScope,
3288 NameInfo, TemplateArgs));
3291 /// We know that the given qualified member reference points only to
3292 /// declarations which do not belong to the static type of the base
3293 /// expression. Diagnose the problem.
3294 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3295 Expr *BaseExpr,
3296 QualType BaseType,
3297 const CXXScopeSpec &SS,
3298 NamedDecl *rep,
3299 const DeclarationNameInfo &nameInfo) {
3300 // If this is an implicit member access, use a different set of
3301 // diagnostics.
3302 if (!BaseExpr)
3303 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
3305 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3306 << SS.getRange() << rep << BaseType;
3309 // Check whether the declarations we found through a nested-name
3310 // specifier in a member expression are actually members of the base
3311 // type. The restriction here is:
3313 // C++ [expr.ref]p2:
3314 // ... In these cases, the id-expression shall name a
3315 // member of the class or of one of its base classes.
3317 // So it's perfectly legitimate for the nested-name specifier to name
3318 // an unrelated class, and for us to find an overload set including
3319 // decls from classes which are not superclasses, as long as the decl
3320 // we actually pick through overload resolution is from a superclass.
3321 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3322 QualType BaseType,
3323 const CXXScopeSpec &SS,
3324 const LookupResult &R) {
3325 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3326 if (!BaseRT) {
3327 // We can't check this yet because the base type is still
3328 // dependent.
3329 assert(BaseType->isDependentType());
3330 return false;
3332 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
3334 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3335 // If this is an implicit member reference and we find a
3336 // non-instance member, it's not an error.
3337 if (!BaseExpr && !(*I)->isCXXInstanceMember())
3338 return false;
3340 // Note that we use the DC of the decl, not the underlying decl.
3341 DeclContext *DC = (*I)->getDeclContext();
3342 while (DC->isTransparentContext())
3343 DC = DC->getParent();
3345 if (!DC->isRecord())
3346 continue;
3348 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
3349 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
3351 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3352 return false;
3355 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3356 R.getRepresentativeDecl(),
3357 R.getLookupNameInfo());
3358 return true;
3361 static bool
3362 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3363 SourceRange BaseRange, const RecordType *RTy,
3364 SourceLocation OpLoc, CXXScopeSpec &SS,
3365 bool HasTemplateArgs) {
3366 RecordDecl *RDecl = RTy->getDecl();
3367 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
3368 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
3369 << BaseRange))
3370 return true;
3372 if (HasTemplateArgs) {
3373 // LookupTemplateName doesn't expect these both to exist simultaneously.
3374 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3376 bool MOUS;
3377 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3378 return false;
3381 DeclContext *DC = RDecl;
3382 if (SS.isSet()) {
3383 // If the member name was a qualified-id, look into the
3384 // nested-name-specifier.
3385 DC = SemaRef.computeDeclContext(SS, false);
3387 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
3388 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3389 << SS.getRange() << DC;
3390 return true;
3393 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
3395 if (!isa<TypeDecl>(DC)) {
3396 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3397 << DC << SS.getRange();
3398 return true;
3402 // The record definition is complete, now look up the member.
3403 SemaRef.LookupQualifiedName(R, DC);
3405 if (!R.empty())
3406 return false;
3408 // We didn't find anything with the given name, so try to correct
3409 // for typos.
3410 DeclarationName Name = R.getLookupName();
3411 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
3412 !R.empty() &&
3413 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3414 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3415 << Name << DC << R.getLookupName() << SS.getRange()
3416 << FixItHint::CreateReplacement(R.getNameLoc(),
3417 R.getLookupName().getAsString());
3418 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3419 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3420 << ND->getDeclName();
3421 return false;
3422 } else {
3423 R.clear();
3424 R.setLookupName(Name);
3427 return false;
3430 ExprResult
3431 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3432 SourceLocation OpLoc, bool IsArrow,
3433 CXXScopeSpec &SS,
3434 NamedDecl *FirstQualifierInScope,
3435 const DeclarationNameInfo &NameInfo,
3436 const TemplateArgumentListInfo *TemplateArgs) {
3437 if (BaseType->isDependentType() ||
3438 (SS.isSet() && isDependentScopeSpecifier(SS)))
3439 return ActOnDependentMemberExpr(Base, BaseType,
3440 IsArrow, OpLoc,
3441 SS, FirstQualifierInScope,
3442 NameInfo, TemplateArgs);
3444 LookupResult R(*this, NameInfo, LookupMemberName);
3446 // Implicit member accesses.
3447 if (!Base) {
3448 QualType RecordTy = BaseType;
3449 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3450 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3451 RecordTy->getAs<RecordType>(),
3452 OpLoc, SS, TemplateArgs != 0))
3453 return ExprError();
3455 // Explicit member accesses.
3456 } else {
3457 ExprResult Result =
3458 LookupMemberExpr(R, Base, IsArrow, OpLoc,
3459 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
3461 if (Result.isInvalid()) {
3462 Owned(Base);
3463 return ExprError();
3466 if (Result.get())
3467 return move(Result);
3469 // LookupMemberExpr can modify Base, and thus change BaseType
3470 BaseType = Base->getType();
3473 return BuildMemberReferenceExpr(Base, BaseType,
3474 OpLoc, IsArrow, SS, FirstQualifierInScope,
3475 R, TemplateArgs);
3478 ExprResult
3479 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
3480 SourceLocation OpLoc, bool IsArrow,
3481 const CXXScopeSpec &SS,
3482 NamedDecl *FirstQualifierInScope,
3483 LookupResult &R,
3484 const TemplateArgumentListInfo *TemplateArgs,
3485 bool SuppressQualifierCheck) {
3486 QualType BaseType = BaseExprType;
3487 if (IsArrow) {
3488 assert(BaseType->isPointerType());
3489 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3491 R.setBaseObjectType(BaseType);
3493 NestedNameSpecifier *Qualifier = SS.getScopeRep();
3494 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3495 DeclarationName MemberName = MemberNameInfo.getName();
3496 SourceLocation MemberLoc = MemberNameInfo.getLoc();
3498 if (R.isAmbiguous())
3499 return ExprError();
3501 if (R.empty()) {
3502 // Rederive where we looked up.
3503 DeclContext *DC = (SS.isSet()
3504 ? computeDeclContext(SS, false)
3505 : BaseType->getAs<RecordType>()->getDecl());
3507 Diag(R.getNameLoc(), diag::err_no_member)
3508 << MemberName << DC
3509 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
3510 return ExprError();
3513 // Diagnose lookups that find only declarations from a non-base
3514 // type. This is possible for either qualified lookups (which may
3515 // have been qualified with an unrelated type) or implicit member
3516 // expressions (which were found with unqualified lookup and thus
3517 // may have come from an enclosing scope). Note that it's okay for
3518 // lookup to find declarations from a non-base type as long as those
3519 // aren't the ones picked by overload resolution.
3520 if ((SS.isSet() || !BaseExpr ||
3521 (isa<CXXThisExpr>(BaseExpr) &&
3522 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
3523 !SuppressQualifierCheck &&
3524 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
3525 return ExprError();
3527 // Construct an unresolved result if we in fact got an unresolved
3528 // result.
3529 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
3530 // Suppress any lookup-related diagnostics; we'll do these when we
3531 // pick a member.
3532 R.suppressDiagnostics();
3534 UnresolvedMemberExpr *MemExpr
3535 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
3536 BaseExpr, BaseExprType,
3537 IsArrow, OpLoc,
3538 Qualifier, SS.getRange(),
3539 MemberNameInfo,
3540 TemplateArgs, R.begin(), R.end());
3542 return Owned(MemExpr);
3545 assert(R.isSingleResult());
3546 DeclAccessPair FoundDecl = R.begin().getPair();
3547 NamedDecl *MemberDecl = R.getFoundDecl();
3549 // FIXME: diagnose the presence of template arguments now.
3551 // If the decl being referenced had an error, return an error for this
3552 // sub-expr without emitting another error, in order to avoid cascading
3553 // error cases.
3554 if (MemberDecl->isInvalidDecl())
3555 return ExprError();
3557 // Handle the implicit-member-access case.
3558 if (!BaseExpr) {
3559 // If this is not an instance member, convert to a non-member access.
3560 if (!MemberDecl->isCXXInstanceMember())
3561 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
3563 SourceLocation Loc = R.getNameLoc();
3564 if (SS.getRange().isValid())
3565 Loc = SS.getRange().getBegin();
3566 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
3569 bool ShouldCheckUse = true;
3570 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3571 // Don't diagnose the use of a virtual member function unless it's
3572 // explicitly qualified.
3573 if (MD->isVirtual() && !SS.isSet())
3574 ShouldCheckUse = false;
3577 // Check the use of this member.
3578 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3579 Owned(BaseExpr);
3580 return ExprError();
3583 // Perform a property load on the base regardless of whether we
3584 // actually need it for the declaration.
3585 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3586 ConvertPropertyForRValue(BaseExpr);
3588 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3589 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3590 SS, FD, FoundDecl, MemberNameInfo);
3592 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3593 // We may have found a field within an anonymous union or struct
3594 // (C++ [class.union]).
3595 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
3596 BaseExpr, OpLoc);
3598 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3599 MarkDeclarationReferenced(MemberLoc, Var);
3600 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3601 Var, FoundDecl, MemberNameInfo,
3602 Var->getType().getNonReferenceType(),
3603 VK_LValue, OK_Ordinary));
3606 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3607 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3608 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3609 MemberFn, FoundDecl, MemberNameInfo,
3610 MemberFn->getType(),
3611 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3612 OK_Ordinary));
3614 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
3616 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3617 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3618 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3619 Enum, FoundDecl, MemberNameInfo,
3620 Enum->getType(), VK_RValue, OK_Ordinary));
3623 Owned(BaseExpr);
3625 // We found something that we didn't expect. Complain.
3626 if (isa<TypeDecl>(MemberDecl))
3627 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
3628 << MemberName << BaseType << int(IsArrow);
3629 else
3630 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3631 << MemberName << BaseType << int(IsArrow);
3633 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3634 << MemberName;
3635 R.suppressDiagnostics();
3636 return ExprError();
3639 /// Given that normal member access failed on the given expression,
3640 /// and given that the expression's type involves builtin-id or
3641 /// builtin-Class, decide whether substituting in the redefinition
3642 /// types would be profitable. The redefinition type is whatever
3643 /// this translation unit tried to typedef to id/Class; we store
3644 /// it to the side and then re-use it in places like this.
3645 static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3646 const ObjCObjectPointerType *opty
3647 = base->getType()->getAs<ObjCObjectPointerType>();
3648 if (!opty) return false;
3650 const ObjCObjectType *ty = opty->getObjectType();
3652 QualType redef;
3653 if (ty->isObjCId()) {
3654 redef = S.Context.ObjCIdRedefinitionType;
3655 } else if (ty->isObjCClass()) {
3656 redef = S.Context.ObjCClassRedefinitionType;
3657 } else {
3658 return false;
3661 // Do the substitution as long as the redefinition type isn't just a
3662 // possibly-qualified pointer to builtin-id or builtin-Class again.
3663 opty = redef->getAs<ObjCObjectPointerType>();
3664 if (opty && !opty->getObjectType()->getInterface() != 0)
3665 return false;
3667 S.ImpCastExprToType(base, redef, CK_BitCast);
3668 return true;
3671 /// Look up the given member of the given non-type-dependent
3672 /// expression. This can return in one of two ways:
3673 /// * If it returns a sentinel null-but-valid result, the caller will
3674 /// assume that lookup was performed and the results written into
3675 /// the provided structure. It will take over from there.
3676 /// * Otherwise, the returned expression will be produced in place of
3677 /// an ordinary member expression.
3679 /// The ObjCImpDecl bit is a gross hack that will need to be properly
3680 /// fixed for ObjC++.
3681 ExprResult
3682 Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
3683 bool &IsArrow, SourceLocation OpLoc,
3684 CXXScopeSpec &SS,
3685 Decl *ObjCImpDecl, bool HasTemplateArgs) {
3686 assert(BaseExpr && "no base expression");
3688 // Perform default conversions.
3689 DefaultFunctionArrayConversion(BaseExpr);
3690 if (IsArrow) DefaultLvalueConversion(BaseExpr);
3692 QualType BaseType = BaseExpr->getType();
3693 assert(!BaseType->isDependentType());
3695 DeclarationName MemberName = R.getLookupName();
3696 SourceLocation MemberLoc = R.getNameLoc();
3698 // For later type-checking purposes, turn arrow accesses into dot
3699 // accesses. The only access type we support that doesn't follow
3700 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3701 // and those never use arrows, so this is unaffected.
3702 if (IsArrow) {
3703 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3704 BaseType = Ptr->getPointeeType();
3705 else if (const ObjCObjectPointerType *Ptr
3706 = BaseType->getAs<ObjCObjectPointerType>())
3707 BaseType = Ptr->getPointeeType();
3708 else if (BaseType->isRecordType()) {
3709 // Recover from arrow accesses to records, e.g.:
3710 // struct MyRecord foo;
3711 // foo->bar
3712 // This is actually well-formed in C++ if MyRecord has an
3713 // overloaded operator->, but that should have been dealt with
3714 // by now.
3715 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3716 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3717 << FixItHint::CreateReplacement(OpLoc, ".");
3718 IsArrow = false;
3719 } else {
3720 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3721 << BaseType << BaseExpr->getSourceRange();
3722 return ExprError();
3726 // Handle field access to simple records.
3727 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3728 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3729 RTy, OpLoc, SS, HasTemplateArgs))
3730 return ExprError();
3732 // Returning valid-but-null is how we indicate to the caller that
3733 // the lookup result was filled in.
3734 return Owned((Expr*) 0);
3737 // Handle ivar access to Objective-C objects.
3738 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
3739 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3741 // There are three cases for the base type:
3742 // - builtin id (qualified or unqualified)
3743 // - builtin Class (qualified or unqualified)
3744 // - an interface
3745 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3746 if (!IDecl) {
3747 // There's an implicit 'isa' ivar on all objects.
3748 // But we only actually find it this way on objects of type 'id',
3749 // apparently.
3750 if (OTy->isObjCId() && Member->isStr("isa"))
3751 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3752 Context.getObjCClassType()));
3754 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3755 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3756 ObjCImpDecl, HasTemplateArgs);
3757 goto fail;
3760 ObjCInterfaceDecl *ClassDeclared;
3761 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3763 if (!IV) {
3764 // Attempt to correct for typos in ivar names.
3765 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3766 LookupMemberName);
3767 if (CorrectTypo(Res, 0, 0, IDecl, false,
3768 IsArrow ? CTC_ObjCIvarLookup
3769 : CTC_ObjCPropertyLookup) &&
3770 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3771 Diag(R.getNameLoc(),
3772 diag::err_typecheck_member_reference_ivar_suggest)
3773 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3774 << FixItHint::CreateReplacement(R.getNameLoc(),
3775 IV->getNameAsString());
3776 Diag(IV->getLocation(), diag::note_previous_decl)
3777 << IV->getDeclName();
3778 } else {
3779 Res.clear();
3780 Res.setLookupName(Member);
3782 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3783 << IDecl->getDeclName() << MemberName
3784 << BaseExpr->getSourceRange();
3785 return ExprError();
3789 // If the decl being referenced had an error, return an error for this
3790 // sub-expr without emitting another error, in order to avoid cascading
3791 // error cases.
3792 if (IV->isInvalidDecl())
3793 return ExprError();
3795 // Check whether we can reference this field.
3796 if (DiagnoseUseOfDecl(IV, MemberLoc))
3797 return ExprError();
3798 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3799 IV->getAccessControl() != ObjCIvarDecl::Package) {
3800 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3801 if (ObjCMethodDecl *MD = getCurMethodDecl())
3802 ClassOfMethodDecl = MD->getClassInterface();
3803 else if (ObjCImpDecl && getCurFunctionDecl()) {
3804 // Case of a c-function declared inside an objc implementation.
3805 // FIXME: For a c-style function nested inside an objc implementation
3806 // class, there is no implementation context available, so we pass
3807 // down the context as argument to this routine. Ideally, this context
3808 // need be passed down in the AST node and somehow calculated from the
3809 // AST for a function decl.
3810 if (ObjCImplementationDecl *IMPD =
3811 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3812 ClassOfMethodDecl = IMPD->getClassInterface();
3813 else if (ObjCCategoryImplDecl* CatImplClass =
3814 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3815 ClassOfMethodDecl = CatImplClass->getClassInterface();
3818 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3819 if (ClassDeclared != IDecl ||
3820 ClassOfMethodDecl != ClassDeclared)
3821 Diag(MemberLoc, diag::error_private_ivar_access)
3822 << IV->getDeclName();
3823 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3824 // @protected
3825 Diag(MemberLoc, diag::error_protected_ivar_access)
3826 << IV->getDeclName();
3829 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3830 MemberLoc, BaseExpr,
3831 IsArrow));
3834 // Objective-C property access.
3835 const ObjCObjectPointerType *OPT;
3836 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3837 // This actually uses the base as an r-value.
3838 DefaultLvalueConversion(BaseExpr);
3839 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3841 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3843 const ObjCObjectType *OT = OPT->getObjectType();
3845 // id, with and without qualifiers.
3846 if (OT->isObjCId()) {
3847 // Check protocols on qualified interfaces.
3848 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3849 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3850 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3851 // Check the use of this declaration
3852 if (DiagnoseUseOfDecl(PD, MemberLoc))
3853 return ExprError();
3855 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3856 VK_LValue,
3857 OK_ObjCProperty,
3858 MemberLoc,
3859 BaseExpr));
3862 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3863 // Check the use of this method.
3864 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3865 return ExprError();
3866 Selector SetterSel =
3867 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3868 PP.getSelectorTable(), Member);
3869 ObjCMethodDecl *SMD = 0;
3870 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3871 SetterSel, Context))
3872 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3873 QualType PType = OMD->getSendResultType();
3875 ExprValueKind VK = VK_LValue;
3876 if (!getLangOptions().CPlusPlus &&
3877 IsCForbiddenLValueType(Context, PType))
3878 VK = VK_RValue;
3879 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3881 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3882 VK, OK,
3883 MemberLoc, BaseExpr));
3887 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3888 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3889 ObjCImpDecl, HasTemplateArgs);
3891 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3892 << MemberName << BaseType);
3895 // 'Class', unqualified only.
3896 if (OT->isObjCClass()) {
3897 // Only works in a method declaration (??!).
3898 ObjCMethodDecl *MD = getCurMethodDecl();
3899 if (!MD) {
3900 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3901 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3902 ObjCImpDecl, HasTemplateArgs);
3904 goto fail;
3907 // Also must look for a getter name which uses property syntax.
3908 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3909 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3910 ObjCMethodDecl *Getter;
3911 if ((Getter = IFace->lookupClassMethod(Sel))) {
3912 // Check the use of this method.
3913 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3914 return ExprError();
3915 } else
3916 Getter = IFace->lookupPrivateMethod(Sel, false);
3917 // If we found a getter then this may be a valid dot-reference, we
3918 // will look for the matching setter, in case it is needed.
3919 Selector SetterSel =
3920 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3921 PP.getSelectorTable(), Member);
3922 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3923 if (!Setter) {
3924 // If this reference is in an @implementation, also check for 'private'
3925 // methods.
3926 Setter = IFace->lookupPrivateMethod(SetterSel, false);
3928 // Look through local category implementations associated with the class.
3929 if (!Setter)
3930 Setter = IFace->getCategoryClassMethod(SetterSel);
3932 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3933 return ExprError();
3935 if (Getter || Setter) {
3936 QualType PType;
3938 ExprValueKind VK = VK_LValue;
3939 if (Getter) {
3940 PType = Getter->getSendResultType();
3941 if (!getLangOptions().CPlusPlus &&
3942 IsCForbiddenLValueType(Context, PType))
3943 VK = VK_RValue;
3944 } else {
3945 // Get the expression type from Setter's incoming parameter.
3946 PType = (*(Setter->param_end() -1))->getType();
3948 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3950 // FIXME: we must check that the setter has property type.
3951 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3952 PType, VK, OK,
3953 MemberLoc, BaseExpr));
3956 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3957 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3958 ObjCImpDecl, HasTemplateArgs);
3960 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3961 << MemberName << BaseType);
3964 // Normal property access.
3965 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3966 SourceLocation(), QualType(), false);
3969 // Handle 'field access' to vectors, such as 'V.xx'.
3970 if (BaseType->isExtVectorType()) {
3971 // FIXME: this expr should store IsArrow.
3972 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3973 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
3974 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3975 Member, MemberLoc);
3976 if (ret.isNull())
3977 return ExprError();
3979 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3980 *Member, MemberLoc));
3983 // Adjust builtin-sel to the appropriate redefinition type if that's
3984 // not just a pointer to builtin-sel again.
3985 if (IsArrow &&
3986 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3987 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3988 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3989 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3990 ObjCImpDecl, HasTemplateArgs);
3993 // Failure cases.
3994 fail:
3996 // There's a possible road to recovery for function types.
3997 const FunctionType *Fun = 0;
3998 SourceLocation ParenInsertionLoc =
3999 PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4001 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
4002 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
4003 // fall out, handled below.
4005 // Recover from dot accesses to pointers, e.g.:
4006 // type *foo;
4007 // foo.bar
4008 // This is actually well-formed in two cases:
4009 // - 'type' is an Objective C type
4010 // - 'bar' is a pseudo-destructor name which happens to refer to
4011 // the appropriate pointer type
4012 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4013 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
4014 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4015 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4016 << FixItHint::CreateReplacement(OpLoc, "->");
4018 // Recurse as an -> access.
4019 IsArrow = true;
4020 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4021 ObjCImpDecl, HasTemplateArgs);
4023 } else {
4024 Fun = BaseType->getAs<FunctionType>();
4027 // If the user is trying to apply -> or . to a function pointer
4028 // type, it's probably because they forgot parentheses to call that
4029 // function. Suggest the addition of those parentheses, build the
4030 // call, and continue on.
4031 if (Fun || BaseType == Context.OverloadTy) {
4032 bool TryCall;
4033 if (BaseType == Context.OverloadTy) {
4034 // Plunder the overload set for something that would make the member
4035 // expression valid.
4036 const OverloadExpr *Overloads = cast<OverloadExpr>(BaseExpr);
4037 UnresolvedSet<4> CandidateOverloads;
4038 bool HasZeroArgCandidateOverload = false;
4039 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
4040 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
4041 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*it);
4042 QualType ResultTy = OverloadDecl->getResultType();
4043 if ((!IsArrow && ResultTy->isRecordType()) ||
4044 (IsArrow && ResultTy->isPointerType() &&
4045 ResultTy->getPointeeType()->isRecordType())) {
4046 CandidateOverloads.addDecl(*it);
4047 if (OverloadDecl->getNumParams() == 0) {
4048 HasZeroArgCandidateOverload = true;
4052 if (HasZeroArgCandidateOverload && CandidateOverloads.size() == 1) {
4053 // We have one reasonable overload, and there's only one way to call it,
4054 // so emit a fixit and try to recover
4055 Diag(ParenInsertionLoc, diag::err_member_reference_needs_call)
4056 << 1
4057 << BaseExpr->getSourceRange()
4058 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4059 TryCall = true;
4060 } else {
4061 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4062 << 0
4063 << BaseExpr->getSourceRange();
4064 int CandidateOverloadCount = CandidateOverloads.size();
4065 int I;
4066 for (I = 0; I < CandidateOverloadCount; ++I) {
4067 // FIXME: Magic number for max shown overloads stolen from
4068 // OverloadCandidateSet::NoteCandidates.
4069 if (I >= 4 && Diags.getShowOverloads() == Diagnostic::Ovl_Best) {
4070 break;
4072 Diag(CandidateOverloads[I].getDecl()->getSourceRange().getBegin(),
4073 diag::note_member_ref_possible_intended_overload);
4075 if (I != CandidateOverloadCount) {
4076 Diag(BaseExpr->getExprLoc(), diag::note_ovl_too_many_candidates)
4077 << int(CandidateOverloadCount - I);
4079 return ExprError();
4081 } else {
4082 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4083 TryCall = (FPT->getNumArgs() == 0);
4084 } else {
4085 TryCall = true;
4088 if (TryCall) {
4089 QualType ResultTy = Fun->getResultType();
4090 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4091 (IsArrow && ResultTy->isPointerType() &&
4092 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
4097 if (TryCall) {
4098 if (Fun) {
4099 Diag(BaseExpr->getExprLoc(),
4100 diag::err_member_reference_needs_call_zero_arg)
4101 << QualType(Fun, 0)
4102 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
4105 ExprResult NewBase
4106 = ActOnCallExpr(0, BaseExpr, ParenInsertionLoc,
4107 MultiExprArg(*this, 0, 0), ParenInsertionLoc);
4108 if (NewBase.isInvalid())
4109 return ExprError();
4110 BaseExpr = NewBase.takeAs<Expr>();
4113 DefaultFunctionArrayConversion(BaseExpr);
4114 BaseType = BaseExpr->getType();
4116 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4117 ObjCImpDecl, HasTemplateArgs);
4121 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4122 << BaseType << BaseExpr->getSourceRange();
4124 return ExprError();
4127 /// The main callback when the parser finds something like
4128 /// expression . [nested-name-specifier] identifier
4129 /// expression -> [nested-name-specifier] identifier
4130 /// where 'identifier' encompasses a fairly broad spectrum of
4131 /// possibilities, including destructor and operator references.
4133 /// \param OpKind either tok::arrow or tok::period
4134 /// \param HasTrailingLParen whether the next token is '(', which
4135 /// is used to diagnose mis-uses of special members that can
4136 /// only be called
4137 /// \param ObjCImpDecl the current ObjC @implementation decl;
4138 /// this is an ugly hack around the fact that ObjC @implementations
4139 /// aren't properly put in the context chain
4140 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
4141 SourceLocation OpLoc,
4142 tok::TokenKind OpKind,
4143 CXXScopeSpec &SS,
4144 UnqualifiedId &Id,
4145 Decl *ObjCImpDecl,
4146 bool HasTrailingLParen) {
4147 if (SS.isSet() && SS.isInvalid())
4148 return ExprError();
4150 // Warn about the explicit constructor calls Microsoft extension.
4151 if (getLangOptions().Microsoft &&
4152 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4153 Diag(Id.getSourceRange().getBegin(),
4154 diag::ext_ms_explicit_constructor_call);
4156 TemplateArgumentListInfo TemplateArgsBuffer;
4158 // Decompose the name into its component parts.
4159 DeclarationNameInfo NameInfo;
4160 const TemplateArgumentListInfo *TemplateArgs;
4161 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
4162 NameInfo, TemplateArgs);
4164 DeclarationName Name = NameInfo.getName();
4165 bool IsArrow = (OpKind == tok::arrow);
4167 NamedDecl *FirstQualifierInScope
4168 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4169 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4171 // This is a postfix expression, so get rid of ParenListExprs.
4172 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
4173 if (Result.isInvalid()) return ExprError();
4174 Base = Result.take();
4176 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4177 isDependentScopeSpecifier(SS)) {
4178 Result = ActOnDependentMemberExpr(Base, Base->getType(),
4179 IsArrow, OpLoc,
4180 SS, FirstQualifierInScope,
4181 NameInfo, TemplateArgs);
4182 } else {
4183 LookupResult R(*this, NameInfo, LookupMemberName);
4184 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4185 SS, ObjCImpDecl, TemplateArgs != 0);
4187 if (Result.isInvalid()) {
4188 Owned(Base);
4189 return ExprError();
4192 if (Result.get()) {
4193 // The only way a reference to a destructor can be used is to
4194 // immediately call it, which falls into this case. If the
4195 // next token is not a '(', produce a diagnostic and build the
4196 // call now.
4197 if (!HasTrailingLParen &&
4198 Id.getKind() == UnqualifiedId::IK_DestructorName)
4199 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
4201 return move(Result);
4204 Result = BuildMemberReferenceExpr(Base, Base->getType(),
4205 OpLoc, IsArrow, SS, FirstQualifierInScope,
4206 R, TemplateArgs);
4209 return move(Result);
4212 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4213 FunctionDecl *FD,
4214 ParmVarDecl *Param) {
4215 if (Param->hasUnparsedDefaultArg()) {
4216 Diag(CallLoc,
4217 diag::err_use_of_default_argument_to_function_declared_later) <<
4218 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4219 Diag(UnparsedDefaultArgLocs[Param],
4220 diag::note_default_argument_declared_here);
4221 return ExprError();
4224 if (Param->hasUninstantiatedDefaultArg()) {
4225 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4227 // Instantiate the expression.
4228 MultiLevelTemplateArgumentList ArgList
4229 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
4231 std::pair<const TemplateArgument *, unsigned> Innermost
4232 = ArgList.getInnermost();
4233 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4234 Innermost.second);
4236 ExprResult Result;
4238 // C++ [dcl.fct.default]p5:
4239 // The names in the [default argument] expression are bound, and
4240 // the semantic constraints are checked, at the point where the
4241 // default argument expression appears.
4242 ContextRAII SavedContext(*this, FD);
4243 Result = SubstExpr(UninstExpr, ArgList);
4245 if (Result.isInvalid())
4246 return ExprError();
4248 // Check the expression as an initializer for the parameter.
4249 InitializedEntity Entity
4250 = InitializedEntity::InitializeParameter(Context, Param);
4251 InitializationKind Kind
4252 = InitializationKind::CreateCopy(Param->getLocation(),
4253 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4254 Expr *ResultE = Result.takeAs<Expr>();
4256 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4257 Result = InitSeq.Perform(*this, Entity, Kind,
4258 MultiExprArg(*this, &ResultE, 1));
4259 if (Result.isInvalid())
4260 return ExprError();
4262 // Build the default argument expression.
4263 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4264 Result.takeAs<Expr>()));
4267 // If the default expression creates temporaries, we need to
4268 // push them to the current stack of expression temporaries so they'll
4269 // be properly destroyed.
4270 // FIXME: We should really be rebuilding the default argument with new
4271 // bound temporaries; see the comment in PR5810.
4272 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4273 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4274 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4275 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4276 ExprTemporaries.push_back(Temporary);
4279 // We already type-checked the argument, so we know it works.
4280 // Just mark all of the declarations in this potentially-evaluated expression
4281 // as being "referenced".
4282 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
4283 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
4286 /// ConvertArgumentsForCall - Converts the arguments specified in
4287 /// Args/NumArgs to the parameter types of the function FDecl with
4288 /// function prototype Proto. Call is the call expression itself, and
4289 /// Fn is the function expression. For a C++ member function, this
4290 /// routine does not attempt to convert the object argument. Returns
4291 /// true if the call is ill-formed.
4292 bool
4293 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4294 FunctionDecl *FDecl,
4295 const FunctionProtoType *Proto,
4296 Expr **Args, unsigned NumArgs,
4297 SourceLocation RParenLoc) {
4298 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4299 // assignment, to the types of the corresponding parameter, ...
4300 unsigned NumArgsInProto = Proto->getNumArgs();
4301 bool Invalid = false;
4303 // If too few arguments are available (and we don't have default
4304 // arguments for the remaining parameters), don't make the call.
4305 if (NumArgs < NumArgsInProto) {
4306 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4307 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4308 << Fn->getType()->isBlockPointerType()
4309 << NumArgsInProto << NumArgs << Fn->getSourceRange();
4310 Call->setNumArgs(Context, NumArgsInProto);
4313 // If too many are passed and not variadic, error on the extras and drop
4314 // them.
4315 if (NumArgs > NumArgsInProto) {
4316 if (!Proto->isVariadic()) {
4317 Diag(Args[NumArgsInProto]->getLocStart(),
4318 diag::err_typecheck_call_too_many_args)
4319 << Fn->getType()->isBlockPointerType()
4320 << NumArgsInProto << NumArgs << Fn->getSourceRange()
4321 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4322 Args[NumArgs-1]->getLocEnd());
4323 // This deletes the extra arguments.
4324 Call->setNumArgs(Context, NumArgsInProto);
4325 return true;
4328 llvm::SmallVector<Expr *, 8> AllArgs;
4329 VariadicCallType CallType =
4330 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4331 if (Fn->getType()->isBlockPointerType())
4332 CallType = VariadicBlock; // Block
4333 else if (isa<MemberExpr>(Fn))
4334 CallType = VariadicMethod;
4335 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
4336 Proto, 0, Args, NumArgs, AllArgs, CallType);
4337 if (Invalid)
4338 return true;
4339 unsigned TotalNumArgs = AllArgs.size();
4340 for (unsigned i = 0; i < TotalNumArgs; ++i)
4341 Call->setArg(i, AllArgs[i]);
4343 return false;
4346 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4347 FunctionDecl *FDecl,
4348 const FunctionProtoType *Proto,
4349 unsigned FirstProtoArg,
4350 Expr **Args, unsigned NumArgs,
4351 llvm::SmallVector<Expr *, 8> &AllArgs,
4352 VariadicCallType CallType) {
4353 unsigned NumArgsInProto = Proto->getNumArgs();
4354 unsigned NumArgsToCheck = NumArgs;
4355 bool Invalid = false;
4356 if (NumArgs != NumArgsInProto)
4357 // Use default arguments for missing arguments
4358 NumArgsToCheck = NumArgsInProto;
4359 unsigned ArgIx = 0;
4360 // Continue to check argument types (even if we have too few/many args).
4361 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4362 QualType ProtoArgType = Proto->getArgType(i);
4364 Expr *Arg;
4365 if (ArgIx < NumArgs) {
4366 Arg = Args[ArgIx++];
4368 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4369 ProtoArgType,
4370 PDiag(diag::err_call_incomplete_argument)
4371 << Arg->getSourceRange()))
4372 return true;
4374 // Pass the argument
4375 ParmVarDecl *Param = 0;
4376 if (FDecl && i < FDecl->getNumParams())
4377 Param = FDecl->getParamDecl(i);
4379 InitializedEntity Entity =
4380 Param? InitializedEntity::InitializeParameter(Context, Param)
4381 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
4382 ExprResult ArgE = PerformCopyInitialization(Entity,
4383 SourceLocation(),
4384 Owned(Arg));
4385 if (ArgE.isInvalid())
4386 return true;
4388 Arg = ArgE.takeAs<Expr>();
4389 } else {
4390 ParmVarDecl *Param = FDecl->getParamDecl(i);
4392 ExprResult ArgExpr =
4393 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4394 if (ArgExpr.isInvalid())
4395 return true;
4397 Arg = ArgExpr.takeAs<Expr>();
4399 AllArgs.push_back(Arg);
4402 // If this is a variadic call, handle args passed through "...".
4403 if (CallType != VariadicDoesNotApply) {
4404 // Promote the arguments (C99 6.5.2.2p7).
4405 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4406 Expr *Arg = Args[i];
4407 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
4408 AllArgs.push_back(Arg);
4411 return Invalid;
4414 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4415 /// This provides the location of the left/right parens and a list of comma
4416 /// locations.
4417 ExprResult
4418 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4419 MultiExprArg args, SourceLocation RParenLoc,
4420 Expr *ExecConfig) {
4421 unsigned NumArgs = args.size();
4423 // Since this might be a postfix expression, get rid of ParenListExprs.
4424 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4425 if (Result.isInvalid()) return ExprError();
4426 Fn = Result.take();
4428 Expr **Args = args.release();
4430 if (getLangOptions().CPlusPlus) {
4431 // If this is a pseudo-destructor expression, build the call immediately.
4432 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4433 if (NumArgs > 0) {
4434 // Pseudo-destructor calls should not have any arguments.
4435 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4436 << FixItHint::CreateRemoval(
4437 SourceRange(Args[0]->getLocStart(),
4438 Args[NumArgs-1]->getLocEnd()));
4440 NumArgs = 0;
4443 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
4444 VK_RValue, RParenLoc));
4447 // Determine whether this is a dependent call inside a C++ template,
4448 // in which case we won't do any semantic analysis now.
4449 // FIXME: Will need to cache the results of name lookup (including ADL) in
4450 // Fn.
4451 bool Dependent = false;
4452 if (Fn->isTypeDependent())
4453 Dependent = true;
4454 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4455 Dependent = true;
4457 if (Dependent) {
4458 if (ExecConfig) {
4459 return Owned(new (Context) CUDAKernelCallExpr(
4460 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4461 Context.DependentTy, VK_RValue, RParenLoc));
4462 } else {
4463 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4464 Context.DependentTy, VK_RValue,
4465 RParenLoc));
4469 // Determine whether this is a call to an object (C++ [over.call.object]).
4470 if (Fn->getType()->isRecordType())
4471 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
4472 RParenLoc));
4474 Expr *NakedFn = Fn->IgnoreParens();
4476 // Determine whether this is a call to an unresolved member function.
4477 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4478 // If lookup was unresolved but not dependent (i.e. didn't find
4479 // an unresolved using declaration), it has to be an overloaded
4480 // function set, which means it must contain either multiple
4481 // declarations (all methods or method templates) or a single
4482 // method template.
4483 assert((MemE->getNumDecls() > 1) ||
4484 isa<FunctionTemplateDecl>(
4485 (*MemE->decls_begin())->getUnderlyingDecl()));
4486 (void)MemE;
4488 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
4489 RParenLoc);
4492 // Determine whether this is a call to a member function.
4493 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
4494 NamedDecl *MemDecl = MemExpr->getMemberDecl();
4495 if (isa<CXXMethodDecl>(MemDecl))
4496 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
4497 RParenLoc);
4500 // Determine whether this is a call to a pointer-to-member function.
4501 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
4502 if (BO->getOpcode() == BO_PtrMemD ||
4503 BO->getOpcode() == BO_PtrMemI) {
4504 if (const FunctionProtoType *FPT
4505 = BO->getType()->getAs<FunctionProtoType>()) {
4506 QualType ResultTy = FPT->getCallResultType(Context);
4507 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
4509 // Check that the object type isn't more qualified than the
4510 // member function we're calling.
4511 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4512 Qualifiers ObjectQuals
4513 = BO->getOpcode() == BO_PtrMemD
4514 ? BO->getLHS()->getType().getQualifiers()
4515 : BO->getLHS()->getType()->getAs<PointerType>()
4516 ->getPointeeType().getQualifiers();
4518 Qualifiers Difference = ObjectQuals - FuncQuals;
4519 Difference.removeObjCGCAttr();
4520 Difference.removeAddressSpace();
4521 if (Difference) {
4522 std::string QualsString = Difference.getAsString();
4523 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4524 << BO->getType().getUnqualifiedType()
4525 << QualsString
4526 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4529 CXXMemberCallExpr *TheCall
4530 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
4531 NumArgs, ResultTy, VK,
4532 RParenLoc);
4534 if (CheckCallReturnType(FPT->getResultType(),
4535 BO->getRHS()->getSourceRange().getBegin(),
4536 TheCall, 0))
4537 return ExprError();
4539 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
4540 RParenLoc))
4541 return ExprError();
4543 return MaybeBindToTemporary(TheCall);
4545 return ExprError(Diag(Fn->getLocStart(),
4546 diag::err_typecheck_call_not_function)
4547 << Fn->getType() << Fn->getSourceRange());
4552 // If we're directly calling a function, get the appropriate declaration.
4553 // Also, in C++, keep track of whether we should perform argument-dependent
4554 // lookup and whether there were any explicitly-specified template arguments.
4556 Expr *NakedFn = Fn->IgnoreParens();
4557 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4558 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4559 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4560 RParenLoc, ExecConfig);
4563 NamedDecl *NDecl = 0;
4564 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4565 if (UnOp->getOpcode() == UO_AddrOf)
4566 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4568 if (isa<DeclRefExpr>(NakedFn))
4569 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4571 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4572 ExecConfig);
4575 ExprResult
4576 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4577 MultiExprArg execConfig, SourceLocation GGGLoc) {
4578 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4579 if (!ConfigDecl)
4580 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4581 << "cudaConfigureCall");
4582 QualType ConfigQTy = ConfigDecl->getType();
4584 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4585 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4587 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
4590 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4591 /// i.e. an expression not of \p OverloadTy. The expression should
4592 /// unary-convert to an expression of function-pointer or
4593 /// block-pointer type.
4595 /// \param NDecl the declaration being called, if available
4596 ExprResult
4597 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4598 SourceLocation LParenLoc,
4599 Expr **Args, unsigned NumArgs,
4600 SourceLocation RParenLoc,
4601 Expr *Config) {
4602 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4604 // Promote the function operand.
4605 UsualUnaryConversions(Fn);
4607 // Make the call expr early, before semantic checks. This guarantees cleanup
4608 // of arguments and function on error.
4609 CallExpr *TheCall;
4610 if (Config) {
4611 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4612 cast<CallExpr>(Config),
4613 Args, NumArgs,
4614 Context.BoolTy,
4615 VK_RValue,
4616 RParenLoc);
4617 } else {
4618 TheCall = new (Context) CallExpr(Context, Fn,
4619 Args, NumArgs,
4620 Context.BoolTy,
4621 VK_RValue,
4622 RParenLoc);
4625 const FunctionType *FuncT;
4626 if (!Fn->getType()->isBlockPointerType()) {
4627 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4628 // have type pointer to function".
4629 const PointerType *PT = Fn->getType()->getAs<PointerType>();
4630 if (PT == 0)
4631 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4632 << Fn->getType() << Fn->getSourceRange());
4633 FuncT = PT->getPointeeType()->getAs<FunctionType>();
4634 } else { // This is a block call.
4635 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
4636 getAs<FunctionType>();
4638 if (FuncT == 0)
4639 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4640 << Fn->getType() << Fn->getSourceRange());
4642 // Check for a valid return type
4643 if (CheckCallReturnType(FuncT->getResultType(),
4644 Fn->getSourceRange().getBegin(), TheCall,
4645 FDecl))
4646 return ExprError();
4648 // We know the result type of the call, set it.
4649 TheCall->setType(FuncT->getCallResultType(Context));
4650 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4652 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
4653 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4654 RParenLoc))
4655 return ExprError();
4656 } else {
4657 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4659 if (FDecl) {
4660 // Check if we have too few/too many template arguments, based
4661 // on our knowledge of the function definition.
4662 const FunctionDecl *Def = 0;
4663 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4664 const FunctionProtoType *Proto
4665 = Def->getType()->getAs<FunctionProtoType>();
4666 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4667 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4668 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4671 // If the function we're calling isn't a function prototype, but we have
4672 // a function prototype from a prior declaratiom, use that prototype.
4673 if (!FDecl->hasPrototype())
4674 Proto = FDecl->getType()->getAs<FunctionProtoType>();
4677 // Promote the arguments (C99 6.5.2.2p6).
4678 for (unsigned i = 0; i != NumArgs; i++) {
4679 Expr *Arg = Args[i];
4681 if (Proto && i < Proto->getNumArgs()) {
4682 InitializedEntity Entity
4683 = InitializedEntity::InitializeParameter(Context,
4684 Proto->getArgType(i));
4685 ExprResult ArgE = PerformCopyInitialization(Entity,
4686 SourceLocation(),
4687 Owned(Arg));
4688 if (ArgE.isInvalid())
4689 return true;
4691 Arg = ArgE.takeAs<Expr>();
4693 } else {
4694 DefaultArgumentPromotion(Arg);
4697 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4698 Arg->getType(),
4699 PDiag(diag::err_call_incomplete_argument)
4700 << Arg->getSourceRange()))
4701 return ExprError();
4703 TheCall->setArg(i, Arg);
4707 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4708 if (!Method->isStatic())
4709 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4710 << Fn->getSourceRange());
4712 // Check for sentinels
4713 if (NDecl)
4714 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4716 // Do special checking on direct calls to functions.
4717 if (FDecl) {
4718 if (CheckFunctionCall(FDecl, TheCall))
4719 return ExprError();
4721 if (unsigned BuiltinID = FDecl->getBuiltinID())
4722 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4723 } else if (NDecl) {
4724 if (CheckBlockCall(NDecl, TheCall))
4725 return ExprError();
4728 return MaybeBindToTemporary(TheCall);
4731 ExprResult
4732 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4733 SourceLocation RParenLoc, Expr *InitExpr) {
4734 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4735 // FIXME: put back this assert when initializers are worked out.
4736 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4738 TypeSourceInfo *TInfo;
4739 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4740 if (!TInfo)
4741 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4743 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4746 ExprResult
4747 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4748 SourceLocation RParenLoc, Expr *literalExpr) {
4749 QualType literalType = TInfo->getType();
4751 if (literalType->isArrayType()) {
4752 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4753 PDiag(diag::err_illegal_decl_array_incomplete_type)
4754 << SourceRange(LParenLoc,
4755 literalExpr->getSourceRange().getEnd())))
4756 return ExprError();
4757 if (literalType->isVariableArrayType())
4758 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4759 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
4760 } else if (!literalType->isDependentType() &&
4761 RequireCompleteType(LParenLoc, literalType,
4762 PDiag(diag::err_typecheck_decl_incomplete_type)
4763 << SourceRange(LParenLoc,
4764 literalExpr->getSourceRange().getEnd())))
4765 return ExprError();
4767 InitializedEntity Entity
4768 = InitializedEntity::InitializeTemporary(literalType);
4769 InitializationKind Kind
4770 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
4771 /*IsCStyleCast=*/true);
4772 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
4773 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4774 MultiExprArg(*this, &literalExpr, 1),
4775 &literalType);
4776 if (Result.isInvalid())
4777 return ExprError();
4778 literalExpr = Result.get();
4780 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4781 if (isFileScope) { // 6.5.2.5p3
4782 if (CheckForConstantInitializer(literalExpr, literalType))
4783 return ExprError();
4786 // In C, compound literals are l-values for some reason.
4787 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4789 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4790 VK, literalExpr, isFileScope));
4793 ExprResult
4794 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
4795 SourceLocation RBraceLoc) {
4796 unsigned NumInit = initlist.size();
4797 Expr **InitList = initlist.release();
4799 // Semantic analysis for initializers is done by ActOnDeclarator() and
4800 // CheckInitializer() - it requires knowledge of the object being intialized.
4802 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4803 NumInit, RBraceLoc);
4804 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4805 return Owned(E);
4808 /// Prepares for a scalar cast, performing all the necessary stages
4809 /// except the final cast and returning the kind required.
4810 static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4811 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4812 // Also, callers should have filtered out the invalid cases with
4813 // pointers. Everything else should be possible.
4815 QualType SrcTy = Src->getType();
4816 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
4817 return CK_NoOp;
4819 switch (SrcTy->getScalarTypeKind()) {
4820 case Type::STK_MemberPointer:
4821 llvm_unreachable("member pointer type in C");
4823 case Type::STK_Pointer:
4824 switch (DestTy->getScalarTypeKind()) {
4825 case Type::STK_Pointer:
4826 return DestTy->isObjCObjectPointerType() ?
4827 CK_AnyPointerToObjCPointerCast :
4828 CK_BitCast;
4829 case Type::STK_Bool:
4830 return CK_PointerToBoolean;
4831 case Type::STK_Integral:
4832 return CK_PointerToIntegral;
4833 case Type::STK_Floating:
4834 case Type::STK_FloatingComplex:
4835 case Type::STK_IntegralComplex:
4836 case Type::STK_MemberPointer:
4837 llvm_unreachable("illegal cast from pointer");
4839 break;
4841 case Type::STK_Bool: // casting from bool is like casting from an integer
4842 case Type::STK_Integral:
4843 switch (DestTy->getScalarTypeKind()) {
4844 case Type::STK_Pointer:
4845 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
4846 return CK_NullToPointer;
4847 return CK_IntegralToPointer;
4848 case Type::STK_Bool:
4849 return CK_IntegralToBoolean;
4850 case Type::STK_Integral:
4851 return CK_IntegralCast;
4852 case Type::STK_Floating:
4853 return CK_IntegralToFloating;
4854 case Type::STK_IntegralComplex:
4855 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4856 CK_IntegralCast);
4857 return CK_IntegralRealToComplex;
4858 case Type::STK_FloatingComplex:
4859 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4860 CK_IntegralToFloating);
4861 return CK_FloatingRealToComplex;
4862 case Type::STK_MemberPointer:
4863 llvm_unreachable("member pointer type in C");
4865 break;
4867 case Type::STK_Floating:
4868 switch (DestTy->getScalarTypeKind()) {
4869 case Type::STK_Floating:
4870 return CK_FloatingCast;
4871 case Type::STK_Bool:
4872 return CK_FloatingToBoolean;
4873 case Type::STK_Integral:
4874 return CK_FloatingToIntegral;
4875 case Type::STK_FloatingComplex:
4876 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4877 CK_FloatingCast);
4878 return CK_FloatingRealToComplex;
4879 case Type::STK_IntegralComplex:
4880 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4881 CK_FloatingToIntegral);
4882 return CK_IntegralRealToComplex;
4883 case Type::STK_Pointer:
4884 llvm_unreachable("valid float->pointer cast?");
4885 case Type::STK_MemberPointer:
4886 llvm_unreachable("member pointer type in C");
4888 break;
4890 case Type::STK_FloatingComplex:
4891 switch (DestTy->getScalarTypeKind()) {
4892 case Type::STK_FloatingComplex:
4893 return CK_FloatingComplexCast;
4894 case Type::STK_IntegralComplex:
4895 return CK_FloatingComplexToIntegralComplex;
4896 case Type::STK_Floating: {
4897 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
4898 if (S.Context.hasSameType(ET, DestTy))
4899 return CK_FloatingComplexToReal;
4900 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4901 return CK_FloatingCast;
4903 case Type::STK_Bool:
4904 return CK_FloatingComplexToBoolean;
4905 case Type::STK_Integral:
4906 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
4907 CK_FloatingComplexToReal);
4908 return CK_FloatingToIntegral;
4909 case Type::STK_Pointer:
4910 llvm_unreachable("valid complex float->pointer cast?");
4911 case Type::STK_MemberPointer:
4912 llvm_unreachable("member pointer type in C");
4914 break;
4916 case Type::STK_IntegralComplex:
4917 switch (DestTy->getScalarTypeKind()) {
4918 case Type::STK_FloatingComplex:
4919 return CK_IntegralComplexToFloatingComplex;
4920 case Type::STK_IntegralComplex:
4921 return CK_IntegralComplexCast;
4922 case Type::STK_Integral: {
4923 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
4924 if (S.Context.hasSameType(ET, DestTy))
4925 return CK_IntegralComplexToReal;
4926 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4927 return CK_IntegralCast;
4929 case Type::STK_Bool:
4930 return CK_IntegralComplexToBoolean;
4931 case Type::STK_Floating:
4932 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
4933 CK_IntegralComplexToReal);
4934 return CK_IntegralToFloating;
4935 case Type::STK_Pointer:
4936 llvm_unreachable("valid complex int->pointer cast?");
4937 case Type::STK_MemberPointer:
4938 llvm_unreachable("member pointer type in C");
4940 break;
4943 llvm_unreachable("Unhandled scalar cast");
4944 return CK_BitCast;
4947 /// CheckCastTypes - Check type constraints for casting between types.
4948 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4949 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4950 CXXCastPath &BasePath, bool FunctionalStyle) {
4951 if (getLangOptions().CPlusPlus)
4952 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4953 castExpr->getLocEnd()),
4954 castType, VK, castExpr, Kind, BasePath,
4955 FunctionalStyle);
4957 // We only support r-value casts in C.
4958 VK = VK_RValue;
4960 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4961 // type needs to be scalar.
4962 if (castType->isVoidType()) {
4963 // We don't necessarily do lvalue-to-rvalue conversions on this.
4964 IgnoredValueConversions(castExpr);
4966 // Cast to void allows any expr type.
4967 Kind = CK_ToVoid;
4968 return false;
4971 DefaultFunctionArrayLvalueConversion(castExpr);
4973 if (RequireCompleteType(TyR.getBegin(), castType,
4974 diag::err_typecheck_cast_to_incomplete))
4975 return true;
4977 if (!castType->isScalarType() && !castType->isVectorType()) {
4978 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
4979 (castType->isStructureType() || castType->isUnionType())) {
4980 // GCC struct/union extension: allow cast to self.
4981 // FIXME: Check that the cast destination type is complete.
4982 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4983 << castType << castExpr->getSourceRange();
4984 Kind = CK_NoOp;
4985 return false;
4988 if (castType->isUnionType()) {
4989 // GCC cast to union extension
4990 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
4991 RecordDecl::field_iterator Field, FieldEnd;
4992 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
4993 Field != FieldEnd; ++Field) {
4994 if (Context.hasSameUnqualifiedType(Field->getType(),
4995 castExpr->getType()) &&
4996 !Field->isUnnamedBitfield()) {
4997 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4998 << castExpr->getSourceRange();
4999 break;
5002 if (Field == FieldEnd)
5003 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
5004 << castExpr->getType() << castExpr->getSourceRange();
5005 Kind = CK_ToUnion;
5006 return false;
5009 // Reject any other conversions to non-scalar types.
5010 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
5011 << castType << castExpr->getSourceRange();
5014 // The type we're casting to is known to be a scalar or vector.
5016 // Require the operand to be a scalar or vector.
5017 if (!castExpr->getType()->isScalarType() &&
5018 !castExpr->getType()->isVectorType()) {
5019 return Diag(castExpr->getLocStart(),
5020 diag::err_typecheck_expect_scalar_operand)
5021 << castExpr->getType() << castExpr->getSourceRange();
5024 if (castType->isExtVectorType())
5025 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
5027 if (castType->isVectorType())
5028 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
5029 if (castExpr->getType()->isVectorType())
5030 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
5032 // The source and target types are both scalars, i.e.
5033 // - arithmetic types (fundamental, enum, and complex)
5034 // - all kinds of pointers
5035 // Note that member pointers were filtered out with C++, above.
5037 if (isa<ObjCSelectorExpr>(castExpr))
5038 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
5040 // If either type is a pointer, the other type has to be either an
5041 // integer or a pointer.
5042 if (!castType->isArithmeticType()) {
5043 QualType castExprType = castExpr->getType();
5044 if (!castExprType->isIntegralType(Context) &&
5045 castExprType->isArithmeticType())
5046 return Diag(castExpr->getLocStart(),
5047 diag::err_cast_pointer_from_non_pointer_int)
5048 << castExprType << castExpr->getSourceRange();
5049 } else if (!castExpr->getType()->isArithmeticType()) {
5050 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
5051 return Diag(castExpr->getLocStart(),
5052 diag::err_cast_pointer_to_non_pointer_int)
5053 << castType << castExpr->getSourceRange();
5056 Kind = PrepareScalarCast(*this, castExpr, castType);
5058 if (Kind == CK_BitCast)
5059 CheckCastAlign(castExpr, castType, TyR);
5061 return false;
5064 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5065 CastKind &Kind) {
5066 assert(VectorTy->isVectorType() && "Not a vector type!");
5068 if (Ty->isVectorType() || Ty->isIntegerType()) {
5069 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
5070 return Diag(R.getBegin(),
5071 Ty->isVectorType() ?
5072 diag::err_invalid_conversion_between_vectors :
5073 diag::err_invalid_conversion_between_vector_and_integer)
5074 << VectorTy << Ty << R;
5075 } else
5076 return Diag(R.getBegin(),
5077 diag::err_invalid_conversion_between_vector_and_scalar)
5078 << VectorTy << Ty << R;
5080 Kind = CK_BitCast;
5081 return false;
5084 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
5085 CastKind &Kind) {
5086 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5088 QualType SrcTy = CastExpr->getType();
5090 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5091 // an ExtVectorType.
5092 if (SrcTy->isVectorType()) {
5093 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5094 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5095 << DestTy << SrcTy << R;
5096 Kind = CK_BitCast;
5097 return false;
5100 // All non-pointer scalars can be cast to ExtVector type. The appropriate
5101 // conversion will take place first from scalar to elt type, and then
5102 // splat from elt type to vector.
5103 if (SrcTy->isPointerType())
5104 return Diag(R.getBegin(),
5105 diag::err_invalid_conversion_between_vector_and_scalar)
5106 << DestTy << SrcTy << R;
5108 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5109 ImpCastExprToType(CastExpr, DestElemTy,
5110 PrepareScalarCast(*this, CastExpr, DestElemTy));
5112 Kind = CK_VectorSplat;
5113 return false;
5116 ExprResult
5117 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
5118 SourceLocation RParenLoc, Expr *castExpr) {
5119 assert((Ty != 0) && (castExpr != 0) &&
5120 "ActOnCastExpr(): missing type or expr");
5122 TypeSourceInfo *castTInfo;
5123 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5124 if (!castTInfo)
5125 castTInfo = Context.getTrivialTypeSourceInfo(castType);
5127 // If the Expr being casted is a ParenListExpr, handle it specially.
5128 if (isa<ParenListExpr>(castExpr))
5129 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
5130 castTInfo);
5132 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
5135 ExprResult
5136 Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
5137 SourceLocation RParenLoc, Expr *castExpr) {
5138 CastKind Kind = CK_Invalid;
5139 ExprValueKind VK = VK_RValue;
5140 CXXCastPath BasePath;
5141 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5142 Kind, VK, BasePath))
5143 return ExprError();
5145 return Owned(CStyleCastExpr::Create(Context,
5146 Ty->getType().getNonLValueExprType(Context),
5147 VK, Kind, castExpr, &BasePath, Ty,
5148 LParenLoc, RParenLoc));
5151 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5152 /// of comma binary operators.
5153 ExprResult
5154 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
5155 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5156 if (!E)
5157 return Owned(expr);
5159 ExprResult Result(E->getExpr(0));
5161 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5162 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5163 E->getExpr(i));
5165 if (Result.isInvalid()) return ExprError();
5167 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5170 ExprResult
5171 Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
5172 SourceLocation RParenLoc, Expr *Op,
5173 TypeSourceInfo *TInfo) {
5174 ParenListExpr *PE = cast<ParenListExpr>(Op);
5175 QualType Ty = TInfo->getType();
5176 bool isAltiVecLiteral = false;
5178 // Check for an altivec literal,
5179 // i.e. all the elements are integer constants.
5180 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5181 if (PE->getNumExprs() == 0) {
5182 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5183 return ExprError();
5185 if (PE->getNumExprs() == 1) {
5186 if (!PE->getExpr(0)->getType()->isVectorType())
5187 isAltiVecLiteral = true;
5189 else
5190 isAltiVecLiteral = true;
5193 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5194 // then handle it as such.
5195 if (isAltiVecLiteral) {
5196 llvm::SmallVector<Expr *, 8> initExprs;
5197 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5198 initExprs.push_back(PE->getExpr(i));
5200 // FIXME: This means that pretty-printing the final AST will produce curly
5201 // braces instead of the original commas.
5202 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5203 &initExprs[0],
5204 initExprs.size(), RParenLoc);
5205 E->setType(Ty);
5206 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
5207 } else {
5208 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5209 // sequence of BinOp comma operators.
5210 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
5211 if (Result.isInvalid()) return ExprError();
5212 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
5216 ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
5217 SourceLocation R,
5218 MultiExprArg Val,
5219 ParsedType TypeOfCast) {
5220 unsigned nexprs = Val.size();
5221 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
5222 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5223 Expr *expr;
5224 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5225 expr = new (Context) ParenExpr(L, R, exprs[0]);
5226 else
5227 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
5228 return Owned(expr);
5231 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5232 /// In that case, lhs = cond.
5233 /// C99 6.5.15
5234 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
5235 ExprValueKind &VK, ExprObjectKind &OK,
5236 SourceLocation QuestionLoc) {
5237 // If both LHS and RHS are overloaded functions, try to resolve them.
5238 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5239 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5240 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5241 if (LHSResult.isInvalid())
5242 return QualType();
5244 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5245 if (RHSResult.isInvalid())
5246 return QualType();
5248 LHS = LHSResult.take();
5249 RHS = RHSResult.take();
5252 // C++ is sufficiently different to merit its own checker.
5253 if (getLangOptions().CPlusPlus)
5254 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5256 VK = VK_RValue;
5257 OK = OK_Ordinary;
5259 UsualUnaryConversions(Cond);
5260 UsualUnaryConversions(LHS);
5261 UsualUnaryConversions(RHS);
5262 QualType CondTy = Cond->getType();
5263 QualType LHSTy = LHS->getType();
5264 QualType RHSTy = RHS->getType();
5266 // first, check the condition.
5267 if (!CondTy->isScalarType()) { // C99 6.5.15p2
5268 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5269 // Throw an error if its not either.
5270 if (getLangOptions().OpenCL) {
5271 if (!CondTy->isVectorType()) {
5272 Diag(Cond->getLocStart(),
5273 diag::err_typecheck_cond_expect_scalar_or_vector)
5274 << CondTy;
5275 return QualType();
5278 else {
5279 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5280 << CondTy;
5281 return QualType();
5285 // Now check the two expressions.
5286 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5287 return CheckVectorOperands(QuestionLoc, LHS, RHS);
5289 // OpenCL: If the condition is a vector, and both operands are scalar,
5290 // attempt to implicity convert them to the vector type to act like the
5291 // built in select.
5292 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5293 // Both operands should be of scalar type.
5294 if (!LHSTy->isScalarType()) {
5295 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5296 << CondTy;
5297 return QualType();
5299 if (!RHSTy->isScalarType()) {
5300 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5301 << CondTy;
5302 return QualType();
5304 // Implicity convert these scalars to the type of the condition.
5305 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5306 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5309 // If both operands have arithmetic type, do the usual arithmetic conversions
5310 // to find a common type: C99 6.5.15p3,5.
5311 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5312 UsualArithmeticConversions(LHS, RHS);
5313 return LHS->getType();
5316 // If both operands are the same structure or union type, the result is that
5317 // type.
5318 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5319 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5320 if (LHSRT->getDecl() == RHSRT->getDecl())
5321 // "If both the operands have structure or union type, the result has
5322 // that type." This implies that CV qualifiers are dropped.
5323 return LHSTy.getUnqualifiedType();
5324 // FIXME: Type of conditional expression must be complete in C mode.
5327 // C99 6.5.15p5: "If both operands have void type, the result has void type."
5328 // The following || allows only one side to be void (a GCC-ism).
5329 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5330 if (!LHSTy->isVoidType())
5331 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5332 << RHS->getSourceRange();
5333 if (!RHSTy->isVoidType())
5334 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5335 << LHS->getSourceRange();
5336 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5337 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
5338 return Context.VoidTy;
5340 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5341 // the type of the other operand."
5342 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
5343 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5344 // promote the null to a pointer.
5345 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
5346 return LHSTy;
5348 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
5349 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5350 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
5351 return RHSTy;
5354 // All objective-c pointer type analysis is done here.
5355 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5356 QuestionLoc);
5357 if (!compositeType.isNull())
5358 return compositeType;
5361 // Handle block pointer types.
5362 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5363 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5364 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5365 QualType destType = Context.getPointerType(Context.VoidTy);
5366 ImpCastExprToType(LHS, destType, CK_BitCast);
5367 ImpCastExprToType(RHS, destType, CK_BitCast);
5368 return destType;
5370 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5371 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5372 return QualType();
5374 // We have 2 block pointer types.
5375 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5376 // Two identical block pointer types are always compatible.
5377 return LHSTy;
5379 // The block pointer types aren't identical, continue checking.
5380 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5381 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
5383 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5384 rhptee.getUnqualifiedType())) {
5385 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5386 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5387 // In this situation, we assume void* type. No especially good
5388 // reason, but this is what gcc does, and we do have to pick
5389 // to get a consistent AST.
5390 QualType incompatTy = Context.getPointerType(Context.VoidTy);
5391 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5392 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5393 return incompatTy;
5395 // The block pointer types are compatible.
5396 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5397 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5398 return LHSTy;
5401 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5402 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5403 // get the "pointed to" types
5404 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5405 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5407 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5408 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5409 // Figure out necessary qualifiers (C99 6.5.15p6)
5410 QualType destPointee
5411 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5412 QualType destType = Context.getPointerType(destPointee);
5413 // Add qualifiers if necessary.
5414 ImpCastExprToType(LHS, destType, CK_NoOp);
5415 // Promote to void*.
5416 ImpCastExprToType(RHS, destType, CK_BitCast);
5417 return destType;
5419 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5420 QualType destPointee
5421 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5422 QualType destType = Context.getPointerType(destPointee);
5423 // Add qualifiers if necessary.
5424 ImpCastExprToType(RHS, destType, CK_NoOp);
5425 // Promote to void*.
5426 ImpCastExprToType(LHS, destType, CK_BitCast);
5427 return destType;
5430 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5431 // Two identical pointer types are always compatible.
5432 return LHSTy;
5434 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5435 rhptee.getUnqualifiedType())) {
5436 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5437 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5438 // In this situation, we assume void* type. No especially good
5439 // reason, but this is what gcc does, and we do have to pick
5440 // to get a consistent AST.
5441 QualType incompatTy = Context.getPointerType(Context.VoidTy);
5442 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5443 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5444 return incompatTy;
5446 // The pointer types are compatible.
5447 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5448 // differently qualified versions of compatible types, the result type is
5449 // a pointer to an appropriately qualified version of the *composite*
5450 // type.
5451 // FIXME: Need to calculate the composite type.
5452 // FIXME: Need to add qualifiers
5453 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5454 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5455 return LHSTy;
5458 // GCC compatibility: soften pointer/integer mismatch. Note that
5459 // null pointers have been filtered out by this point.
5460 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5461 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5462 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5463 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
5464 return RHSTy;
5466 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5467 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5468 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5469 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
5470 return LHSTy;
5473 // Otherwise, the operands are not compatible.
5474 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5475 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5476 return QualType();
5479 /// FindCompositeObjCPointerType - Helper method to find composite type of
5480 /// two objective-c pointer types of the two input expressions.
5481 QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5482 SourceLocation QuestionLoc) {
5483 QualType LHSTy = LHS->getType();
5484 QualType RHSTy = RHS->getType();
5486 // Handle things like Class and struct objc_class*. Here we case the result
5487 // to the pseudo-builtin, because that will be implicitly cast back to the
5488 // redefinition type if an attempt is made to access its fields.
5489 if (LHSTy->isObjCClassType() &&
5490 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
5491 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5492 return LHSTy;
5494 if (RHSTy->isObjCClassType() &&
5495 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
5496 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5497 return RHSTy;
5499 // And the same for struct objc_object* / id
5500 if (LHSTy->isObjCIdType() &&
5501 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
5502 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5503 return LHSTy;
5505 if (RHSTy->isObjCIdType() &&
5506 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
5507 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5508 return RHSTy;
5510 // And the same for struct objc_selector* / SEL
5511 if (Context.isObjCSelType(LHSTy) &&
5512 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
5513 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5514 return LHSTy;
5516 if (Context.isObjCSelType(RHSTy) &&
5517 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
5518 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5519 return RHSTy;
5521 // Check constraints for Objective-C object pointers types.
5522 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5524 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5525 // Two identical object pointer types are always compatible.
5526 return LHSTy;
5528 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5529 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5530 QualType compositeType = LHSTy;
5532 // If both operands are interfaces and either operand can be
5533 // assigned to the other, use that type as the composite
5534 // type. This allows
5535 // xxx ? (A*) a : (B*) b
5536 // where B is a subclass of A.
5538 // Additionally, as for assignment, if either type is 'id'
5539 // allow silent coercion. Finally, if the types are
5540 // incompatible then make sure to use 'id' as the composite
5541 // type so the result is acceptable for sending messages to.
5543 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5544 // It could return the composite type.
5545 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5546 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5547 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5548 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5549 } else if ((LHSTy->isObjCQualifiedIdType() ||
5550 RHSTy->isObjCQualifiedIdType()) &&
5551 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5552 // Need to handle "id<xx>" explicitly.
5553 // GCC allows qualified id and any Objective-C type to devolve to
5554 // id. Currently localizing to here until clear this should be
5555 // part of ObjCQualifiedIdTypesAreCompatible.
5556 compositeType = Context.getObjCIdType();
5557 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5558 compositeType = Context.getObjCIdType();
5559 } else if (!(compositeType =
5560 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5562 else {
5563 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5564 << LHSTy << RHSTy
5565 << LHS->getSourceRange() << RHS->getSourceRange();
5566 QualType incompatTy = Context.getObjCIdType();
5567 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5568 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5569 return incompatTy;
5571 // The object pointer types are compatible.
5572 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5573 ImpCastExprToType(RHS, compositeType, CK_BitCast);
5574 return compositeType;
5576 // Check Objective-C object pointer types and 'void *'
5577 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5578 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5579 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5580 QualType destPointee
5581 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5582 QualType destType = Context.getPointerType(destPointee);
5583 // Add qualifiers if necessary.
5584 ImpCastExprToType(LHS, destType, CK_NoOp);
5585 // Promote to void*.
5586 ImpCastExprToType(RHS, destType, CK_BitCast);
5587 return destType;
5589 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5590 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5591 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5592 QualType destPointee
5593 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5594 QualType destType = Context.getPointerType(destPointee);
5595 // Add qualifiers if necessary.
5596 ImpCastExprToType(RHS, destType, CK_NoOp);
5597 // Promote to void*.
5598 ImpCastExprToType(LHS, destType, CK_BitCast);
5599 return destType;
5601 return QualType();
5604 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5605 /// in the case of a the GNU conditional expr extension.
5606 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5607 SourceLocation ColonLoc,
5608 Expr *CondExpr, Expr *LHSExpr,
5609 Expr *RHSExpr) {
5610 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5611 // was the condition.
5612 OpaqueValueExpr *opaqueValue = 0;
5613 Expr *commonExpr = 0;
5614 if (LHSExpr == 0) {
5615 commonExpr = CondExpr;
5617 // We usually want to apply unary conversions *before* saving, except
5618 // in the special case of a C++ l-value conditional.
5619 if (!(getLangOptions().CPlusPlus
5620 && !commonExpr->isTypeDependent()
5621 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5622 && commonExpr->isGLValue()
5623 && commonExpr->isOrdinaryOrBitFieldObject()
5624 && RHSExpr->isOrdinaryOrBitFieldObject()
5625 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5626 UsualUnaryConversions(commonExpr);
5629 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5630 commonExpr->getType(),
5631 commonExpr->getValueKind(),
5632 commonExpr->getObjectKind());
5633 LHSExpr = CondExpr = opaqueValue;
5636 ExprValueKind VK = VK_RValue;
5637 ExprObjectKind OK = OK_Ordinary;
5638 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
5639 VK, OK, QuestionLoc);
5640 if (result.isNull())
5641 return ExprError();
5643 if (!commonExpr)
5644 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5645 LHSExpr, ColonLoc,
5646 RHSExpr, result, VK, OK));
5648 return Owned(new (Context)
5649 BinaryConditionalOperator(commonExpr, opaqueValue, CondExpr, LHSExpr,
5650 RHSExpr, QuestionLoc, ColonLoc, result, VK, OK));
5653 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5654 // being closely modeled after the C99 spec:-). The odd characteristic of this
5655 // routine is it effectively iqnores the qualifiers on the top level pointee.
5656 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5657 // FIXME: add a couple examples in this comment.
5658 static Sema::AssignConvertType
5659 checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5660 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5661 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5663 // get the "pointed to" type (ignoring qualifiers at the top level)
5664 const Type *lhptee, *rhptee;
5665 Qualifiers lhq, rhq;
5666 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5667 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
5669 Sema::AssignConvertType ConvTy = Sema::Compatible;
5671 // C99 6.5.16.1p1: This following citation is common to constraints
5672 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5673 // qualifiers of the type *pointed to* by the right;
5674 Qualifiers lq;
5676 if (!lhq.compatiblyIncludes(rhq)) {
5677 // Treat address-space mismatches as fatal. TODO: address subspaces
5678 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5679 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5681 // For GCC compatibility, other qualifier mismatches are treated
5682 // as still compatible in C.
5683 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5686 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5687 // incomplete type and the other is a pointer to a qualified or unqualified
5688 // version of void...
5689 if (lhptee->isVoidType()) {
5690 if (rhptee->isIncompleteOrObjectType())
5691 return ConvTy;
5693 // As an extension, we allow cast to/from void* to function pointer.
5694 assert(rhptee->isFunctionType());
5695 return Sema::FunctionVoidPointer;
5698 if (rhptee->isVoidType()) {
5699 if (lhptee->isIncompleteOrObjectType())
5700 return ConvTy;
5702 // As an extension, we allow cast to/from void* to function pointer.
5703 assert(lhptee->isFunctionType());
5704 return Sema::FunctionVoidPointer;
5707 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5708 // unqualified versions of compatible types, ...
5709 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5710 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5711 // Check if the pointee types are compatible ignoring the sign.
5712 // We explicitly check for char so that we catch "char" vs
5713 // "unsigned char" on systems where "char" is unsigned.
5714 if (lhptee->isCharType())
5715 ltrans = S.Context.UnsignedCharTy;
5716 else if (lhptee->hasSignedIntegerRepresentation())
5717 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5719 if (rhptee->isCharType())
5720 rtrans = S.Context.UnsignedCharTy;
5721 else if (rhptee->hasSignedIntegerRepresentation())
5722 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5724 if (ltrans == rtrans) {
5725 // Types are compatible ignoring the sign. Qualifier incompatibility
5726 // takes priority over sign incompatibility because the sign
5727 // warning can be disabled.
5728 if (ConvTy != Sema::Compatible)
5729 return ConvTy;
5731 return Sema::IncompatiblePointerSign;
5734 // If we are a multi-level pointer, it's possible that our issue is simply
5735 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5736 // the eventual target type is the same and the pointers have the same
5737 // level of indirection, this must be the issue.
5738 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5739 do {
5740 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5741 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5742 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5744 if (lhptee == rhptee)
5745 return Sema::IncompatibleNestedPointerQualifiers;
5748 // General pointer incompatibility takes priority over qualifiers.
5749 return Sema::IncompatiblePointer;
5751 return ConvTy;
5754 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5755 /// block pointer types are compatible or whether a block and normal pointer
5756 /// are compatible. It is more restrict than comparing two function pointer
5757 // types.
5758 static Sema::AssignConvertType
5759 checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5760 QualType rhsType) {
5761 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5762 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5764 QualType lhptee, rhptee;
5766 // get the "pointed to" type (ignoring qualifiers at the top level)
5767 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5768 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
5770 // In C++, the types have to match exactly.
5771 if (S.getLangOptions().CPlusPlus)
5772 return Sema::IncompatibleBlockPointer;
5774 Sema::AssignConvertType ConvTy = Sema::Compatible;
5776 // For blocks we enforce that qualifiers are identical.
5777 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5778 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5780 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5781 return Sema::IncompatibleBlockPointer;
5783 return ConvTy;
5786 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5787 /// for assignment compatibility.
5788 static Sema::AssignConvertType
5789 checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5790 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5791 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5793 if (lhsType->isObjCBuiltinType()) {
5794 // Class is not compatible with ObjC object pointers.
5795 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5796 !rhsType->isObjCQualifiedClassType())
5797 return Sema::IncompatiblePointer;
5798 return Sema::Compatible;
5800 if (rhsType->isObjCBuiltinType()) {
5801 // Class is not compatible with ObjC object pointers.
5802 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5803 !lhsType->isObjCQualifiedClassType())
5804 return Sema::IncompatiblePointer;
5805 return Sema::Compatible;
5807 QualType lhptee =
5808 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5809 QualType rhptee =
5810 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5812 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5813 return Sema::CompatiblePointerDiscardsQualifiers;
5815 if (S.Context.typesAreCompatible(lhsType, rhsType))
5816 return Sema::Compatible;
5817 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5818 return Sema::IncompatibleObjCQualifiedId;
5819 return Sema::IncompatiblePointer;
5822 Sema::AssignConvertType
5823 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5824 QualType lhsType, QualType rhsType) {
5825 // Fake up an opaque expression. We don't actually care about what
5826 // cast operations are required, so if CheckAssignmentConstraints
5827 // adds casts to this they'll be wasted, but fortunately that doesn't
5828 // usually happen on valid code.
5829 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
5830 Expr *rhsPtr = &rhs;
5831 CastKind K = CK_Invalid;
5833 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5836 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5837 /// has code to accommodate several GCC extensions when type checking
5838 /// pointers. Here are some objectionable examples that GCC considers warnings:
5840 /// int a, *pint;
5841 /// short *pshort;
5842 /// struct foo *pfoo;
5844 /// pint = pshort; // warning: assignment from incompatible pointer type
5845 /// a = pint; // warning: assignment makes integer from pointer without a cast
5846 /// pint = a; // warning: assignment makes pointer from integer without a cast
5847 /// pint = pfoo; // warning: assignment from incompatible pointer type
5849 /// As a result, the code for dealing with pointers is more complex than the
5850 /// C99 spec dictates.
5852 /// Sets 'Kind' for any result kind except Incompatible.
5853 Sema::AssignConvertType
5854 Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
5855 CastKind &Kind) {
5856 QualType rhsType = rhs->getType();
5858 // Get canonical types. We're not formatting these types, just comparing
5859 // them.
5860 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5861 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
5863 // Common case: no conversion required.
5864 if (lhsType == rhsType) {
5865 Kind = CK_NoOp;
5866 return Compatible;
5869 // If the left-hand side is a reference type, then we are in a
5870 // (rare!) case where we've allowed the use of references in C,
5871 // e.g., as a parameter type in a built-in function. In this case,
5872 // just make sure that the type referenced is compatible with the
5873 // right-hand side type. The caller is responsible for adjusting
5874 // lhsType so that the resulting expression does not have reference
5875 // type.
5876 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
5877 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5878 Kind = CK_LValueBitCast;
5879 return Compatible;
5881 return Incompatible;
5884 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5885 // to the same ExtVector type.
5886 if (lhsType->isExtVectorType()) {
5887 if (rhsType->isExtVectorType())
5888 return Incompatible;
5889 if (rhsType->isArithmeticType()) {
5890 // CK_VectorSplat does T -> vector T, so first cast to the
5891 // element type.
5892 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5893 if (elType != rhsType) {
5894 Kind = PrepareScalarCast(*this, rhs, elType);
5895 ImpCastExprToType(rhs, elType, Kind);
5897 Kind = CK_VectorSplat;
5898 return Compatible;
5902 // Conversions to or from vector type.
5903 if (lhsType->isVectorType() || rhsType->isVectorType()) {
5904 if (lhsType->isVectorType() && rhsType->isVectorType()) {
5905 // Allow assignments of an AltiVec vector type to an equivalent GCC
5906 // vector type and vice versa
5907 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5908 Kind = CK_BitCast;
5909 return Compatible;
5912 // If we are allowing lax vector conversions, and LHS and RHS are both
5913 // vectors, the total size only needs to be the same. This is a bitcast;
5914 // no bits are changed but the result type is different.
5915 if (getLangOptions().LaxVectorConversions &&
5916 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
5917 Kind = CK_BitCast;
5918 return IncompatibleVectors;
5921 return Incompatible;
5924 // Arithmetic conversions.
5925 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
5926 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
5927 Kind = PrepareScalarCast(*this, rhs, lhsType);
5928 return Compatible;
5931 // Conversions to normal pointers.
5932 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5933 // U* -> T*
5934 if (isa<PointerType>(rhsType)) {
5935 Kind = CK_BitCast;
5936 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
5939 // int -> T*
5940 if (rhsType->isIntegerType()) {
5941 Kind = CK_IntegralToPointer; // FIXME: null?
5942 return IntToPointer;
5945 // C pointers are not compatible with ObjC object pointers,
5946 // with two exceptions:
5947 if (isa<ObjCObjectPointerType>(rhsType)) {
5948 // - conversions to void*
5949 if (lhsPointer->getPointeeType()->isVoidType()) {
5950 Kind = CK_AnyPointerToObjCPointerCast;
5951 return Compatible;
5954 // - conversions from 'Class' to the redefinition type
5955 if (rhsType->isObjCClassType() &&
5956 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
5957 Kind = CK_BitCast;
5958 return Compatible;
5961 Kind = CK_BitCast;
5962 return IncompatiblePointer;
5965 // U^ -> void*
5966 if (rhsType->getAs<BlockPointerType>()) {
5967 if (lhsPointer->getPointeeType()->isVoidType()) {
5968 Kind = CK_BitCast;
5969 return Compatible;
5973 return Incompatible;
5976 // Conversions to block pointers.
5977 if (isa<BlockPointerType>(lhsType)) {
5978 // U^ -> T^
5979 if (rhsType->isBlockPointerType()) {
5980 Kind = CK_AnyPointerToBlockPointerCast;
5981 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
5984 // int or null -> T^
5985 if (rhsType->isIntegerType()) {
5986 Kind = CK_IntegralToPointer; // FIXME: null
5987 return IntToBlockPointer;
5990 // id -> T^
5991 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5992 Kind = CK_AnyPointerToBlockPointerCast;
5993 return Compatible;
5996 // void* -> T^
5997 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
5998 if (RHSPT->getPointeeType()->isVoidType()) {
5999 Kind = CK_AnyPointerToBlockPointerCast;
6000 return Compatible;
6003 return Incompatible;
6006 // Conversions to Objective-C pointers.
6007 if (isa<ObjCObjectPointerType>(lhsType)) {
6008 // A* -> B*
6009 if (rhsType->isObjCObjectPointerType()) {
6010 Kind = CK_BitCast;
6011 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
6014 // int or null -> A*
6015 if (rhsType->isIntegerType()) {
6016 Kind = CK_IntegralToPointer; // FIXME: null
6017 return IntToPointer;
6020 // In general, C pointers are not compatible with ObjC object pointers,
6021 // with two exceptions:
6022 if (isa<PointerType>(rhsType)) {
6023 // - conversions from 'void*'
6024 if (rhsType->isVoidPointerType()) {
6025 Kind = CK_AnyPointerToObjCPointerCast;
6026 return Compatible;
6029 // - conversions to 'Class' from its redefinition type
6030 if (lhsType->isObjCClassType() &&
6031 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
6032 Kind = CK_BitCast;
6033 return Compatible;
6036 Kind = CK_AnyPointerToObjCPointerCast;
6037 return IncompatiblePointer;
6040 // T^ -> A*
6041 if (rhsType->isBlockPointerType()) {
6042 Kind = CK_AnyPointerToObjCPointerCast;
6043 return Compatible;
6046 return Incompatible;
6049 // Conversions from pointers that are not covered by the above.
6050 if (isa<PointerType>(rhsType)) {
6051 // T* -> _Bool
6052 if (lhsType == Context.BoolTy) {
6053 Kind = CK_PointerToBoolean;
6054 return Compatible;
6057 // T* -> int
6058 if (lhsType->isIntegerType()) {
6059 Kind = CK_PointerToIntegral;
6060 return PointerToInt;
6063 return Incompatible;
6066 // Conversions from Objective-C pointers that are not covered by the above.
6067 if (isa<ObjCObjectPointerType>(rhsType)) {
6068 // T* -> _Bool
6069 if (lhsType == Context.BoolTy) {
6070 Kind = CK_PointerToBoolean;
6071 return Compatible;
6074 // T* -> int
6075 if (lhsType->isIntegerType()) {
6076 Kind = CK_PointerToIntegral;
6077 return PointerToInt;
6080 return Incompatible;
6083 // struct A -> struct B
6084 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
6085 if (Context.typesAreCompatible(lhsType, rhsType)) {
6086 Kind = CK_NoOp;
6087 return Compatible;
6091 return Incompatible;
6094 /// \brief Constructs a transparent union from an expression that is
6095 /// used to initialize the transparent union.
6096 static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
6097 QualType UnionType, FieldDecl *Field) {
6098 // Build an initializer list that designates the appropriate member
6099 // of the transparent union.
6100 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6101 &E, 1,
6102 SourceLocation());
6103 Initializer->setType(UnionType);
6104 Initializer->setInitializedFieldInUnion(Field);
6106 // Build a compound literal constructing a value of the transparent
6107 // union type from this initializer list.
6108 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6109 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6110 VK_RValue, Initializer, false);
6113 Sema::AssignConvertType
6114 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6115 QualType FromType = rExpr->getType();
6117 // If the ArgType is a Union type, we want to handle a potential
6118 // transparent_union GCC extension.
6119 const RecordType *UT = ArgType->getAsUnionType();
6120 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6121 return Incompatible;
6123 // The field to initialize within the transparent union.
6124 RecordDecl *UD = UT->getDecl();
6125 FieldDecl *InitField = 0;
6126 // It's compatible if the expression matches any of the fields.
6127 for (RecordDecl::field_iterator it = UD->field_begin(),
6128 itend = UD->field_end();
6129 it != itend; ++it) {
6130 if (it->getType()->isPointerType()) {
6131 // If the transparent union contains a pointer type, we allow:
6132 // 1) void pointer
6133 // 2) null pointer constant
6134 if (FromType->isPointerType())
6135 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
6136 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
6137 InitField = *it;
6138 break;
6141 if (rExpr->isNullPointerConstant(Context,
6142 Expr::NPC_ValueDependentIsNull)) {
6143 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
6144 InitField = *it;
6145 break;
6149 Expr *rhs = rExpr;
6150 CastKind Kind = CK_Invalid;
6151 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
6152 == Compatible) {
6153 ImpCastExprToType(rhs, it->getType(), Kind);
6154 rExpr = rhs;
6155 InitField = *it;
6156 break;
6160 if (!InitField)
6161 return Incompatible;
6163 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6164 return Compatible;
6167 Sema::AssignConvertType
6168 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
6169 if (getLangOptions().CPlusPlus) {
6170 if (!lhsType->isRecordType()) {
6171 // C++ 5.17p3: If the left operand is not of class type, the
6172 // expression is implicitly converted (C++ 4) to the
6173 // cv-unqualified type of the left operand.
6174 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
6175 AA_Assigning))
6176 return Incompatible;
6177 return Compatible;
6180 // FIXME: Currently, we fall through and treat C++ classes like C
6181 // structures.
6184 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6185 // a null pointer constant.
6186 if ((lhsType->isPointerType() ||
6187 lhsType->isObjCObjectPointerType() ||
6188 lhsType->isBlockPointerType())
6189 && rExpr->isNullPointerConstant(Context,
6190 Expr::NPC_ValueDependentIsNull)) {
6191 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
6192 return Compatible;
6195 // This check seems unnatural, however it is necessary to ensure the proper
6196 // conversion of functions/arrays. If the conversion were done for all
6197 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6198 // expressions that suppress this implicit conversion (&, sizeof).
6200 // Suppress this for references: C++ 8.5.3p5.
6201 if (!lhsType->isReferenceType())
6202 DefaultFunctionArrayLvalueConversion(rExpr);
6204 CastKind Kind = CK_Invalid;
6205 Sema::AssignConvertType result =
6206 CheckAssignmentConstraints(lhsType, rExpr, Kind);
6208 // C99 6.5.16.1p2: The value of the right operand is converted to the
6209 // type of the assignment expression.
6210 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6211 // so that we can use references in built-in functions even in C.
6212 // The getNonReferenceType() call makes sure that the resulting expression
6213 // does not have reference type.
6214 if (result != Incompatible && rExpr->getType() != lhsType)
6215 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
6216 return result;
6219 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
6220 Diag(Loc, diag::err_typecheck_invalid_operands)
6221 << lex->getType() << rex->getType()
6222 << lex->getSourceRange() << rex->getSourceRange();
6223 return QualType();
6226 QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
6227 // For conversion purposes, we ignore any qualifiers.
6228 // For example, "const float" and "float" are equivalent.
6229 QualType lhsType =
6230 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6231 QualType rhsType =
6232 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
6234 // If the vector types are identical, return.
6235 if (lhsType == rhsType)
6236 return lhsType;
6238 // Handle the case of a vector & extvector type of the same size and element
6239 // type. It would be nice if we only had one vector type someday.
6240 if (getLangOptions().LaxVectorConversions) {
6241 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
6242 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
6243 if (LV->getElementType() == RV->getElementType() &&
6244 LV->getNumElements() == RV->getNumElements()) {
6245 if (lhsType->isExtVectorType()) {
6246 ImpCastExprToType(rex, lhsType, CK_BitCast);
6247 return lhsType;
6250 ImpCastExprToType(lex, rhsType, CK_BitCast);
6251 return rhsType;
6252 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6253 // If we are allowing lax vector conversions, and LHS and RHS are both
6254 // vectors, the total size only needs to be the same. This is a
6255 // bitcast; no bits are changed but the result type is different.
6256 ImpCastExprToType(rex, lhsType, CK_BitCast);
6257 return lhsType;
6263 // Handle the case of equivalent AltiVec and GCC vector types
6264 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6265 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6266 ImpCastExprToType(lex, rhsType, CK_BitCast);
6267 return rhsType;
6270 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6271 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6272 bool swapped = false;
6273 if (rhsType->isExtVectorType()) {
6274 swapped = true;
6275 std::swap(rex, lex);
6276 std::swap(rhsType, lhsType);
6279 // Handle the case of an ext vector and scalar.
6280 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
6281 QualType EltTy = LV->getElementType();
6282 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
6283 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6284 if (order > 0)
6285 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6286 if (order >= 0) {
6287 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
6288 if (swapped) std::swap(rex, lex);
6289 return lhsType;
6292 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6293 rhsType->isRealFloatingType()) {
6294 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6295 if (order > 0)
6296 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6297 if (order >= 0) {
6298 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
6299 if (swapped) std::swap(rex, lex);
6300 return lhsType;
6305 // Vectors of different size or scalar and non-ext-vector are errors.
6306 Diag(Loc, diag::err_typecheck_vector_not_convertable)
6307 << lex->getType() << rex->getType()
6308 << lex->getSourceRange() << rex->getSourceRange();
6309 return QualType();
6312 QualType Sema::CheckMultiplyDivideOperands(
6313 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6314 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6315 return CheckVectorOperands(Loc, lex, rex);
6317 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6319 if (!lex->getType()->isArithmeticType() ||
6320 !rex->getType()->isArithmeticType())
6321 return InvalidOperands(Loc, lex, rex);
6323 // Check for division by zero.
6324 if (isDiv &&
6325 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6326 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
6327 << rex->getSourceRange());
6329 return compType;
6332 QualType Sema::CheckRemainderOperands(
6333 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
6334 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6335 if (lex->getType()->hasIntegerRepresentation() &&
6336 rex->getType()->hasIntegerRepresentation())
6337 return CheckVectorOperands(Loc, lex, rex);
6338 return InvalidOperands(Loc, lex, rex);
6341 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6343 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6344 return InvalidOperands(Loc, lex, rex);
6346 // Check for remainder by zero.
6347 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6348 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6349 << rex->getSourceRange());
6351 return compType;
6354 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6355 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
6356 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6357 QualType compType = CheckVectorOperands(Loc, lex, rex);
6358 if (CompLHSTy) *CompLHSTy = compType;
6359 return compType;
6362 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
6364 // handle the common case first (both operands are arithmetic).
6365 if (lex->getType()->isArithmeticType() &&
6366 rex->getType()->isArithmeticType()) {
6367 if (CompLHSTy) *CompLHSTy = compType;
6368 return compType;
6371 // Put any potential pointer into PExp
6372 Expr* PExp = lex, *IExp = rex;
6373 if (IExp->getType()->isAnyPointerType())
6374 std::swap(PExp, IExp);
6376 if (PExp->getType()->isAnyPointerType()) {
6378 if (IExp->getType()->isIntegerType()) {
6379 QualType PointeeTy = PExp->getType()->getPointeeType();
6381 // Check for arithmetic on pointers to incomplete types.
6382 if (PointeeTy->isVoidType()) {
6383 if (getLangOptions().CPlusPlus) {
6384 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6385 << lex->getSourceRange() << rex->getSourceRange();
6386 return QualType();
6389 // GNU extension: arithmetic on pointer to void
6390 Diag(Loc, diag::ext_gnu_void_ptr)
6391 << lex->getSourceRange() << rex->getSourceRange();
6392 } else if (PointeeTy->isFunctionType()) {
6393 if (getLangOptions().CPlusPlus) {
6394 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6395 << lex->getType() << lex->getSourceRange();
6396 return QualType();
6399 // GNU extension: arithmetic on pointer to function
6400 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6401 << lex->getType() << lex->getSourceRange();
6402 } else {
6403 // Check if we require a complete type.
6404 if (((PExp->getType()->isPointerType() &&
6405 !PExp->getType()->isDependentType()) ||
6406 PExp->getType()->isObjCObjectPointerType()) &&
6407 RequireCompleteType(Loc, PointeeTy,
6408 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6409 << PExp->getSourceRange()
6410 << PExp->getType()))
6411 return QualType();
6413 // Diagnose bad cases where we step over interface counts.
6414 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6415 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6416 << PointeeTy << PExp->getSourceRange();
6417 return QualType();
6420 if (CompLHSTy) {
6421 QualType LHSTy = Context.isPromotableBitField(lex);
6422 if (LHSTy.isNull()) {
6423 LHSTy = lex->getType();
6424 if (LHSTy->isPromotableIntegerType())
6425 LHSTy = Context.getPromotedIntegerType(LHSTy);
6427 *CompLHSTy = LHSTy;
6429 return PExp->getType();
6433 return InvalidOperands(Loc, lex, rex);
6436 // C99 6.5.6
6437 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
6438 SourceLocation Loc, QualType* CompLHSTy) {
6439 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6440 QualType compType = CheckVectorOperands(Loc, lex, rex);
6441 if (CompLHSTy) *CompLHSTy = compType;
6442 return compType;
6445 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
6447 // Enforce type constraints: C99 6.5.6p3.
6449 // Handle the common case first (both operands are arithmetic).
6450 if (lex->getType()->isArithmeticType()
6451 && rex->getType()->isArithmeticType()) {
6452 if (CompLHSTy) *CompLHSTy = compType;
6453 return compType;
6456 // Either ptr - int or ptr - ptr.
6457 if (lex->getType()->isAnyPointerType()) {
6458 QualType lpointee = lex->getType()->getPointeeType();
6460 // The LHS must be an completely-defined object type.
6462 bool ComplainAboutVoid = false;
6463 Expr *ComplainAboutFunc = 0;
6464 if (lpointee->isVoidType()) {
6465 if (getLangOptions().CPlusPlus) {
6466 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6467 << lex->getSourceRange() << rex->getSourceRange();
6468 return QualType();
6471 // GNU C extension: arithmetic on pointer to void
6472 ComplainAboutVoid = true;
6473 } else if (lpointee->isFunctionType()) {
6474 if (getLangOptions().CPlusPlus) {
6475 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6476 << lex->getType() << lex->getSourceRange();
6477 return QualType();
6480 // GNU C extension: arithmetic on pointer to function
6481 ComplainAboutFunc = lex;
6482 } else if (!lpointee->isDependentType() &&
6483 RequireCompleteType(Loc, lpointee,
6484 PDiag(diag::err_typecheck_sub_ptr_object)
6485 << lex->getSourceRange()
6486 << lex->getType()))
6487 return QualType();
6489 // Diagnose bad cases where we step over interface counts.
6490 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6491 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6492 << lpointee << lex->getSourceRange();
6493 return QualType();
6496 // The result type of a pointer-int computation is the pointer type.
6497 if (rex->getType()->isIntegerType()) {
6498 if (ComplainAboutVoid)
6499 Diag(Loc, diag::ext_gnu_void_ptr)
6500 << lex->getSourceRange() << rex->getSourceRange();
6501 if (ComplainAboutFunc)
6502 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6503 << ComplainAboutFunc->getType()
6504 << ComplainAboutFunc->getSourceRange();
6506 if (CompLHSTy) *CompLHSTy = lex->getType();
6507 return lex->getType();
6510 // Handle pointer-pointer subtractions.
6511 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
6512 QualType rpointee = RHSPTy->getPointeeType();
6514 // RHS must be a completely-type object type.
6515 // Handle the GNU void* extension.
6516 if (rpointee->isVoidType()) {
6517 if (getLangOptions().CPlusPlus) {
6518 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6519 << lex->getSourceRange() << rex->getSourceRange();
6520 return QualType();
6523 ComplainAboutVoid = true;
6524 } else if (rpointee->isFunctionType()) {
6525 if (getLangOptions().CPlusPlus) {
6526 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6527 << rex->getType() << rex->getSourceRange();
6528 return QualType();
6531 // GNU extension: arithmetic on pointer to function
6532 if (!ComplainAboutFunc)
6533 ComplainAboutFunc = rex;
6534 } else if (!rpointee->isDependentType() &&
6535 RequireCompleteType(Loc, rpointee,
6536 PDiag(diag::err_typecheck_sub_ptr_object)
6537 << rex->getSourceRange()
6538 << rex->getType()))
6539 return QualType();
6541 if (getLangOptions().CPlusPlus) {
6542 // Pointee types must be the same: C++ [expr.add]
6543 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6544 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6545 << lex->getType() << rex->getType()
6546 << lex->getSourceRange() << rex->getSourceRange();
6547 return QualType();
6549 } else {
6550 // Pointee types must be compatible C99 6.5.6p3
6551 if (!Context.typesAreCompatible(
6552 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6553 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6554 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6555 << lex->getType() << rex->getType()
6556 << lex->getSourceRange() << rex->getSourceRange();
6557 return QualType();
6561 if (ComplainAboutVoid)
6562 Diag(Loc, diag::ext_gnu_void_ptr)
6563 << lex->getSourceRange() << rex->getSourceRange();
6564 if (ComplainAboutFunc)
6565 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6566 << ComplainAboutFunc->getType()
6567 << ComplainAboutFunc->getSourceRange();
6569 if (CompLHSTy) *CompLHSTy = lex->getType();
6570 return Context.getPointerDiffType();
6574 return InvalidOperands(Loc, lex, rex);
6577 static bool isScopedEnumerationType(QualType T) {
6578 if (const EnumType *ET = dyn_cast<EnumType>(T))
6579 return ET->getDecl()->isScoped();
6580 return false;
6583 // C99 6.5.7
6584 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
6585 bool isCompAssign) {
6586 // C99 6.5.7p2: Each of the operands shall have integer type.
6587 if (!lex->getType()->hasIntegerRepresentation() ||
6588 !rex->getType()->hasIntegerRepresentation())
6589 return InvalidOperands(Loc, lex, rex);
6591 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6592 // hasIntegerRepresentation() above instead of this.
6593 if (isScopedEnumerationType(lex->getType()) ||
6594 isScopedEnumerationType(rex->getType())) {
6595 return InvalidOperands(Loc, lex, rex);
6598 // Vector shifts promote their scalar inputs to vector type.
6599 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6600 return CheckVectorOperands(Loc, lex, rex);
6602 // Shifts don't perform usual arithmetic conversions, they just do integer
6603 // promotions on each operand. C99 6.5.7p3
6605 // For the LHS, do usual unary conversions, but then reset them away
6606 // if this is a compound assignment.
6607 Expr *old_lex = lex;
6608 UsualUnaryConversions(lex);
6609 QualType LHSTy = lex->getType();
6610 if (isCompAssign) lex = old_lex;
6612 // The RHS is simpler.
6613 UsualUnaryConversions(rex);
6615 // Sanity-check shift operands
6616 llvm::APSInt Right;
6617 // Check right/shifter operand
6618 if (!rex->isValueDependent() &&
6619 rex->isIntegerConstantExpr(Right, Context)) {
6620 if (Right.isNegative())
6621 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6622 else {
6623 llvm::APInt LeftBits(Right.getBitWidth(),
6624 Context.getTypeSize(lex->getType()));
6625 if (Right.uge(LeftBits))
6626 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6630 // "The type of the result is that of the promoted left operand."
6631 return LHSTy;
6634 static bool IsWithinTemplateSpecialization(Decl *D) {
6635 if (DeclContext *DC = D->getDeclContext()) {
6636 if (isa<ClassTemplateSpecializationDecl>(DC))
6637 return true;
6638 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6639 return FD->isFunctionTemplateSpecialization();
6641 return false;
6644 // C99 6.5.8, C++ [expr.rel]
6645 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
6646 unsigned OpaqueOpc, bool isRelational) {
6647 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6649 // Handle vector comparisons separately.
6650 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6651 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
6653 QualType lType = lex->getType();
6654 QualType rType = rex->getType();
6656 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6657 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6658 QualType LHSStrippedType = LHSStripped->getType();
6659 QualType RHSStrippedType = RHSStripped->getType();
6661 // Two different enums will raise a warning when compared.
6662 if (const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>()) {
6663 if (const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>()) {
6664 if (LHSEnumType->getDecl()->getIdentifier() &&
6665 RHSEnumType->getDecl()->getIdentifier() &&
6666 !Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
6667 Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6668 << LHSStrippedType << RHSStrippedType
6669 << lex->getSourceRange() << rex->getSourceRange();
6674 if (!lType->hasFloatingRepresentation() &&
6675 !(lType->isBlockPointerType() && isRelational) &&
6676 !lex->getLocStart().isMacroID() &&
6677 !rex->getLocStart().isMacroID()) {
6678 // For non-floating point types, check for self-comparisons of the form
6679 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6680 // often indicate logic errors in the program.
6682 // NOTE: Don't warn about comparison expressions resulting from macro
6683 // expansion. Also don't warn about comparisons which are only self
6684 // comparisons within a template specialization. The warnings should catch
6685 // obvious cases in the definition of the template anyways. The idea is to
6686 // warn when the typed comparison operator will always evaluate to the same
6687 // result.
6688 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6689 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6690 if (DRL->getDecl() == DRR->getDecl() &&
6691 !IsWithinTemplateSpecialization(DRL->getDecl())) {
6692 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6693 << 0 // self-
6694 << (Opc == BO_EQ
6695 || Opc == BO_LE
6696 || Opc == BO_GE));
6697 } else if (lType->isArrayType() && rType->isArrayType() &&
6698 !DRL->getDecl()->getType()->isReferenceType() &&
6699 !DRR->getDecl()->getType()->isReferenceType()) {
6700 // what is it always going to eval to?
6701 char always_evals_to;
6702 switch(Opc) {
6703 case BO_EQ: // e.g. array1 == array2
6704 always_evals_to = 0; // false
6705 break;
6706 case BO_NE: // e.g. array1 != array2
6707 always_evals_to = 1; // true
6708 break;
6709 default:
6710 // best we can say is 'a constant'
6711 always_evals_to = 2; // e.g. array1 <= array2
6712 break;
6714 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6715 << 1 // array
6716 << always_evals_to);
6721 if (isa<CastExpr>(LHSStripped))
6722 LHSStripped = LHSStripped->IgnoreParenCasts();
6723 if (isa<CastExpr>(RHSStripped))
6724 RHSStripped = RHSStripped->IgnoreParenCasts();
6726 // Warn about comparisons against a string constant (unless the other
6727 // operand is null), the user probably wants strcmp.
6728 Expr *literalString = 0;
6729 Expr *literalStringStripped = 0;
6730 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6731 !RHSStripped->isNullPointerConstant(Context,
6732 Expr::NPC_ValueDependentIsNull)) {
6733 literalString = lex;
6734 literalStringStripped = LHSStripped;
6735 } else if ((isa<StringLiteral>(RHSStripped) ||
6736 isa<ObjCEncodeExpr>(RHSStripped)) &&
6737 !LHSStripped->isNullPointerConstant(Context,
6738 Expr::NPC_ValueDependentIsNull)) {
6739 literalString = rex;
6740 literalStringStripped = RHSStripped;
6743 if (literalString) {
6744 std::string resultComparison;
6745 switch (Opc) {
6746 case BO_LT: resultComparison = ") < 0"; break;
6747 case BO_GT: resultComparison = ") > 0"; break;
6748 case BO_LE: resultComparison = ") <= 0"; break;
6749 case BO_GE: resultComparison = ") >= 0"; break;
6750 case BO_EQ: resultComparison = ") == 0"; break;
6751 case BO_NE: resultComparison = ") != 0"; break;
6752 default: assert(false && "Invalid comparison operator");
6755 DiagRuntimeBehavior(Loc,
6756 PDiag(diag::warn_stringcompare)
6757 << isa<ObjCEncodeExpr>(literalStringStripped)
6758 << literalString->getSourceRange());
6762 // C99 6.5.8p3 / C99 6.5.9p4
6763 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6764 UsualArithmeticConversions(lex, rex);
6765 else {
6766 UsualUnaryConversions(lex);
6767 UsualUnaryConversions(rex);
6770 lType = lex->getType();
6771 rType = rex->getType();
6773 // The result of comparisons is 'bool' in C++, 'int' in C.
6774 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
6776 if (isRelational) {
6777 if (lType->isRealType() && rType->isRealType())
6778 return ResultTy;
6779 } else {
6780 // Check for comparisons of floating point operands using != and ==.
6781 if (lType->hasFloatingRepresentation())
6782 CheckFloatComparison(Loc,lex,rex);
6784 if (lType->isArithmeticType() && rType->isArithmeticType())
6785 return ResultTy;
6788 bool LHSIsNull = lex->isNullPointerConstant(Context,
6789 Expr::NPC_ValueDependentIsNull);
6790 bool RHSIsNull = rex->isNullPointerConstant(Context,
6791 Expr::NPC_ValueDependentIsNull);
6793 // All of the following pointer-related warnings are GCC extensions, except
6794 // when handling null pointer constants.
6795 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
6796 QualType LCanPointeeTy =
6797 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
6798 QualType RCanPointeeTy =
6799 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
6801 if (getLangOptions().CPlusPlus) {
6802 if (LCanPointeeTy == RCanPointeeTy)
6803 return ResultTy;
6804 if (!isRelational &&
6805 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6806 // Valid unless comparison between non-null pointer and function pointer
6807 // This is a gcc extension compatibility comparison.
6808 // In a SFINAE context, we treat this as a hard error to maintain
6809 // conformance with the C++ standard.
6810 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6811 && !LHSIsNull && !RHSIsNull) {
6812 Diag(Loc,
6813 isSFINAEContext()?
6814 diag::err_typecheck_comparison_of_fptr_to_void
6815 : diag::ext_typecheck_comparison_of_fptr_to_void)
6816 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6818 if (isSFINAEContext())
6819 return QualType();
6821 ImpCastExprToType(rex, lType, CK_BitCast);
6822 return ResultTy;
6826 // C++ [expr.rel]p2:
6827 // [...] Pointer conversions (4.10) and qualification
6828 // conversions (4.4) are performed on pointer operands (or on
6829 // a pointer operand and a null pointer constant) to bring
6830 // them to their composite pointer type. [...]
6832 // C++ [expr.eq]p1 uses the same notion for (in)equality
6833 // comparisons of pointers.
6834 bool NonStandardCompositeType = false;
6835 QualType T = FindCompositePointerType(Loc, lex, rex,
6836 isSFINAEContext()? 0 : &NonStandardCompositeType);
6837 if (T.isNull()) {
6838 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6839 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6840 return QualType();
6841 } else if (NonStandardCompositeType) {
6842 Diag(Loc,
6843 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6844 << lType << rType << T
6845 << lex->getSourceRange() << rex->getSourceRange();
6848 ImpCastExprToType(lex, T, CK_BitCast);
6849 ImpCastExprToType(rex, T, CK_BitCast);
6850 return ResultTy;
6852 // C99 6.5.9p2 and C99 6.5.8p2
6853 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6854 RCanPointeeTy.getUnqualifiedType())) {
6855 // Valid unless a relational comparison of function pointers
6856 if (isRelational && LCanPointeeTy->isFunctionType()) {
6857 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6858 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6860 } else if (!isRelational &&
6861 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6862 // Valid unless comparison between non-null pointer and function pointer
6863 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6864 && !LHSIsNull && !RHSIsNull) {
6865 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6866 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6868 } else {
6869 // Invalid
6870 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6871 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6873 if (LCanPointeeTy != RCanPointeeTy)
6874 ImpCastExprToType(rex, lType, CK_BitCast);
6875 return ResultTy;
6878 if (getLangOptions().CPlusPlus) {
6879 // Comparison of nullptr_t with itself.
6880 if (lType->isNullPtrType() && rType->isNullPtrType())
6881 return ResultTy;
6883 // Comparison of pointers with null pointer constants and equality
6884 // comparisons of member pointers to null pointer constants.
6885 if (RHSIsNull &&
6886 ((lType->isPointerType() || lType->isNullPtrType()) ||
6887 (!isRelational && lType->isMemberPointerType()))) {
6888 ImpCastExprToType(rex, lType,
6889 lType->isMemberPointerType()
6890 ? CK_NullToMemberPointer
6891 : CK_NullToPointer);
6892 return ResultTy;
6894 if (LHSIsNull &&
6895 ((rType->isPointerType() || rType->isNullPtrType()) ||
6896 (!isRelational && rType->isMemberPointerType()))) {
6897 ImpCastExprToType(lex, rType,
6898 rType->isMemberPointerType()
6899 ? CK_NullToMemberPointer
6900 : CK_NullToPointer);
6901 return ResultTy;
6904 // Comparison of member pointers.
6905 if (!isRelational &&
6906 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6907 // C++ [expr.eq]p2:
6908 // In addition, pointers to members can be compared, or a pointer to
6909 // member and a null pointer constant. Pointer to member conversions
6910 // (4.11) and qualification conversions (4.4) are performed to bring
6911 // them to a common type. If one operand is a null pointer constant,
6912 // the common type is the type of the other operand. Otherwise, the
6913 // common type is a pointer to member type similar (4.4) to the type
6914 // of one of the operands, with a cv-qualification signature (4.4)
6915 // that is the union of the cv-qualification signatures of the operand
6916 // types.
6917 bool NonStandardCompositeType = false;
6918 QualType T = FindCompositePointerType(Loc, lex, rex,
6919 isSFINAEContext()? 0 : &NonStandardCompositeType);
6920 if (T.isNull()) {
6921 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6922 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6923 return QualType();
6924 } else if (NonStandardCompositeType) {
6925 Diag(Loc,
6926 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6927 << lType << rType << T
6928 << lex->getSourceRange() << rex->getSourceRange();
6931 ImpCastExprToType(lex, T, CK_BitCast);
6932 ImpCastExprToType(rex, T, CK_BitCast);
6933 return ResultTy;
6937 // Handle block pointer types.
6938 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
6939 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6940 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
6942 if (!LHSIsNull && !RHSIsNull &&
6943 !Context.typesAreCompatible(lpointee, rpointee)) {
6944 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6945 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6947 ImpCastExprToType(rex, lType, CK_BitCast);
6948 return ResultTy;
6950 // Allow block pointers to be compared with null pointer constants.
6951 if (!isRelational
6952 && ((lType->isBlockPointerType() && rType->isPointerType())
6953 || (lType->isPointerType() && rType->isBlockPointerType()))) {
6954 if (!LHSIsNull && !RHSIsNull) {
6955 if (!((rType->isPointerType() && rType->getAs<PointerType>()
6956 ->getPointeeType()->isVoidType())
6957 || (lType->isPointerType() && lType->getAs<PointerType>()
6958 ->getPointeeType()->isVoidType())))
6959 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6960 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6962 ImpCastExprToType(rex, lType, CK_BitCast);
6963 return ResultTy;
6966 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
6967 if (lType->isPointerType() || rType->isPointerType()) {
6968 const PointerType *LPT = lType->getAs<PointerType>();
6969 const PointerType *RPT = rType->getAs<PointerType>();
6970 bool LPtrToVoid = LPT ?
6971 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
6972 bool RPtrToVoid = RPT ?
6973 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
6975 if (!LPtrToVoid && !RPtrToVoid &&
6976 !Context.typesAreCompatible(lType, rType)) {
6977 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6978 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6980 ImpCastExprToType(rex, lType, CK_BitCast);
6981 return ResultTy;
6983 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
6984 if (!Context.areComparableObjCPointerTypes(lType, rType))
6985 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6986 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6987 ImpCastExprToType(rex, lType, CK_BitCast);
6988 return ResultTy;
6991 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6992 (lType->isIntegerType() && rType->isAnyPointerType())) {
6993 unsigned DiagID = 0;
6994 bool isError = false;
6995 if ((LHSIsNull && lType->isIntegerType()) ||
6996 (RHSIsNull && rType->isIntegerType())) {
6997 if (isRelational && !getLangOptions().CPlusPlus)
6998 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
6999 } else if (isRelational && !getLangOptions().CPlusPlus)
7000 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7001 else if (getLangOptions().CPlusPlus) {
7002 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7003 isError = true;
7004 } else
7005 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7007 if (DiagID) {
7008 Diag(Loc, DiagID)
7009 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
7010 if (isError)
7011 return QualType();
7014 if (lType->isIntegerType())
7015 ImpCastExprToType(lex, rType,
7016 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7017 else
7018 ImpCastExprToType(rex, lType,
7019 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7020 return ResultTy;
7023 // Handle block pointers.
7024 if (!isRelational && RHSIsNull
7025 && lType->isBlockPointerType() && rType->isIntegerType()) {
7026 ImpCastExprToType(rex, lType, CK_NullToPointer);
7027 return ResultTy;
7029 if (!isRelational && LHSIsNull
7030 && lType->isIntegerType() && rType->isBlockPointerType()) {
7031 ImpCastExprToType(lex, rType, CK_NullToPointer);
7032 return ResultTy;
7034 return InvalidOperands(Loc, lex, rex);
7037 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7038 /// operates on extended vector types. Instead of producing an IntTy result,
7039 /// like a scalar comparison, a vector comparison produces a vector of integer
7040 /// types.
7041 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
7042 SourceLocation Loc,
7043 bool isRelational) {
7044 // Check to make sure we're operating on vectors of the same type and width,
7045 // Allowing one side to be a scalar of element type.
7046 QualType vType = CheckVectorOperands(Loc, lex, rex);
7047 if (vType.isNull())
7048 return vType;
7050 // If AltiVec, the comparison results in a numeric type, i.e.
7051 // bool for C++, int for C
7052 if (getLangOptions().AltiVec)
7053 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
7055 QualType lType = lex->getType();
7056 QualType rType = rex->getType();
7058 // For non-floating point types, check for self-comparisons of the form
7059 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7060 // often indicate logic errors in the program.
7061 if (!lType->hasFloatingRepresentation()) {
7062 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
7063 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
7064 if (DRL->getDecl() == DRR->getDecl())
7065 DiagRuntimeBehavior(Loc,
7066 PDiag(diag::warn_comparison_always)
7067 << 0 // self-
7068 << 2 // "a constant"
7072 // Check for comparisons of floating point operands using != and ==.
7073 if (!isRelational && lType->hasFloatingRepresentation()) {
7074 assert (rType->hasFloatingRepresentation());
7075 CheckFloatComparison(Loc,lex,rex);
7078 // Return the type for the comparison, which is the same as vector type for
7079 // integer vectors, or an integer type of identical size and number of
7080 // elements for floating point vectors.
7081 if (lType->hasIntegerRepresentation())
7082 return lType;
7084 const VectorType *VTy = lType->getAs<VectorType>();
7085 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7086 if (TypeSize == Context.getTypeSize(Context.IntTy))
7087 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7088 if (TypeSize == Context.getTypeSize(Context.LongTy))
7089 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7091 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7092 "Unhandled vector element size in vector compare");
7093 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7096 inline QualType Sema::CheckBitwiseOperands(
7097 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
7098 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7099 if (lex->getType()->hasIntegerRepresentation() &&
7100 rex->getType()->hasIntegerRepresentation())
7101 return CheckVectorOperands(Loc, lex, rex);
7103 return InvalidOperands(Loc, lex, rex);
7106 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
7108 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7109 rex->getType()->isIntegralOrUnscopedEnumerationType())
7110 return compType;
7111 return InvalidOperands(Loc, lex, rex);
7114 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7115 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7117 // Diagnose cases where the user write a logical and/or but probably meant a
7118 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7119 // is a constant.
7120 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
7121 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
7122 // Don't warn in macros.
7123 !Loc.isMacroID()) {
7124 // If the RHS can be constant folded, and if it constant folds to something
7125 // that isn't 0 or 1 (which indicate a potential logical operation that
7126 // happened to fold to true/false) then warn.
7127 Expr::EvalResult Result;
7128 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7129 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7130 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7131 << rex->getSourceRange()
7132 << (Opc == BO_LAnd ? "&&" : "||")
7133 << (Opc == BO_LAnd ? "&" : "|");
7137 if (!Context.getLangOptions().CPlusPlus) {
7138 UsualUnaryConversions(lex);
7139 UsualUnaryConversions(rex);
7141 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7142 return InvalidOperands(Loc, lex, rex);
7144 return Context.IntTy;
7147 // The following is safe because we only use this method for
7148 // non-overloadable operands.
7150 // C++ [expr.log.and]p1
7151 // C++ [expr.log.or]p1
7152 // The operands are both contextually converted to type bool.
7153 if (PerformContextuallyConvertToBool(lex) ||
7154 PerformContextuallyConvertToBool(rex))
7155 return InvalidOperands(Loc, lex, rex);
7157 // C++ [expr.log.and]p2
7158 // C++ [expr.log.or]p2
7159 // The result is a bool.
7160 return Context.BoolTy;
7163 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7164 /// is a read-only property; return true if so. A readonly property expression
7165 /// depends on various declarations and thus must be treated specially.
7167 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7168 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7169 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7170 if (PropExpr->isImplicitProperty()) return false;
7172 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7173 QualType BaseType = PropExpr->isSuperReceiver() ?
7174 PropExpr->getSuperReceiverType() :
7175 PropExpr->getBase()->getType();
7177 if (const ObjCObjectPointerType *OPT =
7178 BaseType->getAsObjCInterfacePointerType())
7179 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7180 if (S.isPropertyReadonly(PDecl, IFace))
7181 return true;
7183 return false;
7186 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7187 /// emit an error and return true. If so, return false.
7188 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7189 SourceLocation OrigLoc = Loc;
7190 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7191 &Loc);
7192 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7193 IsLV = Expr::MLV_ReadonlyProperty;
7194 if (IsLV == Expr::MLV_Valid)
7195 return false;
7197 unsigned Diag = 0;
7198 bool NeedType = false;
7199 switch (IsLV) { // C99 6.5.16p2
7200 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
7201 case Expr::MLV_ArrayType:
7202 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7203 NeedType = true;
7204 break;
7205 case Expr::MLV_NotObjectType:
7206 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7207 NeedType = true;
7208 break;
7209 case Expr::MLV_LValueCast:
7210 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7211 break;
7212 case Expr::MLV_Valid:
7213 llvm_unreachable("did not take early return for MLV_Valid");
7214 case Expr::MLV_InvalidExpression:
7215 case Expr::MLV_MemberFunction:
7216 case Expr::MLV_ClassTemporary:
7217 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7218 break;
7219 case Expr::MLV_IncompleteType:
7220 case Expr::MLV_IncompleteVoidType:
7221 return S.RequireCompleteType(Loc, E->getType(),
7222 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
7223 << E->getSourceRange());
7224 case Expr::MLV_DuplicateVectorComponents:
7225 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7226 break;
7227 case Expr::MLV_NotBlockQualified:
7228 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7229 break;
7230 case Expr::MLV_ReadonlyProperty:
7231 Diag = diag::error_readonly_property_assignment;
7232 break;
7233 case Expr::MLV_NoSetterProperty:
7234 Diag = diag::error_nosetter_property_assignment;
7235 break;
7236 case Expr::MLV_SubObjCPropertySetting:
7237 Diag = diag::error_no_subobject_property_setting;
7238 break;
7241 SourceRange Assign;
7242 if (Loc != OrigLoc)
7243 Assign = SourceRange(OrigLoc, OrigLoc);
7244 if (NeedType)
7245 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7246 else
7247 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7248 return true;
7253 // C99 6.5.16.1
7254 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7255 SourceLocation Loc,
7256 QualType CompoundType) {
7257 // Verify that LHS is a modifiable lvalue, and emit error if not.
7258 if (CheckForModifiableLvalue(LHS, Loc, *this))
7259 return QualType();
7261 QualType LHSType = LHS->getType();
7262 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
7263 AssignConvertType ConvTy;
7264 if (CompoundType.isNull()) {
7265 QualType LHSTy(LHSType);
7266 // Simple assignment "x = y".
7267 if (LHS->getObjectKind() == OK_ObjCProperty)
7268 ConvertPropertyForLValue(LHS, RHS, LHSTy);
7269 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7270 // Special case of NSObject attributes on c-style pointer types.
7271 if (ConvTy == IncompatiblePointer &&
7272 ((Context.isObjCNSObjectType(LHSType) &&
7273 RHSType->isObjCObjectPointerType()) ||
7274 (Context.isObjCNSObjectType(RHSType) &&
7275 LHSType->isObjCObjectPointerType())))
7276 ConvTy = Compatible;
7278 if (ConvTy == Compatible &&
7279 getLangOptions().ObjCNonFragileABI &&
7280 LHSType->isObjCObjectType())
7281 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7282 << LHSType;
7284 // If the RHS is a unary plus or minus, check to see if they = and + are
7285 // right next to each other. If so, the user may have typo'd "x =+ 4"
7286 // instead of "x += 4".
7287 Expr *RHSCheck = RHS;
7288 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7289 RHSCheck = ICE->getSubExpr();
7290 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7291 if ((UO->getOpcode() == UO_Plus ||
7292 UO->getOpcode() == UO_Minus) &&
7293 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7294 // Only if the two operators are exactly adjacent.
7295 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7296 // And there is a space or other character before the subexpr of the
7297 // unary +/-. We don't want to warn on "x=-1".
7298 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7299 UO->getSubExpr()->getLocStart().isFileID()) {
7300 Diag(Loc, diag::warn_not_compound_assign)
7301 << (UO->getOpcode() == UO_Plus ? "+" : "-")
7302 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7305 } else {
7306 // Compound assignment "x += y"
7307 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7310 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7311 RHS, AA_Assigning))
7312 return QualType();
7315 // Check to see if the destination operand is a dereferenced null pointer. If
7316 // so, and if not volatile-qualified, this is undefined behavior that the
7317 // optimizer will delete, so warn about it. People sometimes try to use this
7318 // to get a deterministic trap and are surprised by clang's behavior. This
7319 // only handles the pattern "*null = whatever", which is a very syntactic
7320 // check.
7321 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
7322 if (UO->getOpcode() == UO_Deref &&
7323 UO->getSubExpr()->IgnoreParenCasts()->
7324 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7325 !UO->getType().isVolatileQualified()) {
7326 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
7327 << UO->getSubExpr()->getSourceRange();
7328 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
7331 // Check for trivial buffer overflows.
7332 if (const ArraySubscriptExpr *ae
7333 = dyn_cast<ArraySubscriptExpr>(LHS->IgnoreParenCasts()))
7334 CheckArrayAccess(ae);
7336 // C99 6.5.16p3: The type of an assignment expression is the type of the
7337 // left operand unless the left operand has qualified type, in which case
7338 // it is the unqualified version of the type of the left operand.
7339 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7340 // is converted to the type of the assignment expression (above).
7341 // C++ 5.17p1: the type of the assignment expression is that of its left
7342 // operand.
7343 return (getLangOptions().CPlusPlus
7344 ? LHSType : LHSType.getUnqualifiedType());
7347 // C99 6.5.17
7348 static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
7349 SourceLocation Loc) {
7350 S.DiagnoseUnusedExprResult(LHS);
7352 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
7353 if (LHSResult.isInvalid())
7354 return QualType();
7356 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
7357 if (RHSResult.isInvalid())
7358 return QualType();
7359 RHS = RHSResult.take();
7361 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7362 // operands, but not unary promotions.
7363 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7365 // So we treat the LHS as a ignored value, and in C++ we allow the
7366 // containing site to determine what should be done with the RHS.
7367 S.IgnoredValueConversions(LHS);
7369 if (!S.getLangOptions().CPlusPlus) {
7370 S.DefaultFunctionArrayLvalueConversion(RHS);
7371 if (!RHS->getType()->isVoidType())
7372 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
7375 return RHS->getType();
7378 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7379 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7380 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7381 ExprValueKind &VK,
7382 SourceLocation OpLoc,
7383 bool isInc, bool isPrefix) {
7384 if (Op->isTypeDependent())
7385 return S.Context.DependentTy;
7387 QualType ResType = Op->getType();
7388 assert(!ResType.isNull() && "no type for increment/decrement expression");
7390 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
7391 // Decrement of bool is not allowed.
7392 if (!isInc) {
7393 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7394 return QualType();
7396 // Increment of bool sets it to true, but is deprecated.
7397 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7398 } else if (ResType->isRealType()) {
7399 // OK!
7400 } else if (ResType->isAnyPointerType()) {
7401 QualType PointeeTy = ResType->getPointeeType();
7403 // C99 6.5.2.4p2, 6.5.6p2
7404 if (PointeeTy->isVoidType()) {
7405 if (S.getLangOptions().CPlusPlus) {
7406 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
7407 << Op->getSourceRange();
7408 return QualType();
7411 // Pointer to void is a GNU extension in C.
7412 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
7413 } else if (PointeeTy->isFunctionType()) {
7414 if (S.getLangOptions().CPlusPlus) {
7415 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
7416 << Op->getType() << Op->getSourceRange();
7417 return QualType();
7420 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
7421 << ResType << Op->getSourceRange();
7422 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7423 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
7424 << Op->getSourceRange()
7425 << ResType))
7426 return QualType();
7427 // Diagnose bad cases where we step over interface counts.
7428 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7429 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
7430 << PointeeTy << Op->getSourceRange();
7431 return QualType();
7433 } else if (ResType->isAnyComplexType()) {
7434 // C99 does not support ++/-- on complex types, we allow as an extension.
7435 S.Diag(OpLoc, diag::ext_integer_increment_complex)
7436 << ResType << Op->getSourceRange();
7437 } else if (ResType->isPlaceholderType()) {
7438 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
7439 if (PR.isInvalid()) return QualType();
7440 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7441 isInc, isPrefix);
7442 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7443 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7444 } else {
7445 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7446 << ResType << int(isInc) << Op->getSourceRange();
7447 return QualType();
7449 // At this point, we know we have a real, complex or pointer type.
7450 // Now make sure the operand is a modifiable lvalue.
7451 if (CheckForModifiableLvalue(Op, OpLoc, S))
7452 return QualType();
7453 // In C++, a prefix increment is the same type as the operand. Otherwise
7454 // (in C or with postfix), the increment is the unqualified type of the
7455 // operand.
7456 if (isPrefix && S.getLangOptions().CPlusPlus) {
7457 VK = VK_LValue;
7458 return ResType;
7459 } else {
7460 VK = VK_RValue;
7461 return ResType.getUnqualifiedType();
7465 void Sema::ConvertPropertyForRValue(Expr *&E) {
7466 assert(E->getValueKind() == VK_LValue &&
7467 E->getObjectKind() == OK_ObjCProperty);
7468 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7470 ExprValueKind VK = VK_RValue;
7471 if (PRE->isImplicitProperty()) {
7472 if (const ObjCMethodDecl *GetterMethod =
7473 PRE->getImplicitPropertyGetter()) {
7474 QualType Result = GetterMethod->getResultType();
7475 VK = Expr::getValueKindForType(Result);
7477 else {
7478 Diag(PRE->getLocation(), diag::err_getter_not_found)
7479 << PRE->getBase()->getType();
7483 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7484 E, 0, VK);
7486 ExprResult Result = MaybeBindToTemporary(E);
7487 if (!Result.isInvalid())
7488 E = Result.take();
7491 void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7492 assert(LHS->getValueKind() == VK_LValue &&
7493 LHS->getObjectKind() == OK_ObjCProperty);
7494 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7496 if (PRE->isImplicitProperty()) {
7497 // If using property-dot syntax notation for assignment, and there is a
7498 // setter, RHS expression is being passed to the setter argument. So,
7499 // type conversion (and comparison) is RHS to setter's argument type.
7500 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7501 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7502 LHSTy = (*P)->getType();
7504 // Otherwise, if the getter returns an l-value, just call that.
7505 } else {
7506 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7507 ExprValueKind VK = Expr::getValueKindForType(Result);
7508 if (VK == VK_LValue) {
7509 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7510 CK_GetObjCProperty, LHS, 0, VK);
7511 return;
7516 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
7517 InitializedEntity Entity =
7518 InitializedEntity::InitializeParameter(Context, LHSTy);
7519 Expr *Arg = RHS;
7520 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7521 Owned(Arg));
7522 if (!ArgE.isInvalid())
7523 RHS = ArgE.takeAs<Expr>();
7528 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7529 /// This routine allows us to typecheck complex/recursive expressions
7530 /// where the declaration is needed for type checking. We only need to
7531 /// handle cases when the expression references a function designator
7532 /// or is an lvalue. Here are some examples:
7533 /// - &(x) => x
7534 /// - &*****f => f for f a function designator.
7535 /// - &s.xx => s
7536 /// - &s.zz[1].yy -> s, if zz is an array
7537 /// - *(x + 1) -> x, if x is an array
7538 /// - &"123"[2] -> 0
7539 /// - & __real__ x -> x
7540 static ValueDecl *getPrimaryDecl(Expr *E) {
7541 switch (E->getStmtClass()) {
7542 case Stmt::DeclRefExprClass:
7543 return cast<DeclRefExpr>(E)->getDecl();
7544 case Stmt::MemberExprClass:
7545 // If this is an arrow operator, the address is an offset from
7546 // the base's value, so the object the base refers to is
7547 // irrelevant.
7548 if (cast<MemberExpr>(E)->isArrow())
7549 return 0;
7550 // Otherwise, the expression refers to a part of the base
7551 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7552 case Stmt::ArraySubscriptExprClass: {
7553 // FIXME: This code shouldn't be necessary! We should catch the implicit
7554 // promotion of register arrays earlier.
7555 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7556 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7557 if (ICE->getSubExpr()->getType()->isArrayType())
7558 return getPrimaryDecl(ICE->getSubExpr());
7560 return 0;
7562 case Stmt::UnaryOperatorClass: {
7563 UnaryOperator *UO = cast<UnaryOperator>(E);
7565 switch(UO->getOpcode()) {
7566 case UO_Real:
7567 case UO_Imag:
7568 case UO_Extension:
7569 return getPrimaryDecl(UO->getSubExpr());
7570 default:
7571 return 0;
7574 case Stmt::ParenExprClass:
7575 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7576 case Stmt::ImplicitCastExprClass:
7577 // If the result of an implicit cast is an l-value, we care about
7578 // the sub-expression; otherwise, the result here doesn't matter.
7579 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7580 default:
7581 return 0;
7585 /// CheckAddressOfOperand - The operand of & must be either a function
7586 /// designator or an lvalue designating an object. If it is an lvalue, the
7587 /// object cannot be declared with storage class register or be a bit field.
7588 /// Note: The usual conversions are *not* applied to the operand of the &
7589 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7590 /// In C++, the operand might be an overloaded function name, in which case
7591 /// we allow the '&' but retain the overloaded-function type.
7592 static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7593 SourceLocation OpLoc) {
7594 if (OrigOp->isTypeDependent())
7595 return S.Context.DependentTy;
7596 if (OrigOp->getType() == S.Context.OverloadTy)
7597 return S.Context.OverloadTy;
7599 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
7600 if (PR.isInvalid()) return QualType();
7601 OrigOp = PR.take();
7603 // Make sure to ignore parentheses in subsequent checks
7604 Expr *op = OrigOp->IgnoreParens();
7606 if (S.getLangOptions().C99) {
7607 // Implement C99-only parts of addressof rules.
7608 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7609 if (uOp->getOpcode() == UO_Deref)
7610 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7611 // (assuming the deref expression is valid).
7612 return uOp->getSubExpr()->getType();
7614 // Technically, there should be a check for array subscript
7615 // expressions here, but the result of one is always an lvalue anyway.
7617 ValueDecl *dcl = getPrimaryDecl(op);
7618 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7620 if (lval == Expr::LV_ClassTemporary) {
7621 bool sfinae = S.isSFINAEContext();
7622 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7623 : diag::ext_typecheck_addrof_class_temporary)
7624 << op->getType() << op->getSourceRange();
7625 if (sfinae)
7626 return QualType();
7627 } else if (isa<ObjCSelectorExpr>(op)) {
7628 return S.Context.getPointerType(op->getType());
7629 } else if (lval == Expr::LV_MemberFunction) {
7630 // If it's an instance method, make a member pointer.
7631 // The expression must have exactly the form &A::foo.
7633 // If the underlying expression isn't a decl ref, give up.
7634 if (!isa<DeclRefExpr>(op)) {
7635 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7636 << OrigOp->getSourceRange();
7637 return QualType();
7639 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7640 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7642 // The id-expression was parenthesized.
7643 if (OrigOp != DRE) {
7644 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7645 << OrigOp->getSourceRange();
7647 // The method was named without a qualifier.
7648 } else if (!DRE->getQualifier()) {
7649 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7650 << op->getSourceRange();
7653 return S.Context.getMemberPointerType(op->getType(),
7654 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7655 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7656 // C99 6.5.3.2p1
7657 // The operand must be either an l-value or a function designator
7658 if (!op->getType()->isFunctionType()) {
7659 // FIXME: emit more specific diag...
7660 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7661 << op->getSourceRange();
7662 return QualType();
7664 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7665 // The operand cannot be a bit-field
7666 S.Diag(OpLoc, diag::err_typecheck_address_of)
7667 << "bit-field" << op->getSourceRange();
7668 return QualType();
7669 } else if (op->getObjectKind() == OK_VectorComponent) {
7670 // The operand cannot be an element of a vector
7671 S.Diag(OpLoc, diag::err_typecheck_address_of)
7672 << "vector element" << op->getSourceRange();
7673 return QualType();
7674 } else if (op->getObjectKind() == OK_ObjCProperty) {
7675 // cannot take address of a property expression.
7676 S.Diag(OpLoc, diag::err_typecheck_address_of)
7677 << "property expression" << op->getSourceRange();
7678 return QualType();
7679 } else if (dcl) { // C99 6.5.3.2p1
7680 // We have an lvalue with a decl. Make sure the decl is not declared
7681 // with the register storage-class specifier.
7682 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
7683 // in C++ it is not error to take address of a register
7684 // variable (c++03 7.1.1P3)
7685 if (vd->getStorageClass() == SC_Register &&
7686 !S.getLangOptions().CPlusPlus) {
7687 S.Diag(OpLoc, diag::err_typecheck_address_of)
7688 << "register variable" << op->getSourceRange();
7689 return QualType();
7691 } else if (isa<FunctionTemplateDecl>(dcl)) {
7692 return S.Context.OverloadTy;
7693 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
7694 // Okay: we can take the address of a field.
7695 // Could be a pointer to member, though, if there is an explicit
7696 // scope qualifier for the class.
7697 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
7698 DeclContext *Ctx = dcl->getDeclContext();
7699 if (Ctx && Ctx->isRecord()) {
7700 if (dcl->getType()->isReferenceType()) {
7701 S.Diag(OpLoc,
7702 diag::err_cannot_form_pointer_to_member_of_reference_type)
7703 << dcl->getDeclName() << dcl->getType();
7704 return QualType();
7707 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7708 Ctx = Ctx->getParent();
7709 return S.Context.getMemberPointerType(op->getType(),
7710 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
7713 } else if (!isa<FunctionDecl>(dcl))
7714 assert(0 && "Unknown/unexpected decl type");
7717 if (lval == Expr::LV_IncompleteVoidType) {
7718 // Taking the address of a void variable is technically illegal, but we
7719 // allow it in cases which are otherwise valid.
7720 // Example: "extern void x; void* y = &x;".
7721 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
7724 // If the operand has type "type", the result has type "pointer to type".
7725 if (op->getType()->isObjCObjectType())
7726 return S.Context.getObjCObjectPointerType(op->getType());
7727 return S.Context.getPointerType(op->getType());
7730 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
7731 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7732 SourceLocation OpLoc) {
7733 if (Op->isTypeDependent())
7734 return S.Context.DependentTy;
7736 S.UsualUnaryConversions(Op);
7737 QualType OpTy = Op->getType();
7738 QualType Result;
7740 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7741 // is an incomplete type or void. It would be possible to warn about
7742 // dereferencing a void pointer, but it's completely well-defined, and such a
7743 // warning is unlikely to catch any mistakes.
7744 if (const PointerType *PT = OpTy->getAs<PointerType>())
7745 Result = PT->getPointeeType();
7746 else if (const ObjCObjectPointerType *OPT =
7747 OpTy->getAs<ObjCObjectPointerType>())
7748 Result = OPT->getPointeeType();
7749 else {
7750 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
7751 if (PR.isInvalid()) return QualType();
7752 if (PR.take() != Op)
7753 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
7756 if (Result.isNull()) {
7757 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
7758 << OpTy << Op->getSourceRange();
7759 return QualType();
7762 // Dereferences are usually l-values...
7763 VK = VK_LValue;
7765 // ...except that certain expressions are never l-values in C.
7766 if (!S.getLangOptions().CPlusPlus &&
7767 IsCForbiddenLValueType(S.Context, Result))
7768 VK = VK_RValue;
7770 return Result;
7773 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
7774 tok::TokenKind Kind) {
7775 BinaryOperatorKind Opc;
7776 switch (Kind) {
7777 default: assert(0 && "Unknown binop!");
7778 case tok::periodstar: Opc = BO_PtrMemD; break;
7779 case tok::arrowstar: Opc = BO_PtrMemI; break;
7780 case tok::star: Opc = BO_Mul; break;
7781 case tok::slash: Opc = BO_Div; break;
7782 case tok::percent: Opc = BO_Rem; break;
7783 case tok::plus: Opc = BO_Add; break;
7784 case tok::minus: Opc = BO_Sub; break;
7785 case tok::lessless: Opc = BO_Shl; break;
7786 case tok::greatergreater: Opc = BO_Shr; break;
7787 case tok::lessequal: Opc = BO_LE; break;
7788 case tok::less: Opc = BO_LT; break;
7789 case tok::greaterequal: Opc = BO_GE; break;
7790 case tok::greater: Opc = BO_GT; break;
7791 case tok::exclaimequal: Opc = BO_NE; break;
7792 case tok::equalequal: Opc = BO_EQ; break;
7793 case tok::amp: Opc = BO_And; break;
7794 case tok::caret: Opc = BO_Xor; break;
7795 case tok::pipe: Opc = BO_Or; break;
7796 case tok::ampamp: Opc = BO_LAnd; break;
7797 case tok::pipepipe: Opc = BO_LOr; break;
7798 case tok::equal: Opc = BO_Assign; break;
7799 case tok::starequal: Opc = BO_MulAssign; break;
7800 case tok::slashequal: Opc = BO_DivAssign; break;
7801 case tok::percentequal: Opc = BO_RemAssign; break;
7802 case tok::plusequal: Opc = BO_AddAssign; break;
7803 case tok::minusequal: Opc = BO_SubAssign; break;
7804 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7805 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7806 case tok::ampequal: Opc = BO_AndAssign; break;
7807 case tok::caretequal: Opc = BO_XorAssign; break;
7808 case tok::pipeequal: Opc = BO_OrAssign; break;
7809 case tok::comma: Opc = BO_Comma; break;
7811 return Opc;
7814 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
7815 tok::TokenKind Kind) {
7816 UnaryOperatorKind Opc;
7817 switch (Kind) {
7818 default: assert(0 && "Unknown unary op!");
7819 case tok::plusplus: Opc = UO_PreInc; break;
7820 case tok::minusminus: Opc = UO_PreDec; break;
7821 case tok::amp: Opc = UO_AddrOf; break;
7822 case tok::star: Opc = UO_Deref; break;
7823 case tok::plus: Opc = UO_Plus; break;
7824 case tok::minus: Opc = UO_Minus; break;
7825 case tok::tilde: Opc = UO_Not; break;
7826 case tok::exclaim: Opc = UO_LNot; break;
7827 case tok::kw___real: Opc = UO_Real; break;
7828 case tok::kw___imag: Opc = UO_Imag; break;
7829 case tok::kw___extension__: Opc = UO_Extension; break;
7831 return Opc;
7834 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7835 /// This warning is only emitted for builtin assignment operations. It is also
7836 /// suppressed in the event of macro expansions.
7837 static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7838 SourceLocation OpLoc) {
7839 if (!S.ActiveTemplateInstantiations.empty())
7840 return;
7841 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7842 return;
7843 lhs = lhs->IgnoreParenImpCasts();
7844 rhs = rhs->IgnoreParenImpCasts();
7845 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7846 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7847 if (!LeftDeclRef || !RightDeclRef ||
7848 LeftDeclRef->getLocation().isMacroID() ||
7849 RightDeclRef->getLocation().isMacroID())
7850 return;
7851 const ValueDecl *LeftDecl =
7852 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7853 const ValueDecl *RightDecl =
7854 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7855 if (LeftDecl != RightDecl)
7856 return;
7857 if (LeftDecl->getType().isVolatileQualified())
7858 return;
7859 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7860 if (RefTy->getPointeeType().isVolatileQualified())
7861 return;
7863 S.Diag(OpLoc, diag::warn_self_assignment)
7864 << LeftDeclRef->getType()
7865 << lhs->getSourceRange() << rhs->getSourceRange();
7868 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7869 /// operator @p Opc at location @c TokLoc. This routine only supports
7870 /// built-in operations; ActOnBinOp handles overloaded operators.
7871 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
7872 BinaryOperatorKind Opc,
7873 Expr *lhs, Expr *rhs) {
7874 QualType ResultTy; // Result type of the binary operator.
7875 // The following two variables are used for compound assignment operators
7876 QualType CompLHSTy; // Type of LHS after promotions for computation
7877 QualType CompResultTy; // Type of computation result
7878 ExprValueKind VK = VK_RValue;
7879 ExprObjectKind OK = OK_Ordinary;
7881 switch (Opc) {
7882 case BO_Assign:
7883 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
7884 if (getLangOptions().CPlusPlus &&
7885 lhs->getObjectKind() != OK_ObjCProperty) {
7886 VK = lhs->getValueKind();
7887 OK = lhs->getObjectKind();
7889 if (!ResultTy.isNull())
7890 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
7891 break;
7892 case BO_PtrMemD:
7893 case BO_PtrMemI:
7894 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
7895 Opc == BO_PtrMemI);
7896 break;
7897 case BO_Mul:
7898 case BO_Div:
7899 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
7900 Opc == BO_Div);
7901 break;
7902 case BO_Rem:
7903 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7904 break;
7905 case BO_Add:
7906 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7907 break;
7908 case BO_Sub:
7909 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7910 break;
7911 case BO_Shl:
7912 case BO_Shr:
7913 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7914 break;
7915 case BO_LE:
7916 case BO_LT:
7917 case BO_GE:
7918 case BO_GT:
7919 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
7920 break;
7921 case BO_EQ:
7922 case BO_NE:
7923 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
7924 break;
7925 case BO_And:
7926 case BO_Xor:
7927 case BO_Or:
7928 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7929 break;
7930 case BO_LAnd:
7931 case BO_LOr:
7932 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
7933 break;
7934 case BO_MulAssign:
7935 case BO_DivAssign:
7936 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
7937 Opc == BO_DivAssign);
7938 CompLHSTy = CompResultTy;
7939 if (!CompResultTy.isNull())
7940 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7941 break;
7942 case BO_RemAssign:
7943 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7944 CompLHSTy = CompResultTy;
7945 if (!CompResultTy.isNull())
7946 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7947 break;
7948 case BO_AddAssign:
7949 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7950 if (!CompResultTy.isNull())
7951 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7952 break;
7953 case BO_SubAssign:
7954 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7955 if (!CompResultTy.isNull())
7956 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7957 break;
7958 case BO_ShlAssign:
7959 case BO_ShrAssign:
7960 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7961 CompLHSTy = CompResultTy;
7962 if (!CompResultTy.isNull())
7963 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7964 break;
7965 case BO_AndAssign:
7966 case BO_XorAssign:
7967 case BO_OrAssign:
7968 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7969 CompLHSTy = CompResultTy;
7970 if (!CompResultTy.isNull())
7971 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7972 break;
7973 case BO_Comma:
7974 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
7975 if (getLangOptions().CPlusPlus) {
7976 VK = rhs->getValueKind();
7977 OK = rhs->getObjectKind();
7979 break;
7981 if (ResultTy.isNull())
7982 return ExprError();
7983 if (CompResultTy.isNull())
7984 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7985 VK, OK, OpLoc));
7987 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
7988 VK = VK_LValue;
7989 OK = lhs->getObjectKind();
7991 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7992 VK, OK, CompLHSTy,
7993 CompResultTy, OpLoc));
7996 /// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7997 /// ParenRange in parentheses.
7998 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7999 const PartialDiagnostic &PD,
8000 const PartialDiagnostic &FirstNote,
8001 SourceRange FirstParenRange,
8002 const PartialDiagnostic &SecondNote,
8003 SourceRange SecondParenRange) {
8004 Self.Diag(Loc, PD);
8006 if (!FirstNote.getDiagID())
8007 return;
8009 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
8010 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8011 // We can't display the parentheses, so just return.
8012 return;
8015 Self.Diag(Loc, FirstNote)
8016 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
8017 << FixItHint::CreateInsertion(EndLoc, ")");
8019 if (!SecondNote.getDiagID())
8020 return;
8022 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
8023 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
8024 // We can't display the parentheses, so just dig the
8025 // warning/error and return.
8026 Self.Diag(Loc, SecondNote);
8027 return;
8030 Self.Diag(Loc, SecondNote)
8031 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
8032 << FixItHint::CreateInsertion(EndLoc, ")");
8035 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8036 /// operators are mixed in a way that suggests that the programmer forgot that
8037 /// comparison operators have higher precedence. The most typical example of
8038 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8039 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8040 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
8041 typedef BinaryOperator BinOp;
8042 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
8043 rhsopc = static_cast<BinOp::Opcode>(-1);
8044 if (BinOp *BO = dyn_cast<BinOp>(lhs))
8045 lhsopc = BO->getOpcode();
8046 if (BinOp *BO = dyn_cast<BinOp>(rhs))
8047 rhsopc = BO->getOpcode();
8049 // Subs are not binary operators.
8050 if (lhsopc == -1 && rhsopc == -1)
8051 return;
8053 // Bitwise operations are sometimes used as eager logical ops.
8054 // Don't diagnose this.
8055 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
8056 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
8057 return;
8059 if (BinOp::isComparisonOp(lhsopc))
8060 SuggestParentheses(Self, OpLoc,
8061 Self.PDiag(diag::warn_precedence_bitwise_rel)
8062 << SourceRange(lhs->getLocStart(), OpLoc)
8063 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
8064 Self.PDiag(diag::note_precedence_bitwise_first)
8065 << BinOp::getOpcodeStr(Opc),
8066 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
8067 Self.PDiag(diag::note_precedence_bitwise_silence)
8068 << BinOp::getOpcodeStr(lhsopc),
8069 lhs->getSourceRange());
8070 else if (BinOp::isComparisonOp(rhsopc))
8071 SuggestParentheses(Self, OpLoc,
8072 Self.PDiag(diag::warn_precedence_bitwise_rel)
8073 << SourceRange(OpLoc, rhs->getLocEnd())
8074 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
8075 Self.PDiag(diag::note_precedence_bitwise_first)
8076 << BinOp::getOpcodeStr(Opc),
8077 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
8078 Self.PDiag(diag::note_precedence_bitwise_silence)
8079 << BinOp::getOpcodeStr(rhsopc),
8080 rhs->getSourceRange());
8083 /// \brief It accepts a '&&' expr that is inside a '||' one.
8084 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8085 /// in parentheses.
8086 static void
8087 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8088 Expr *E) {
8089 assert(isa<BinaryOperator>(E) &&
8090 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8091 SuggestParentheses(Self, OpLoc,
8092 Self.PDiag(diag::warn_logical_and_in_logical_or)
8093 << E->getSourceRange(),
8094 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8095 E->getSourceRange(),
8096 Self.PDiag(0), SourceRange());
8099 /// \brief Returns true if the given expression can be evaluated as a constant
8100 /// 'true'.
8101 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8102 bool Res;
8103 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8106 /// \brief Returns true if the given expression can be evaluated as a constant
8107 /// 'false'.
8108 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8109 bool Res;
8110 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8113 /// \brief Look for '&&' in the left hand of a '||' expr.
8114 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8115 Expr *OrLHS, Expr *OrRHS) {
8116 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
8117 if (Bop->getOpcode() == BO_LAnd) {
8118 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8119 if (EvaluatesAsFalse(S, OrRHS))
8120 return;
8121 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8122 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8123 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8124 } else if (Bop->getOpcode() == BO_LOr) {
8125 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8126 // If it's "a || b && 1 || c" we didn't warn earlier for
8127 // "a || b && 1", but warn now.
8128 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8129 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8135 /// \brief Look for '&&' in the right hand of a '||' expr.
8136 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8137 Expr *OrLHS, Expr *OrRHS) {
8138 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
8139 if (Bop->getOpcode() == BO_LAnd) {
8140 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8141 if (EvaluatesAsFalse(S, OrLHS))
8142 return;
8143 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8144 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8145 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8150 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8151 /// precedence.
8152 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8153 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
8154 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8155 if (BinaryOperator::isBitwiseOp(Opc))
8156 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8158 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8159 // We don't warn for 'assert(a || b && "bad")' since this is safe.
8160 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8161 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8162 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
8166 // Binary Operators. 'Tok' is the token for the operator.
8167 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8168 tok::TokenKind Kind,
8169 Expr *lhs, Expr *rhs) {
8170 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8171 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8172 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
8174 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8175 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8177 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8180 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8181 BinaryOperatorKind Opc,
8182 Expr *lhs, Expr *rhs) {
8183 if (getLangOptions().CPlusPlus) {
8184 bool UseBuiltinOperator;
8186 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8187 UseBuiltinOperator = false;
8188 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8189 UseBuiltinOperator = true;
8190 } else {
8191 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8192 !rhs->getType()->isOverloadableType();
8195 if (!UseBuiltinOperator) {
8196 // Find all of the overloaded operators visible from this
8197 // point. We perform both an operator-name lookup from the local
8198 // scope and an argument-dependent lookup based on the types of
8199 // the arguments.
8200 UnresolvedSet<16> Functions;
8201 OverloadedOperatorKind OverOp
8202 = BinaryOperator::getOverloadedOperator(Opc);
8203 if (S && OverOp != OO_None)
8204 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8205 Functions);
8207 // Build the (potentially-overloaded, potentially-dependent)
8208 // binary operation.
8209 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8213 // Build a built-in binary operation.
8214 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
8217 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8218 UnaryOperatorKind Opc,
8219 Expr *Input) {
8220 ExprValueKind VK = VK_RValue;
8221 ExprObjectKind OK = OK_Ordinary;
8222 QualType resultType;
8223 switch (Opc) {
8224 case UO_PreInc:
8225 case UO_PreDec:
8226 case UO_PostInc:
8227 case UO_PostDec:
8228 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
8229 Opc == UO_PreInc ||
8230 Opc == UO_PostInc,
8231 Opc == UO_PreInc ||
8232 Opc == UO_PreDec);
8233 break;
8234 case UO_AddrOf:
8235 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8236 break;
8237 case UO_Deref:
8238 DefaultFunctionArrayLvalueConversion(Input);
8239 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
8240 break;
8241 case UO_Plus:
8242 case UO_Minus:
8243 UsualUnaryConversions(Input);
8244 resultType = Input->getType();
8245 if (resultType->isDependentType())
8246 break;
8247 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8248 resultType->isVectorType())
8249 break;
8250 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8251 resultType->isEnumeralType())
8252 break;
8253 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
8254 Opc == UO_Plus &&
8255 resultType->isPointerType())
8256 break;
8257 else if (resultType->isPlaceholderType()) {
8258 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8259 if (PR.isInvalid()) return ExprError();
8260 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
8263 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8264 << resultType << Input->getSourceRange());
8265 case UO_Not: // bitwise complement
8266 UsualUnaryConversions(Input);
8267 resultType = Input->getType();
8268 if (resultType->isDependentType())
8269 break;
8270 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8271 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8272 // C99 does not support '~' for complex conjugation.
8273 Diag(OpLoc, diag::ext_integer_complement_complex)
8274 << resultType << Input->getSourceRange();
8275 else if (resultType->hasIntegerRepresentation())
8276 break;
8277 else if (resultType->isPlaceholderType()) {
8278 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8279 if (PR.isInvalid()) return ExprError();
8280 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
8281 } else {
8282 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8283 << resultType << Input->getSourceRange());
8285 break;
8286 case UO_LNot: // logical negation
8287 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8288 DefaultFunctionArrayLvalueConversion(Input);
8289 resultType = Input->getType();
8290 if (resultType->isDependentType())
8291 break;
8292 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8293 // ok, fallthrough
8294 } else if (resultType->isPlaceholderType()) {
8295 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8296 if (PR.isInvalid()) return ExprError();
8297 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
8298 } else {
8299 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8300 << resultType << Input->getSourceRange());
8303 // LNot always has type int. C99 6.5.3.3p5.
8304 // In C++, it's bool. C++ 5.3.1p8
8305 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
8306 break;
8307 case UO_Real:
8308 case UO_Imag:
8309 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8310 // _Real and _Imag map ordinary l-values into ordinary l-values.
8311 if (Input->getValueKind() != VK_RValue &&
8312 Input->getObjectKind() == OK_Ordinary)
8313 VK = Input->getValueKind();
8314 break;
8315 case UO_Extension:
8316 resultType = Input->getType();
8317 VK = Input->getValueKind();
8318 OK = Input->getObjectKind();
8319 break;
8321 if (resultType.isNull())
8322 return ExprError();
8324 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8325 VK, OK, OpLoc));
8328 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8329 UnaryOperatorKind Opc,
8330 Expr *Input) {
8331 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
8332 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
8333 // Find all of the overloaded operators visible from this
8334 // point. We perform both an operator-name lookup from the local
8335 // scope and an argument-dependent lookup based on the types of
8336 // the arguments.
8337 UnresolvedSet<16> Functions;
8338 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8339 if (S && OverOp != OO_None)
8340 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8341 Functions);
8343 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8346 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8349 // Unary Operators. 'Tok' is the token for the operator.
8350 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8351 tok::TokenKind Op, Expr *Input) {
8352 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8355 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8356 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8357 LabelDecl *TheDecl) {
8358 TheDecl->setUsed();
8359 // Create the AST node. The address of a label always has type 'void*'.
8360 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8361 Context.getPointerType(Context.VoidTy)));
8364 ExprResult
8365 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8366 SourceLocation RPLoc) { // "({..})"
8367 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8368 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8370 bool isFileScope
8371 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8372 if (isFileScope)
8373 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8375 // FIXME: there are a variety of strange constraints to enforce here, for
8376 // example, it is not possible to goto into a stmt expression apparently.
8377 // More semantic analysis is needed.
8379 // If there are sub stmts in the compound stmt, take the type of the last one
8380 // as the type of the stmtexpr.
8381 QualType Ty = Context.VoidTy;
8382 bool StmtExprMayBindToTemp = false;
8383 if (!Compound->body_empty()) {
8384 Stmt *LastStmt = Compound->body_back();
8385 LabelStmt *LastLabelStmt = 0;
8386 // If LastStmt is a label, skip down through into the body.
8387 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8388 LastLabelStmt = Label;
8389 LastStmt = Label->getSubStmt();
8391 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
8392 // Do function/array conversion on the last expression, but not
8393 // lvalue-to-rvalue. However, initialize an unqualified type.
8394 DefaultFunctionArrayConversion(LastExpr);
8395 Ty = LastExpr->getType().getUnqualifiedType();
8397 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8398 ExprResult Res = PerformCopyInitialization(
8399 InitializedEntity::InitializeResult(LPLoc,
8401 false),
8402 SourceLocation(),
8403 Owned(LastExpr));
8404 if (Res.isInvalid())
8405 return ExprError();
8406 if ((LastExpr = Res.takeAs<Expr>())) {
8407 if (!LastLabelStmt)
8408 Compound->setLastStmt(LastExpr);
8409 else
8410 LastLabelStmt->setSubStmt(LastExpr);
8411 StmtExprMayBindToTemp = true;
8417 // FIXME: Check that expression type is complete/non-abstract; statement
8418 // expressions are not lvalues.
8419 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8420 if (StmtExprMayBindToTemp)
8421 return MaybeBindToTemporary(ResStmtExpr);
8422 return Owned(ResStmtExpr);
8425 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8426 TypeSourceInfo *TInfo,
8427 OffsetOfComponent *CompPtr,
8428 unsigned NumComponents,
8429 SourceLocation RParenLoc) {
8430 QualType ArgTy = TInfo->getType();
8431 bool Dependent = ArgTy->isDependentType();
8432 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8434 // We must have at least one component that refers to the type, and the first
8435 // one is known to be a field designator. Verify that the ArgTy represents
8436 // a struct/union/class.
8437 if (!Dependent && !ArgTy->isRecordType())
8438 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8439 << ArgTy << TypeRange);
8441 // Type must be complete per C99 7.17p3 because a declaring a variable
8442 // with an incomplete type would be ill-formed.
8443 if (!Dependent
8444 && RequireCompleteType(BuiltinLoc, ArgTy,
8445 PDiag(diag::err_offsetof_incomplete_type)
8446 << TypeRange))
8447 return ExprError();
8449 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8450 // GCC extension, diagnose them.
8451 // FIXME: This diagnostic isn't actually visible because the location is in
8452 // a system header!
8453 if (NumComponents != 1)
8454 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8455 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
8457 bool DidWarnAboutNonPOD = false;
8458 QualType CurrentType = ArgTy;
8459 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8460 llvm::SmallVector<OffsetOfNode, 4> Comps;
8461 llvm::SmallVector<Expr*, 4> Exprs;
8462 for (unsigned i = 0; i != NumComponents; ++i) {
8463 const OffsetOfComponent &OC = CompPtr[i];
8464 if (OC.isBrackets) {
8465 // Offset of an array sub-field. TODO: Should we allow vector elements?
8466 if (!CurrentType->isDependentType()) {
8467 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8468 if(!AT)
8469 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8470 << CurrentType);
8471 CurrentType = AT->getElementType();
8472 } else
8473 CurrentType = Context.DependentTy;
8475 // The expression must be an integral expression.
8476 // FIXME: An integral constant expression?
8477 Expr *Idx = static_cast<Expr*>(OC.U.E);
8478 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8479 !Idx->getType()->isIntegerType())
8480 return ExprError(Diag(Idx->getLocStart(),
8481 diag::err_typecheck_subscript_not_integer)
8482 << Idx->getSourceRange());
8484 // Record this array index.
8485 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8486 Exprs.push_back(Idx);
8487 continue;
8490 // Offset of a field.
8491 if (CurrentType->isDependentType()) {
8492 // We have the offset of a field, but we can't look into the dependent
8493 // type. Just record the identifier of the field.
8494 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8495 CurrentType = Context.DependentTy;
8496 continue;
8499 // We need to have a complete type to look into.
8500 if (RequireCompleteType(OC.LocStart, CurrentType,
8501 diag::err_offsetof_incomplete_type))
8502 return ExprError();
8504 // Look for the designated field.
8505 const RecordType *RC = CurrentType->getAs<RecordType>();
8506 if (!RC)
8507 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8508 << CurrentType);
8509 RecordDecl *RD = RC->getDecl();
8511 // C++ [lib.support.types]p5:
8512 // The macro offsetof accepts a restricted set of type arguments in this
8513 // International Standard. type shall be a POD structure or a POD union
8514 // (clause 9).
8515 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8516 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8517 DiagRuntimeBehavior(BuiltinLoc,
8518 PDiag(diag::warn_offsetof_non_pod_type)
8519 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8520 << CurrentType))
8521 DidWarnAboutNonPOD = true;
8524 // Look for the field.
8525 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8526 LookupQualifiedName(R, RD);
8527 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
8528 IndirectFieldDecl *IndirectMemberDecl = 0;
8529 if (!MemberDecl) {
8530 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
8531 MemberDecl = IndirectMemberDecl->getAnonField();
8534 if (!MemberDecl)
8535 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8536 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8537 OC.LocEnd));
8539 // C99 7.17p3:
8540 // (If the specified member is a bit-field, the behavior is undefined.)
8542 // We diagnose this as an error.
8543 if (MemberDecl->getBitWidth()) {
8544 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8545 << MemberDecl->getDeclName()
8546 << SourceRange(BuiltinLoc, RParenLoc);
8547 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8548 return ExprError();
8551 RecordDecl *Parent = MemberDecl->getParent();
8552 if (IndirectMemberDecl)
8553 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
8555 // If the member was found in a base class, introduce OffsetOfNodes for
8556 // the base class indirections.
8557 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8558 /*DetectVirtual=*/false);
8559 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
8560 CXXBasePath &Path = Paths.front();
8561 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8562 B != BEnd; ++B)
8563 Comps.push_back(OffsetOfNode(B->Base));
8566 if (IndirectMemberDecl) {
8567 for (IndirectFieldDecl::chain_iterator FI =
8568 IndirectMemberDecl->chain_begin(),
8569 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8570 assert(isa<FieldDecl>(*FI));
8571 Comps.push_back(OffsetOfNode(OC.LocStart,
8572 cast<FieldDecl>(*FI), OC.LocEnd));
8574 } else
8575 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
8577 CurrentType = MemberDecl->getType().getNonReferenceType();
8580 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8581 TInfo, Comps.data(), Comps.size(),
8582 Exprs.data(), Exprs.size(), RParenLoc));
8585 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
8586 SourceLocation BuiltinLoc,
8587 SourceLocation TypeLoc,
8588 ParsedType argty,
8589 OffsetOfComponent *CompPtr,
8590 unsigned NumComponents,
8591 SourceLocation RPLoc) {
8593 TypeSourceInfo *ArgTInfo;
8594 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8595 if (ArgTy.isNull())
8596 return ExprError();
8598 if (!ArgTInfo)
8599 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8601 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8602 RPLoc);
8606 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
8607 Expr *CondExpr,
8608 Expr *LHSExpr, Expr *RHSExpr,
8609 SourceLocation RPLoc) {
8610 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8612 ExprValueKind VK = VK_RValue;
8613 ExprObjectKind OK = OK_Ordinary;
8614 QualType resType;
8615 bool ValueDependent = false;
8616 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
8617 resType = Context.DependentTy;
8618 ValueDependent = true;
8619 } else {
8620 // The conditional expression is required to be a constant expression.
8621 llvm::APSInt condEval(32);
8622 SourceLocation ExpLoc;
8623 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
8624 return ExprError(Diag(ExpLoc,
8625 diag::err_typecheck_choose_expr_requires_constant)
8626 << CondExpr->getSourceRange());
8628 // If the condition is > zero, then the AST type is the same as the LSHExpr.
8629 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8631 resType = ActiveExpr->getType();
8632 ValueDependent = ActiveExpr->isValueDependent();
8633 VK = ActiveExpr->getValueKind();
8634 OK = ActiveExpr->getObjectKind();
8637 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
8638 resType, VK, OK, RPLoc,
8639 resType->isDependentType(),
8640 ValueDependent));
8643 //===----------------------------------------------------------------------===//
8644 // Clang Extensions.
8645 //===----------------------------------------------------------------------===//
8647 /// ActOnBlockStart - This callback is invoked when a block literal is started.
8648 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
8649 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8650 PushBlockScope(BlockScope, Block);
8651 CurContext->addDecl(Block);
8652 if (BlockScope)
8653 PushDeclContext(BlockScope, Block);
8654 else
8655 CurContext = Block;
8658 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
8659 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
8660 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
8661 BlockScopeInfo *CurBlock = getCurBlock();
8663 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
8664 QualType T = Sig->getType();
8666 // GetTypeForDeclarator always produces a function type for a block
8667 // literal signature. Furthermore, it is always a FunctionProtoType
8668 // unless the function was written with a typedef.
8669 assert(T->isFunctionType() &&
8670 "GetTypeForDeclarator made a non-function block signature");
8672 // Look for an explicit signature in that function type.
8673 FunctionProtoTypeLoc ExplicitSignature;
8675 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8676 if (isa<FunctionProtoTypeLoc>(tmp)) {
8677 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8679 // Check whether that explicit signature was synthesized by
8680 // GetTypeForDeclarator. If so, don't save that as part of the
8681 // written signature.
8682 if (ExplicitSignature.getLParenLoc() ==
8683 ExplicitSignature.getRParenLoc()) {
8684 // This would be much cheaper if we stored TypeLocs instead of
8685 // TypeSourceInfos.
8686 TypeLoc Result = ExplicitSignature.getResultLoc();
8687 unsigned Size = Result.getFullDataSize();
8688 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8689 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8691 ExplicitSignature = FunctionProtoTypeLoc();
8695 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8696 CurBlock->FunctionType = T;
8698 const FunctionType *Fn = T->getAs<FunctionType>();
8699 QualType RetTy = Fn->getResultType();
8700 bool isVariadic =
8701 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8703 CurBlock->TheDecl->setIsVariadic(isVariadic);
8705 // Don't allow returning a objc interface by value.
8706 if (RetTy->isObjCObjectType()) {
8707 Diag(ParamInfo.getSourceRange().getBegin(),
8708 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8709 return;
8712 // Context.DependentTy is used as a placeholder for a missing block
8713 // return type. TODO: what should we do with declarators like:
8714 // ^ * { ... }
8715 // If the answer is "apply template argument deduction"....
8716 if (RetTy != Context.DependentTy)
8717 CurBlock->ReturnType = RetTy;
8719 // Push block parameters from the declarator if we had them.
8720 llvm::SmallVector<ParmVarDecl*, 8> Params;
8721 if (ExplicitSignature) {
8722 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8723 ParmVarDecl *Param = ExplicitSignature.getArg(I);
8724 if (Param->getIdentifier() == 0 &&
8725 !Param->isImplicit() &&
8726 !Param->isInvalidDecl() &&
8727 !getLangOptions().CPlusPlus)
8728 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8729 Params.push_back(Param);
8732 // Fake up parameter variables if we have a typedef, like
8733 // ^ fntype { ... }
8734 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8735 for (FunctionProtoType::arg_type_iterator
8736 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8737 ParmVarDecl *Param =
8738 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8739 ParamInfo.getSourceRange().getBegin(),
8740 *I);
8741 Params.push_back(Param);
8745 // Set the parameters on the block decl.
8746 if (!Params.empty()) {
8747 CurBlock->TheDecl->setParams(Params.data(), Params.size());
8748 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8749 CurBlock->TheDecl->param_end(),
8750 /*CheckParameterNames=*/false);
8753 // Finally we can process decl attributes.
8754 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
8756 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
8757 Diag(ParamInfo.getAttributes()->getLoc(),
8758 diag::warn_attribute_sentinel_not_variadic) << 1;
8759 // FIXME: remove the attribute.
8762 // Put the parameter variables in scope. We can bail out immediately
8763 // if we don't have any.
8764 if (Params.empty())
8765 return;
8767 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
8768 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8769 (*AI)->setOwningFunction(CurBlock->TheDecl);
8771 // If this has an identifier, add it to the scope stack.
8772 if ((*AI)->getIdentifier()) {
8773 CheckShadow(CurBlock->TheScope, *AI);
8775 PushOnScopeChains(*AI, CurBlock->TheScope);
8780 /// ActOnBlockError - If there is an error parsing a block, this callback
8781 /// is invoked to pop the information about the block from the action impl.
8782 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
8783 // Pop off CurBlock, handle nested blocks.
8784 PopDeclContext();
8785 PopFunctionOrBlockScope();
8788 /// ActOnBlockStmtExpr - This is called when the body of a block statement
8789 /// literal was successfully completed. ^(int x){...}
8790 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
8791 Stmt *Body, Scope *CurScope) {
8792 // If blocks are disabled, emit an error.
8793 if (!LangOpts.Blocks)
8794 Diag(CaretLoc, diag::err_blocks_disable);
8796 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
8798 PopDeclContext();
8800 QualType RetTy = Context.VoidTy;
8801 if (!BSI->ReturnType.isNull())
8802 RetTy = BSI->ReturnType;
8804 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
8805 QualType BlockTy;
8807 // Set the captured variables on the block.
8808 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8809 BSI->CapturesCXXThis);
8811 // If the user wrote a function type in some form, try to use that.
8812 if (!BSI->FunctionType.isNull()) {
8813 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8815 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8816 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8818 // Turn protoless block types into nullary block types.
8819 if (isa<FunctionNoProtoType>(FTy)) {
8820 FunctionProtoType::ExtProtoInfo EPI;
8821 EPI.ExtInfo = Ext;
8822 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8824 // Otherwise, if we don't need to change anything about the function type,
8825 // preserve its sugar structure.
8826 } else if (FTy->getResultType() == RetTy &&
8827 (!NoReturn || FTy->getNoReturnAttr())) {
8828 BlockTy = BSI->FunctionType;
8830 // Otherwise, make the minimal modifications to the function type.
8831 } else {
8832 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
8833 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8834 EPI.TypeQuals = 0; // FIXME: silently?
8835 EPI.ExtInfo = Ext;
8836 BlockTy = Context.getFunctionType(RetTy,
8837 FPT->arg_type_begin(),
8838 FPT->getNumArgs(),
8839 EPI);
8842 // If we don't have a function type, just build one from nothing.
8843 } else {
8844 FunctionProtoType::ExtProtoInfo EPI;
8845 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8846 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8849 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8850 BSI->TheDecl->param_end());
8851 BlockTy = Context.getBlockPointerType(BlockTy);
8853 // If needed, diagnose invalid gotos and switches in the block.
8854 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
8855 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
8857 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
8859 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8861 // Issue any analysis-based warnings.
8862 const sema::AnalysisBasedWarnings::Policy &WP =
8863 AnalysisWarnings.getDefaultPolicy();
8864 AnalysisWarnings.IssueWarnings(WP, Result);
8866 PopFunctionOrBlockScope();
8867 return Owned(Result);
8870 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
8871 Expr *expr, ParsedType type,
8872 SourceLocation RPLoc) {
8873 TypeSourceInfo *TInfo;
8874 GetTypeFromParser(type, &TInfo);
8875 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
8878 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
8879 Expr *E, TypeSourceInfo *TInfo,
8880 SourceLocation RPLoc) {
8881 Expr *OrigExpr = E;
8883 // Get the va_list type
8884 QualType VaListType = Context.getBuiltinVaListType();
8885 if (VaListType->isArrayType()) {
8886 // Deal with implicit array decay; for example, on x86-64,
8887 // va_list is an array, but it's supposed to decay to
8888 // a pointer for va_arg.
8889 VaListType = Context.getArrayDecayedType(VaListType);
8890 // Make sure the input expression also decays appropriately.
8891 UsualUnaryConversions(E);
8892 } else {
8893 // Otherwise, the va_list argument must be an l-value because
8894 // it is modified by va_arg.
8895 if (!E->isTypeDependent() &&
8896 CheckForModifiableLvalue(E, BuiltinLoc, *this))
8897 return ExprError();
8900 if (!E->isTypeDependent() &&
8901 !Context.hasSameType(VaListType, E->getType())) {
8902 return ExprError(Diag(E->getLocStart(),
8903 diag::err_first_argument_to_va_arg_not_of_type_va_list)
8904 << OrigExpr->getType() << E->getSourceRange());
8907 // FIXME: Check that type is complete/non-abstract
8908 // FIXME: Warn if a non-POD type is passed in.
8910 QualType T = TInfo->getType().getNonLValueExprType(Context);
8911 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
8914 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
8915 // The type of __null will be int or long, depending on the size of
8916 // pointers on the target.
8917 QualType Ty;
8918 unsigned pw = Context.Target.getPointerWidth(0);
8919 if (pw == Context.Target.getIntWidth())
8920 Ty = Context.IntTy;
8921 else if (pw == Context.Target.getLongWidth())
8922 Ty = Context.LongTy;
8923 else if (pw == Context.Target.getLongLongWidth())
8924 Ty = Context.LongLongTy;
8925 else {
8926 assert(!"I don't know size of pointer!");
8927 Ty = Context.IntTy;
8930 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
8933 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
8934 Expr *SrcExpr, FixItHint &Hint) {
8935 if (!SemaRef.getLangOptions().ObjC1)
8936 return;
8938 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8939 if (!PT)
8940 return;
8942 // Check if the destination is of type 'id'.
8943 if (!PT->isObjCIdType()) {
8944 // Check if the destination is the 'NSString' interface.
8945 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8946 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8947 return;
8950 // Strip off any parens and casts.
8951 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8952 if (!SL || SL->isWide())
8953 return;
8955 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
8958 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8959 SourceLocation Loc,
8960 QualType DstType, QualType SrcType,
8961 Expr *SrcExpr, AssignmentAction Action,
8962 bool *Complained) {
8963 if (Complained)
8964 *Complained = false;
8966 // Decode the result (notice that AST's are still created for extensions).
8967 bool isInvalid = false;
8968 unsigned DiagKind;
8969 FixItHint Hint;
8971 switch (ConvTy) {
8972 default: assert(0 && "Unknown conversion type");
8973 case Compatible: return false;
8974 case PointerToInt:
8975 DiagKind = diag::ext_typecheck_convert_pointer_int;
8976 break;
8977 case IntToPointer:
8978 DiagKind = diag::ext_typecheck_convert_int_pointer;
8979 break;
8980 case IncompatiblePointer:
8981 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
8982 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8983 break;
8984 case IncompatiblePointerSign:
8985 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8986 break;
8987 case FunctionVoidPointer:
8988 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8989 break;
8990 case IncompatiblePointerDiscardsQualifiers: {
8991 // Perform array-to-pointer decay if necessary.
8992 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8994 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8995 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8996 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8997 DiagKind = diag::err_typecheck_incompatible_address_space;
8998 break;
9001 llvm_unreachable("unknown error case for discarding qualifiers!");
9002 // fallthrough
9004 case CompatiblePointerDiscardsQualifiers:
9005 // If the qualifiers lost were because we were applying the
9006 // (deprecated) C++ conversion from a string literal to a char*
9007 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9008 // Ideally, this check would be performed in
9009 // checkPointerTypesForAssignment. However, that would require a
9010 // bit of refactoring (so that the second argument is an
9011 // expression, rather than a type), which should be done as part
9012 // of a larger effort to fix checkPointerTypesForAssignment for
9013 // C++ semantics.
9014 if (getLangOptions().CPlusPlus &&
9015 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9016 return false;
9017 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9018 break;
9019 case IncompatibleNestedPointerQualifiers:
9020 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9021 break;
9022 case IntToBlockPointer:
9023 DiagKind = diag::err_int_to_block_pointer;
9024 break;
9025 case IncompatibleBlockPointer:
9026 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9027 break;
9028 case IncompatibleObjCQualifiedId:
9029 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9030 // it can give a more specific diagnostic.
9031 DiagKind = diag::warn_incompatible_qualified_id;
9032 break;
9033 case IncompatibleVectors:
9034 DiagKind = diag::warn_incompatible_vectors;
9035 break;
9036 case Incompatible:
9037 DiagKind = diag::err_typecheck_convert_incompatible;
9038 isInvalid = true;
9039 break;
9042 QualType FirstType, SecondType;
9043 switch (Action) {
9044 case AA_Assigning:
9045 case AA_Initializing:
9046 // The destination type comes first.
9047 FirstType = DstType;
9048 SecondType = SrcType;
9049 break;
9051 case AA_Returning:
9052 case AA_Passing:
9053 case AA_Converting:
9054 case AA_Sending:
9055 case AA_Casting:
9056 // The source type comes first.
9057 FirstType = SrcType;
9058 SecondType = DstType;
9059 break;
9062 Diag(Loc, DiagKind) << FirstType << SecondType << Action
9063 << SrcExpr->getSourceRange() << Hint;
9064 if (Complained)
9065 *Complained = true;
9066 return isInvalid;
9069 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
9070 llvm::APSInt ICEResult;
9071 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9072 if (Result)
9073 *Result = ICEResult;
9074 return false;
9077 Expr::EvalResult EvalResult;
9079 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
9080 EvalResult.HasSideEffects) {
9081 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9083 if (EvalResult.Diag) {
9084 // We only show the note if it's not the usual "invalid subexpression"
9085 // or if it's actually in a subexpression.
9086 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9087 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9088 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9091 return true;
9094 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9095 E->getSourceRange();
9097 if (EvalResult.Diag &&
9098 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9099 != Diagnostic::Ignored)
9100 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9102 if (Result)
9103 *Result = EvalResult.Val.getInt();
9104 return false;
9107 void
9108 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
9109 ExprEvalContexts.push_back(
9110 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
9113 void
9114 Sema::PopExpressionEvaluationContext() {
9115 // Pop the current expression evaluation context off the stack.
9116 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9117 ExprEvalContexts.pop_back();
9119 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9120 if (Rec.PotentiallyReferenced) {
9121 // Mark any remaining declarations in the current position of the stack
9122 // as "referenced". If they were not meant to be referenced, semantic
9123 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
9124 for (PotentiallyReferencedDecls::iterator
9125 I = Rec.PotentiallyReferenced->begin(),
9126 IEnd = Rec.PotentiallyReferenced->end();
9127 I != IEnd; ++I)
9128 MarkDeclarationReferenced(I->first, I->second);
9131 if (Rec.PotentiallyDiagnosed) {
9132 // Emit any pending diagnostics.
9133 for (PotentiallyEmittedDiagnostics::iterator
9134 I = Rec.PotentiallyDiagnosed->begin(),
9135 IEnd = Rec.PotentiallyDiagnosed->end();
9136 I != IEnd; ++I)
9137 Diag(I->first, I->second);
9141 // When are coming out of an unevaluated context, clear out any
9142 // temporaries that we may have created as part of the evaluation of
9143 // the expression in that context: they aren't relevant because they
9144 // will never be constructed.
9145 if (Rec.Context == Unevaluated &&
9146 ExprTemporaries.size() > Rec.NumTemporaries)
9147 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9148 ExprTemporaries.end());
9150 // Destroy the popped expression evaluation record.
9151 Rec.Destroy();
9154 /// \brief Note that the given declaration was referenced in the source code.
9156 /// This routine should be invoke whenever a given declaration is referenced
9157 /// in the source code, and where that reference occurred. If this declaration
9158 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9159 /// C99 6.9p3), then the declaration will be marked as used.
9161 /// \param Loc the location where the declaration was referenced.
9163 /// \param D the declaration that has been referenced by the source code.
9164 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9165 assert(D && "No declaration?");
9167 if (D->isUsed(false))
9168 return;
9170 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9171 // template or not. The reason for this is that unevaluated expressions
9172 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9173 // -Wunused-parameters)
9174 if (isa<ParmVarDecl>(D) ||
9175 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
9176 D->setUsed();
9177 return;
9180 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9181 return;
9183 // Do not mark anything as "used" within a dependent context; wait for
9184 // an instantiation.
9185 if (CurContext->isDependentContext())
9186 return;
9188 switch (ExprEvalContexts.back().Context) {
9189 case Unevaluated:
9190 // We are in an expression that is not potentially evaluated; do nothing.
9191 return;
9193 case PotentiallyEvaluated:
9194 // We are in a potentially-evaluated expression, so this declaration is
9195 // "used"; handle this below.
9196 break;
9198 case PotentiallyPotentiallyEvaluated:
9199 // We are in an expression that may be potentially evaluated; queue this
9200 // declaration reference until we know whether the expression is
9201 // potentially evaluated.
9202 ExprEvalContexts.back().addReferencedDecl(Loc, D);
9203 return;
9205 case PotentiallyEvaluatedIfUsed:
9206 // Referenced declarations will only be used if the construct in the
9207 // containing expression is used.
9208 return;
9211 // Note that this declaration has been used.
9212 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
9213 unsigned TypeQuals;
9214 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
9215 if (Constructor->getParent()->hasTrivialConstructor())
9216 return;
9217 if (!Constructor->isUsed(false))
9218 DefineImplicitDefaultConstructor(Loc, Constructor);
9219 } else if (Constructor->isImplicit() &&
9220 Constructor->isCopyConstructor(TypeQuals)) {
9221 if (!Constructor->isUsed(false))
9222 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9225 MarkVTableUsed(Loc, Constructor->getParent());
9226 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
9227 if (Destructor->isImplicit() && !Destructor->isUsed(false))
9228 DefineImplicitDestructor(Loc, Destructor);
9229 if (Destructor->isVirtual())
9230 MarkVTableUsed(Loc, Destructor->getParent());
9231 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9232 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9233 MethodDecl->getOverloadedOperator() == OO_Equal) {
9234 if (!MethodDecl->isUsed(false))
9235 DefineImplicitCopyAssignment(Loc, MethodDecl);
9236 } else if (MethodDecl->isVirtual())
9237 MarkVTableUsed(Loc, MethodDecl->getParent());
9239 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
9240 // Implicit instantiation of function templates and member functions of
9241 // class templates.
9242 if (Function->isImplicitlyInstantiable()) {
9243 bool AlreadyInstantiated = false;
9244 if (FunctionTemplateSpecializationInfo *SpecInfo
9245 = Function->getTemplateSpecializationInfo()) {
9246 if (SpecInfo->getPointOfInstantiation().isInvalid())
9247 SpecInfo->setPointOfInstantiation(Loc);
9248 else if (SpecInfo->getTemplateSpecializationKind()
9249 == TSK_ImplicitInstantiation)
9250 AlreadyInstantiated = true;
9251 } else if (MemberSpecializationInfo *MSInfo
9252 = Function->getMemberSpecializationInfo()) {
9253 if (MSInfo->getPointOfInstantiation().isInvalid())
9254 MSInfo->setPointOfInstantiation(Loc);
9255 else if (MSInfo->getTemplateSpecializationKind()
9256 == TSK_ImplicitInstantiation)
9257 AlreadyInstantiated = true;
9260 if (!AlreadyInstantiated) {
9261 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9262 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9263 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9264 Loc));
9265 else
9266 PendingInstantiations.push_back(std::make_pair(Function, Loc));
9268 } else // Walk redefinitions, as some of them may be instantiable.
9269 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9270 e(Function->redecls_end()); i != e; ++i) {
9271 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9272 MarkDeclarationReferenced(Loc, *i);
9275 // FIXME: keep track of references to static functions
9277 // Recursive functions should be marked when used from another function.
9278 if (CurContext != Function)
9279 Function->setUsed(true);
9281 return;
9284 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
9285 // Implicit instantiation of static data members of class templates.
9286 if (Var->isStaticDataMember() &&
9287 Var->getInstantiatedFromStaticDataMember()) {
9288 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9289 assert(MSInfo && "Missing member specialization information?");
9290 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9291 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9292 MSInfo->setPointOfInstantiation(Loc);
9293 PendingInstantiations.push_back(std::make_pair(Var, Loc));
9297 // FIXME: keep track of references to static data?
9299 D->setUsed(true);
9300 return;
9304 namespace {
9305 // Mark all of the declarations referenced
9306 // FIXME: Not fully implemented yet! We need to have a better understanding
9307 // of when we're entering
9308 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9309 Sema &S;
9310 SourceLocation Loc;
9312 public:
9313 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
9315 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
9317 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9318 bool TraverseRecordType(RecordType *T);
9322 bool MarkReferencedDecls::TraverseTemplateArgument(
9323 const TemplateArgument &Arg) {
9324 if (Arg.getKind() == TemplateArgument::Declaration) {
9325 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9328 return Inherited::TraverseTemplateArgument(Arg);
9331 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
9332 if (ClassTemplateSpecializationDecl *Spec
9333 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9334 const TemplateArgumentList &Args = Spec->getTemplateArgs();
9335 return TraverseTemplateArguments(Args.data(), Args.size());
9338 return true;
9341 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9342 MarkReferencedDecls Marker(*this, Loc);
9343 Marker.TraverseType(Context.getCanonicalType(T));
9346 namespace {
9347 /// \brief Helper class that marks all of the declarations referenced by
9348 /// potentially-evaluated subexpressions as "referenced".
9349 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9350 Sema &S;
9352 public:
9353 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9355 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9357 void VisitDeclRefExpr(DeclRefExpr *E) {
9358 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9361 void VisitMemberExpr(MemberExpr *E) {
9362 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
9363 Inherited::VisitMemberExpr(E);
9366 void VisitCXXNewExpr(CXXNewExpr *E) {
9367 if (E->getConstructor())
9368 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9369 if (E->getOperatorNew())
9370 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9371 if (E->getOperatorDelete())
9372 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9373 Inherited::VisitCXXNewExpr(E);
9376 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9377 if (E->getOperatorDelete())
9378 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9379 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9380 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9381 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9382 S.MarkDeclarationReferenced(E->getLocStart(),
9383 S.LookupDestructor(Record));
9386 Inherited::VisitCXXDeleteExpr(E);
9389 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9390 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9391 Inherited::VisitCXXConstructExpr(E);
9394 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9395 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9398 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9399 Visit(E->getExpr());
9404 /// \brief Mark any declarations that appear within this expression or any
9405 /// potentially-evaluated subexpressions as "referenced".
9406 void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9407 EvaluatedExprMarker(*this).Visit(E);
9410 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
9411 /// of the program being compiled.
9413 /// This routine emits the given diagnostic when the code currently being
9414 /// type-checked is "potentially evaluated", meaning that there is a
9415 /// possibility that the code will actually be executable. Code in sizeof()
9416 /// expressions, code used only during overload resolution, etc., are not
9417 /// potentially evaluated. This routine will suppress such diagnostics or,
9418 /// in the absolutely nutty case of potentially potentially evaluated
9419 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
9420 /// later.
9422 /// This routine should be used for all diagnostics that describe the run-time
9423 /// behavior of a program, such as passing a non-POD value through an ellipsis.
9424 /// Failure to do so will likely result in spurious diagnostics or failures
9425 /// during overload resolution or within sizeof/alignof/typeof/typeid.
9426 bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
9427 const PartialDiagnostic &PD) {
9428 switch (ExprEvalContexts.back().Context ) {
9429 case Unevaluated:
9430 // The argument will never be evaluated, so don't complain.
9431 break;
9433 case PotentiallyEvaluated:
9434 case PotentiallyEvaluatedIfUsed:
9435 Diag(Loc, PD);
9436 return true;
9438 case PotentiallyPotentiallyEvaluated:
9439 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9440 break;
9443 return false;
9446 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9447 CallExpr *CE, FunctionDecl *FD) {
9448 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9449 return false;
9451 PartialDiagnostic Note =
9452 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9453 << FD->getDeclName() : PDiag();
9454 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
9456 if (RequireCompleteType(Loc, ReturnType,
9457 FD ?
9458 PDiag(diag::err_call_function_incomplete_return)
9459 << CE->getSourceRange() << FD->getDeclName() :
9460 PDiag(diag::err_call_incomplete_return)
9461 << CE->getSourceRange(),
9462 std::make_pair(NoteLoc, Note)))
9463 return true;
9465 return false;
9468 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
9469 // will prevent this condition from triggering, which is what we want.
9470 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9471 SourceLocation Loc;
9473 unsigned diagnostic = diag::warn_condition_is_assignment;
9474 bool IsOrAssign = false;
9476 if (isa<BinaryOperator>(E)) {
9477 BinaryOperator *Op = cast<BinaryOperator>(E);
9478 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
9479 return;
9481 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9483 // Greylist some idioms by putting them into a warning subcategory.
9484 if (ObjCMessageExpr *ME
9485 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9486 Selector Sel = ME->getSelector();
9488 // self = [<foo> init...]
9489 if (isSelfExpr(Op->getLHS())
9490 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9491 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9493 // <foo> = [<bar> nextObject]
9494 else if (Sel.isUnarySelector() &&
9495 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9496 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9499 Loc = Op->getOperatorLoc();
9500 } else if (isa<CXXOperatorCallExpr>(E)) {
9501 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
9502 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
9503 return;
9505 IsOrAssign = Op->getOperator() == OO_PipeEqual;
9506 Loc = Op->getOperatorLoc();
9507 } else {
9508 // Not an assignment.
9509 return;
9512 SourceLocation Open = E->getSourceRange().getBegin();
9513 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9515 Diag(Loc, diagnostic) << E->getSourceRange();
9517 if (IsOrAssign)
9518 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9519 << FixItHint::CreateReplacement(Loc, "!=");
9520 else
9521 Diag(Loc, diag::note_condition_assign_to_comparison)
9522 << FixItHint::CreateReplacement(Loc, "==");
9524 Diag(Loc, diag::note_condition_assign_silence)
9525 << FixItHint::CreateInsertion(Open, "(")
9526 << FixItHint::CreateInsertion(Close, ")");
9529 /// \brief Redundant parentheses over an equality comparison can indicate
9530 /// that the user intended an assignment used as condition.
9531 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
9532 // Don't warn if the parens came from a macro.
9533 SourceLocation parenLoc = parenE->getLocStart();
9534 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9535 return;
9537 Expr *E = parenE->IgnoreParens();
9539 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
9540 if (opE->getOpcode() == BO_EQ &&
9541 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9542 == Expr::MLV_Valid) {
9543 SourceLocation Loc = opE->getOperatorLoc();
9545 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9546 Diag(Loc, diag::note_equality_comparison_to_assign)
9547 << FixItHint::CreateReplacement(Loc, "=");
9548 Diag(Loc, diag::note_equality_comparison_silence)
9549 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9550 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
9554 bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9555 DiagnoseAssignmentAsCondition(E);
9556 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9557 DiagnoseEqualityWithExtraParens(parenE);
9559 if (!E->isTypeDependent()) {
9560 if (E->isBoundMemberFunction(Context))
9561 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9562 << E->getSourceRange();
9564 if (getLangOptions().CPlusPlus)
9565 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9567 DefaultFunctionArrayLvalueConversion(E);
9569 QualType T = E->getType();
9570 if (!T->isScalarType()) // C99 6.8.4.1p1
9571 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9572 << T << E->getSourceRange();
9575 return false;
9578 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9579 Expr *Sub) {
9580 if (!Sub)
9581 return ExprError();
9583 if (CheckBooleanCondition(Sub, Loc))
9584 return ExprError();
9586 return Owned(Sub);
9589 /// Check for operands with placeholder types and complain if found.
9590 /// Returns true if there was an error and no recovery was possible.
9591 ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9592 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9593 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9595 // If this is overload, check for a single overload.
9596 if (BT->getKind() == BuiltinType::Overload) {
9597 if (FunctionDecl *Specialization
9598 = ResolveSingleFunctionTemplateSpecialization(E)) {
9599 // The access doesn't really matter in this case.
9600 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9601 Specialization->getAccess());
9602 E = FixOverloadedFunctionReference(E, Found, Specialization);
9603 if (!E) return ExprError();
9604 return Owned(E);
9607 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
9608 return ExprError();
9611 // Otherwise it's a use of undeduced auto.
9612 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9614 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9615 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9616 << DRE->getDecl() << E->getSourceRange();
9617 return ExprError();