1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
;
43 /// \brief Determine whether the use of this declaration is valid, and
44 /// emit any corresponding diagnostics.
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.
52 /// If IgnoreDeprecated is set to true, this should not want about deprecated
55 /// \returns true if there was an error (this declaration cannot be
56 /// referenced), false otherwise.
58 bool Sema::DiagnoseUseOfDecl(NamedDecl
*D
, SourceLocation Loc
) {
59 if (getLangOptions().CPlusPlus
&& isa
<FunctionDecl
>(D
)) {
60 // If there were any diagnostics suppressed by template argument deduction,
62 llvm::DenseMap
<Decl
*, llvm::SmallVector
<PartialDiagnosticAt
, 1> >::iterator
63 Pos
= SuppressedDiagnostics
.find(D
->getCanonicalDecl());
64 if (Pos
!= SuppressedDiagnostics
.end()) {
65 llvm::SmallVectorImpl
<PartialDiagnosticAt
> &Suppressed
= Pos
->second
;
66 for (unsigned I
= 0, N
= Suppressed
.size(); I
!= N
; ++I
)
67 Diag(Suppressed
[I
].first
, Suppressed
[I
].second
);
69 // Clear out the list of suppressed diagnostics, so that we don't emit
70 // them again for this specialization. However, we don't remove this
71 // entry from the table, because we want to avoid ever emitting these
77 // See if the decl is deprecated.
78 if (const DeprecatedAttr
*DA
= D
->getAttr
<DeprecatedAttr
>())
79 EmitDeprecationWarning(D
, DA
->getMessage(), Loc
);
81 // See if the decl is unavailable
82 if (const UnavailableAttr
*UA
= D
->getAttr
<UnavailableAttr
>()) {
83 if (UA
->getMessage().empty())
84 Diag(Loc
, diag::err_unavailable
) << D
->getDeclName();
86 Diag(Loc
, diag::err_unavailable_message
)
87 << D
->getDeclName() << UA
->getMessage();
88 Diag(D
->getLocation(), diag::note_unavailable_here
) << 0;
91 // See if this is a deleted function.
92 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
93 if (FD
->isDeleted()) {
94 Diag(Loc
, diag::err_deleted_function_use
);
95 Diag(D
->getLocation(), diag::note_unavailable_here
) << true;
100 // Warn if this is used but marked unused.
101 if (D
->hasAttr
<UnusedAttr
>())
102 Diag(Loc
, diag::warn_used_but_marked_unused
) << D
->getDeclName();
107 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
108 /// (and other functions in future), which have been declared with sentinel
109 /// attribute. It warns if call does not have the sentinel argument.
111 void Sema::DiagnoseSentinelCalls(NamedDecl
*D
, SourceLocation Loc
,
112 Expr
**Args
, unsigned NumArgs
) {
113 const SentinelAttr
*attr
= D
->getAttr
<SentinelAttr
>();
117 // FIXME: In C++0x, if any of the arguments are parameter pack
118 // expansions, we can't check for the sentinel now.
119 int sentinelPos
= attr
->getSentinel();
120 int nullPos
= attr
->getNullPos();
122 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
123 // base class. Then we won't be needing two versions of the same code.
125 bool warnNotEnoughArgs
= false;
127 if (ObjCMethodDecl
*MD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
128 // skip over named parameters.
129 ObjCMethodDecl::param_iterator P
, E
= MD
->param_end();
130 for (P
= MD
->param_begin(); (P
!= E
&& i
< NumArgs
); ++P
) {
136 warnNotEnoughArgs
= (P
!= E
|| i
>= NumArgs
);
138 } else if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
139 // skip over named parameters.
140 ObjCMethodDecl::param_iterator P
, E
= FD
->param_end();
141 for (P
= FD
->param_begin(); (P
!= E
&& i
< NumArgs
); ++P
) {
147 warnNotEnoughArgs
= (P
!= E
|| i
>= NumArgs
);
148 } else if (VarDecl
*V
= dyn_cast
<VarDecl
>(D
)) {
149 // block or function pointer call.
150 QualType Ty
= V
->getType();
151 if (Ty
->isBlockPointerType() || Ty
->isFunctionPointerType()) {
152 const FunctionType
*FT
= Ty
->isFunctionPointerType()
153 ? Ty
->getAs
<PointerType
>()->getPointeeType()->getAs
<FunctionType
>()
154 : Ty
->getAs
<BlockPointerType
>()->getPointeeType()->getAs
<FunctionType
>();
155 if (const FunctionProtoType
*Proto
= dyn_cast
<FunctionProtoType
>(FT
)) {
156 unsigned NumArgsInProto
= Proto
->getNumArgs();
158 for (k
= 0; (k
!= NumArgsInProto
&& i
< NumArgs
); k
++) {
164 warnNotEnoughArgs
= (k
!= NumArgsInProto
|| i
>= NumArgs
);
166 if (Ty
->isBlockPointerType())
173 if (warnNotEnoughArgs
) {
174 Diag(Loc
, diag::warn_not_enough_argument
) << D
->getDeclName();
175 Diag(D
->getLocation(), diag::note_sentinel_here
) << isMethod
;
179 while (sentinelPos
> 0 && i
< NumArgs
-1) {
183 if (sentinelPos
> 0) {
184 Diag(Loc
, diag::warn_not_enough_argument
) << D
->getDeclName();
185 Diag(D
->getLocation(), diag::note_sentinel_here
) << isMethod
;
188 while (i
< NumArgs
-1) {
192 Expr
*sentinelExpr
= Args
[sentinel
];
193 if (!sentinelExpr
) return;
194 if (sentinelExpr
->isTypeDependent()) return;
195 if (sentinelExpr
->isValueDependent()) return;
197 // nullptr_t is always treated as null.
198 if (sentinelExpr
->getType()->isNullPtrType()) return;
200 if (sentinelExpr
->getType()->isAnyPointerType() &&
201 sentinelExpr
->IgnoreParenCasts()->isNullPointerConstant(Context
,
202 Expr::NPC_ValueDependentIsNull
))
205 // Unfortunately, __null has type 'int'.
206 if (isa
<GNUNullExpr
>(sentinelExpr
)) return;
208 Diag(Loc
, diag::warn_missing_sentinel
) << isMethod
;
209 Diag(D
->getLocation(), diag::note_sentinel_here
) << isMethod
;
212 SourceRange
Sema::getExprRange(ExprTy
*E
) const {
213 Expr
*Ex
= (Expr
*)E
;
214 return Ex
? Ex
->getSourceRange() : SourceRange();
217 //===----------------------------------------------------------------------===//
218 // Standard Promotions and Conversions
219 //===----------------------------------------------------------------------===//
221 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
222 void Sema::DefaultFunctionArrayConversion(Expr
*&E
) {
223 QualType Ty
= E
->getType();
224 assert(!Ty
.isNull() && "DefaultFunctionArrayConversion - missing type");
226 if (Ty
->isFunctionType())
227 ImpCastExprToType(E
, Context
.getPointerType(Ty
),
228 CK_FunctionToPointerDecay
);
229 else if (Ty
->isArrayType()) {
230 // In C90 mode, arrays only promote to pointers if the array expression is
231 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
232 // type 'array of type' is converted to an expression that has type 'pointer
233 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
234 // that has type 'array of type' ...". The relevant change is "an lvalue"
235 // (C90) to "an expression" (C99).
238 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
239 // T" can be converted to an rvalue of type "pointer to T".
241 if (getLangOptions().C99
|| getLangOptions().CPlusPlus
||
242 E
->isLvalue(Context
) == Expr::LV_Valid
)
243 ImpCastExprToType(E
, Context
.getArrayDecayedType(Ty
),
244 CK_ArrayToPointerDecay
);
248 void Sema::DefaultFunctionArrayLvalueConversion(Expr
*&E
) {
249 DefaultFunctionArrayConversion(E
);
251 QualType Ty
= E
->getType();
252 assert(!Ty
.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
253 if (!Ty
->isDependentType() && Ty
.hasQualifiers() &&
254 (!getLangOptions().CPlusPlus
|| !Ty
->isRecordType()) &&
255 E
->isLvalue(Context
) == Expr::LV_Valid
) {
256 // C++ [conv.lval]p1:
257 // [...] If T is a non-class type, the type of the rvalue is the
258 // cv-unqualified version of T. Otherwise, the type of the
262 // If the lvalue has qualified type, the value has the unqualified
263 // version of the type of the lvalue; otherwise, the value has the
264 // type of the lvalue.
265 ImpCastExprToType(E
, Ty
.getUnqualifiedType(), CK_NoOp
);
270 /// UsualUnaryConversions - Performs various conversions that are common to most
271 /// operators (C99 6.3). The conversions of array and function types are
272 /// sometimes surpressed. For example, the array->pointer conversion doesn't
273 /// apply if the array is an argument to the sizeof or address (&) operators.
274 /// In these instances, this routine should *not* be called.
275 Expr
*Sema::UsualUnaryConversions(Expr
*&Expr
) {
276 QualType Ty
= Expr
->getType();
277 assert(!Ty
.isNull() && "UsualUnaryConversions - missing type");
281 // The following may be used in an expression wherever an int or
282 // unsigned int may be used:
283 // - an object or expression with an integer type whose integer
284 // conversion rank is less than or equal to the rank of int
286 // - A bit-field of type _Bool, int, signed int, or unsigned int.
288 // If an int can represent all values of the original type, the
289 // value is converted to an int; otherwise, it is converted to an
290 // unsigned int. These are called the integer promotions. All
291 // other types are unchanged by the integer promotions.
292 QualType PTy
= Context
.isPromotableBitField(Expr
);
294 ImpCastExprToType(Expr
, PTy
, CK_IntegralCast
);
297 if (Ty
->isPromotableIntegerType()) {
298 QualType PT
= Context
.getPromotedIntegerType(Ty
);
299 ImpCastExprToType(Expr
, PT
, CK_IntegralCast
);
303 DefaultFunctionArrayLvalueConversion(Expr
);
307 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
308 /// do not have a prototype. Arguments that have type float are promoted to
309 /// double. All other argument types are converted by UsualUnaryConversions().
310 void Sema::DefaultArgumentPromotion(Expr
*&Expr
) {
311 QualType Ty
= Expr
->getType();
312 assert(!Ty
.isNull() && "DefaultArgumentPromotion - missing type");
314 // If this is a 'float' (CVR qualified or typedef) promote to double.
315 if (Ty
->isSpecificBuiltinType(BuiltinType::Float
))
316 return ImpCastExprToType(Expr
, Context
.DoubleTy
,
319 UsualUnaryConversions(Expr
);
322 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
323 /// will warn if the resulting type is not a POD type, and rejects ObjC
324 /// interfaces passed by value. This returns true if the argument type is
325 /// completely illegal.
326 bool Sema::DefaultVariadicArgumentPromotion(Expr
*&Expr
, VariadicCallType CT
,
327 FunctionDecl
*FDecl
) {
328 DefaultArgumentPromotion(Expr
);
330 // __builtin_va_start takes the second argument as a "varargs" argument, but
331 // it doesn't actually do anything with it. It doesn't need to be non-pod
333 if (FDecl
&& FDecl
->getBuiltinID() == Builtin::BI__builtin_va_start
)
336 if (Expr
->getType()->isObjCObjectType() &&
337 DiagRuntimeBehavior(Expr
->getLocStart(),
338 PDiag(diag::err_cannot_pass_objc_interface_to_vararg
)
339 << Expr
->getType() << CT
))
342 if (!Expr
->getType()->isPODType() &&
343 DiagRuntimeBehavior(Expr
->getLocStart(),
344 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg
)
345 << Expr
->getType() << CT
))
351 /// UsualArithmeticConversions - Performs various conversions that are common to
352 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
353 /// routine returns the first non-arithmetic type found. The client is
354 /// responsible for emitting appropriate error diagnostics.
355 /// FIXME: verify the conversion rules for "complex int" are consistent with
357 QualType
Sema::UsualArithmeticConversions(Expr
*&lhsExpr
, Expr
*&rhsExpr
,
360 UsualUnaryConversions(lhsExpr
);
362 UsualUnaryConversions(rhsExpr
);
364 // For conversion purposes, we ignore any qualifiers.
365 // For example, "const float" and "float" are equivalent.
367 Context
.getCanonicalType(lhsExpr
->getType()).getUnqualifiedType();
369 Context
.getCanonicalType(rhsExpr
->getType()).getUnqualifiedType();
371 // If both types are identical, no conversion is needed.
375 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
376 // The caller can deal with this (e.g. pointer + int).
377 if (!lhs
->isArithmeticType() || !rhs
->isArithmeticType())
380 // Apply unary and bitfield promotions to the LHS's type.
381 QualType lhs_unpromoted
= lhs
;
382 if (lhs
->isPromotableIntegerType())
383 lhs
= Context
.getPromotedIntegerType(lhs
);
384 QualType LHSBitfieldPromoteTy
= Context
.isPromotableBitField(lhsExpr
);
385 if (!LHSBitfieldPromoteTy
.isNull())
386 lhs
= LHSBitfieldPromoteTy
;
387 if (lhs
!= lhs_unpromoted
&& !isCompAssign
)
388 ImpCastExprToType(lhsExpr
, lhs
, CK_IntegralCast
);
390 // If both types are identical, no conversion is needed.
394 // At this point, we have two different arithmetic types.
396 // Handle complex types first (C99 6.3.1.8p1).
397 bool LHSComplexFloat
= lhs
->isComplexType();
398 bool RHSComplexFloat
= rhs
->isComplexType();
399 if (LHSComplexFloat
|| RHSComplexFloat
) {
400 // if we have an integer operand, the result is the complex type.
402 if (!RHSComplexFloat
&& !rhs
->isRealFloatingType()) {
403 if (rhs
->isIntegerType()) {
404 QualType fp
= cast
<ComplexType
>(lhs
)->getElementType();
405 ImpCastExprToType(rhsExpr
, fp
, CK_IntegralToFloating
);
406 ImpCastExprToType(rhsExpr
, lhs
, CK_FloatingRealToComplex
);
408 assert(rhs
->isComplexIntegerType());
409 ImpCastExprToType(rhsExpr
, lhs
, CK_IntegralComplexToFloatingComplex
);
414 if (!LHSComplexFloat
&& !lhs
->isRealFloatingType()) {
416 // int -> float -> _Complex float
417 if (lhs
->isIntegerType()) {
418 QualType fp
= cast
<ComplexType
>(rhs
)->getElementType();
419 ImpCastExprToType(lhsExpr
, fp
, CK_IntegralToFloating
);
420 ImpCastExprToType(lhsExpr
, rhs
, CK_FloatingRealToComplex
);
422 assert(lhs
->isComplexIntegerType());
423 ImpCastExprToType(lhsExpr
, rhs
, CK_IntegralComplexToFloatingComplex
);
429 // This handles complex/complex, complex/float, or float/complex.
430 // When both operands are complex, the shorter operand is converted to the
431 // type of the longer, and that is the type of the result. This corresponds
432 // to what is done when combining two real floating-point operands.
433 // The fun begins when size promotion occur across type domains.
434 // From H&S 6.3.4: When one operand is complex and the other is a real
435 // floating-point type, the less precise type is converted, within it's
436 // real or complex domain, to the precision of the other type. For example,
437 // when combining a "long double" with a "double _Complex", the
438 // "double _Complex" is promoted to "long double _Complex".
439 int order
= Context
.getFloatingTypeOrder(lhs
, rhs
);
441 // If both are complex, just cast to the more precise type.
442 if (LHSComplexFloat
&& RHSComplexFloat
) {
444 // _Complex float -> _Complex double
445 ImpCastExprToType(rhsExpr
, lhs
, CK_FloatingComplexCast
);
448 } else if (order
< 0) {
449 // _Complex float -> _Complex double
451 ImpCastExprToType(lhsExpr
, rhs
, CK_FloatingComplexCast
);
457 // If just the LHS is complex, the RHS needs to be converted,
458 // and the LHS might need to be promoted.
459 if (LHSComplexFloat
) {
460 if (order
> 0) { // LHS is wider
461 // float -> _Complex double
462 QualType fp
= cast
<ComplexType
>(lhs
)->getElementType();
463 ImpCastExprToType(rhsExpr
, fp
, CK_FloatingCast
);
464 ImpCastExprToType(rhsExpr
, lhs
, CK_FloatingRealToComplex
);
468 // RHS is at least as wide. Find its corresponding complex type.
469 QualType result
= (order
== 0 ? lhs
: Context
.getComplexType(rhs
));
471 // double -> _Complex double
472 ImpCastExprToType(rhsExpr
, result
, CK_FloatingRealToComplex
);
474 // _Complex float -> _Complex double
475 if (!isCompAssign
&& order
< 0)
476 ImpCastExprToType(lhsExpr
, result
, CK_FloatingComplexCast
);
481 // Just the RHS is complex, so the LHS needs to be converted
482 // and the RHS might need to be promoted.
483 assert(RHSComplexFloat
);
485 if (order
< 0) { // RHS is wider
486 // float -> _Complex double
488 ImpCastExprToType(lhsExpr
, rhs
, CK_FloatingCast
);
489 ImpCastExprToType(lhsExpr
, rhs
, CK_FloatingRealToComplex
);
494 // LHS is at least as wide. Find its corresponding complex type.
495 QualType result
= (order
== 0 ? rhs
: Context
.getComplexType(lhs
));
497 // double -> _Complex double
499 ImpCastExprToType(lhsExpr
, result
, CK_FloatingRealToComplex
);
501 // _Complex float -> _Complex double
503 ImpCastExprToType(rhsExpr
, result
, CK_FloatingComplexCast
);
508 // Now handle "real" floating types (i.e. float, double, long double).
509 bool LHSFloat
= lhs
->isRealFloatingType();
510 bool RHSFloat
= rhs
->isRealFloatingType();
511 if (LHSFloat
|| RHSFloat
) {
512 // If we have two real floating types, convert the smaller operand
513 // to the bigger result.
514 if (LHSFloat
&& RHSFloat
) {
515 int order
= Context
.getFloatingTypeOrder(lhs
, rhs
);
517 ImpCastExprToType(rhsExpr
, lhs
, CK_FloatingCast
);
521 assert(order
< 0 && "illegal float comparison");
523 ImpCastExprToType(lhsExpr
, rhs
, CK_FloatingCast
);
527 // If we have an integer operand, the result is the real floating type.
529 if (rhs
->isIntegerType()) {
530 // Convert rhs to the lhs floating point type.
531 ImpCastExprToType(rhsExpr
, lhs
, CK_IntegralToFloating
);
535 // Convert both sides to the appropriate complex float.
536 assert(rhs
->isComplexIntegerType());
537 QualType result
= Context
.getComplexType(lhs
);
539 // _Complex int -> _Complex float
540 ImpCastExprToType(rhsExpr
, result
, CK_IntegralComplexToFloatingComplex
);
542 // float -> _Complex float
544 ImpCastExprToType(lhsExpr
, result
, CK_FloatingRealToComplex
);
550 if (lhs
->isIntegerType()) {
551 // Convert lhs to the rhs floating point type.
553 ImpCastExprToType(lhsExpr
, rhs
, CK_IntegralToFloating
);
557 // Convert both sides to the appropriate complex float.
558 assert(lhs
->isComplexIntegerType());
559 QualType result
= Context
.getComplexType(rhs
);
561 // _Complex int -> _Complex float
563 ImpCastExprToType(lhsExpr
, result
, CK_IntegralComplexToFloatingComplex
);
565 // float -> _Complex float
566 ImpCastExprToType(rhsExpr
, result
, CK_FloatingRealToComplex
);
571 // Handle GCC complex int extension.
572 // FIXME: if the operands are (int, _Complex long), we currently
573 // don't promote the complex. Also, signedness?
574 const ComplexType
*lhsComplexInt
= lhs
->getAsComplexIntegerType();
575 const ComplexType
*rhsComplexInt
= rhs
->getAsComplexIntegerType();
576 if (lhsComplexInt
&& rhsComplexInt
) {
577 int order
= Context
.getIntegerTypeOrder(lhsComplexInt
->getElementType(),
578 rhsComplexInt
->getElementType());
579 assert(order
&& "inequal types with equal element ordering");
581 // _Complex int -> _Complex long
582 ImpCastExprToType(rhsExpr
, lhs
, CK_IntegralComplexCast
);
587 ImpCastExprToType(lhsExpr
, rhs
, CK_IntegralComplexCast
);
589 } else if (lhsComplexInt
) {
590 // int -> _Complex int
591 ImpCastExprToType(rhsExpr
, lhs
, CK_IntegralRealToComplex
);
593 } else if (rhsComplexInt
) {
594 // int -> _Complex int
596 ImpCastExprToType(lhsExpr
, rhs
, CK_IntegralRealToComplex
);
600 // Finally, we have two differing integer types.
601 // The rules for this case are in C99 6.3.1.8
602 int compare
= Context
.getIntegerTypeOrder(lhs
, rhs
);
603 bool lhsSigned
= lhs
->hasSignedIntegerRepresentation(),
604 rhsSigned
= rhs
->hasSignedIntegerRepresentation();
605 if (lhsSigned
== rhsSigned
) {
606 // Same signedness; use the higher-ranked type
608 ImpCastExprToType(rhsExpr
, lhs
, CK_IntegralCast
);
610 } else if (!isCompAssign
)
611 ImpCastExprToType(lhsExpr
, rhs
, CK_IntegralCast
);
613 } else if (compare
!= (lhsSigned
? 1 : -1)) {
614 // The unsigned type has greater than or equal rank to the
615 // signed type, so use the unsigned type
617 ImpCastExprToType(rhsExpr
, lhs
, CK_IntegralCast
);
619 } else if (!isCompAssign
)
620 ImpCastExprToType(lhsExpr
, rhs
, CK_IntegralCast
);
622 } else if (Context
.getIntWidth(lhs
) != Context
.getIntWidth(rhs
)) {
623 // The two types are different widths; if we are here, that
624 // means the signed type is larger than the unsigned type, so
625 // use the signed type.
627 ImpCastExprToType(rhsExpr
, lhs
, CK_IntegralCast
);
629 } else if (!isCompAssign
)
630 ImpCastExprToType(lhsExpr
, rhs
, CK_IntegralCast
);
633 // The signed type is higher-ranked than the unsigned type,
634 // but isn't actually any bigger (like unsigned int and long
635 // on most 32-bit systems). Use the unsigned type corresponding
636 // to the signed type.
638 Context
.getCorrespondingUnsignedType(lhsSigned
? lhs
: rhs
);
639 ImpCastExprToType(rhsExpr
, result
, CK_IntegralCast
);
641 ImpCastExprToType(lhsExpr
, result
, CK_IntegralCast
);
646 //===----------------------------------------------------------------------===//
647 // Semantic Analysis for various Expression Types
648 //===----------------------------------------------------------------------===//
651 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
652 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
653 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
654 /// multiple tokens. However, the common case is that StringToks points to one
658 Sema::ActOnStringLiteral(const Token
*StringToks
, unsigned NumStringToks
) {
659 assert(NumStringToks
&& "Must have at least one string!");
661 StringLiteralParser
Literal(StringToks
, NumStringToks
, PP
);
662 if (Literal
.hadError
)
665 llvm::SmallVector
<SourceLocation
, 4> StringTokLocs
;
666 for (unsigned i
= 0; i
!= NumStringToks
; ++i
)
667 StringTokLocs
.push_back(StringToks
[i
].getLocation());
669 QualType StrTy
= Context
.CharTy
;
670 if (Literal
.AnyWide
) StrTy
= Context
.getWCharType();
671 if (Literal
.Pascal
) StrTy
= Context
.UnsignedCharTy
;
673 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
674 if (getLangOptions().CPlusPlus
|| getLangOptions().ConstStrings
)
677 // Get an array type for the string, according to C99 6.4.5. This includes
678 // the nul terminator character as well as the string length for pascal
680 StrTy
= Context
.getConstantArrayType(StrTy
,
681 llvm::APInt(32, Literal
.GetNumStringChars()+1),
682 ArrayType::Normal
, 0);
684 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
685 return Owned(StringLiteral::Create(Context
, Literal
.GetString(),
686 Literal
.GetStringLength(),
687 Literal
.AnyWide
, StrTy
,
689 StringTokLocs
.size()));
692 /// ShouldSnapshotBlockValueReference - Return true if a reference inside of
693 /// CurBlock to VD should cause it to be snapshotted (as we do for auto
694 /// variables defined outside the block) or false if this is not needed (e.g.
695 /// for values inside the block or for globals).
697 /// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
700 static bool ShouldSnapshotBlockValueReference(Sema
&S
, BlockScopeInfo
*CurBlock
,
702 // If the value is defined inside the block, we couldn't snapshot it even if
704 if (CurBlock
->TheDecl
== VD
->getDeclContext())
707 // If this is an enum constant or function, it is constant, don't snapshot.
708 if (isa
<EnumConstantDecl
>(VD
) || isa
<FunctionDecl
>(VD
))
711 // If this is a reference to an extern, static, or global variable, no need to
713 // FIXME: What about 'const' variables in C++?
714 if (const VarDecl
*Var
= dyn_cast
<VarDecl
>(VD
))
715 if (!Var
->hasLocalStorage())
718 // Blocks that have these can't be constant.
719 CurBlock
->hasBlockDeclRefExprs
= true;
721 // If we have nested blocks, the decl may be declared in an outer block (in
722 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
723 // be defined outside all of the current blocks (in which case the blocks do
724 // all get the bit). Walk the nesting chain.
725 for (unsigned I
= S
.FunctionScopes
.size() - 1; I
; --I
) {
726 BlockScopeInfo
*NextBlock
= dyn_cast
<BlockScopeInfo
>(S
.FunctionScopes
[I
]);
731 // If we found the defining block for the variable, don't mark the block as
732 // having a reference outside it.
733 if (NextBlock
->TheDecl
== VD
->getDeclContext())
736 // Otherwise, the DeclRef from the inner block causes the outer one to need
737 // a snapshot as well.
738 NextBlock
->hasBlockDeclRefExprs
= true;
746 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
, SourceLocation Loc
,
747 const CXXScopeSpec
*SS
) {
748 DeclarationNameInfo
NameInfo(D
->getDeclName(), Loc
);
749 return BuildDeclRefExpr(D
, Ty
, NameInfo
, SS
);
752 /// BuildDeclRefExpr - Build a DeclRefExpr.
754 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
,
755 const DeclarationNameInfo
&NameInfo
,
756 const CXXScopeSpec
*SS
) {
757 if (Context
.getCanonicalType(Ty
) == Context
.UndeducedAutoTy
) {
758 Diag(NameInfo
.getLoc(),
759 diag::err_auto_variable_cannot_appear_in_own_initializer
)
764 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
765 if (isa
<NonTypeTemplateParmDecl
>(VD
)) {
766 // Non-type template parameters can be referenced anywhere they are
768 Ty
= Ty
.getNonLValueExprType(Context
);
769 } else if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(CurContext
)) {
770 if (const FunctionDecl
*FD
= MD
->getParent()->isLocalClass()) {
771 if (VD
->hasLocalStorage() && VD
->getDeclContext() != CurContext
) {
772 Diag(NameInfo
.getLoc(),
773 diag::err_reference_to_local_var_in_enclosing_function
)
774 << D
->getIdentifier() << FD
->getDeclName();
775 Diag(D
->getLocation(), diag::note_local_variable_declared_here
)
776 << D
->getIdentifier();
783 MarkDeclarationReferenced(NameInfo
.getLoc(), D
);
785 return Owned(DeclRefExpr::Create(Context
,
786 SS
? (NestedNameSpecifier
*)SS
->getScopeRep() : 0,
787 SS
? SS
->getRange() : SourceRange(),
791 /// \brief Given a field that represents a member of an anonymous
792 /// struct/union, build the path from that field's context to the
795 /// Construct the sequence of field member references we'll have to
796 /// perform to get to the field in the anonymous union/struct. The
797 /// list of members is built from the field outward, so traverse it
798 /// backwards to go from an object in the current context to the field
801 /// \returns The variable from which the field access should begin,
802 /// for an anonymous struct/union that is not a member of another
803 /// class. Otherwise, returns NULL.
804 VarDecl
*Sema::BuildAnonymousStructUnionMemberPath(FieldDecl
*Field
,
805 llvm::SmallVectorImpl
<FieldDecl
*> &Path
) {
806 assert(Field
->getDeclContext()->isRecord() &&
807 cast
<RecordDecl
>(Field
->getDeclContext())->isAnonymousStructOrUnion()
808 && "Field must be stored inside an anonymous struct or union");
810 Path
.push_back(Field
);
811 VarDecl
*BaseObject
= 0;
812 DeclContext
*Ctx
= Field
->getDeclContext();
814 RecordDecl
*Record
= cast
<RecordDecl
>(Ctx
);
815 ValueDecl
*AnonObject
= Record
->getAnonymousStructOrUnionObject();
816 if (FieldDecl
*AnonField
= dyn_cast
<FieldDecl
>(AnonObject
))
817 Path
.push_back(AnonField
);
819 BaseObject
= cast
<VarDecl
>(AnonObject
);
822 Ctx
= Ctx
->getParent();
823 } while (Ctx
->isRecord() &&
824 cast
<RecordDecl
>(Ctx
)->isAnonymousStructOrUnion());
830 Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc
,
832 Expr
*BaseObjectExpr
,
833 SourceLocation OpLoc
) {
834 llvm::SmallVector
<FieldDecl
*, 4> AnonFields
;
835 VarDecl
*BaseObject
= BuildAnonymousStructUnionMemberPath(Field
,
838 // Build the expression that refers to the base object, from
839 // which we will build a sequence of member references to each
840 // of the anonymous union objects and, eventually, the field we
841 // found via name lookup.
842 bool BaseObjectIsPointer
= false;
843 Qualifiers BaseQuals
;
845 // BaseObject is an anonymous struct/union variable (and is,
846 // therefore, not part of another non-anonymous record).
847 MarkDeclarationReferenced(Loc
, BaseObject
);
848 BaseObjectExpr
= new (Context
) DeclRefExpr(BaseObject
,BaseObject
->getType(),
851 = Context
.getCanonicalType(BaseObject
->getType()).getQualifiers();
852 } else if (BaseObjectExpr
) {
853 // The caller provided the base object expression. Determine
854 // whether its a pointer and whether it adds any qualifiers to the
855 // anonymous struct/union fields we're looking into.
856 QualType ObjectType
= BaseObjectExpr
->getType();
857 if (const PointerType
*ObjectPtr
= ObjectType
->getAs
<PointerType
>()) {
858 BaseObjectIsPointer
= true;
859 ObjectType
= ObjectPtr
->getPointeeType();
862 = Context
.getCanonicalType(ObjectType
).getQualifiers();
864 // We've found a member of an anonymous struct/union that is
865 // inside a non-anonymous struct/union, so in a well-formed
866 // program our base object expression is "this".
867 DeclContext
*DC
= getFunctionLevelDeclContext();
868 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(DC
)) {
869 if (!MD
->isStatic()) {
870 QualType AnonFieldType
871 = Context
.getTagDeclType(
872 cast
<RecordDecl
>(AnonFields
.back()->getDeclContext()));
873 QualType ThisType
= Context
.getTagDeclType(MD
->getParent());
874 if ((Context
.getCanonicalType(AnonFieldType
)
875 == Context
.getCanonicalType(ThisType
)) ||
876 IsDerivedFrom(ThisType
, AnonFieldType
)) {
877 // Our base object expression is "this".
878 BaseObjectExpr
= new (Context
) CXXThisExpr(Loc
,
879 MD
->getThisType(Context
),
880 /*isImplicit=*/true);
881 BaseObjectIsPointer
= true;
884 return ExprError(Diag(Loc
,diag::err_invalid_member_use_in_static_method
)
885 << Field
->getDeclName());
887 BaseQuals
= Qualifiers::fromCVRMask(MD
->getTypeQualifiers());
891 return ExprError(Diag(Loc
, diag::err_invalid_non_static_member_use
)
892 << Field
->getDeclName());
895 // Build the implicit member references to the field of the
896 // anonymous struct/union.
897 Expr
*Result
= BaseObjectExpr
;
898 Qualifiers ResultQuals
= BaseQuals
;
899 for (llvm::SmallVector
<FieldDecl
*, 4>::reverse_iterator
900 FI
= AnonFields
.rbegin(), FIEnd
= AnonFields
.rend();
902 QualType MemberType
= (*FI
)->getType();
903 Qualifiers MemberTypeQuals
=
904 Context
.getCanonicalType(MemberType
).getQualifiers();
906 // CVR attributes from the base are picked up by members,
907 // except that 'mutable' members don't pick up 'const'.
908 if ((*FI
)->isMutable())
909 ResultQuals
.removeConst();
911 // GC attributes are never picked up by members.
912 ResultQuals
.removeObjCGCAttr();
914 // TR 18037 does not allow fields to be declared with address spaces.
915 assert(!MemberTypeQuals
.hasAddressSpace());
917 Qualifiers NewQuals
= ResultQuals
+ MemberTypeQuals
;
918 if (NewQuals
!= MemberTypeQuals
)
919 MemberType
= Context
.getQualifiedType(MemberType
, NewQuals
);
921 MarkDeclarationReferenced(Loc
, *FI
);
922 PerformObjectMemberConversion(Result
, /*FIXME:Qualifier=*/0, *FI
, *FI
);
923 // FIXME: Might this end up being a qualified name?
924 Result
= new (Context
) MemberExpr(Result
, BaseObjectIsPointer
, *FI
,
926 BaseObjectIsPointer
= false;
927 ResultQuals
= NewQuals
;
930 return Owned(Result
);
933 /// Decomposes the given name into a DeclarationNameInfo, its location, and
934 /// possibly a list of template arguments.
936 /// If this produces template arguments, it is permitted to call
937 /// DecomposeTemplateName.
939 /// This actually loses a lot of source location information for
940 /// non-standard name kinds; we should consider preserving that in
942 static void DecomposeUnqualifiedId(Sema
&SemaRef
,
943 const UnqualifiedId
&Id
,
944 TemplateArgumentListInfo
&Buffer
,
945 DeclarationNameInfo
&NameInfo
,
946 const TemplateArgumentListInfo
*&TemplateArgs
) {
947 if (Id
.getKind() == UnqualifiedId::IK_TemplateId
) {
948 Buffer
.setLAngleLoc(Id
.TemplateId
->LAngleLoc
);
949 Buffer
.setRAngleLoc(Id
.TemplateId
->RAngleLoc
);
951 ASTTemplateArgsPtr
TemplateArgsPtr(SemaRef
,
952 Id
.TemplateId
->getTemplateArgs(),
953 Id
.TemplateId
->NumArgs
);
954 SemaRef
.translateTemplateArguments(TemplateArgsPtr
, Buffer
);
955 TemplateArgsPtr
.release();
957 TemplateName TName
= Id
.TemplateId
->Template
.get();
958 SourceLocation TNameLoc
= Id
.TemplateId
->TemplateNameLoc
;
959 NameInfo
= SemaRef
.Context
.getNameForTemplate(TName
, TNameLoc
);
960 TemplateArgs
= &Buffer
;
962 NameInfo
= SemaRef
.GetNameFromUnqualifiedId(Id
);
967 /// Determines whether the given record is "fully-formed" at the given
968 /// location, i.e. whether a qualified lookup into it is assured of
969 /// getting consistent results already.
970 static bool IsFullyFormedScope(Sema
&SemaRef
, CXXRecordDecl
*Record
) {
971 if (!Record
->hasDefinition())
974 for (CXXRecordDecl::base_class_iterator I
= Record
->bases_begin(),
975 E
= Record
->bases_end(); I
!= E
; ++I
) {
976 CanQualType BaseT
= SemaRef
.Context
.getCanonicalType((*I
).getType());
977 CanQual
<RecordType
> BaseRT
= BaseT
->getAs
<RecordType
>();
978 if (!BaseRT
) return false;
980 CXXRecordDecl
*BaseRecord
= cast
<CXXRecordDecl
>(BaseRT
->getDecl());
981 if (!BaseRecord
->hasDefinition() ||
982 !IsFullyFormedScope(SemaRef
, BaseRecord
))
989 /// Determines if the given class is provably not derived from all of
990 /// the prospective base classes.
991 static bool IsProvablyNotDerivedFrom(Sema
&SemaRef
,
992 CXXRecordDecl
*Record
,
993 const llvm::SmallPtrSet
<CXXRecordDecl
*, 4> &Bases
) {
994 if (Bases
.count(Record
->getCanonicalDecl()))
997 RecordDecl
*RD
= Record
->getDefinition();
998 if (!RD
) return false;
999 Record
= cast
<CXXRecordDecl
>(RD
);
1001 for (CXXRecordDecl::base_class_iterator I
= Record
->bases_begin(),
1002 E
= Record
->bases_end(); I
!= E
; ++I
) {
1003 CanQualType BaseT
= SemaRef
.Context
.getCanonicalType((*I
).getType());
1004 CanQual
<RecordType
> BaseRT
= BaseT
->getAs
<RecordType
>();
1005 if (!BaseRT
) return false;
1007 CXXRecordDecl
*BaseRecord
= cast
<CXXRecordDecl
>(BaseRT
->getDecl());
1008 if (!IsProvablyNotDerivedFrom(SemaRef
, BaseRecord
, Bases
))
1016 /// The reference is definitely not an instance member access.
1019 /// The reference may be an implicit instance member access.
1022 /// The reference may be to an instance member, but it is invalid if
1023 /// so, because the context is not an instance method.
1024 IMA_Mixed_StaticContext
,
1026 /// The reference may be to an instance member, but it is invalid if
1027 /// so, because the context is from an unrelated class.
1028 IMA_Mixed_Unrelated
,
1030 /// The reference is definitely an implicit instance member access.
1033 /// The reference may be to an unresolved using declaration.
1036 /// The reference may be to an unresolved using declaration and the
1037 /// context is not an instance method.
1038 IMA_Unresolved_StaticContext
,
1040 /// The reference is to a member of an anonymous structure in a
1041 /// non-class context.
1042 IMA_AnonymousMember
,
1044 /// All possible referrents are instance members and the current
1045 /// context is not an instance method.
1046 IMA_Error_StaticContext
,
1048 /// All possible referrents are instance members of an unrelated
1053 /// The given lookup names class member(s) and is not being used for
1054 /// an address-of-member expression. Classify the type of access
1055 /// according to whether it's possible that this reference names an
1056 /// instance member. This is best-effort; it is okay to
1057 /// conservatively answer "yes", in which case some errors will simply
1058 /// not be caught until template-instantiation.
1059 static IMAKind
ClassifyImplicitMemberAccess(Sema
&SemaRef
,
1060 const LookupResult
&R
) {
1061 assert(!R
.empty() && (*R
.begin())->isCXXClassMember());
1063 DeclContext
*DC
= SemaRef
.getFunctionLevelDeclContext();
1064 bool isStaticContext
=
1065 (!isa
<CXXMethodDecl
>(DC
) ||
1066 cast
<CXXMethodDecl
>(DC
)->isStatic());
1068 if (R
.isUnresolvableResult())
1069 return isStaticContext
? IMA_Unresolved_StaticContext
: IMA_Unresolved
;
1071 // Collect all the declaring classes of instance members we find.
1072 bool hasNonInstance
= false;
1073 llvm::SmallPtrSet
<CXXRecordDecl
*, 4> Classes
;
1074 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
) {
1076 if (D
->isCXXInstanceMember()) {
1077 CXXRecordDecl
*R
= cast
<CXXRecordDecl
>(D
->getDeclContext());
1079 // If this is a member of an anonymous record, move out to the
1080 // innermost non-anonymous struct or union. If there isn't one,
1081 // that's a special case.
1082 while (R
->isAnonymousStructOrUnion()) {
1083 R
= dyn_cast
<CXXRecordDecl
>(R
->getParent());
1084 if (!R
) return IMA_AnonymousMember
;
1086 Classes
.insert(R
->getCanonicalDecl());
1089 hasNonInstance
= true;
1092 // If we didn't find any instance members, it can't be an implicit
1093 // member reference.
1094 if (Classes
.empty())
1097 // If the current context is not an instance method, it can't be
1098 // an implicit member reference.
1099 if (isStaticContext
)
1100 return (hasNonInstance
? IMA_Mixed_StaticContext
: IMA_Error_StaticContext
);
1102 // If we can prove that the current context is unrelated to all the
1103 // declaring classes, it can't be an implicit member reference (in
1104 // which case it's an error if any of those members are selected).
1105 if (IsProvablyNotDerivedFrom(SemaRef
,
1106 cast
<CXXMethodDecl
>(DC
)->getParent(),
1108 return (hasNonInstance
? IMA_Mixed_Unrelated
: IMA_Error_Unrelated
);
1110 return (hasNonInstance
? IMA_Mixed
: IMA_Instance
);
1113 /// Diagnose a reference to a field with no object available.
1114 static void DiagnoseInstanceReference(Sema
&SemaRef
,
1115 const CXXScopeSpec
&SS
,
1116 const LookupResult
&R
) {
1117 SourceLocation Loc
= R
.getNameLoc();
1118 SourceRange
Range(Loc
);
1119 if (SS
.isSet()) Range
.setBegin(SS
.getRange().getBegin());
1121 if (R
.getAsSingle
<FieldDecl
>()) {
1122 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(SemaRef
.CurContext
)) {
1123 if (MD
->isStatic()) {
1124 // "invalid use of member 'x' in static member function"
1125 SemaRef
.Diag(Loc
, diag::err_invalid_member_use_in_static_method
)
1126 << Range
<< R
.getLookupName();
1131 SemaRef
.Diag(Loc
, diag::err_invalid_non_static_member_use
)
1132 << R
.getLookupName() << Range
;
1136 SemaRef
.Diag(Loc
, diag::err_member_call_without_object
) << Range
;
1139 /// Diagnose an empty lookup.
1141 /// \return false if new lookup candidates were found
1142 bool Sema::DiagnoseEmptyLookup(Scope
*S
, CXXScopeSpec
&SS
, LookupResult
&R
,
1143 CorrectTypoContext CTC
) {
1144 DeclarationName Name
= R
.getLookupName();
1146 unsigned diagnostic
= diag::err_undeclared_var_use
;
1147 unsigned diagnostic_suggest
= diag::err_undeclared_var_use_suggest
;
1148 if (Name
.getNameKind() == DeclarationName::CXXOperatorName
||
1149 Name
.getNameKind() == DeclarationName::CXXLiteralOperatorName
||
1150 Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
) {
1151 diagnostic
= diag::err_undeclared_use
;
1152 diagnostic_suggest
= diag::err_undeclared_use_suggest
;
1155 // If the original lookup was an unqualified lookup, fake an
1156 // unqualified lookup. This is useful when (for example) the
1157 // original lookup would not have found something because it was a
1159 for (DeclContext
*DC
= SS
.isEmpty() ? CurContext
: 0;
1160 DC
; DC
= DC
->getParent()) {
1161 if (isa
<CXXRecordDecl
>(DC
)) {
1162 LookupQualifiedName(R
, DC
);
1165 // Don't give errors about ambiguities in this lookup.
1166 R
.suppressDiagnostics();
1168 CXXMethodDecl
*CurMethod
= dyn_cast
<CXXMethodDecl
>(CurContext
);
1169 bool isInstance
= CurMethod
&&
1170 CurMethod
->isInstance() &&
1171 DC
== CurMethod
->getParent();
1173 // Give a code modification hint to insert 'this->'.
1174 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1175 // Actually quite difficult!
1177 UnresolvedLookupExpr
*ULE
= cast
<UnresolvedLookupExpr
>(
1178 CallsUndergoingInstantiation
.back()->getCallee());
1179 CXXMethodDecl
*DepMethod
= cast_or_null
<CXXMethodDecl
>(
1180 CurMethod
->getInstantiatedFromMemberFunction());
1182 Diag(R
.getNameLoc(), diagnostic
) << Name
1183 << FixItHint::CreateInsertion(R
.getNameLoc(), "this->");
1184 QualType DepThisType
= DepMethod
->getThisType(Context
);
1185 CXXThisExpr
*DepThis
= new (Context
) CXXThisExpr(
1186 R
.getNameLoc(), DepThisType
, false);
1187 TemplateArgumentListInfo TList
;
1188 if (ULE
->hasExplicitTemplateArgs())
1189 ULE
->copyTemplateArgumentsInto(TList
);
1190 CXXDependentScopeMemberExpr
*DepExpr
=
1191 CXXDependentScopeMemberExpr::Create(
1192 Context
, DepThis
, DepThisType
, true, SourceLocation(),
1193 ULE
->getQualifier(), ULE
->getQualifierRange(), NULL
,
1194 R
.getLookupNameInfo(), &TList
);
1195 CallsUndergoingInstantiation
.back()->setCallee(DepExpr
);
1197 // FIXME: we should be able to handle this case too. It is correct
1198 // to add this-> here. This is a workaround for PR7947.
1199 Diag(R
.getNameLoc(), diagnostic
) << Name
;
1202 Diag(R
.getNameLoc(), diagnostic
) << Name
;
1205 // Do we really want to note all of these?
1206 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
)
1207 Diag((*I
)->getLocation(), diag::note_dependent_var_use
);
1209 // Tell the callee to try to recover.
1217 // We didn't find anything, so try to correct for a typo.
1218 DeclarationName Corrected
;
1219 if (S
&& (Corrected
= CorrectTypo(R
, S
, &SS
, 0, false, CTC
))) {
1221 if (isa
<ValueDecl
>(*R
.begin()) || isa
<FunctionTemplateDecl
>(*R
.begin())) {
1223 Diag(R
.getNameLoc(), diagnostic_suggest
) << Name
<< R
.getLookupName()
1224 << FixItHint::CreateReplacement(R
.getNameLoc(),
1225 R
.getLookupName().getAsString());
1227 Diag(R
.getNameLoc(), diag::err_no_member_suggest
)
1228 << Name
<< computeDeclContext(SS
, false) << R
.getLookupName()
1230 << FixItHint::CreateReplacement(R
.getNameLoc(),
1231 R
.getLookupName().getAsString());
1232 if (NamedDecl
*ND
= R
.getAsSingle
<NamedDecl
>())
1233 Diag(ND
->getLocation(), diag::note_previous_decl
)
1234 << ND
->getDeclName();
1236 // Tell the callee to try to recover.
1240 if (isa
<TypeDecl
>(*R
.begin()) || isa
<ObjCInterfaceDecl
>(*R
.begin())) {
1241 // FIXME: If we ended up with a typo for a type name or
1242 // Objective-C class name, we're in trouble because the parser
1243 // is in the wrong place to recover. Suggest the typo
1244 // correction, but don't make it a fix-it since we're not going
1245 // to recover well anyway.
1247 Diag(R
.getNameLoc(), diagnostic_suggest
) << Name
<< R
.getLookupName();
1249 Diag(R
.getNameLoc(), diag::err_no_member_suggest
)
1250 << Name
<< computeDeclContext(SS
, false) << R
.getLookupName()
1253 // Don't try to recover; it won't work.
1257 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1258 // because we aren't able to recover.
1260 Diag(R
.getNameLoc(), diagnostic_suggest
) << Name
<< Corrected
;
1262 Diag(R
.getNameLoc(), diag::err_no_member_suggest
)
1263 << Name
<< computeDeclContext(SS
, false) << Corrected
1270 // Emit a special diagnostic for failed member lookups.
1271 // FIXME: computing the declaration context might fail here (?)
1272 if (!SS
.isEmpty()) {
1273 Diag(R
.getNameLoc(), diag::err_no_member
)
1274 << Name
<< computeDeclContext(SS
, false)
1279 // Give up, we can't recover.
1280 Diag(R
.getNameLoc(), diagnostic
) << Name
;
1284 ObjCPropertyDecl
*Sema::canSynthesizeProvisionalIvar(IdentifierInfo
*II
) {
1285 ObjCMethodDecl
*CurMeth
= getCurMethodDecl();
1286 ObjCInterfaceDecl
*IDecl
= CurMeth
->getClassInterface();
1289 ObjCImplementationDecl
*ClassImpDecl
= IDecl
->getImplementation();
1292 ObjCPropertyDecl
*property
= LookupPropertyDecl(IDecl
, II
);
1295 if (ObjCPropertyImplDecl
*PIDecl
= ClassImpDecl
->FindPropertyImplDecl(II
))
1296 if (PIDecl
->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic
||
1297 PIDecl
->getPropertyIvarDecl())
1302 bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl
*Property
) {
1303 ObjCMethodDecl
*CurMeth
= getCurMethodDecl();
1304 ObjCInterfaceDecl
*IDecl
= CurMeth
->getClassInterface();
1307 ObjCImplementationDecl
*ClassImpDecl
= IDecl
->getImplementation();
1310 if (ObjCPropertyImplDecl
*PIDecl
1311 = ClassImpDecl
->FindPropertyImplDecl(Property
->getIdentifier()))
1312 if (PIDecl
->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic
||
1313 PIDecl
->getPropertyIvarDecl())
1319 static ObjCIvarDecl
*SynthesizeProvisionalIvar(Sema
&SemaRef
,
1320 LookupResult
&Lookup
,
1322 SourceLocation NameLoc
) {
1323 ObjCMethodDecl
*CurMeth
= SemaRef
.getCurMethodDecl();
1326 LookForIvars
= true;
1327 else if (CurMeth
->isClassMethod())
1328 LookForIvars
= false;
1330 LookForIvars
= (Lookup
.isSingleResult() &&
1331 Lookup
.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1335 ObjCInterfaceDecl
*IDecl
= CurMeth
->getClassInterface();
1338 ObjCImplementationDecl
*ClassImpDecl
= IDecl
->getImplementation();
1341 bool DynamicImplSeen
= false;
1342 ObjCPropertyDecl
*property
= SemaRef
.LookupPropertyDecl(IDecl
, II
);
1345 if (ObjCPropertyImplDecl
*PIDecl
= ClassImpDecl
->FindPropertyImplDecl(II
)) {
1347 (PIDecl
->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic
);
1348 // property implementation has a designated ivar. No need to assume a new
1350 if (!DynamicImplSeen
&& PIDecl
->getPropertyIvarDecl())
1353 if (!DynamicImplSeen
) {
1354 QualType PropType
= SemaRef
.Context
.getCanonicalType(property
->getType());
1355 ObjCIvarDecl
*Ivar
= ObjCIvarDecl::Create(SemaRef
.Context
, ClassImpDecl
,
1357 II
, PropType
, /*Dinfo=*/0,
1358 ObjCIvarDecl::Protected
,
1360 ClassImpDecl
->addDecl(Ivar
);
1361 IDecl
->makeDeclVisibleInContext(Ivar
, false);
1362 property
->setPropertyIvarDecl(Ivar
);
1368 ExprResult
Sema::ActOnIdExpression(Scope
*S
,
1371 bool HasTrailingLParen
,
1372 bool isAddressOfOperand
) {
1373 assert(!(isAddressOfOperand
&& HasTrailingLParen
) &&
1374 "cannot be direct & operand and have a trailing lparen");
1379 TemplateArgumentListInfo TemplateArgsBuffer
;
1381 // Decompose the UnqualifiedId into the following data.
1382 DeclarationNameInfo NameInfo
;
1383 const TemplateArgumentListInfo
*TemplateArgs
;
1384 DecomposeUnqualifiedId(*this, Id
, TemplateArgsBuffer
, NameInfo
, TemplateArgs
);
1386 DeclarationName Name
= NameInfo
.getName();
1387 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
1388 SourceLocation NameLoc
= NameInfo
.getLoc();
1390 // C++ [temp.dep.expr]p3:
1391 // An id-expression is type-dependent if it contains:
1392 // -- an identifier that was declared with a dependent type,
1393 // (note: handled after lookup)
1394 // -- a template-id that is dependent,
1395 // (note: handled in BuildTemplateIdExpr)
1396 // -- a conversion-function-id that specifies a dependent type,
1397 // -- a nested-name-specifier that contains a class-name that
1398 // names a dependent type.
1399 // Determine whether this is a member of an unknown specialization;
1400 // we need to handle these differently.
1401 bool DependentID
= false;
1402 if (Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
&&
1403 Name
.getCXXNameType()->isDependentType()) {
1405 } else if (SS
.isSet()) {
1406 DeclContext
*DC
= computeDeclContext(SS
, false);
1408 if (RequireCompleteDeclContext(SS
, DC
))
1410 // FIXME: We should be checking whether DC is the current instantiation.
1411 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(DC
))
1412 DependentID
= !IsFullyFormedScope(*this, RD
);
1419 return ActOnDependentIdExpression(SS
, NameInfo
, isAddressOfOperand
,
1422 bool IvarLookupFollowUp
= false;
1423 // Perform the required lookup.
1424 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
1426 // Lookup the template name again to correctly establish the context in
1427 // which it was found. This is really unfortunate as we already did the
1428 // lookup to determine that it was a template name in the first place. If
1429 // this becomes a performance hit, we can work harder to preserve those
1430 // results until we get here but it's likely not worth it.
1431 bool MemberOfUnknownSpecialization
;
1432 LookupTemplateName(R
, S
, SS
, QualType(), /*EnteringContext=*/false,
1433 MemberOfUnknownSpecialization
);
1435 IvarLookupFollowUp
= (!SS
.isSet() && II
&& getCurMethodDecl());
1436 LookupParsedName(R
, S
, &SS
, !IvarLookupFollowUp
);
1438 // If this reference is in an Objective-C method, then we need to do
1439 // some special Objective-C lookup, too.
1440 if (IvarLookupFollowUp
) {
1441 ExprResult
E(LookupInObjCMethod(R
, S
, II
, true));
1445 Expr
*Ex
= E
.takeAs
<Expr
>();
1446 if (Ex
) return Owned(Ex
);
1447 // Synthesize ivars lazily
1448 if (getLangOptions().ObjCNonFragileABI2
) {
1449 if (SynthesizeProvisionalIvar(*this, R
, II
, NameLoc
))
1450 return ActOnIdExpression(S
, SS
, Id
, HasTrailingLParen
,
1451 isAddressOfOperand
);
1453 // for further use, this must be set to false if in class method.
1454 IvarLookupFollowUp
= getCurMethodDecl()->isInstanceMethod();
1458 if (R
.isAmbiguous())
1461 // Determine whether this name might be a candidate for
1462 // argument-dependent lookup.
1463 bool ADL
= UseArgumentDependentLookup(SS
, R
, HasTrailingLParen
);
1465 if (R
.empty() && !ADL
) {
1466 // Otherwise, this could be an implicitly declared function reference (legal
1467 // in C90, extension in C99, forbidden in C++).
1468 if (HasTrailingLParen
&& II
&& !getLangOptions().CPlusPlus
) {
1469 NamedDecl
*D
= ImplicitlyDefineFunction(NameLoc
, *II
, S
);
1470 if (D
) R
.addDecl(D
);
1473 // If this name wasn't predeclared and if this is not a function
1474 // call, diagnose the problem.
1476 if (DiagnoseEmptyLookup(S
, SS
, R
, CTC_Unknown
))
1479 assert(!R
.empty() &&
1480 "DiagnoseEmptyLookup returned false but added no results");
1482 // If we found an Objective-C instance variable, let
1483 // LookupInObjCMethod build the appropriate expression to
1484 // reference the ivar.
1485 if (ObjCIvarDecl
*Ivar
= R
.getAsSingle
<ObjCIvarDecl
>()) {
1487 ExprResult
E(LookupInObjCMethod(R
, S
, Ivar
->getIdentifier()));
1488 assert(E
.isInvalid() || E
.get());
1494 // This is guaranteed from this point on.
1495 assert(!R
.empty() || ADL
);
1497 if (VarDecl
*Var
= R
.getAsSingle
<VarDecl
>()) {
1498 if (getLangOptions().ObjCNonFragileABI
&& IvarLookupFollowUp
&&
1499 !getLangOptions().ObjCNonFragileABI2
&&
1500 Var
->isFileVarDecl()) {
1501 ObjCPropertyDecl
*Property
= canSynthesizeProvisionalIvar(II
);
1503 Diag(NameLoc
, diag::warn_ivar_variable_conflict
) << Var
->getDeclName();
1504 Diag(Property
->getLocation(), diag::note_property_declare
);
1505 Diag(Var
->getLocation(), diag::note_global_declared_at
);
1508 } else if (FunctionDecl
*Func
= R
.getAsSingle
<FunctionDecl
>()) {
1509 if (!getLangOptions().CPlusPlus
&& !Func
->hasPrototype()) {
1510 // C99 DR 316 says that, if a function type comes from a
1511 // function definition (without a prototype), that type is only
1512 // used for checking compatibility. Therefore, when referencing
1513 // the function, we pretend that we don't have the full function
1515 if (DiagnoseUseOfDecl(Func
, NameLoc
))
1518 QualType T
= Func
->getType();
1519 QualType NoProtoType
= T
;
1520 if (const FunctionProtoType
*Proto
= T
->getAs
<FunctionProtoType
>())
1521 NoProtoType
= Context
.getFunctionNoProtoType(Proto
->getResultType(),
1522 Proto
->getExtInfo());
1523 return BuildDeclRefExpr(Func
, NoProtoType
, NameLoc
, &SS
);
1527 // Check whether this might be a C++ implicit instance member access.
1528 // C++ [class.mfct.non-static]p3:
1529 // When an id-expression that is not part of a class member access
1530 // syntax and not used to form a pointer to member is used in the
1531 // body of a non-static member function of class X, if name lookup
1532 // resolves the name in the id-expression to a non-static non-type
1533 // member of some class C, the id-expression is transformed into a
1534 // class member access expression using (*this) as the
1535 // postfix-expression to the left of the . operator.
1537 // But we don't actually need to do this for '&' operands if R
1538 // resolved to a function or overloaded function set, because the
1539 // expression is ill-formed if it actually works out to be a
1540 // non-static member function:
1542 // C++ [expr.ref]p4:
1543 // Otherwise, if E1.E2 refers to a non-static member function. . .
1544 // [t]he expression can be used only as the left-hand operand of a
1545 // member function call.
1547 // There are other safeguards against such uses, but it's important
1548 // to get this right here so that we don't end up making a
1549 // spuriously dependent expression if we're inside a dependent
1551 if (!R
.empty() && (*R
.begin())->isCXXClassMember()) {
1552 bool MightBeImplicitMember
;
1553 if (!isAddressOfOperand
)
1554 MightBeImplicitMember
= true;
1555 else if (!SS
.isEmpty())
1556 MightBeImplicitMember
= false;
1557 else if (R
.isOverloadedResult())
1558 MightBeImplicitMember
= false;
1559 else if (R
.isUnresolvableResult())
1560 MightBeImplicitMember
= true;
1562 MightBeImplicitMember
= isa
<FieldDecl
>(R
.getFoundDecl());
1564 if (MightBeImplicitMember
)
1565 return BuildPossibleImplicitMemberExpr(SS
, R
, TemplateArgs
);
1569 return BuildTemplateIdExpr(SS
, R
, ADL
, *TemplateArgs
);
1571 return BuildDeclarationNameExpr(SS
, R
, ADL
);
1574 /// Builds an expression which might be an implicit member expression.
1576 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec
&SS
,
1578 const TemplateArgumentListInfo
*TemplateArgs
) {
1579 switch (ClassifyImplicitMemberAccess(*this, R
)) {
1581 return BuildImplicitMemberExpr(SS
, R
, TemplateArgs
, true);
1583 case IMA_AnonymousMember
:
1584 assert(R
.isSingleResult());
1585 return BuildAnonymousStructUnionMemberReference(R
.getNameLoc(),
1586 R
.getAsSingle
<FieldDecl
>());
1589 case IMA_Mixed_Unrelated
:
1590 case IMA_Unresolved
:
1591 return BuildImplicitMemberExpr(SS
, R
, TemplateArgs
, false);
1594 case IMA_Mixed_StaticContext
:
1595 case IMA_Unresolved_StaticContext
:
1597 return BuildTemplateIdExpr(SS
, R
, false, *TemplateArgs
);
1598 return BuildDeclarationNameExpr(SS
, R
, false);
1600 case IMA_Error_StaticContext
:
1601 case IMA_Error_Unrelated
:
1602 DiagnoseInstanceReference(*this, SS
, R
);
1606 llvm_unreachable("unexpected instance member access kind");
1610 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1611 /// declaration name, generally during template instantiation.
1612 /// There's a large number of things which don't need to be done along
1615 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec
&SS
,
1616 const DeclarationNameInfo
&NameInfo
) {
1618 if (!(DC
= computeDeclContext(SS
, false)) || DC
->isDependentContext())
1619 return BuildDependentDeclRefExpr(SS
, NameInfo
, 0);
1621 if (RequireCompleteDeclContext(SS
, DC
))
1624 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
1625 LookupQualifiedName(R
, DC
);
1627 if (R
.isAmbiguous())
1631 Diag(NameInfo
.getLoc(), diag::err_no_member
)
1632 << NameInfo
.getName() << DC
<< SS
.getRange();
1636 return BuildDeclarationNameExpr(SS
, R
, /*ADL*/ false);
1639 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1640 /// detected that we're currently inside an ObjC method. Perform some
1641 /// additional lookup.
1643 /// Ideally, most of this would be done by lookup, but there's
1644 /// actually quite a lot of extra work involved.
1646 /// Returns a null sentinel to indicate trivial success.
1648 Sema::LookupInObjCMethod(LookupResult
&Lookup
, Scope
*S
,
1649 IdentifierInfo
*II
, bool AllowBuiltinCreation
) {
1650 SourceLocation Loc
= Lookup
.getNameLoc();
1651 ObjCMethodDecl
*CurMethod
= getCurMethodDecl();
1653 // There are two cases to handle here. 1) scoped lookup could have failed,
1654 // in which case we should look for an ivar. 2) scoped lookup could have
1655 // found a decl, but that decl is outside the current instance method (i.e.
1656 // a global variable). In these two cases, we do a lookup for an ivar with
1657 // this name, if the lookup sucedes, we replace it our current decl.
1659 // If we're in a class method, we don't normally want to look for
1660 // ivars. But if we don't find anything else, and there's an
1661 // ivar, that's an error.
1662 bool IsClassMethod
= CurMethod
->isClassMethod();
1666 LookForIvars
= true;
1667 else if (IsClassMethod
)
1668 LookForIvars
= false;
1670 LookForIvars
= (Lookup
.isSingleResult() &&
1671 Lookup
.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1672 ObjCInterfaceDecl
*IFace
= 0;
1674 IFace
= CurMethod
->getClassInterface();
1675 ObjCInterfaceDecl
*ClassDeclared
;
1676 if (ObjCIvarDecl
*IV
= IFace
->lookupInstanceVariable(II
, ClassDeclared
)) {
1677 // Diagnose using an ivar in a class method.
1679 return ExprError(Diag(Loc
, diag::error_ivar_use_in_class_method
)
1680 << IV
->getDeclName());
1682 // If we're referencing an invalid decl, just return this as a silent
1683 // error node. The error diagnostic was already emitted on the decl.
1684 if (IV
->isInvalidDecl())
1687 // Check if referencing a field with __attribute__((deprecated)).
1688 if (DiagnoseUseOfDecl(IV
, Loc
))
1691 // Diagnose the use of an ivar outside of the declaring class.
1692 if (IV
->getAccessControl() == ObjCIvarDecl::Private
&&
1693 ClassDeclared
!= IFace
)
1694 Diag(Loc
, diag::error_private_ivar_access
) << IV
->getDeclName();
1696 // FIXME: This should use a new expr for a direct reference, don't
1697 // turn this into Self->ivar, just return a BareIVarExpr or something.
1698 IdentifierInfo
&II
= Context
.Idents
.get("self");
1699 UnqualifiedId SelfName
;
1700 SelfName
.setIdentifier(&II
, SourceLocation());
1701 CXXScopeSpec SelfScopeSpec
;
1702 ExprResult SelfExpr
= ActOnIdExpression(S
, SelfScopeSpec
,
1703 SelfName
, false, false);
1704 if (SelfExpr
.isInvalid())
1707 MarkDeclarationReferenced(Loc
, IV
);
1708 return Owned(new (Context
)
1709 ObjCIvarRefExpr(IV
, IV
->getType(), Loc
,
1710 SelfExpr
.takeAs
<Expr
>(), true, true));
1712 } else if (CurMethod
->isInstanceMethod()) {
1713 // We should warn if a local variable hides an ivar.
1714 ObjCInterfaceDecl
*IFace
= CurMethod
->getClassInterface();
1715 ObjCInterfaceDecl
*ClassDeclared
;
1716 if (ObjCIvarDecl
*IV
= IFace
->lookupInstanceVariable(II
, ClassDeclared
)) {
1717 if (IV
->getAccessControl() != ObjCIvarDecl::Private
||
1718 IFace
== ClassDeclared
)
1719 Diag(Loc
, diag::warn_ivar_use_hidden
) << IV
->getDeclName();
1723 if (Lookup
.empty() && II
&& AllowBuiltinCreation
) {
1724 // FIXME. Consolidate this with similar code in LookupName.
1725 if (unsigned BuiltinID
= II
->getBuiltinID()) {
1726 if (!(getLangOptions().CPlusPlus
&&
1727 Context
.BuiltinInfo
.isPredefinedLibFunction(BuiltinID
))) {
1728 NamedDecl
*D
= LazilyCreateBuiltin((IdentifierInfo
*)II
, BuiltinID
,
1729 S
, Lookup
.isForRedeclaration(),
1730 Lookup
.getNameLoc());
1731 if (D
) Lookup
.addDecl(D
);
1735 // Sentinel value saying that we didn't do anything special.
1736 return Owned((Expr
*) 0);
1739 /// \brief Cast a base object to a member's actual type.
1741 /// Logically this happens in three phases:
1743 /// * First we cast from the base type to the naming class.
1744 /// The naming class is the class into which we were looking
1745 /// when we found the member; it's the qualifier type if a
1746 /// qualifier was provided, and otherwise it's the base type.
1748 /// * Next we cast from the naming class to the declaring class.
1749 /// If the member we found was brought into a class's scope by
1750 /// a using declaration, this is that class; otherwise it's
1751 /// the class declaring the member.
1753 /// * Finally we cast from the declaring class to the "true"
1754 /// declaring class of the member. This conversion does not
1755 /// obey access control.
1757 Sema::PerformObjectMemberConversion(Expr
*&From
,
1758 NestedNameSpecifier
*Qualifier
,
1759 NamedDecl
*FoundDecl
,
1760 NamedDecl
*Member
) {
1761 CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Member
->getDeclContext());
1765 QualType DestRecordType
;
1767 QualType FromRecordType
;
1768 QualType FromType
= From
->getType();
1769 bool PointerConversions
= false;
1770 if (isa
<FieldDecl
>(Member
)) {
1771 DestRecordType
= Context
.getCanonicalType(Context
.getTypeDeclType(RD
));
1773 if (FromType
->getAs
<PointerType
>()) {
1774 DestType
= Context
.getPointerType(DestRecordType
);
1775 FromRecordType
= FromType
->getPointeeType();
1776 PointerConversions
= true;
1778 DestType
= DestRecordType
;
1779 FromRecordType
= FromType
;
1781 } else if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Member
)) {
1782 if (Method
->isStatic())
1785 DestType
= Method
->getThisType(Context
);
1786 DestRecordType
= DestType
->getPointeeType();
1788 if (FromType
->getAs
<PointerType
>()) {
1789 FromRecordType
= FromType
->getPointeeType();
1790 PointerConversions
= true;
1792 FromRecordType
= FromType
;
1793 DestType
= DestRecordType
;
1796 // No conversion necessary.
1800 if (DestType
->isDependentType() || FromType
->isDependentType())
1803 // If the unqualified types are the same, no conversion is necessary.
1804 if (Context
.hasSameUnqualifiedType(FromRecordType
, DestRecordType
))
1807 SourceRange FromRange
= From
->getSourceRange();
1808 SourceLocation FromLoc
= FromRange
.getBegin();
1810 ExprValueKind VK
= CastCategory(From
);
1812 // C++ [class.member.lookup]p8:
1813 // [...] Ambiguities can often be resolved by qualifying a name with its
1816 // If the member was a qualified name and the qualified referred to a
1817 // specific base subobject type, we'll cast to that intermediate type
1818 // first and then to the object in which the member is declared. That allows
1819 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1821 // class Base { public: int x; };
1822 // class Derived1 : public Base { };
1823 // class Derived2 : public Base { };
1824 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1826 // void VeryDerived::f() {
1827 // x = 17; // error: ambiguous base subobjects
1828 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1831 QualType QType
= QualType(Qualifier
->getAsType(), 0);
1832 assert(!QType
.isNull() && "lookup done with dependent qualifier?");
1833 assert(QType
->isRecordType() && "lookup done with non-record type");
1835 QualType QRecordType
= QualType(QType
->getAs
<RecordType
>(), 0);
1837 // In C++98, the qualifier type doesn't actually have to be a base
1838 // type of the object type, in which case we just ignore it.
1839 // Otherwise build the appropriate casts.
1840 if (IsDerivedFrom(FromRecordType
, QRecordType
)) {
1841 CXXCastPath BasePath
;
1842 if (CheckDerivedToBaseConversion(FromRecordType
, QRecordType
,
1843 FromLoc
, FromRange
, &BasePath
))
1846 if (PointerConversions
)
1847 QType
= Context
.getPointerType(QType
);
1848 ImpCastExprToType(From
, QType
, CK_UncheckedDerivedToBase
,
1852 FromRecordType
= QRecordType
;
1854 // If the qualifier type was the same as the destination type,
1856 if (Context
.hasSameUnqualifiedType(FromRecordType
, DestRecordType
))
1861 bool IgnoreAccess
= false;
1863 // If we actually found the member through a using declaration, cast
1864 // down to the using declaration's type.
1866 // Pointer equality is fine here because only one declaration of a
1867 // class ever has member declarations.
1868 if (FoundDecl
->getDeclContext() != Member
->getDeclContext()) {
1869 assert(isa
<UsingShadowDecl
>(FoundDecl
));
1870 QualType URecordType
= Context
.getTypeDeclType(
1871 cast
<CXXRecordDecl
>(FoundDecl
->getDeclContext()));
1873 // We only need to do this if the naming-class to declaring-class
1874 // conversion is non-trivial.
1875 if (!Context
.hasSameUnqualifiedType(FromRecordType
, URecordType
)) {
1876 assert(IsDerivedFrom(FromRecordType
, URecordType
));
1877 CXXCastPath BasePath
;
1878 if (CheckDerivedToBaseConversion(FromRecordType
, URecordType
,
1879 FromLoc
, FromRange
, &BasePath
))
1882 QualType UType
= URecordType
;
1883 if (PointerConversions
)
1884 UType
= Context
.getPointerType(UType
);
1885 ImpCastExprToType(From
, UType
, CK_UncheckedDerivedToBase
,
1888 FromRecordType
= URecordType
;
1891 // We don't do access control for the conversion from the
1892 // declaring class to the true declaring class.
1893 IgnoreAccess
= true;
1896 CXXCastPath BasePath
;
1897 if (CheckDerivedToBaseConversion(FromRecordType
, DestRecordType
,
1898 FromLoc
, FromRange
, &BasePath
,
1902 ImpCastExprToType(From
, DestType
, CK_UncheckedDerivedToBase
,
1907 /// \brief Build a MemberExpr AST node.
1908 static MemberExpr
*BuildMemberExpr(ASTContext
&C
, Expr
*Base
, bool isArrow
,
1909 const CXXScopeSpec
&SS
, ValueDecl
*Member
,
1910 DeclAccessPair FoundDecl
,
1911 const DeclarationNameInfo
&MemberNameInfo
,
1913 const TemplateArgumentListInfo
*TemplateArgs
= 0) {
1914 NestedNameSpecifier
*Qualifier
= 0;
1915 SourceRange QualifierRange
;
1917 Qualifier
= (NestedNameSpecifier
*) SS
.getScopeRep();
1918 QualifierRange
= SS
.getRange();
1921 return MemberExpr::Create(C
, Base
, isArrow
, Qualifier
, QualifierRange
,
1922 Member
, FoundDecl
, MemberNameInfo
,
1926 /// Builds an implicit member access expression. The current context
1927 /// is known to be an instance method, and the given unqualified lookup
1928 /// set is known to contain only instance members, at least one of which
1929 /// is from an appropriate type.
1931 Sema::BuildImplicitMemberExpr(const CXXScopeSpec
&SS
,
1933 const TemplateArgumentListInfo
*TemplateArgs
,
1934 bool IsKnownInstance
) {
1935 assert(!R
.empty() && !R
.isAmbiguous());
1937 SourceLocation Loc
= R
.getNameLoc();
1939 // We may have found a field within an anonymous union or struct
1940 // (C++ [class.union]).
1941 // FIXME: This needs to happen post-isImplicitMemberReference?
1942 // FIXME: template-ids inside anonymous structs?
1943 if (FieldDecl
*FD
= R
.getAsSingle
<FieldDecl
>())
1944 if (cast
<RecordDecl
>(FD
->getDeclContext())->isAnonymousStructOrUnion())
1945 return BuildAnonymousStructUnionMemberReference(Loc
, FD
);
1947 // If this is known to be an instance access, go ahead and build a
1948 // 'this' expression now.
1949 DeclContext
*DC
= getFunctionLevelDeclContext();
1950 QualType ThisType
= cast
<CXXMethodDecl
>(DC
)->getThisType(Context
);
1951 Expr
*This
= 0; // null signifies implicit access
1952 if (IsKnownInstance
) {
1953 SourceLocation Loc
= R
.getNameLoc();
1954 if (SS
.getRange().isValid())
1955 Loc
= SS
.getRange().getBegin();
1956 This
= new (Context
) CXXThisExpr(Loc
, ThisType
, /*isImplicit=*/true);
1959 return BuildMemberReferenceExpr(This
, ThisType
,
1960 /*OpLoc*/ SourceLocation(),
1963 /*FirstQualifierInScope*/ 0,
1967 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec
&SS
,
1968 const LookupResult
&R
,
1969 bool HasTrailingLParen
) {
1970 // Only when used directly as the postfix-expression of a call.
1971 if (!HasTrailingLParen
)
1974 // Never if a scope specifier was provided.
1978 // Only in C++ or ObjC++.
1979 if (!getLangOptions().CPlusPlus
)
1982 // Turn off ADL when we find certain kinds of declarations during
1984 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
) {
1987 // C++0x [basic.lookup.argdep]p3:
1988 // -- a declaration of a class member
1989 // Since using decls preserve this property, we check this on the
1991 if (D
->isCXXClassMember())
1994 // C++0x [basic.lookup.argdep]p3:
1995 // -- a block-scope function declaration that is not a
1996 // using-declaration
1997 // NOTE: we also trigger this for function templates (in fact, we
1998 // don't check the decl type at all, since all other decl types
1999 // turn off ADL anyway).
2000 if (isa
<UsingShadowDecl
>(D
))
2001 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
2002 else if (D
->getDeclContext()->isFunctionOrMethod())
2005 // C++0x [basic.lookup.argdep]p3:
2006 // -- a declaration that is neither a function or a function
2008 // And also for builtin functions.
2009 if (isa
<FunctionDecl
>(D
)) {
2010 FunctionDecl
*FDecl
= cast
<FunctionDecl
>(D
);
2012 // But also builtin functions.
2013 if (FDecl
->getBuiltinID() && FDecl
->isImplicit())
2015 } else if (!isa
<FunctionTemplateDecl
>(D
))
2023 /// Diagnoses obvious problems with the use of the given declaration
2024 /// as an expression. This is only actually called for lookups that
2025 /// were not overloaded, and it doesn't promise that the declaration
2026 /// will in fact be used.
2027 static bool CheckDeclInExpr(Sema
&S
, SourceLocation Loc
, NamedDecl
*D
) {
2028 if (isa
<TypedefDecl
>(D
)) {
2029 S
.Diag(Loc
, diag::err_unexpected_typedef
) << D
->getDeclName();
2033 if (isa
<ObjCInterfaceDecl
>(D
)) {
2034 S
.Diag(Loc
, diag::err_unexpected_interface
) << D
->getDeclName();
2038 if (isa
<NamespaceDecl
>(D
)) {
2039 S
.Diag(Loc
, diag::err_unexpected_namespace
) << D
->getDeclName();
2047 Sema::BuildDeclarationNameExpr(const CXXScopeSpec
&SS
,
2050 // If this is a single, fully-resolved result and we don't need ADL,
2051 // just build an ordinary singleton decl ref.
2052 if (!NeedsADL
&& R
.isSingleResult() && !R
.getAsSingle
<FunctionTemplateDecl
>())
2053 return BuildDeclarationNameExpr(SS
, R
.getLookupNameInfo(),
2056 // We only need to check the declaration if there's exactly one
2057 // result, because in the overloaded case the results can only be
2058 // functions and function templates.
2059 if (R
.isSingleResult() &&
2060 CheckDeclInExpr(*this, R
.getNameLoc(), R
.getFoundDecl()))
2063 // Otherwise, just build an unresolved lookup expression. Suppress
2064 // any lookup-related diagnostics; we'll hash these out later, when
2065 // we've picked a target.
2066 R
.suppressDiagnostics();
2069 = UnresolvedLookupExpr::ComputeDependence(R
.begin(), R
.end(), 0);
2070 UnresolvedLookupExpr
*ULE
2071 = UnresolvedLookupExpr::Create(Context
, Dependent
, R
.getNamingClass(),
2072 (NestedNameSpecifier
*) SS
.getScopeRep(),
2073 SS
.getRange(), R
.getLookupNameInfo(),
2074 NeedsADL
, R
.isOverloadedResult(),
2075 R
.begin(), R
.end());
2081 /// \brief Complete semantic analysis for a reference to the given declaration.
2083 Sema::BuildDeclarationNameExpr(const CXXScopeSpec
&SS
,
2084 const DeclarationNameInfo
&NameInfo
,
2086 assert(D
&& "Cannot refer to a NULL declaration");
2087 assert(!isa
<FunctionTemplateDecl
>(D
) &&
2088 "Cannot refer unambiguously to a function template");
2090 SourceLocation Loc
= NameInfo
.getLoc();
2091 if (CheckDeclInExpr(*this, Loc
, D
))
2094 if (TemplateDecl
*Template
= dyn_cast
<TemplateDecl
>(D
)) {
2095 // Specifically diagnose references to class templates that are missing
2096 // a template argument list.
2097 Diag(Loc
, diag::err_template_decl_ref
)
2098 << Template
<< SS
.getRange();
2099 Diag(Template
->getLocation(), diag::note_template_decl_here
);
2103 // Make sure that we're referring to a value.
2104 ValueDecl
*VD
= dyn_cast
<ValueDecl
>(D
);
2106 Diag(Loc
, diag::err_ref_non_value
)
2107 << D
<< SS
.getRange();
2108 Diag(D
->getLocation(), diag::note_declared_at
);
2112 // Check whether this declaration can be used. Note that we suppress
2113 // this check when we're going to perform argument-dependent lookup
2114 // on this function name, because this might not be the function
2115 // that overload resolution actually selects.
2116 if (DiagnoseUseOfDecl(VD
, Loc
))
2119 // Only create DeclRefExpr's for valid Decl's.
2120 if (VD
->isInvalidDecl())
2123 // If the identifier reference is inside a block, and it refers to a value
2124 // that is outside the block, create a BlockDeclRefExpr instead of a
2125 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2126 // the block is formed.
2128 // We do not do this for things like enum constants, global variables, etc,
2129 // as they do not get snapshotted.
2131 if (getCurBlock() &&
2132 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD
)) {
2133 if (VD
->getType().getTypePtr()->isVariablyModifiedType()) {
2134 Diag(Loc
, diag::err_ref_vm_type
);
2135 Diag(D
->getLocation(), diag::note_declared_at
);
2139 if (VD
->getType()->isArrayType()) {
2140 Diag(Loc
, diag::err_ref_array_type
);
2141 Diag(D
->getLocation(), diag::note_declared_at
);
2145 MarkDeclarationReferenced(Loc
, VD
);
2146 QualType ExprTy
= VD
->getType().getNonReferenceType();
2147 // The BlocksAttr indicates the variable is bound by-reference.
2148 bool byrefVar
= (VD
->getAttr
<BlocksAttr
>() != 0);
2149 QualType T
= VD
->getType();
2150 BlockDeclRefExpr
*BDRE
;
2153 // This is to record that a 'const' was actually synthesize and added.
2154 bool constAdded
= !ExprTy
.isConstQualified();
2155 // Variable will be bound by-copy, make it const within the closure.
2157 BDRE
= new (Context
) BlockDeclRefExpr(VD
, ExprTy
, Loc
, false,
2161 BDRE
= new (Context
) BlockDeclRefExpr(VD
, ExprTy
, Loc
, true);
2163 if (getLangOptions().CPlusPlus
) {
2164 if (!T
->isDependentType() && !T
->isReferenceType()) {
2165 Expr
*E
= new (Context
)
2166 DeclRefExpr(const_cast<ValueDecl
*>(BDRE
->getDecl()), T
,
2168 if (T
->getAs
<RecordType
>())
2169 if (!T
->isUnionType()) {
2170 ExprResult Res
= PerformCopyInitialization(
2171 InitializedEntity::InitializeBlock(VD
->getLocation(),
2175 if (!Res
.isInvalid()) {
2176 Res
= MaybeCreateCXXExprWithTemporaries(Res
.get());
2177 Expr
*Init
= Res
.takeAs
<Expr
>();
2178 BDRE
->setCopyConstructorExpr(Init
);
2185 // If this reference is not in a block or if the referenced variable is
2186 // within the block, create a normal DeclRefExpr.
2188 return BuildDeclRefExpr(VD
, VD
->getType().getNonReferenceType(),
2192 ExprResult
Sema::ActOnPredefinedExpr(SourceLocation Loc
,
2193 tok::TokenKind Kind
) {
2194 PredefinedExpr::IdentType IT
;
2197 default: assert(0 && "Unknown simple primary expr!");
2198 case tok::kw___func__
: IT
= PredefinedExpr::Func
; break; // [C99 6.4.2.2]
2199 case tok::kw___FUNCTION__
: IT
= PredefinedExpr::Function
; break;
2200 case tok::kw___PRETTY_FUNCTION__
: IT
= PredefinedExpr::PrettyFunction
; break;
2203 // Pre-defined identifiers are of type char[x], where x is the length of the
2206 Decl
*currentDecl
= getCurFunctionOrMethodDecl();
2207 if (!currentDecl
&& getCurBlock())
2208 currentDecl
= getCurBlock()->TheDecl
;
2210 Diag(Loc
, diag::ext_predef_outside_function
);
2211 currentDecl
= Context
.getTranslationUnitDecl();
2215 if (cast
<DeclContext
>(currentDecl
)->isDependentContext()) {
2216 ResTy
= Context
.DependentTy
;
2218 unsigned Length
= PredefinedExpr::ComputeName(IT
, currentDecl
).length();
2220 llvm::APInt
LengthI(32, Length
+ 1);
2221 ResTy
= Context
.CharTy
.withConst();
2222 ResTy
= Context
.getConstantArrayType(ResTy
, LengthI
, ArrayType::Normal
, 0);
2224 return Owned(new (Context
) PredefinedExpr(Loc
, ResTy
, IT
));
2227 ExprResult
Sema::ActOnCharacterConstant(const Token
&Tok
) {
2228 llvm::SmallString
<16> CharBuffer
;
2229 bool Invalid
= false;
2230 llvm::StringRef ThisTok
= PP
.getSpelling(Tok
, CharBuffer
, &Invalid
);
2234 CharLiteralParser
Literal(ThisTok
.begin(), ThisTok
.end(), Tok
.getLocation(),
2236 if (Literal
.hadError())
2240 if (!getLangOptions().CPlusPlus
)
2241 Ty
= Context
.IntTy
; // 'x' and L'x' -> int in C.
2242 else if (Literal
.isWide())
2243 Ty
= Context
.WCharTy
; // L'x' -> wchar_t in C++.
2244 else if (Literal
.isMultiChar())
2245 Ty
= Context
.IntTy
; // 'wxyz' -> int in C++.
2247 Ty
= Context
.CharTy
; // 'x' -> char in C++
2249 return Owned(new (Context
) CharacterLiteral(Literal
.getValue(),
2251 Ty
, Tok
.getLocation()));
2254 ExprResult
Sema::ActOnNumericConstant(const Token
&Tok
) {
2255 // Fast path for a single digit (which is quite common). A single digit
2256 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2257 if (Tok
.getLength() == 1) {
2258 const char Val
= PP
.getSpellingOfSingleCharacterNumericConstant(Tok
);
2259 unsigned IntSize
= Context
.Target
.getIntWidth();
2260 return Owned(IntegerLiteral::Create(Context
, llvm::APInt(IntSize
, Val
-'0'),
2261 Context
.IntTy
, Tok
.getLocation()));
2264 llvm::SmallString
<512> IntegerBuffer
;
2265 // Add padding so that NumericLiteralParser can overread by one character.
2266 IntegerBuffer
.resize(Tok
.getLength()+1);
2267 const char *ThisTokBegin
= &IntegerBuffer
[0];
2269 // Get the spelling of the token, which eliminates trigraphs, etc.
2270 bool Invalid
= false;
2271 unsigned ActualLength
= PP
.getSpelling(Tok
, ThisTokBegin
, &Invalid
);
2275 NumericLiteralParser
Literal(ThisTokBegin
, ThisTokBegin
+ActualLength
,
2276 Tok
.getLocation(), PP
);
2277 if (Literal
.hadError
)
2282 if (Literal
.isFloatingLiteral()) {
2284 if (Literal
.isFloat
)
2285 Ty
= Context
.FloatTy
;
2286 else if (!Literal
.isLong
)
2287 Ty
= Context
.DoubleTy
;
2289 Ty
= Context
.LongDoubleTy
;
2291 const llvm::fltSemantics
&Format
= Context
.getFloatTypeSemantics(Ty
);
2293 using llvm::APFloat
;
2294 APFloat
Val(Format
);
2296 APFloat::opStatus result
= Literal
.GetFloatValue(Val
);
2298 // Overflow is always an error, but underflow is only an error if
2299 // we underflowed to zero (APFloat reports denormals as underflow).
2300 if ((result
& APFloat::opOverflow
) ||
2301 ((result
& APFloat::opUnderflow
) && Val
.isZero())) {
2302 unsigned diagnostic
;
2303 llvm::SmallString
<20> buffer
;
2304 if (result
& APFloat::opOverflow
) {
2305 diagnostic
= diag::warn_float_overflow
;
2306 APFloat::getLargest(Format
).toString(buffer
);
2308 diagnostic
= diag::warn_float_underflow
;
2309 APFloat::getSmallest(Format
).toString(buffer
);
2312 Diag(Tok
.getLocation(), diagnostic
)
2314 << llvm::StringRef(buffer
.data(), buffer
.size());
2317 bool isExact
= (result
== APFloat::opOK
);
2318 Res
= FloatingLiteral::Create(Context
, Val
, isExact
, Ty
, Tok
.getLocation());
2320 } else if (!Literal
.isIntegerLiteral()) {
2325 // long long is a C99 feature.
2326 if (!getLangOptions().C99
&& !getLangOptions().CPlusPlus0x
&&
2328 Diag(Tok
.getLocation(), diag::ext_longlong
);
2330 // Get the value in the widest-possible width.
2331 llvm::APInt
ResultVal(Context
.Target
.getIntMaxTWidth(), 0);
2333 if (Literal
.GetIntegerValue(ResultVal
)) {
2334 // If this value didn't fit into uintmax_t, warn and force to ull.
2335 Diag(Tok
.getLocation(), diag::warn_integer_too_large
);
2336 Ty
= Context
.UnsignedLongLongTy
;
2337 assert(Context
.getTypeSize(Ty
) == ResultVal
.getBitWidth() &&
2338 "long long is not intmax_t?");
2340 // If this value fits into a ULL, try to figure out what else it fits into
2341 // according to the rules of C99 6.4.4.1p5.
2343 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2344 // be an unsigned int.
2345 bool AllowUnsigned
= Literal
.isUnsigned
|| Literal
.getRadix() != 10;
2347 // Check from smallest to largest, picking the smallest type we can.
2349 if (!Literal
.isLong
&& !Literal
.isLongLong
) {
2350 // Are int/unsigned possibilities?
2351 unsigned IntSize
= Context
.Target
.getIntWidth();
2353 // Does it fit in a unsigned int?
2354 if (ResultVal
.isIntN(IntSize
)) {
2355 // Does it fit in a signed int?
2356 if (!Literal
.isUnsigned
&& ResultVal
[IntSize
-1] == 0)
2358 else if (AllowUnsigned
)
2359 Ty
= Context
.UnsignedIntTy
;
2364 // Are long/unsigned long possibilities?
2365 if (Ty
.isNull() && !Literal
.isLongLong
) {
2366 unsigned LongSize
= Context
.Target
.getLongWidth();
2368 // Does it fit in a unsigned long?
2369 if (ResultVal
.isIntN(LongSize
)) {
2370 // Does it fit in a signed long?
2371 if (!Literal
.isUnsigned
&& ResultVal
[LongSize
-1] == 0)
2372 Ty
= Context
.LongTy
;
2373 else if (AllowUnsigned
)
2374 Ty
= Context
.UnsignedLongTy
;
2379 // Finally, check long long if needed.
2381 unsigned LongLongSize
= Context
.Target
.getLongLongWidth();
2383 // Does it fit in a unsigned long long?
2384 if (ResultVal
.isIntN(LongLongSize
)) {
2385 // Does it fit in a signed long long?
2386 if (!Literal
.isUnsigned
&& ResultVal
[LongLongSize
-1] == 0)
2387 Ty
= Context
.LongLongTy
;
2388 else if (AllowUnsigned
)
2389 Ty
= Context
.UnsignedLongLongTy
;
2390 Width
= LongLongSize
;
2394 // If we still couldn't decide a type, we probably have something that
2395 // does not fit in a signed long long, but has no U suffix.
2397 Diag(Tok
.getLocation(), diag::warn_integer_too_large_for_signed
);
2398 Ty
= Context
.UnsignedLongLongTy
;
2399 Width
= Context
.Target
.getLongLongWidth();
2402 if (ResultVal
.getBitWidth() != Width
)
2403 ResultVal
.trunc(Width
);
2405 Res
= IntegerLiteral::Create(Context
, ResultVal
, Ty
, Tok
.getLocation());
2408 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2409 if (Literal
.isImaginary
)
2410 Res
= new (Context
) ImaginaryLiteral(Res
,
2411 Context
.getComplexType(Res
->getType()));
2416 ExprResult
Sema::ActOnParenExpr(SourceLocation L
,
2417 SourceLocation R
, Expr
*E
) {
2418 assert((E
!= 0) && "ActOnParenExpr() missing expr");
2419 return Owned(new (Context
) ParenExpr(L
, R
, E
));
2422 /// The UsualUnaryConversions() function is *not* called by this routine.
2423 /// See C99 6.3.2.1p[2-4] for more details.
2424 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType
,
2425 SourceLocation OpLoc
,
2426 SourceRange ExprRange
,
2428 if (exprType
->isDependentType())
2431 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2432 // the result is the size of the referenced type."
2433 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2434 // result shall be the alignment of the referenced type."
2435 if (const ReferenceType
*Ref
= exprType
->getAs
<ReferenceType
>())
2436 exprType
= Ref
->getPointeeType();
2439 if (exprType
->isFunctionType()) {
2440 // alignof(function) is allowed as an extension.
2442 Diag(OpLoc
, diag::ext_sizeof_function_type
) << ExprRange
;
2446 // Allow sizeof(void)/alignof(void) as an extension.
2447 if (exprType
->isVoidType()) {
2448 Diag(OpLoc
, diag::ext_sizeof_void_type
)
2449 << (isSizeof
? "sizeof" : "__alignof") << ExprRange
;
2453 if (RequireCompleteType(OpLoc
, exprType
,
2454 PDiag(diag::err_sizeof_alignof_incomplete_type
)
2455 << int(!isSizeof
) << ExprRange
))
2458 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2459 if (LangOpts
.ObjCNonFragileABI
&& exprType
->isObjCObjectType()) {
2460 Diag(OpLoc
, diag::err_sizeof_nonfragile_interface
)
2461 << exprType
<< isSizeof
<< ExprRange
;
2468 static bool CheckAlignOfExpr(Sema
&S
, Expr
*E
, SourceLocation OpLoc
,
2469 SourceRange ExprRange
) {
2470 E
= E
->IgnoreParens();
2472 // alignof decl is always ok.
2473 if (isa
<DeclRefExpr
>(E
))
2476 // Cannot know anything else if the expression is dependent.
2477 if (E
->isTypeDependent())
2480 if (E
->getBitField()) {
2481 S
. Diag(OpLoc
, diag::err_sizeof_alignof_bitfield
) << 1 << ExprRange
;
2485 // Alignment of a field access is always okay, so long as it isn't a
2487 if (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
))
2488 if (isa
<FieldDecl
>(ME
->getMemberDecl()))
2491 return S
.CheckSizeOfAlignOfOperand(E
->getType(), OpLoc
, ExprRange
, false);
2494 /// \brief Build a sizeof or alignof expression given a type operand.
2496 Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo
*TInfo
,
2497 SourceLocation OpLoc
,
2498 bool isSizeOf
, SourceRange R
) {
2502 QualType T
= TInfo
->getType();
2504 if (!T
->isDependentType() &&
2505 CheckSizeOfAlignOfOperand(T
, OpLoc
, R
, isSizeOf
))
2508 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2509 return Owned(new (Context
) SizeOfAlignOfExpr(isSizeOf
, TInfo
,
2510 Context
.getSizeType(), OpLoc
,
2514 /// \brief Build a sizeof or alignof expression given an expression
2517 Sema::CreateSizeOfAlignOfExpr(Expr
*E
, SourceLocation OpLoc
,
2518 bool isSizeOf
, SourceRange R
) {
2519 // Verify that the operand is valid.
2520 bool isInvalid
= false;
2521 if (E
->isTypeDependent()) {
2522 // Delay type-checking for type-dependent expressions.
2523 } else if (!isSizeOf
) {
2524 isInvalid
= CheckAlignOfExpr(*this, E
, OpLoc
, R
);
2525 } else if (E
->getBitField()) { // C99 6.5.3.4p1.
2526 Diag(OpLoc
, diag::err_sizeof_alignof_bitfield
) << 0;
2528 } else if (E
->getType()->isPlaceholderType()) {
2529 ExprResult PE
= CheckPlaceholderExpr(E
, OpLoc
);
2530 if (PE
.isInvalid()) return ExprError();
2531 return CreateSizeOfAlignOfExpr(PE
.take(), OpLoc
, isSizeOf
, R
);
2533 isInvalid
= CheckSizeOfAlignOfOperand(E
->getType(), OpLoc
, R
, true);
2539 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2540 return Owned(new (Context
) SizeOfAlignOfExpr(isSizeOf
, E
,
2541 Context
.getSizeType(), OpLoc
,
2545 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2546 /// the same for @c alignof and @c __alignof
2547 /// Note that the ArgRange is invalid if isType is false.
2549 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc
, bool isSizeof
, bool isType
,
2550 void *TyOrEx
, const SourceRange
&ArgRange
) {
2551 // If error parsing type, ignore.
2552 if (TyOrEx
== 0) return ExprError();
2555 TypeSourceInfo
*TInfo
;
2556 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx
), &TInfo
);
2557 return CreateSizeOfAlignOfExpr(TInfo
, OpLoc
, isSizeof
, ArgRange
);
2560 Expr
*ArgEx
= (Expr
*)TyOrEx
;
2562 = CreateSizeOfAlignOfExpr(ArgEx
, OpLoc
, isSizeof
, ArgEx
->getSourceRange());
2564 return move(Result
);
2567 QualType
Sema::CheckRealImagOperand(Expr
*&V
, SourceLocation Loc
, bool isReal
) {
2568 if (V
->isTypeDependent())
2569 return Context
.DependentTy
;
2571 // These operators return the element type of a complex type.
2572 if (const ComplexType
*CT
= V
->getType()->getAs
<ComplexType
>())
2573 return CT
->getElementType();
2575 // Otherwise they pass through real integer and floating point types here.
2576 if (V
->getType()->isArithmeticType())
2577 return V
->getType();
2579 // Test for placeholders.
2580 ExprResult PR
= CheckPlaceholderExpr(V
, Loc
);
2581 if (PR
.isInvalid()) return QualType();
2582 if (PR
.take() != V
) {
2584 return CheckRealImagOperand(V
, Loc
, isReal
);
2587 // Reject anything else.
2588 Diag(Loc
, diag::err_realimag_invalid_type
) << V
->getType()
2589 << (isReal
? "__real" : "__imag");
2596 Sema::ActOnPostfixUnaryOp(Scope
*S
, SourceLocation OpLoc
,
2597 tok::TokenKind Kind
, Expr
*Input
) {
2598 UnaryOperatorKind Opc
;
2600 default: assert(0 && "Unknown unary op!");
2601 case tok::plusplus
: Opc
= UO_PostInc
; break;
2602 case tok::minusminus
: Opc
= UO_PostDec
; break;
2605 return BuildUnaryOp(S
, OpLoc
, Opc
, Input
);
2609 Sema::ActOnArraySubscriptExpr(Scope
*S
, Expr
*Base
, SourceLocation LLoc
,
2610 Expr
*Idx
, SourceLocation RLoc
) {
2611 // Since this might be a postfix expression, get rid of ParenListExprs.
2612 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, Base
);
2613 if (Result
.isInvalid()) return ExprError();
2614 Base
= Result
.take();
2616 Expr
*LHSExp
= Base
, *RHSExp
= Idx
;
2618 if (getLangOptions().CPlusPlus
&&
2619 (LHSExp
->isTypeDependent() || RHSExp
->isTypeDependent())) {
2620 return Owned(new (Context
) ArraySubscriptExpr(LHSExp
, RHSExp
,
2621 Context
.DependentTy
, RLoc
));
2624 if (getLangOptions().CPlusPlus
&&
2625 (LHSExp
->getType()->isRecordType() ||
2626 LHSExp
->getType()->isEnumeralType() ||
2627 RHSExp
->getType()->isRecordType() ||
2628 RHSExp
->getType()->isEnumeralType())) {
2629 return CreateOverloadedArraySubscriptExpr(LLoc
, RLoc
, Base
, Idx
);
2632 return CreateBuiltinArraySubscriptExpr(Base
, LLoc
, Idx
, RLoc
);
2637 Sema::CreateBuiltinArraySubscriptExpr(Expr
*Base
, SourceLocation LLoc
,
2638 Expr
*Idx
, SourceLocation RLoc
) {
2639 Expr
*LHSExp
= Base
;
2642 // Perform default conversions.
2643 if (!LHSExp
->getType()->getAs
<VectorType
>())
2644 DefaultFunctionArrayLvalueConversion(LHSExp
);
2645 DefaultFunctionArrayLvalueConversion(RHSExp
);
2647 QualType LHSTy
= LHSExp
->getType(), RHSTy
= RHSExp
->getType();
2649 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
2650 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
2651 // in the subscript position. As a result, we need to derive the array base
2652 // and index from the expression types.
2653 Expr
*BaseExpr
, *IndexExpr
;
2654 QualType ResultType
;
2655 if (LHSTy
->isDependentType() || RHSTy
->isDependentType()) {
2658 ResultType
= Context
.DependentTy
;
2659 } else if (const PointerType
*PTy
= LHSTy
->getAs
<PointerType
>()) {
2662 ResultType
= PTy
->getPointeeType();
2663 } else if (const PointerType
*PTy
= RHSTy
->getAs
<PointerType
>()) {
2664 // Handle the uncommon case of "123[Ptr]".
2667 ResultType
= PTy
->getPointeeType();
2668 } else if (const ObjCObjectPointerType
*PTy
=
2669 LHSTy
->getAs
<ObjCObjectPointerType
>()) {
2672 ResultType
= PTy
->getPointeeType();
2673 } else if (const ObjCObjectPointerType
*PTy
=
2674 RHSTy
->getAs
<ObjCObjectPointerType
>()) {
2675 // Handle the uncommon case of "123[Ptr]".
2678 ResultType
= PTy
->getPointeeType();
2679 } else if (const VectorType
*VTy
= LHSTy
->getAs
<VectorType
>()) {
2680 BaseExpr
= LHSExp
; // vectors: V[123]
2683 // FIXME: need to deal with const...
2684 ResultType
= VTy
->getElementType();
2685 } else if (LHSTy
->isArrayType()) {
2686 // If we see an array that wasn't promoted by
2687 // DefaultFunctionArrayLvalueConversion, it must be an array that
2688 // wasn't promoted because of the C90 rule that doesn't
2689 // allow promoting non-lvalue arrays. Warn, then
2690 // force the promotion here.
2691 Diag(LHSExp
->getLocStart(), diag::ext_subscript_non_lvalue
) <<
2692 LHSExp
->getSourceRange();
2693 ImpCastExprToType(LHSExp
, Context
.getArrayDecayedType(LHSTy
),
2694 CK_ArrayToPointerDecay
);
2695 LHSTy
= LHSExp
->getType();
2699 ResultType
= LHSTy
->getAs
<PointerType
>()->getPointeeType();
2700 } else if (RHSTy
->isArrayType()) {
2701 // Same as previous, except for 123[f().a] case
2702 Diag(RHSExp
->getLocStart(), diag::ext_subscript_non_lvalue
) <<
2703 RHSExp
->getSourceRange();
2704 ImpCastExprToType(RHSExp
, Context
.getArrayDecayedType(RHSTy
),
2705 CK_ArrayToPointerDecay
);
2706 RHSTy
= RHSExp
->getType();
2710 ResultType
= RHSTy
->getAs
<PointerType
>()->getPointeeType();
2712 return ExprError(Diag(LLoc
, diag::err_typecheck_subscript_value
)
2713 << LHSExp
->getSourceRange() << RHSExp
->getSourceRange());
2716 if (!IndexExpr
->getType()->isIntegerType() && !IndexExpr
->isTypeDependent())
2717 return ExprError(Diag(LLoc
, diag::err_typecheck_subscript_not_integer
)
2718 << IndexExpr
->getSourceRange());
2720 if ((IndexExpr
->getType()->isSpecificBuiltinType(BuiltinType::Char_S
) ||
2721 IndexExpr
->getType()->isSpecificBuiltinType(BuiltinType::Char_U
))
2722 && !IndexExpr
->isTypeDependent())
2723 Diag(LLoc
, diag::warn_subscript_is_char
) << IndexExpr
->getSourceRange();
2725 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
2726 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2727 // type. Note that Functions are not objects, and that (in C99 parlance)
2728 // incomplete types are not object types.
2729 if (ResultType
->isFunctionType()) {
2730 Diag(BaseExpr
->getLocStart(), diag::err_subscript_function_type
)
2731 << ResultType
<< BaseExpr
->getSourceRange();
2735 if (ResultType
->isVoidType() && !getLangOptions().CPlusPlus
) {
2736 // GNU extension: subscripting on pointer to void
2737 Diag(LLoc
, diag::ext_gnu_void_ptr
)
2738 << BaseExpr
->getSourceRange();
2739 } else if (!ResultType
->isDependentType() &&
2740 RequireCompleteType(LLoc
, ResultType
,
2741 PDiag(diag::err_subscript_incomplete_type
)
2742 << BaseExpr
->getSourceRange()))
2745 // Diagnose bad cases where we step over interface counts.
2746 if (ResultType
->isObjCObjectType() && LangOpts
.ObjCNonFragileABI
) {
2747 Diag(LLoc
, diag::err_subscript_nonfragile_interface
)
2748 << ResultType
<< BaseExpr
->getSourceRange();
2752 return Owned(new (Context
) ArraySubscriptExpr(LHSExp
, RHSExp
,
2757 CheckExtVectorComponent(QualType baseType
, SourceLocation OpLoc
,
2758 const IdentifierInfo
*CompName
,
2759 SourceLocation CompLoc
) {
2760 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2763 // FIXME: This logic can be greatly simplified by splitting it along
2764 // halving/not halving and reworking the component checking.
2765 const ExtVectorType
*vecType
= baseType
->getAs
<ExtVectorType
>();
2767 // The vector accessor can't exceed the number of elements.
2768 const char *compStr
= CompName
->getNameStart();
2770 // This flag determines whether or not the component is one of the four
2771 // special names that indicate a subset of exactly half the elements are
2773 bool HalvingSwizzle
= false;
2775 // This flag determines whether or not CompName has an 's' char prefix,
2776 // indicating that it is a string of hex values to be used as vector indices.
2777 bool HexSwizzle
= *compStr
== 's' || *compStr
== 'S';
2779 // Check that we've found one of the special components, or that the component
2780 // names must come from the same set.
2781 if (!strcmp(compStr
, "hi") || !strcmp(compStr
, "lo") ||
2782 !strcmp(compStr
, "even") || !strcmp(compStr
, "odd")) {
2783 HalvingSwizzle
= true;
2784 } else if (vecType
->getPointAccessorIdx(*compStr
) != -1) {
2787 while (*compStr
&& vecType
->getPointAccessorIdx(*compStr
) != -1);
2788 } else if (HexSwizzle
|| vecType
->getNumericAccessorIdx(*compStr
) != -1) {
2791 while (*compStr
&& vecType
->getNumericAccessorIdx(*compStr
) != -1);
2794 if (!HalvingSwizzle
&& *compStr
) {
2795 // We didn't get to the end of the string. This means the component names
2796 // didn't come from the same set *or* we encountered an illegal name.
2797 Diag(OpLoc
, diag::err_ext_vector_component_name_illegal
)
2798 << llvm::StringRef(compStr
, 1) << SourceRange(CompLoc
);
2802 // Ensure no component accessor exceeds the width of the vector type it
2804 if (!HalvingSwizzle
) {
2805 compStr
= CompName
->getNameStart();
2811 if (!vecType
->isAccessorWithinNumElements(*compStr
++)) {
2812 Diag(OpLoc
, diag::err_ext_vector_component_exceeds_length
)
2813 << baseType
<< SourceRange(CompLoc
);
2819 // The component accessor looks fine - now we need to compute the actual type.
2820 // The vector type is implied by the component accessor. For example,
2821 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
2822 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
2823 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
2824 unsigned CompSize
= HalvingSwizzle
? (vecType
->getNumElements() + 1) / 2
2825 : CompName
->getLength();
2830 return vecType
->getElementType();
2832 QualType VT
= Context
.getExtVectorType(vecType
->getElementType(), CompSize
);
2833 // Now look up the TypeDefDecl from the vector type. Without this,
2834 // diagostics look bad. We want extended vector types to appear built-in.
2835 for (unsigned i
= 0, E
= ExtVectorDecls
.size(); i
!= E
; ++i
) {
2836 if (ExtVectorDecls
[i
]->getUnderlyingType() == VT
)
2837 return Context
.getTypedefType(ExtVectorDecls
[i
]);
2839 return VT
; // should never get here (a typedef type should always be found).
2842 static Decl
*FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl
*PDecl
,
2843 IdentifierInfo
*Member
,
2844 const Selector
&Sel
,
2845 ASTContext
&Context
) {
2847 if (ObjCPropertyDecl
*PD
= PDecl
->FindPropertyDeclaration(Member
))
2849 if (ObjCMethodDecl
*OMD
= PDecl
->getInstanceMethod(Sel
))
2852 for (ObjCProtocolDecl::protocol_iterator I
= PDecl
->protocol_begin(),
2853 E
= PDecl
->protocol_end(); I
!= E
; ++I
) {
2854 if (Decl
*D
= FindGetterSetterNameDeclFromProtocolList(*I
, Member
, Sel
,
2861 static Decl
*FindGetterSetterNameDecl(const ObjCObjectPointerType
*QIdTy
,
2862 IdentifierInfo
*Member
,
2863 const Selector
&Sel
,
2864 ASTContext
&Context
) {
2865 // Check protocols on qualified interfaces.
2867 for (ObjCObjectPointerType::qual_iterator I
= QIdTy
->qual_begin(),
2868 E
= QIdTy
->qual_end(); I
!= E
; ++I
) {
2870 if (ObjCPropertyDecl
*PD
= (*I
)->FindPropertyDeclaration(Member
)) {
2874 // Also must look for a getter or setter name which uses property syntax.
2875 if (ObjCMethodDecl
*OMD
= (*I
)->getInstanceMethod(Sel
)) {
2881 for (ObjCObjectPointerType::qual_iterator I
= QIdTy
->qual_begin(),
2882 E
= QIdTy
->qual_end(); I
!= E
; ++I
) {
2883 // Search in the protocol-qualifier list of current protocol.
2884 GDecl
= FindGetterSetterNameDeclFromProtocolList(*I
, Member
, Sel
,
2894 Sema::ActOnDependentMemberExpr(Expr
*BaseExpr
, QualType BaseType
,
2895 bool IsArrow
, SourceLocation OpLoc
,
2896 const CXXScopeSpec
&SS
,
2897 NamedDecl
*FirstQualifierInScope
,
2898 const DeclarationNameInfo
&NameInfo
,
2899 const TemplateArgumentListInfo
*TemplateArgs
) {
2900 // Even in dependent contexts, try to diagnose base expressions with
2901 // obviously wrong types, e.g.:
2906 // In Obj-C++, however, the above expression is valid, since it could be
2907 // accessing the 'f' property if T is an Obj-C interface. The extra check
2908 // allows this, while still reporting an error if T is a struct pointer.
2910 const PointerType
*PT
= BaseType
->getAs
<PointerType
>();
2911 if (PT
&& (!getLangOptions().ObjC1
||
2912 PT
->getPointeeType()->isRecordType())) {
2913 assert(BaseExpr
&& "cannot happen with implicit member accesses");
2914 Diag(NameInfo
.getLoc(), diag::err_typecheck_member_reference_struct_union
)
2915 << BaseType
<< BaseExpr
->getSourceRange();
2920 assert(BaseType
->isDependentType() ||
2921 NameInfo
.getName().isDependentName() ||
2922 isDependentScopeSpecifier(SS
));
2924 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2925 // must have pointer type, and the accessed type is the pointee.
2926 return Owned(CXXDependentScopeMemberExpr::Create(Context
, BaseExpr
, BaseType
,
2930 FirstQualifierInScope
,
2931 NameInfo
, TemplateArgs
));
2934 /// We know that the given qualified member reference points only to
2935 /// declarations which do not belong to the static type of the base
2936 /// expression. Diagnose the problem.
2937 static void DiagnoseQualifiedMemberReference(Sema
&SemaRef
,
2940 const CXXScopeSpec
&SS
,
2941 const LookupResult
&R
) {
2942 // If this is an implicit member access, use a different set of
2945 return DiagnoseInstanceReference(SemaRef
, SS
, R
);
2947 SemaRef
.Diag(R
.getNameLoc(), diag::err_qualified_member_of_unrelated
)
2948 << SS
.getRange() << R
.getRepresentativeDecl() << BaseType
;
2951 // Check whether the declarations we found through a nested-name
2952 // specifier in a member expression are actually members of the base
2953 // type. The restriction here is:
2955 // C++ [expr.ref]p2:
2956 // ... In these cases, the id-expression shall name a
2957 // member of the class or of one of its base classes.
2959 // So it's perfectly legitimate for the nested-name specifier to name
2960 // an unrelated class, and for us to find an overload set including
2961 // decls from classes which are not superclasses, as long as the decl
2962 // we actually pick through overload resolution is from a superclass.
2963 bool Sema::CheckQualifiedMemberReference(Expr
*BaseExpr
,
2965 const CXXScopeSpec
&SS
,
2966 const LookupResult
&R
) {
2967 const RecordType
*BaseRT
= BaseType
->getAs
<RecordType
>();
2969 // We can't check this yet because the base type is still
2971 assert(BaseType
->isDependentType());
2974 CXXRecordDecl
*BaseRecord
= cast
<CXXRecordDecl
>(BaseRT
->getDecl());
2976 for (LookupResult::iterator I
= R
.begin(), E
= R
.end(); I
!= E
; ++I
) {
2977 // If this is an implicit member reference and we find a
2978 // non-instance member, it's not an error.
2979 if (!BaseExpr
&& !(*I
)->isCXXInstanceMember())
2982 // Note that we use the DC of the decl, not the underlying decl.
2983 DeclContext
*DC
= (*I
)->getDeclContext();
2984 while (DC
->isTransparentContext())
2985 DC
= DC
->getParent();
2987 if (!DC
->isRecord())
2990 llvm::SmallPtrSet
<CXXRecordDecl
*,4> MemberRecord
;
2991 MemberRecord
.insert(cast
<CXXRecordDecl
>(DC
)->getCanonicalDecl());
2993 if (!IsProvablyNotDerivedFrom(*this, BaseRecord
, MemberRecord
))
2997 DiagnoseQualifiedMemberReference(*this, BaseExpr
, BaseType
, SS
, R
);
3002 LookupMemberExprInRecord(Sema
&SemaRef
, LookupResult
&R
,
3003 SourceRange BaseRange
, const RecordType
*RTy
,
3004 SourceLocation OpLoc
, CXXScopeSpec
&SS
,
3005 bool HasTemplateArgs
) {
3006 RecordDecl
*RDecl
= RTy
->getDecl();
3007 if (SemaRef
.RequireCompleteType(OpLoc
, QualType(RTy
, 0),
3008 SemaRef
.PDiag(diag::err_typecheck_incomplete_tag
)
3012 if (HasTemplateArgs
) {
3013 // LookupTemplateName doesn't expect these both to exist simultaneously.
3014 QualType ObjectType
= SS
.isSet() ? QualType() : QualType(RTy
, 0);
3017 SemaRef
.LookupTemplateName(R
, 0, SS
, ObjectType
, false, MOUS
);
3021 DeclContext
*DC
= RDecl
;
3023 // If the member name was a qualified-id, look into the
3024 // nested-name-specifier.
3025 DC
= SemaRef
.computeDeclContext(SS
, false);
3027 if (SemaRef
.RequireCompleteDeclContext(SS
, DC
)) {
3028 SemaRef
.Diag(SS
.getRange().getEnd(), diag::err_typecheck_incomplete_tag
)
3029 << SS
.getRange() << DC
;
3033 assert(DC
&& "Cannot handle non-computable dependent contexts in lookup");
3035 if (!isa
<TypeDecl
>(DC
)) {
3036 SemaRef
.Diag(R
.getNameLoc(), diag::err_qualified_member_nonclass
)
3037 << DC
<< SS
.getRange();
3042 // The record definition is complete, now look up the member.
3043 SemaRef
.LookupQualifiedName(R
, DC
);
3048 // We didn't find anything with the given name, so try to correct
3050 DeclarationName Name
= R
.getLookupName();
3051 if (SemaRef
.CorrectTypo(R
, 0, &SS
, DC
, false, Sema::CTC_MemberLookup
) &&
3053 (isa
<ValueDecl
>(*R
.begin()) || isa
<FunctionTemplateDecl
>(*R
.begin()))) {
3054 SemaRef
.Diag(R
.getNameLoc(), diag::err_no_member_suggest
)
3055 << Name
<< DC
<< R
.getLookupName() << SS
.getRange()
3056 << FixItHint::CreateReplacement(R
.getNameLoc(),
3057 R
.getLookupName().getAsString());
3058 if (NamedDecl
*ND
= R
.getAsSingle
<NamedDecl
>())
3059 SemaRef
.Diag(ND
->getLocation(), diag::note_previous_decl
)
3060 << ND
->getDeclName();
3064 R
.setLookupName(Name
);
3071 Sema::BuildMemberReferenceExpr(Expr
*Base
, QualType BaseType
,
3072 SourceLocation OpLoc
, bool IsArrow
,
3074 NamedDecl
*FirstQualifierInScope
,
3075 const DeclarationNameInfo
&NameInfo
,
3076 const TemplateArgumentListInfo
*TemplateArgs
) {
3077 if (BaseType
->isDependentType() ||
3078 (SS
.isSet() && isDependentScopeSpecifier(SS
)))
3079 return ActOnDependentMemberExpr(Base
, BaseType
,
3081 SS
, FirstQualifierInScope
,
3082 NameInfo
, TemplateArgs
);
3084 LookupResult
R(*this, NameInfo
, LookupMemberName
);
3086 // Implicit member accesses.
3088 QualType RecordTy
= BaseType
;
3089 if (IsArrow
) RecordTy
= RecordTy
->getAs
<PointerType
>()->getPointeeType();
3090 if (LookupMemberExprInRecord(*this, R
, SourceRange(),
3091 RecordTy
->getAs
<RecordType
>(),
3092 OpLoc
, SS
, TemplateArgs
!= 0))
3095 // Explicit member accesses.
3098 LookupMemberExpr(R
, Base
, IsArrow
, OpLoc
,
3099 SS
, /*ObjCImpDecl*/ 0, TemplateArgs
!= 0);
3101 if (Result
.isInvalid()) {
3107 return move(Result
);
3109 // LookupMemberExpr can modify Base, and thus change BaseType
3110 BaseType
= Base
->getType();
3113 return BuildMemberReferenceExpr(Base
, BaseType
,
3114 OpLoc
, IsArrow
, SS
, FirstQualifierInScope
,
3119 Sema::BuildMemberReferenceExpr(Expr
*BaseExpr
, QualType BaseExprType
,
3120 SourceLocation OpLoc
, bool IsArrow
,
3121 const CXXScopeSpec
&SS
,
3122 NamedDecl
*FirstQualifierInScope
,
3124 const TemplateArgumentListInfo
*TemplateArgs
,
3125 bool SuppressQualifierCheck
) {
3126 QualType BaseType
= BaseExprType
;
3128 assert(BaseType
->isPointerType());
3129 BaseType
= BaseType
->getAs
<PointerType
>()->getPointeeType();
3131 R
.setBaseObjectType(BaseType
);
3133 NestedNameSpecifier
*Qualifier
= SS
.getScopeRep();
3134 const DeclarationNameInfo
&MemberNameInfo
= R
.getLookupNameInfo();
3135 DeclarationName MemberName
= MemberNameInfo
.getName();
3136 SourceLocation MemberLoc
= MemberNameInfo
.getLoc();
3138 if (R
.isAmbiguous())
3142 // Rederive where we looked up.
3143 DeclContext
*DC
= (SS
.isSet()
3144 ? computeDeclContext(SS
, false)
3145 : BaseType
->getAs
<RecordType
>()->getDecl());
3147 Diag(R
.getNameLoc(), diag::err_no_member
)
3149 << (BaseExpr
? BaseExpr
->getSourceRange() : SourceRange());
3153 // Diagnose lookups that find only declarations from a non-base
3154 // type. This is possible for either qualified lookups (which may
3155 // have been qualified with an unrelated type) or implicit member
3156 // expressions (which were found with unqualified lookup and thus
3157 // may have come from an enclosing scope). Note that it's okay for
3158 // lookup to find declarations from a non-base type as long as those
3159 // aren't the ones picked by overload resolution.
3160 if ((SS
.isSet() || !BaseExpr
||
3161 (isa
<CXXThisExpr
>(BaseExpr
) &&
3162 cast
<CXXThisExpr
>(BaseExpr
)->isImplicit())) &&
3163 !SuppressQualifierCheck
&&
3164 CheckQualifiedMemberReference(BaseExpr
, BaseType
, SS
, R
))
3167 // Construct an unresolved result if we in fact got an unresolved
3169 if (R
.isOverloadedResult() || R
.isUnresolvableResult()) {
3171 BaseExprType
->isDependentType() ||
3172 R
.isUnresolvableResult() ||
3173 OverloadExpr::ComputeDependence(R
.begin(), R
.end(), TemplateArgs
);
3175 // Suppress any lookup-related diagnostics; we'll do these when we
3177 R
.suppressDiagnostics();
3179 UnresolvedMemberExpr
*MemExpr
3180 = UnresolvedMemberExpr::Create(Context
, Dependent
,
3181 R
.isUnresolvableResult(),
3182 BaseExpr
, BaseExprType
,
3184 Qualifier
, SS
.getRange(),
3186 TemplateArgs
, R
.begin(), R
.end());
3188 return Owned(MemExpr
);
3191 assert(R
.isSingleResult());
3192 DeclAccessPair FoundDecl
= R
.begin().getPair();
3193 NamedDecl
*MemberDecl
= R
.getFoundDecl();
3195 // FIXME: diagnose the presence of template arguments now.
3197 // If the decl being referenced had an error, return an error for this
3198 // sub-expr without emitting another error, in order to avoid cascading
3200 if (MemberDecl
->isInvalidDecl())
3203 // Handle the implicit-member-access case.
3205 // If this is not an instance member, convert to a non-member access.
3206 if (!MemberDecl
->isCXXInstanceMember())
3207 return BuildDeclarationNameExpr(SS
, R
.getLookupNameInfo(), MemberDecl
);
3209 SourceLocation Loc
= R
.getNameLoc();
3210 if (SS
.getRange().isValid())
3211 Loc
= SS
.getRange().getBegin();
3212 BaseExpr
= new (Context
) CXXThisExpr(Loc
, BaseExprType
,/*isImplicit=*/true);
3215 bool ShouldCheckUse
= true;
3216 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(MemberDecl
)) {
3217 // Don't diagnose the use of a virtual member function unless it's
3218 // explicitly qualified.
3219 if (MD
->isVirtual() && !SS
.isSet())
3220 ShouldCheckUse
= false;
3223 // Check the use of this member.
3224 if (ShouldCheckUse
&& DiagnoseUseOfDecl(MemberDecl
, MemberLoc
)) {
3229 if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(MemberDecl
)) {
3230 // We may have found a field within an anonymous union or struct
3231 // (C++ [class.union]).
3232 if (cast
<RecordDecl
>(FD
->getDeclContext())->isAnonymousStructOrUnion() &&
3233 !BaseType
->getAs
<RecordType
>()->getDecl()->isAnonymousStructOrUnion())
3234 return BuildAnonymousStructUnionMemberReference(MemberLoc
, FD
,
3237 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
3238 QualType MemberType
= FD
->getType();
3239 if (const ReferenceType
*Ref
= MemberType
->getAs
<ReferenceType
>())
3240 MemberType
= Ref
->getPointeeType();
3242 Qualifiers BaseQuals
= BaseType
.getQualifiers();
3243 BaseQuals
.removeObjCGCAttr();
3244 if (FD
->isMutable()) BaseQuals
.removeConst();
3246 Qualifiers MemberQuals
3247 = Context
.getCanonicalType(MemberType
).getQualifiers();
3249 Qualifiers Combined
= BaseQuals
+ MemberQuals
;
3250 if (Combined
!= MemberQuals
)
3251 MemberType
= Context
.getQualifiedType(MemberType
, Combined
);
3254 MarkDeclarationReferenced(MemberLoc
, FD
);
3255 if (PerformObjectMemberConversion(BaseExpr
, Qualifier
, FoundDecl
, FD
))
3257 return Owned(BuildMemberExpr(Context
, BaseExpr
, IsArrow
, SS
,
3258 FD
, FoundDecl
, MemberNameInfo
,
3262 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(MemberDecl
)) {
3263 MarkDeclarationReferenced(MemberLoc
, Var
);
3264 return Owned(BuildMemberExpr(Context
, BaseExpr
, IsArrow
, SS
,
3265 Var
, FoundDecl
, MemberNameInfo
,
3266 Var
->getType().getNonReferenceType()));
3269 if (FunctionDecl
*MemberFn
= dyn_cast
<FunctionDecl
>(MemberDecl
)) {
3270 MarkDeclarationReferenced(MemberLoc
, MemberDecl
);
3271 return Owned(BuildMemberExpr(Context
, BaseExpr
, IsArrow
, SS
,
3272 MemberFn
, FoundDecl
, MemberNameInfo
,
3273 MemberFn
->getType()));
3276 if (EnumConstantDecl
*Enum
= dyn_cast
<EnumConstantDecl
>(MemberDecl
)) {
3277 MarkDeclarationReferenced(MemberLoc
, MemberDecl
);
3278 return Owned(BuildMemberExpr(Context
, BaseExpr
, IsArrow
, SS
,
3279 Enum
, FoundDecl
, MemberNameInfo
,
3285 // We found something that we didn't expect. Complain.
3286 if (isa
<TypeDecl
>(MemberDecl
))
3287 Diag(MemberLoc
, diag::err_typecheck_member_reference_type
)
3288 << MemberName
<< BaseType
<< int(IsArrow
);
3290 Diag(MemberLoc
, diag::err_typecheck_member_reference_unknown
)
3291 << MemberName
<< BaseType
<< int(IsArrow
);
3293 Diag(MemberDecl
->getLocation(), diag::note_member_declared_here
)
3295 R
.suppressDiagnostics();
3299 /// Look up the given member of the given non-type-dependent
3300 /// expression. This can return in one of two ways:
3301 /// * If it returns a sentinel null-but-valid result, the caller will
3302 /// assume that lookup was performed and the results written into
3303 /// the provided structure. It will take over from there.
3304 /// * Otherwise, the returned expression will be produced in place of
3305 /// an ordinary member expression.
3307 /// The ObjCImpDecl bit is a gross hack that will need to be properly
3308 /// fixed for ObjC++.
3310 Sema::LookupMemberExpr(LookupResult
&R
, Expr
*&BaseExpr
,
3311 bool &IsArrow
, SourceLocation OpLoc
,
3313 Decl
*ObjCImpDecl
, bool HasTemplateArgs
) {
3314 assert(BaseExpr
&& "no base expression");
3316 // Perform default conversions.
3317 DefaultFunctionArrayConversion(BaseExpr
);
3319 QualType BaseType
= BaseExpr
->getType();
3320 assert(!BaseType
->isDependentType());
3322 DeclarationName MemberName
= R
.getLookupName();
3323 SourceLocation MemberLoc
= R
.getNameLoc();
3325 // If the user is trying to apply -> or . to a function pointer
3326 // type, it's probably because they forgot parentheses to call that
3327 // function. Suggest the addition of those parentheses, build the
3328 // call, and continue on.
3329 if (const PointerType
*Ptr
= BaseType
->getAs
<PointerType
>()) {
3330 if (const FunctionProtoType
*Fun
3331 = Ptr
->getPointeeType()->getAs
<FunctionProtoType
>()) {
3332 QualType ResultTy
= Fun
->getResultType();
3333 if (Fun
->getNumArgs() == 0 &&
3334 ((!IsArrow
&& ResultTy
->isRecordType()) ||
3335 (IsArrow
&& ResultTy
->isPointerType() &&
3336 ResultTy
->getAs
<PointerType
>()->getPointeeType()
3337 ->isRecordType()))) {
3338 SourceLocation Loc
= PP
.getLocForEndOfToken(BaseExpr
->getLocEnd());
3339 Diag(BaseExpr
->getExprLoc(), diag::err_member_reference_needs_call
)
3341 << FixItHint::CreateInsertion(Loc
, "()");
3344 = ActOnCallExpr(0, BaseExpr
, Loc
, MultiExprArg(*this, 0, 0), Loc
);
3346 if (NewBase
.isInvalid())
3349 BaseExpr
= NewBase
.takeAs
<Expr
>();
3350 DefaultFunctionArrayConversion(BaseExpr
);
3351 BaseType
= BaseExpr
->getType();
3356 // If this is an Objective-C pseudo-builtin and a definition is provided then
3358 if (BaseType
->isObjCIdType()) {
3360 // Handle the following exceptional case PObj->isa.
3361 if (const ObjCObjectPointerType
*OPT
=
3362 BaseType
->getAs
<ObjCObjectPointerType
>()) {
3363 if (OPT
->getObjectType()->isObjCId() &&
3364 MemberName
.getAsIdentifierInfo()->isStr("isa"))
3365 return Owned(new (Context
) ObjCIsaExpr(BaseExpr
, true, MemberLoc
,
3366 Context
.getObjCClassType()));
3369 // We have an 'id' type. Rather than fall through, we check if this
3370 // is a reference to 'isa'.
3371 if (BaseType
!= Context
.ObjCIdRedefinitionType
) {
3372 BaseType
= Context
.ObjCIdRedefinitionType
;
3373 ImpCastExprToType(BaseExpr
, BaseType
, CK_BitCast
);
3377 // If this is an Objective-C pseudo-builtin and a definition is provided then
3379 if (Context
.isObjCSelType(BaseType
)) {
3380 // We have an 'SEL' type. Rather than fall through, we check if this
3381 // is a reference to 'sel_id'.
3382 if (BaseType
!= Context
.ObjCSelRedefinitionType
) {
3383 BaseType
= Context
.ObjCSelRedefinitionType
;
3384 ImpCastExprToType(BaseExpr
, BaseType
, CK_BitCast
);
3388 assert(!BaseType
.isNull() && "no type for member expression");
3390 // Handle properties on ObjC 'Class' types.
3391 if (!IsArrow
&& BaseType
->isObjCClassType()) {
3392 // Also must look for a getter name which uses property syntax.
3393 IdentifierInfo
*Member
= MemberName
.getAsIdentifierInfo();
3394 Selector Sel
= PP
.getSelectorTable().getNullarySelector(Member
);
3395 if (ObjCMethodDecl
*MD
= getCurMethodDecl()) {
3396 ObjCInterfaceDecl
*IFace
= MD
->getClassInterface();
3397 ObjCMethodDecl
*Getter
;
3398 // FIXME: need to also look locally in the implementation.
3399 if ((Getter
= IFace
->lookupClassMethod(Sel
))) {
3400 // Check the use of this method.
3401 if (DiagnoseUseOfDecl(Getter
, MemberLoc
))
3404 // If we found a getter then this may be a valid dot-reference, we
3405 // will look for the matching setter, in case it is needed.
3406 Selector SetterSel
=
3407 SelectorTable::constructSetterName(PP
.getIdentifierTable(),
3408 PP
.getSelectorTable(), Member
);
3409 ObjCMethodDecl
*Setter
= IFace
->lookupClassMethod(SetterSel
);
3411 // If this reference is in an @implementation, also check for 'private'
3413 Setter
= IFace
->lookupPrivateInstanceMethod(SetterSel
);
3415 // Look through local category implementations associated with the class.
3417 Setter
= IFace
->getCategoryClassMethod(SetterSel
);
3419 if (Setter
&& DiagnoseUseOfDecl(Setter
, MemberLoc
))
3422 if (Getter
|| Setter
) {
3426 PType
= Getter
->getSendResultType();
3428 // Get the expression type from Setter's incoming parameter.
3429 PType
= (*(Setter
->param_end() -1))->getType();
3430 // FIXME: we must check that the setter has property type.
3431 return Owned(new (Context
) ObjCImplicitSetterGetterRefExpr(Getter
,
3433 Setter
, MemberLoc
, BaseExpr
));
3435 return ExprError(Diag(MemberLoc
, diag::err_property_not_found
)
3436 << MemberName
<< BaseType
);
3440 if (BaseType
->isObjCClassType() &&
3441 BaseType
!= Context
.ObjCClassRedefinitionType
) {
3442 BaseType
= Context
.ObjCClassRedefinitionType
;
3443 ImpCastExprToType(BaseExpr
, BaseType
, CK_BitCast
);
3447 if (const PointerType
*PT
= BaseType
->getAs
<PointerType
>())
3448 BaseType
= PT
->getPointeeType();
3449 else if (BaseType
->isObjCObjectPointerType())
3451 else if (BaseType
->isRecordType()) {
3452 // Recover from arrow accesses to records, e.g.:
3453 // struct MyRecord foo;
3455 // This is actually well-formed in C++ if MyRecord has an
3456 // overloaded operator->, but that should have been dealt with
3458 Diag(OpLoc
, diag::err_typecheck_member_reference_suggestion
)
3459 << BaseType
<< int(IsArrow
) << BaseExpr
->getSourceRange()
3460 << FixItHint::CreateReplacement(OpLoc
, ".");
3463 Diag(MemberLoc
, diag::err_typecheck_member_reference_arrow
)
3464 << BaseType
<< BaseExpr
->getSourceRange();
3468 // Recover from dot accesses to pointers, e.g.:
3471 // This is actually well-formed in two cases:
3472 // - 'type' is an Objective C type
3473 // - 'bar' is a pseudo-destructor name which happens to refer to
3474 // the appropriate pointer type
3475 if (MemberName
.getNameKind() != DeclarationName::CXXDestructorName
) {
3476 const PointerType
*PT
= BaseType
->getAs
<PointerType
>();
3477 if (PT
&& PT
->getPointeeType()->isRecordType()) {
3478 Diag(OpLoc
, diag::err_typecheck_member_reference_suggestion
)
3479 << BaseType
<< int(IsArrow
) << BaseExpr
->getSourceRange()
3480 << FixItHint::CreateReplacement(OpLoc
, "->");
3481 BaseType
= PT
->getPointeeType();
3487 // Handle field access to simple records.
3488 if (const RecordType
*RTy
= BaseType
->getAs
<RecordType
>()) {
3489 if (LookupMemberExprInRecord(*this, R
, BaseExpr
->getSourceRange(),
3490 RTy
, OpLoc
, SS
, HasTemplateArgs
))
3492 return Owned((Expr
*) 0);
3495 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3497 if ((IsArrow
&& BaseType
->isObjCObjectPointerType()) ||
3498 (!IsArrow
&& BaseType
->isObjCObjectType())) {
3499 const ObjCObjectPointerType
*OPT
= BaseType
->getAs
<ObjCObjectPointerType
>();
3500 ObjCInterfaceDecl
*IDecl
=
3501 OPT
? OPT
->getInterfaceDecl()
3502 : BaseType
->getAs
<ObjCObjectType
>()->getInterface();
3504 IdentifierInfo
*Member
= MemberName
.getAsIdentifierInfo();
3506 ObjCInterfaceDecl
*ClassDeclared
;
3507 ObjCIvarDecl
*IV
= IDecl
->lookupInstanceVariable(Member
, ClassDeclared
);
3510 // Attempt to correct for typos in ivar names.
3511 LookupResult
Res(*this, R
.getLookupName(), R
.getNameLoc(),
3513 if (CorrectTypo(Res
, 0, 0, IDecl
, false,
3514 IsArrow
? CTC_ObjCIvarLookup
3515 : CTC_ObjCPropertyLookup
) &&
3516 (IV
= Res
.getAsSingle
<ObjCIvarDecl
>())) {
3517 Diag(R
.getNameLoc(),
3518 diag::err_typecheck_member_reference_ivar_suggest
)
3519 << IDecl
->getDeclName() << MemberName
<< IV
->getDeclName()
3520 << FixItHint::CreateReplacement(R
.getNameLoc(),
3521 IV
->getNameAsString());
3522 Diag(IV
->getLocation(), diag::note_previous_decl
)
3523 << IV
->getDeclName();
3526 Res
.setLookupName(Member
);
3531 // If the decl being referenced had an error, return an error for this
3532 // sub-expr without emitting another error, in order to avoid cascading
3534 if (IV
->isInvalidDecl())
3537 // Check whether we can reference this field.
3538 if (DiagnoseUseOfDecl(IV
, MemberLoc
))
3540 if (IV
->getAccessControl() != ObjCIvarDecl::Public
&&
3541 IV
->getAccessControl() != ObjCIvarDecl::Package
) {
3542 ObjCInterfaceDecl
*ClassOfMethodDecl
= 0;
3543 if (ObjCMethodDecl
*MD
= getCurMethodDecl())
3544 ClassOfMethodDecl
= MD
->getClassInterface();
3545 else if (ObjCImpDecl
&& getCurFunctionDecl()) {
3546 // Case of a c-function declared inside an objc implementation.
3547 // FIXME: For a c-style function nested inside an objc implementation
3548 // class, there is no implementation context available, so we pass
3549 // down the context as argument to this routine. Ideally, this context
3550 // need be passed down in the AST node and somehow calculated from the
3551 // AST for a function decl.
3552 if (ObjCImplementationDecl
*IMPD
=
3553 dyn_cast
<ObjCImplementationDecl
>(ObjCImpDecl
))
3554 ClassOfMethodDecl
= IMPD
->getClassInterface();
3555 else if (ObjCCategoryImplDecl
* CatImplClass
=
3556 dyn_cast
<ObjCCategoryImplDecl
>(ObjCImpDecl
))
3557 ClassOfMethodDecl
= CatImplClass
->getClassInterface();
3560 if (IV
->getAccessControl() == ObjCIvarDecl::Private
) {
3561 if (ClassDeclared
!= IDecl
||
3562 ClassOfMethodDecl
!= ClassDeclared
)
3563 Diag(MemberLoc
, diag::error_private_ivar_access
)
3564 << IV
->getDeclName();
3565 } else if (!IDecl
->isSuperClassOf(ClassOfMethodDecl
))
3567 Diag(MemberLoc
, diag::error_protected_ivar_access
)
3568 << IV
->getDeclName();
3571 return Owned(new (Context
) ObjCIvarRefExpr(IV
, IV
->getType(),
3572 MemberLoc
, BaseExpr
,
3575 return ExprError(Diag(MemberLoc
, diag::err_typecheck_member_reference_ivar
)
3576 << IDecl
->getDeclName() << MemberName
3577 << BaseExpr
->getSourceRange());
3580 // Handle properties on 'id' and qualified "id".
3581 if (!IsArrow
&& (BaseType
->isObjCIdType() ||
3582 BaseType
->isObjCQualifiedIdType())) {
3583 const ObjCObjectPointerType
*QIdTy
= BaseType
->getAs
<ObjCObjectPointerType
>();
3584 IdentifierInfo
*Member
= MemberName
.getAsIdentifierInfo();
3586 // Check protocols on qualified interfaces.
3587 Selector Sel
= PP
.getSelectorTable().getNullarySelector(Member
);
3588 if (Decl
*PMDecl
= FindGetterSetterNameDecl(QIdTy
, Member
, Sel
,
3590 if (ObjCPropertyDecl
*PD
= dyn_cast
<ObjCPropertyDecl
>(PMDecl
)) {
3591 // Check the use of this declaration
3592 if (DiagnoseUseOfDecl(PD
, MemberLoc
))
3595 return Owned(new (Context
) ObjCPropertyRefExpr(PD
, PD
->getType(),
3599 if (ObjCMethodDecl
*OMD
= dyn_cast
<ObjCMethodDecl
>(PMDecl
)) {
3600 // Check the use of this method.
3601 if (DiagnoseUseOfDecl(OMD
, MemberLoc
))
3603 Selector SetterSel
=
3604 SelectorTable::constructSetterName(PP
.getIdentifierTable(),
3605 PP
.getSelectorTable(), Member
);
3606 ObjCMethodDecl
*SMD
= 0;
3607 if (Decl
*SDecl
= FindGetterSetterNameDecl(QIdTy
, /*Property id*/0,
3608 SetterSel
, Context
))
3609 SMD
= dyn_cast
<ObjCMethodDecl
>(SDecl
);
3610 QualType PType
= OMD
->getSendResultType();
3611 return Owned(new (Context
) ObjCImplicitSetterGetterRefExpr(OMD
, PType
,
3618 return ExprError(Diag(MemberLoc
, diag::err_property_not_found
)
3619 << MemberName
<< BaseType
);
3622 // Handle Objective-C property access, which is "Obj.property" where Obj is a
3623 // pointer to a (potentially qualified) interface type.
3625 if (const ObjCObjectPointerType
*OPT
=
3626 BaseType
->getAsObjCInterfacePointerType())
3627 return HandleExprPropertyRefExpr(OPT
, BaseExpr
, MemberName
, MemberLoc
,
3628 SourceLocation(), QualType(), false);
3630 // Handle the following exceptional case (*Obj).isa.
3632 BaseType
->isObjCObjectType() &&
3633 BaseType
->getAs
<ObjCObjectType
>()->isObjCId() &&
3634 MemberName
.getAsIdentifierInfo()->isStr("isa"))
3635 return Owned(new (Context
) ObjCIsaExpr(BaseExpr
, false, MemberLoc
,
3636 Context
.getObjCClassType()));
3638 // Handle 'field access' to vectors, such as 'V.xx'.
3639 if (BaseType
->isExtVectorType()) {
3640 IdentifierInfo
*Member
= MemberName
.getAsIdentifierInfo();
3641 QualType ret
= CheckExtVectorComponent(BaseType
, OpLoc
, Member
, MemberLoc
);
3644 return Owned(new (Context
) ExtVectorElementExpr(ret
, BaseExpr
, *Member
,
3648 Diag(MemberLoc
, diag::err_typecheck_member_reference_struct_union
)
3649 << BaseType
<< BaseExpr
->getSourceRange();
3654 /// The main callback when the parser finds something like
3655 /// expression . [nested-name-specifier] identifier
3656 /// expression -> [nested-name-specifier] identifier
3657 /// where 'identifier' encompasses a fairly broad spectrum of
3658 /// possibilities, including destructor and operator references.
3660 /// \param OpKind either tok::arrow or tok::period
3661 /// \param HasTrailingLParen whether the next token is '(', which
3662 /// is used to diagnose mis-uses of special members that can
3664 /// \param ObjCImpDecl the current ObjC @implementation decl;
3665 /// this is an ugly hack around the fact that ObjC @implementations
3666 /// aren't properly put in the context chain
3667 ExprResult
Sema::ActOnMemberAccessExpr(Scope
*S
, Expr
*Base
,
3668 SourceLocation OpLoc
,
3669 tok::TokenKind OpKind
,
3673 bool HasTrailingLParen
) {
3674 if (SS
.isSet() && SS
.isInvalid())
3677 TemplateArgumentListInfo TemplateArgsBuffer
;
3679 // Decompose the name into its component parts.
3680 DeclarationNameInfo NameInfo
;
3681 const TemplateArgumentListInfo
*TemplateArgs
;
3682 DecomposeUnqualifiedId(*this, Id
, TemplateArgsBuffer
,
3683 NameInfo
, TemplateArgs
);
3685 DeclarationName Name
= NameInfo
.getName();
3686 bool IsArrow
= (OpKind
== tok::arrow
);
3688 NamedDecl
*FirstQualifierInScope
3689 = (!SS
.isSet() ? 0 : FindFirstQualifierInScope(S
,
3690 static_cast<NestedNameSpecifier
*>(SS
.getScopeRep())));
3692 // This is a postfix expression, so get rid of ParenListExprs.
3693 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, Base
);
3694 if (Result
.isInvalid()) return ExprError();
3695 Base
= Result
.take();
3697 if (Base
->getType()->isDependentType() || Name
.isDependentName() ||
3698 isDependentScopeSpecifier(SS
)) {
3699 Result
= ActOnDependentMemberExpr(Base
, Base
->getType(),
3701 SS
, FirstQualifierInScope
,
3702 NameInfo
, TemplateArgs
);
3704 LookupResult
R(*this, NameInfo
, LookupMemberName
);
3705 Result
= LookupMemberExpr(R
, Base
, IsArrow
, OpLoc
,
3706 SS
, ObjCImpDecl
, TemplateArgs
!= 0);
3708 if (Result
.isInvalid()) {
3714 // The only way a reference to a destructor can be used is to
3715 // immediately call it, which falls into this case. If the
3716 // next token is not a '(', produce a diagnostic and build the
3718 if (!HasTrailingLParen
&&
3719 Id
.getKind() == UnqualifiedId::IK_DestructorName
)
3720 return DiagnoseDtorReference(NameInfo
.getLoc(), Result
.get());
3722 return move(Result
);
3725 Result
= BuildMemberReferenceExpr(Base
, Base
->getType(),
3726 OpLoc
, IsArrow
, SS
, FirstQualifierInScope
,
3730 return move(Result
);
3733 ExprResult
Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc
,
3735 ParmVarDecl
*Param
) {
3736 if (Param
->hasUnparsedDefaultArg()) {
3738 diag::err_use_of_default_argument_to_function_declared_later
) <<
3739 FD
<< cast
<CXXRecordDecl
>(FD
->getDeclContext())->getDeclName();
3740 Diag(UnparsedDefaultArgLocs
[Param
],
3741 diag::note_default_argument_declared_here
);
3745 if (Param
->hasUninstantiatedDefaultArg()) {
3746 Expr
*UninstExpr
= Param
->getUninstantiatedDefaultArg();
3748 // Instantiate the expression.
3749 MultiLevelTemplateArgumentList ArgList
3750 = getTemplateInstantiationArgs(FD
, 0, /*RelativeToPrimary=*/true);
3752 std::pair
<const TemplateArgument
*, unsigned> Innermost
3753 = ArgList
.getInnermost();
3754 InstantiatingTemplate
Inst(*this, CallLoc
, Param
, Innermost
.first
,
3757 ExprResult Result
= SubstExpr(UninstExpr
, ArgList
);
3758 if (Result
.isInvalid())
3761 // Check the expression as an initializer for the parameter.
3762 InitializedEntity Entity
3763 = InitializedEntity::InitializeParameter(Context
, Param
);
3764 InitializationKind Kind
3765 = InitializationKind::CreateCopy(Param
->getLocation(),
3766 /*FIXME:EqualLoc*/UninstExpr
->getSourceRange().getBegin());
3767 Expr
*ResultE
= Result
.takeAs
<Expr
>();
3769 InitializationSequence
InitSeq(*this, Entity
, Kind
, &ResultE
, 1);
3770 Result
= InitSeq
.Perform(*this, Entity
, Kind
,
3771 MultiExprArg(*this, &ResultE
, 1));
3772 if (Result
.isInvalid())
3775 // Build the default argument expression.
3776 return Owned(CXXDefaultArgExpr::Create(Context
, CallLoc
, Param
,
3777 Result
.takeAs
<Expr
>()));
3780 // If the default expression creates temporaries, we need to
3781 // push them to the current stack of expression temporaries so they'll
3782 // be properly destroyed.
3783 // FIXME: We should really be rebuilding the default argument with new
3784 // bound temporaries; see the comment in PR5810.
3785 for (unsigned i
= 0, e
= Param
->getNumDefaultArgTemporaries(); i
!= e
; ++i
) {
3786 CXXTemporary
*Temporary
= Param
->getDefaultArgTemporary(i
);
3787 MarkDeclarationReferenced(Param
->getDefaultArg()->getLocStart(),
3788 const_cast<CXXDestructorDecl
*>(Temporary
->getDestructor()));
3789 ExprTemporaries
.push_back(Temporary
);
3792 // We already type-checked the argument, so we know it works.
3793 // Just mark all of the declarations in this potentially-evaluated expression
3794 // as being "referenced".
3795 MarkDeclarationsReferencedInExpr(Param
->getDefaultArg());
3796 return Owned(CXXDefaultArgExpr::Create(Context
, CallLoc
, Param
));
3799 /// ConvertArgumentsForCall - Converts the arguments specified in
3800 /// Args/NumArgs to the parameter types of the function FDecl with
3801 /// function prototype Proto. Call is the call expression itself, and
3802 /// Fn is the function expression. For a C++ member function, this
3803 /// routine does not attempt to convert the object argument. Returns
3804 /// true if the call is ill-formed.
3806 Sema::ConvertArgumentsForCall(CallExpr
*Call
, Expr
*Fn
,
3807 FunctionDecl
*FDecl
,
3808 const FunctionProtoType
*Proto
,
3809 Expr
**Args
, unsigned NumArgs
,
3810 SourceLocation RParenLoc
) {
3811 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3812 // assignment, to the types of the corresponding parameter, ...
3813 unsigned NumArgsInProto
= Proto
->getNumArgs();
3814 bool Invalid
= false;
3816 // If too few arguments are available (and we don't have default
3817 // arguments for the remaining parameters), don't make the call.
3818 if (NumArgs
< NumArgsInProto
) {
3819 if (!FDecl
|| NumArgs
< FDecl
->getMinRequiredArguments())
3820 return Diag(RParenLoc
, diag::err_typecheck_call_too_few_args
)
3821 << Fn
->getType()->isBlockPointerType()
3822 << NumArgsInProto
<< NumArgs
<< Fn
->getSourceRange();
3823 Call
->setNumArgs(Context
, NumArgsInProto
);
3826 // If too many are passed and not variadic, error on the extras and drop
3828 if (NumArgs
> NumArgsInProto
) {
3829 if (!Proto
->isVariadic()) {
3830 Diag(Args
[NumArgsInProto
]->getLocStart(),
3831 diag::err_typecheck_call_too_many_args
)
3832 << Fn
->getType()->isBlockPointerType()
3833 << NumArgsInProto
<< NumArgs
<< Fn
->getSourceRange()
3834 << SourceRange(Args
[NumArgsInProto
]->getLocStart(),
3835 Args
[NumArgs
-1]->getLocEnd());
3836 // This deletes the extra arguments.
3837 Call
->setNumArgs(Context
, NumArgsInProto
);
3841 llvm::SmallVector
<Expr
*, 8> AllArgs
;
3842 VariadicCallType CallType
=
3843 Proto
->isVariadic() ? VariadicFunction
: VariadicDoesNotApply
;
3844 if (Fn
->getType()->isBlockPointerType())
3845 CallType
= VariadicBlock
; // Block
3846 else if (isa
<MemberExpr
>(Fn
))
3847 CallType
= VariadicMethod
;
3848 Invalid
= GatherArgumentsForCall(Call
->getSourceRange().getBegin(), FDecl
,
3849 Proto
, 0, Args
, NumArgs
, AllArgs
, CallType
);
3852 unsigned TotalNumArgs
= AllArgs
.size();
3853 for (unsigned i
= 0; i
< TotalNumArgs
; ++i
)
3854 Call
->setArg(i
, AllArgs
[i
]);
3859 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc
,
3860 FunctionDecl
*FDecl
,
3861 const FunctionProtoType
*Proto
,
3862 unsigned FirstProtoArg
,
3863 Expr
**Args
, unsigned NumArgs
,
3864 llvm::SmallVector
<Expr
*, 8> &AllArgs
,
3865 VariadicCallType CallType
) {
3866 unsigned NumArgsInProto
= Proto
->getNumArgs();
3867 unsigned NumArgsToCheck
= NumArgs
;
3868 bool Invalid
= false;
3869 if (NumArgs
!= NumArgsInProto
)
3870 // Use default arguments for missing arguments
3871 NumArgsToCheck
= NumArgsInProto
;
3873 // Continue to check argument types (even if we have too few/many args).
3874 for (unsigned i
= FirstProtoArg
; i
!= NumArgsToCheck
; i
++) {
3875 QualType ProtoArgType
= Proto
->getArgType(i
);
3878 if (ArgIx
< NumArgs
) {
3879 Arg
= Args
[ArgIx
++];
3881 if (RequireCompleteType(Arg
->getSourceRange().getBegin(),
3883 PDiag(diag::err_call_incomplete_argument
)
3884 << Arg
->getSourceRange()))
3887 // Pass the argument
3888 ParmVarDecl
*Param
= 0;
3889 if (FDecl
&& i
< FDecl
->getNumParams())
3890 Param
= FDecl
->getParamDecl(i
);
3892 InitializedEntity Entity
=
3893 Param
? InitializedEntity::InitializeParameter(Context
, Param
)
3894 : InitializedEntity::InitializeParameter(Context
, ProtoArgType
);
3895 ExprResult ArgE
= PerformCopyInitialization(Entity
,
3898 if (ArgE
.isInvalid())
3901 Arg
= ArgE
.takeAs
<Expr
>();
3903 ParmVarDecl
*Param
= FDecl
->getParamDecl(i
);
3905 ExprResult ArgExpr
=
3906 BuildCXXDefaultArgExpr(CallLoc
, FDecl
, Param
);
3907 if (ArgExpr
.isInvalid())
3910 Arg
= ArgExpr
.takeAs
<Expr
>();
3912 AllArgs
.push_back(Arg
);
3915 // If this is a variadic call, handle args passed through "...".
3916 if (CallType
!= VariadicDoesNotApply
) {
3917 // Promote the arguments (C99 6.5.2.2p7).
3918 for (unsigned i
= ArgIx
; i
!= NumArgs
; ++i
) {
3919 Expr
*Arg
= Args
[i
];
3920 Invalid
|= DefaultVariadicArgumentPromotion(Arg
, CallType
, FDecl
);
3921 AllArgs
.push_back(Arg
);
3927 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3928 /// This provides the location of the left/right parens and a list of comma
3931 Sema::ActOnCallExpr(Scope
*S
, Expr
*Fn
, SourceLocation LParenLoc
,
3932 MultiExprArg args
, SourceLocation RParenLoc
) {
3933 unsigned NumArgs
= args
.size();
3935 // Since this might be a postfix expression, get rid of ParenListExprs.
3936 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, Fn
);
3937 if (Result
.isInvalid()) return ExprError();
3940 Expr
**Args
= args
.release();
3942 if (getLangOptions().CPlusPlus
) {
3943 // If this is a pseudo-destructor expression, build the call immediately.
3944 if (isa
<CXXPseudoDestructorExpr
>(Fn
)) {
3946 // Pseudo-destructor calls should not have any arguments.
3947 Diag(Fn
->getLocStart(), diag::err_pseudo_dtor_call_with_args
)
3948 << FixItHint::CreateRemoval(
3949 SourceRange(Args
[0]->getLocStart(),
3950 Args
[NumArgs
-1]->getLocEnd()));
3955 return Owned(new (Context
) CallExpr(Context
, Fn
, 0, 0, Context
.VoidTy
,
3959 // Determine whether this is a dependent call inside a C++ template,
3960 // in which case we won't do any semantic analysis now.
3961 // FIXME: Will need to cache the results of name lookup (including ADL) in
3963 bool Dependent
= false;
3964 if (Fn
->isTypeDependent())
3966 else if (Expr::hasAnyTypeDependentArguments(Args
, NumArgs
))
3970 return Owned(new (Context
) CallExpr(Context
, Fn
, Args
, NumArgs
,
3971 Context
.DependentTy
, RParenLoc
));
3973 // Determine whether this is a call to an object (C++ [over.call.object]).
3974 if (Fn
->getType()->isRecordType())
3975 return Owned(BuildCallToObjectOfClassType(S
, Fn
, LParenLoc
, Args
, NumArgs
,
3978 Expr
*NakedFn
= Fn
->IgnoreParens();
3980 // Determine whether this is a call to an unresolved member function.
3981 if (UnresolvedMemberExpr
*MemE
= dyn_cast
<UnresolvedMemberExpr
>(NakedFn
)) {
3982 // If lookup was unresolved but not dependent (i.e. didn't find
3983 // an unresolved using declaration), it has to be an overloaded
3984 // function set, which means it must contain either multiple
3985 // declarations (all methods or method templates) or a single
3987 assert((MemE
->getNumDecls() > 1) ||
3988 isa
<FunctionTemplateDecl
>(
3989 (*MemE
->decls_begin())->getUnderlyingDecl()));
3992 return BuildCallToMemberFunction(S
, Fn
, LParenLoc
, Args
, NumArgs
,
3996 // Determine whether this is a call to a member function.
3997 if (MemberExpr
*MemExpr
= dyn_cast
<MemberExpr
>(NakedFn
)) {
3998 NamedDecl
*MemDecl
= MemExpr
->getMemberDecl();
3999 if (isa
<CXXMethodDecl
>(MemDecl
))
4000 return BuildCallToMemberFunction(S
, Fn
, LParenLoc
, Args
, NumArgs
,
4004 // Determine whether this is a call to a pointer-to-member function.
4005 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(NakedFn
)) {
4006 if (BO
->getOpcode() == BO_PtrMemD
||
4007 BO
->getOpcode() == BO_PtrMemI
) {
4008 if (const FunctionProtoType
*FPT
4009 = BO
->getType()->getAs
<FunctionProtoType
>()) {
4010 QualType ResultTy
= FPT
->getCallResultType(Context
);
4012 CXXMemberCallExpr
*TheCall
4013 = new (Context
) CXXMemberCallExpr(Context
, BO
, Args
,
4017 if (CheckCallReturnType(FPT
->getResultType(),
4018 BO
->getRHS()->getSourceRange().getBegin(),
4022 if (ConvertArgumentsForCall(TheCall
, BO
, 0, FPT
, Args
, NumArgs
,
4026 return MaybeBindToTemporary(TheCall
);
4028 return ExprError(Diag(Fn
->getLocStart(),
4029 diag::err_typecheck_call_not_function
)
4030 << Fn
->getType() << Fn
->getSourceRange());
4035 // If we're directly calling a function, get the appropriate declaration.
4036 // Also, in C++, keep track of whether we should perform argument-dependent
4037 // lookup and whether there were any explicitly-specified template arguments.
4039 Expr
*NakedFn
= Fn
->IgnoreParens();
4040 if (isa
<UnresolvedLookupExpr
>(NakedFn
)) {
4041 UnresolvedLookupExpr
*ULE
= cast
<UnresolvedLookupExpr
>(NakedFn
);
4042 return BuildOverloadedCallExpr(S
, Fn
, ULE
, LParenLoc
, Args
, NumArgs
,
4046 NamedDecl
*NDecl
= 0;
4047 if (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(NakedFn
))
4048 if (UnOp
->getOpcode() == UO_AddrOf
)
4049 NakedFn
= UnOp
->getSubExpr()->IgnoreParens();
4051 if (isa
<DeclRefExpr
>(NakedFn
))
4052 NDecl
= cast
<DeclRefExpr
>(NakedFn
)->getDecl();
4054 return BuildResolvedCallExpr(Fn
, NDecl
, LParenLoc
, Args
, NumArgs
, RParenLoc
);
4057 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4058 /// i.e. an expression not of \p OverloadTy. The expression should
4059 /// unary-convert to an expression of function-pointer or
4060 /// block-pointer type.
4062 /// \param NDecl the declaration being called, if available
4064 Sema::BuildResolvedCallExpr(Expr
*Fn
, NamedDecl
*NDecl
,
4065 SourceLocation LParenLoc
,
4066 Expr
**Args
, unsigned NumArgs
,
4067 SourceLocation RParenLoc
) {
4068 FunctionDecl
*FDecl
= dyn_cast_or_null
<FunctionDecl
>(NDecl
);
4070 // Promote the function operand.
4071 UsualUnaryConversions(Fn
);
4073 // Make the call expr early, before semantic checks. This guarantees cleanup
4074 // of arguments and function on error.
4075 CallExpr
*TheCall
= new (Context
) CallExpr(Context
, Fn
,
4080 const FunctionType
*FuncT
;
4081 if (!Fn
->getType()->isBlockPointerType()) {
4082 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4083 // have type pointer to function".
4084 const PointerType
*PT
= Fn
->getType()->getAs
<PointerType
>();
4086 return ExprError(Diag(LParenLoc
, diag::err_typecheck_call_not_function
)
4087 << Fn
->getType() << Fn
->getSourceRange());
4088 FuncT
= PT
->getPointeeType()->getAs
<FunctionType
>();
4089 } else { // This is a block call.
4090 FuncT
= Fn
->getType()->getAs
<BlockPointerType
>()->getPointeeType()->
4091 getAs
<FunctionType
>();
4094 return ExprError(Diag(LParenLoc
, diag::err_typecheck_call_not_function
)
4095 << Fn
->getType() << Fn
->getSourceRange());
4097 // Check for a valid return type
4098 if (CheckCallReturnType(FuncT
->getResultType(),
4099 Fn
->getSourceRange().getBegin(), TheCall
,
4103 // We know the result type of the call, set it.
4104 TheCall
->setType(FuncT
->getCallResultType(Context
));
4106 if (const FunctionProtoType
*Proto
= dyn_cast
<FunctionProtoType
>(FuncT
)) {
4107 if (ConvertArgumentsForCall(TheCall
, Fn
, FDecl
, Proto
, Args
, NumArgs
,
4111 assert(isa
<FunctionNoProtoType
>(FuncT
) && "Unknown FunctionType!");
4114 // Check if we have too few/too many template arguments, based
4115 // on our knowledge of the function definition.
4116 const FunctionDecl
*Def
= 0;
4117 if (FDecl
->hasBody(Def
) && NumArgs
!= Def
->param_size()) {
4118 const FunctionProtoType
*Proto
4119 = Def
->getType()->getAs
<FunctionProtoType
>();
4120 if (!Proto
|| !(Proto
->isVariadic() && NumArgs
>= Def
->param_size()))
4121 Diag(RParenLoc
, diag::warn_call_wrong_number_of_arguments
)
4122 << (NumArgs
> Def
->param_size()) << FDecl
<< Fn
->getSourceRange();
4125 // If the function we're calling isn't a function prototype, but we have
4126 // a function prototype from a prior declaratiom, use that prototype.
4127 if (!FDecl
->hasPrototype())
4128 Proto
= FDecl
->getType()->getAs
<FunctionProtoType
>();
4131 // Promote the arguments (C99 6.5.2.2p6).
4132 for (unsigned i
= 0; i
!= NumArgs
; i
++) {
4133 Expr
*Arg
= Args
[i
];
4135 if (Proto
&& i
< Proto
->getNumArgs()) {
4136 InitializedEntity Entity
4137 = InitializedEntity::InitializeParameter(Context
,
4138 Proto
->getArgType(i
));
4139 ExprResult ArgE
= PerformCopyInitialization(Entity
,
4142 if (ArgE
.isInvalid())
4145 Arg
= ArgE
.takeAs
<Expr
>();
4148 DefaultArgumentPromotion(Arg
);
4151 if (RequireCompleteType(Arg
->getSourceRange().getBegin(),
4153 PDiag(diag::err_call_incomplete_argument
)
4154 << Arg
->getSourceRange()))
4157 TheCall
->setArg(i
, Arg
);
4161 if (CXXMethodDecl
*Method
= dyn_cast_or_null
<CXXMethodDecl
>(FDecl
))
4162 if (!Method
->isStatic())
4163 return ExprError(Diag(LParenLoc
, diag::err_member_call_without_object
)
4164 << Fn
->getSourceRange());
4166 // Check for sentinels
4168 DiagnoseSentinelCalls(NDecl
, LParenLoc
, Args
, NumArgs
);
4170 // Do special checking on direct calls to functions.
4172 if (CheckFunctionCall(FDecl
, TheCall
))
4175 if (unsigned BuiltinID
= FDecl
->getBuiltinID())
4176 return CheckBuiltinFunctionCall(BuiltinID
, TheCall
);
4178 if (CheckBlockCall(NDecl
, TheCall
))
4182 return MaybeBindToTemporary(TheCall
);
4186 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc
, ParsedType Ty
,
4187 SourceLocation RParenLoc
, Expr
*InitExpr
) {
4188 assert((Ty
!= 0) && "ActOnCompoundLiteral(): missing type");
4189 // FIXME: put back this assert when initializers are worked out.
4190 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4192 TypeSourceInfo
*TInfo
;
4193 QualType literalType
= GetTypeFromParser(Ty
, &TInfo
);
4195 TInfo
= Context
.getTrivialTypeSourceInfo(literalType
);
4197 return BuildCompoundLiteralExpr(LParenLoc
, TInfo
, RParenLoc
, InitExpr
);
4201 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc
, TypeSourceInfo
*TInfo
,
4202 SourceLocation RParenLoc
, Expr
*literalExpr
) {
4203 QualType literalType
= TInfo
->getType();
4205 if (literalType
->isArrayType()) {
4206 if (RequireCompleteType(LParenLoc
, Context
.getBaseElementType(literalType
),
4207 PDiag(diag::err_illegal_decl_array_incomplete_type
)
4208 << SourceRange(LParenLoc
,
4209 literalExpr
->getSourceRange().getEnd())))
4211 if (literalType
->isVariableArrayType())
4212 return ExprError(Diag(LParenLoc
, diag::err_variable_object_no_init
)
4213 << SourceRange(LParenLoc
, literalExpr
->getSourceRange().getEnd()));
4214 } else if (!literalType
->isDependentType() &&
4215 RequireCompleteType(LParenLoc
, literalType
,
4216 PDiag(diag::err_typecheck_decl_incomplete_type
)
4217 << SourceRange(LParenLoc
,
4218 literalExpr
->getSourceRange().getEnd())))
4221 InitializedEntity Entity
4222 = InitializedEntity::InitializeTemporary(literalType
);
4223 InitializationKind Kind
4224 = InitializationKind::CreateCast(SourceRange(LParenLoc
, RParenLoc
),
4225 /*IsCStyleCast=*/true);
4226 InitializationSequence
InitSeq(*this, Entity
, Kind
, &literalExpr
, 1);
4227 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
,
4228 MultiExprArg(*this, &literalExpr
, 1),
4230 if (Result
.isInvalid())
4232 literalExpr
= Result
.get();
4234 bool isFileScope
= getCurFunctionOrMethodDecl() == 0;
4235 if (isFileScope
) { // 6.5.2.5p3
4236 if (CheckForConstantInitializer(literalExpr
, literalType
))
4240 return Owned(new (Context
) CompoundLiteralExpr(LParenLoc
, TInfo
, literalType
,
4241 literalExpr
, isFileScope
));
4245 Sema::ActOnInitList(SourceLocation LBraceLoc
, MultiExprArg initlist
,
4246 SourceLocation RBraceLoc
) {
4247 unsigned NumInit
= initlist
.size();
4248 Expr
**InitList
= initlist
.release();
4250 // Semantic analysis for initializers is done by ActOnDeclarator() and
4251 // CheckInitializer() - it requires knowledge of the object being intialized.
4253 InitListExpr
*E
= new (Context
) InitListExpr(Context
, LBraceLoc
, InitList
,
4254 NumInit
, RBraceLoc
);
4255 E
->setType(Context
.VoidTy
); // FIXME: just a place holder for now.
4259 /// Prepares for a scalar cast, performing all the necessary stages
4260 /// except the final cast and returning the kind required.
4261 static CastKind
PrepareScalarCast(Sema
&S
, Expr
*&Src
, QualType DestTy
) {
4262 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4263 // Also, callers should have filtered out the invalid cases with
4264 // pointers. Everything else should be possible.
4266 QualType SrcTy
= Src
->getType();
4267 if (S
.Context
.hasSameUnqualifiedType(SrcTy
, DestTy
))
4270 switch (SrcTy
->getScalarTypeKind()) {
4271 case Type::STK_MemberPointer
:
4272 llvm_unreachable("member pointer type in C");
4274 case Type::STK_Pointer
:
4275 switch (DestTy
->getScalarTypeKind()) {
4276 case Type::STK_Pointer
:
4277 return DestTy
->isObjCObjectPointerType() ?
4278 CK_AnyPointerToObjCPointerCast
:
4280 case Type::STK_Bool
:
4281 return CK_PointerToBoolean
;
4282 case Type::STK_Integral
:
4283 return CK_PointerToIntegral
;
4284 case Type::STK_Floating
:
4285 case Type::STK_FloatingComplex
:
4286 case Type::STK_IntegralComplex
:
4287 case Type::STK_MemberPointer
:
4288 llvm_unreachable("illegal cast from pointer");
4292 case Type::STK_Bool
: // casting from bool is like casting from an integer
4293 case Type::STK_Integral
:
4294 switch (DestTy
->getScalarTypeKind()) {
4295 case Type::STK_Pointer
:
4296 if (Src
->isNullPointerConstant(S
.Context
, Expr::NPC_ValueDependentIsNull
))
4297 return CK_NullToPointer
;
4298 return CK_IntegralToPointer
;
4299 case Type::STK_Bool
:
4300 return CK_IntegralToBoolean
;
4301 case Type::STK_Integral
:
4302 return CK_IntegralCast
;
4303 case Type::STK_Floating
:
4304 return CK_IntegralToFloating
;
4305 case Type::STK_IntegralComplex
:
4306 return CK_IntegralRealToComplex
;
4307 case Type::STK_FloatingComplex
:
4308 S
.ImpCastExprToType(Src
, cast
<ComplexType
>(DestTy
)->getElementType(),
4309 CK_IntegralToFloating
);
4310 return CK_FloatingRealToComplex
;
4311 case Type::STK_MemberPointer
:
4312 llvm_unreachable("member pointer type in C");
4316 case Type::STK_Floating
:
4317 switch (DestTy
->getScalarTypeKind()) {
4318 case Type::STK_Floating
:
4319 return CK_FloatingCast
;
4320 case Type::STK_Bool
:
4321 return CK_FloatingToBoolean
;
4322 case Type::STK_Integral
:
4323 return CK_FloatingToIntegral
;
4324 case Type::STK_FloatingComplex
:
4325 return CK_FloatingRealToComplex
;
4326 case Type::STK_IntegralComplex
:
4327 S
.ImpCastExprToType(Src
, cast
<ComplexType
>(DestTy
)->getElementType(),
4328 CK_FloatingToIntegral
);
4329 return CK_IntegralRealToComplex
;
4330 case Type::STK_Pointer
:
4331 llvm_unreachable("valid float->pointer cast?");
4332 case Type::STK_MemberPointer
:
4333 llvm_unreachable("member pointer type in C");
4337 case Type::STK_FloatingComplex
:
4338 switch (DestTy
->getScalarTypeKind()) {
4339 case Type::STK_FloatingComplex
:
4340 return CK_FloatingComplexCast
;
4341 case Type::STK_IntegralComplex
:
4342 return CK_FloatingComplexToIntegralComplex
;
4343 case Type::STK_Floating
:
4344 return CK_FloatingComplexToReal
;
4345 case Type::STK_Bool
:
4346 return CK_FloatingComplexToBoolean
;
4347 case Type::STK_Integral
:
4348 S
.ImpCastExprToType(Src
, cast
<ComplexType
>(SrcTy
)->getElementType(),
4349 CK_FloatingComplexToReal
);
4350 return CK_FloatingToIntegral
;
4351 case Type::STK_Pointer
:
4352 llvm_unreachable("valid complex float->pointer cast?");
4353 case Type::STK_MemberPointer
:
4354 llvm_unreachable("member pointer type in C");
4358 case Type::STK_IntegralComplex
:
4359 switch (DestTy
->getScalarTypeKind()) {
4360 case Type::STK_FloatingComplex
:
4361 return CK_IntegralComplexToFloatingComplex
;
4362 case Type::STK_IntegralComplex
:
4363 return CK_IntegralComplexCast
;
4364 case Type::STK_Integral
:
4365 return CK_IntegralComplexToReal
;
4366 case Type::STK_Bool
:
4367 return CK_IntegralComplexToBoolean
;
4368 case Type::STK_Floating
:
4369 S
.ImpCastExprToType(Src
, cast
<ComplexType
>(SrcTy
)->getElementType(),
4370 CK_IntegralComplexToReal
);
4371 return CK_IntegralToFloating
;
4372 case Type::STK_Pointer
:
4373 llvm_unreachable("valid complex int->pointer cast?");
4374 case Type::STK_MemberPointer
:
4375 llvm_unreachable("member pointer type in C");
4380 llvm_unreachable("Unhandled scalar cast");
4384 /// CheckCastTypes - Check type constraints for casting between types.
4385 bool Sema::CheckCastTypes(SourceRange TyR
, QualType castType
, Expr
*&castExpr
,
4387 CXXCastPath
&BasePath
,
4388 bool FunctionalStyle
) {
4389 if (getLangOptions().CPlusPlus
)
4390 return CXXCheckCStyleCast(SourceRange(TyR
.getBegin(),
4391 castExpr
->getLocEnd()),
4392 castType
, castExpr
, Kind
, BasePath
,
4395 DefaultFunctionArrayLvalueConversion(castExpr
);
4397 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4398 // type needs to be scalar.
4399 if (castType
->isVoidType()) {
4400 // Cast to void allows any expr type.
4405 if (RequireCompleteType(TyR
.getBegin(), castType
,
4406 diag::err_typecheck_cast_to_incomplete
))
4409 if (!castType
->isScalarType() && !castType
->isVectorType()) {
4410 if (Context
.hasSameUnqualifiedType(castType
, castExpr
->getType()) &&
4411 (castType
->isStructureType() || castType
->isUnionType())) {
4412 // GCC struct/union extension: allow cast to self.
4413 // FIXME: Check that the cast destination type is complete.
4414 Diag(TyR
.getBegin(), diag::ext_typecheck_cast_nonscalar
)
4415 << castType
<< castExpr
->getSourceRange();
4420 if (castType
->isUnionType()) {
4421 // GCC cast to union extension
4422 RecordDecl
*RD
= castType
->getAs
<RecordType
>()->getDecl();
4423 RecordDecl::field_iterator Field
, FieldEnd
;
4424 for (Field
= RD
->field_begin(), FieldEnd
= RD
->field_end();
4425 Field
!= FieldEnd
; ++Field
) {
4426 if (Context
.hasSameUnqualifiedType(Field
->getType(),
4427 castExpr
->getType()) &&
4428 !Field
->isUnnamedBitfield()) {
4429 Diag(TyR
.getBegin(), diag::ext_typecheck_cast_to_union
)
4430 << castExpr
->getSourceRange();
4434 if (Field
== FieldEnd
)
4435 return Diag(TyR
.getBegin(), diag::err_typecheck_cast_to_union_no_type
)
4436 << castExpr
->getType() << castExpr
->getSourceRange();
4441 // Reject any other conversions to non-scalar types.
4442 return Diag(TyR
.getBegin(), diag::err_typecheck_cond_expect_scalar
)
4443 << castType
<< castExpr
->getSourceRange();
4446 // The type we're casting to is known to be a scalar or vector.
4448 // Require the operand to be a scalar or vector.
4449 if (!castExpr
->getType()->isScalarType() &&
4450 !castExpr
->getType()->isVectorType()) {
4451 return Diag(castExpr
->getLocStart(),
4452 diag::err_typecheck_expect_scalar_operand
)
4453 << castExpr
->getType() << castExpr
->getSourceRange();
4456 if (castType
->isExtVectorType())
4457 return CheckExtVectorCast(TyR
, castType
, castExpr
, Kind
);
4459 if (castType
->isVectorType())
4460 return CheckVectorCast(TyR
, castType
, castExpr
->getType(), Kind
);
4461 if (castExpr
->getType()->isVectorType())
4462 return CheckVectorCast(TyR
, castExpr
->getType(), castType
, Kind
);
4464 // The source and target types are both scalars, i.e.
4465 // - arithmetic types (fundamental, enum, and complex)
4466 // - all kinds of pointers
4467 // Note that member pointers were filtered out with C++, above.
4469 if (isa
<ObjCSelectorExpr
>(castExpr
))
4470 return Diag(castExpr
->getLocStart(), diag::err_cast_selector_expr
);
4472 // If either type is a pointer, the other type has to be either an
4473 // integer or a pointer.
4474 if (!castType
->isArithmeticType()) {
4475 QualType castExprType
= castExpr
->getType();
4476 if (!castExprType
->isIntegralType(Context
) &&
4477 castExprType
->isArithmeticType())
4478 return Diag(castExpr
->getLocStart(),
4479 diag::err_cast_pointer_from_non_pointer_int
)
4480 << castExprType
<< castExpr
->getSourceRange();
4481 } else if (!castExpr
->getType()->isArithmeticType()) {
4482 if (!castType
->isIntegralType(Context
) && castType
->isArithmeticType())
4483 return Diag(castExpr
->getLocStart(),
4484 diag::err_cast_pointer_to_non_pointer_int
)
4485 << castType
<< castExpr
->getSourceRange();
4488 Kind
= PrepareScalarCast(*this, castExpr
, castType
);
4490 if (Kind
== CK_BitCast
)
4491 CheckCastAlign(castExpr
, castType
, TyR
);
4496 bool Sema::CheckVectorCast(SourceRange R
, QualType VectorTy
, QualType Ty
,
4498 assert(VectorTy
->isVectorType() && "Not a vector type!");
4500 if (Ty
->isVectorType() || Ty
->isIntegerType()) {
4501 if (Context
.getTypeSize(VectorTy
) != Context
.getTypeSize(Ty
))
4502 return Diag(R
.getBegin(),
4503 Ty
->isVectorType() ?
4504 diag::err_invalid_conversion_between_vectors
:
4505 diag::err_invalid_conversion_between_vector_and_integer
)
4506 << VectorTy
<< Ty
<< R
;
4508 return Diag(R
.getBegin(),
4509 diag::err_invalid_conversion_between_vector_and_scalar
)
4510 << VectorTy
<< Ty
<< R
;
4516 bool Sema::CheckExtVectorCast(SourceRange R
, QualType DestTy
, Expr
*&CastExpr
,
4518 assert(DestTy
->isExtVectorType() && "Not an extended vector type!");
4520 QualType SrcTy
= CastExpr
->getType();
4522 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4523 // an ExtVectorType.
4524 if (SrcTy
->isVectorType()) {
4525 if (Context
.getTypeSize(DestTy
) != Context
.getTypeSize(SrcTy
))
4526 return Diag(R
.getBegin(),diag::err_invalid_conversion_between_ext_vectors
)
4527 << DestTy
<< SrcTy
<< R
;
4532 // All non-pointer scalars can be cast to ExtVector type. The appropriate
4533 // conversion will take place first from scalar to elt type, and then
4534 // splat from elt type to vector.
4535 if (SrcTy
->isPointerType())
4536 return Diag(R
.getBegin(),
4537 diag::err_invalid_conversion_between_vector_and_scalar
)
4538 << DestTy
<< SrcTy
<< R
;
4540 QualType DestElemTy
= DestTy
->getAs
<ExtVectorType
>()->getElementType();
4541 ImpCastExprToType(CastExpr
, DestElemTy
,
4542 PrepareScalarCast(*this, CastExpr
, DestElemTy
));
4544 Kind
= CK_VectorSplat
;
4549 Sema::ActOnCastExpr(Scope
*S
, SourceLocation LParenLoc
, ParsedType Ty
,
4550 SourceLocation RParenLoc
, Expr
*castExpr
) {
4551 assert((Ty
!= 0) && (castExpr
!= 0) &&
4552 "ActOnCastExpr(): missing type or expr");
4554 TypeSourceInfo
*castTInfo
;
4555 QualType castType
= GetTypeFromParser(Ty
, &castTInfo
);
4557 castTInfo
= Context
.getTrivialTypeSourceInfo(castType
);
4559 // If the Expr being casted is a ParenListExpr, handle it specially.
4560 if (isa
<ParenListExpr
>(castExpr
))
4561 return ActOnCastOfParenListExpr(S
, LParenLoc
, RParenLoc
, castExpr
,
4564 return BuildCStyleCastExpr(LParenLoc
, castTInfo
, RParenLoc
, castExpr
);
4568 Sema::BuildCStyleCastExpr(SourceLocation LParenLoc
, TypeSourceInfo
*Ty
,
4569 SourceLocation RParenLoc
, Expr
*castExpr
) {
4570 CastKind Kind
= CK_Invalid
;
4571 CXXCastPath BasePath
;
4572 if (CheckCastTypes(SourceRange(LParenLoc
, RParenLoc
), Ty
->getType(), castExpr
,
4576 return Owned(CStyleCastExpr::Create(Context
,
4577 Ty
->getType().getNonLValueExprType(Context
),
4578 Kind
, castExpr
, &BasePath
, Ty
,
4579 LParenLoc
, RParenLoc
));
4582 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4583 /// of comma binary operators.
4585 Sema::MaybeConvertParenListExprToParenExpr(Scope
*S
, Expr
*expr
) {
4586 ParenListExpr
*E
= dyn_cast
<ParenListExpr
>(expr
);
4590 ExprResult
Result(E
->getExpr(0));
4592 for (unsigned i
= 1, e
= E
->getNumExprs(); i
!= e
&& !Result
.isInvalid(); ++i
)
4593 Result
= ActOnBinOp(S
, E
->getExprLoc(), tok::comma
, Result
.get(),
4596 if (Result
.isInvalid()) return ExprError();
4598 return ActOnParenExpr(E
->getLParenLoc(), E
->getRParenLoc(), Result
.get());
4602 Sema::ActOnCastOfParenListExpr(Scope
*S
, SourceLocation LParenLoc
,
4603 SourceLocation RParenLoc
, Expr
*Op
,
4604 TypeSourceInfo
*TInfo
) {
4605 ParenListExpr
*PE
= cast
<ParenListExpr
>(Op
);
4606 QualType Ty
= TInfo
->getType();
4607 bool isAltiVecLiteral
= false;
4609 // Check for an altivec literal,
4610 // i.e. all the elements are integer constants.
4611 if (getLangOptions().AltiVec
&& Ty
->isVectorType()) {
4612 if (PE
->getNumExprs() == 0) {
4613 Diag(PE
->getExprLoc(), diag::err_altivec_empty_initializer
);
4616 if (PE
->getNumExprs() == 1) {
4617 if (!PE
->getExpr(0)->getType()->isVectorType())
4618 isAltiVecLiteral
= true;
4621 isAltiVecLiteral
= true;
4624 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4625 // then handle it as such.
4626 if (isAltiVecLiteral
) {
4627 llvm::SmallVector
<Expr
*, 8> initExprs
;
4628 for (unsigned i
= 0, e
= PE
->getNumExprs(); i
!= e
; ++i
)
4629 initExprs
.push_back(PE
->getExpr(i
));
4631 // FIXME: This means that pretty-printing the final AST will produce curly
4632 // braces instead of the original commas.
4633 InitListExpr
*E
= new (Context
) InitListExpr(Context
, LParenLoc
,
4635 initExprs
.size(), RParenLoc
);
4637 return BuildCompoundLiteralExpr(LParenLoc
, TInfo
, RParenLoc
, E
);
4639 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4640 // sequence of BinOp comma operators.
4641 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, Op
);
4642 if (Result
.isInvalid()) return ExprError();
4643 return BuildCStyleCastExpr(LParenLoc
, TInfo
, RParenLoc
, Result
.take());
4647 ExprResult
Sema::ActOnParenOrParenListExpr(SourceLocation L
,
4650 ParsedType TypeOfCast
) {
4651 unsigned nexprs
= Val
.size();
4652 Expr
**exprs
= reinterpret_cast<Expr
**>(Val
.release());
4653 assert((exprs
!= 0) && "ActOnParenOrParenListExpr() missing expr list");
4655 if (nexprs
== 1 && TypeOfCast
&& !TypeIsVectorType(TypeOfCast
))
4656 expr
= new (Context
) ParenExpr(L
, R
, exprs
[0]);
4658 expr
= new (Context
) ParenListExpr(Context
, L
, exprs
, nexprs
, R
);
4662 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4663 /// In that case, lhs = cond.
4665 QualType
Sema::CheckConditionalOperands(Expr
*&Cond
, Expr
*&LHS
, Expr
*&RHS
,
4667 SourceLocation QuestionLoc
) {
4668 // If both LHS and RHS are overloaded functions, try to resolve them.
4669 if (Context
.hasSameType(LHS
->getType(), RHS
->getType()) &&
4670 LHS
->getType()->isSpecificBuiltinType(BuiltinType::Overload
)) {
4671 ExprResult LHSResult
= CheckPlaceholderExpr(LHS
, QuestionLoc
);
4672 if (LHSResult
.isInvalid())
4675 ExprResult RHSResult
= CheckPlaceholderExpr(RHS
, QuestionLoc
);
4676 if (RHSResult
.isInvalid())
4679 LHS
= LHSResult
.take();
4680 RHS
= RHSResult
.take();
4683 // C++ is sufficiently different to merit its own checker.
4684 if (getLangOptions().CPlusPlus
)
4685 return CXXCheckConditionalOperands(Cond
, LHS
, RHS
, SAVE
, QuestionLoc
);
4687 UsualUnaryConversions(Cond
);
4692 UsualUnaryConversions(LHS
);
4693 UsualUnaryConversions(RHS
);
4694 QualType CondTy
= Cond
->getType();
4695 QualType LHSTy
= LHS
->getType();
4696 QualType RHSTy
= RHS
->getType();
4698 // first, check the condition.
4699 if (!CondTy
->isScalarType()) { // C99 6.5.15p2
4700 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4701 // Throw an error if its not either.
4702 if (getLangOptions().OpenCL
) {
4703 if (!CondTy
->isVectorType()) {
4704 Diag(Cond
->getLocStart(),
4705 diag::err_typecheck_cond_expect_scalar_or_vector
)
4711 Diag(Cond
->getLocStart(), diag::err_typecheck_cond_expect_scalar
)
4717 // Now check the two expressions.
4718 if (LHSTy
->isVectorType() || RHSTy
->isVectorType())
4719 return CheckVectorOperands(QuestionLoc
, LHS
, RHS
);
4721 // OpenCL: If the condition is a vector, and both operands are scalar,
4722 // attempt to implicity convert them to the vector type to act like the
4724 if (getLangOptions().OpenCL
&& CondTy
->isVectorType()) {
4725 // Both operands should be of scalar type.
4726 if (!LHSTy
->isScalarType()) {
4727 Diag(LHS
->getLocStart(), diag::err_typecheck_cond_expect_scalar
)
4731 if (!RHSTy
->isScalarType()) {
4732 Diag(RHS
->getLocStart(), diag::err_typecheck_cond_expect_scalar
)
4736 // Implicity convert these scalars to the type of the condition.
4737 ImpCastExprToType(LHS
, CondTy
, CK_IntegralCast
);
4738 ImpCastExprToType(RHS
, CondTy
, CK_IntegralCast
);
4741 // If both operands have arithmetic type, do the usual arithmetic conversions
4742 // to find a common type: C99 6.5.15p3,5.
4743 if (LHSTy
->isArithmeticType() && RHSTy
->isArithmeticType()) {
4744 UsualArithmeticConversions(LHS
, RHS
);
4745 return LHS
->getType();
4748 // If both operands are the same structure or union type, the result is that
4750 if (const RecordType
*LHSRT
= LHSTy
->getAs
<RecordType
>()) { // C99 6.5.15p3
4751 if (const RecordType
*RHSRT
= RHSTy
->getAs
<RecordType
>())
4752 if (LHSRT
->getDecl() == RHSRT
->getDecl())
4753 // "If both the operands have structure or union type, the result has
4754 // that type." This implies that CV qualifiers are dropped.
4755 return LHSTy
.getUnqualifiedType();
4756 // FIXME: Type of conditional expression must be complete in C mode.
4759 // C99 6.5.15p5: "If both operands have void type, the result has void type."
4760 // The following || allows only one side to be void (a GCC-ism).
4761 if (LHSTy
->isVoidType() || RHSTy
->isVoidType()) {
4762 if (!LHSTy
->isVoidType())
4763 Diag(RHS
->getLocStart(), diag::ext_typecheck_cond_one_void
)
4764 << RHS
->getSourceRange();
4765 if (!RHSTy
->isVoidType())
4766 Diag(LHS
->getLocStart(), diag::ext_typecheck_cond_one_void
)
4767 << LHS
->getSourceRange();
4768 ImpCastExprToType(LHS
, Context
.VoidTy
, CK_ToVoid
);
4769 ImpCastExprToType(RHS
, Context
.VoidTy
, CK_ToVoid
);
4770 return Context
.VoidTy
;
4772 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4773 // the type of the other operand."
4774 if ((LHSTy
->isAnyPointerType() || LHSTy
->isBlockPointerType()) &&
4775 RHS
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
)) {
4776 // promote the null to a pointer.
4777 ImpCastExprToType(RHS
, LHSTy
, CK_NullToPointer
);
4780 if ((RHSTy
->isAnyPointerType() || RHSTy
->isBlockPointerType()) &&
4781 LHS
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
)) {
4782 ImpCastExprToType(LHS
, RHSTy
, CK_NullToPointer
);
4786 // All objective-c pointer type analysis is done here.
4787 QualType compositeType
= FindCompositeObjCPointerType(LHS
, RHS
,
4789 if (!compositeType
.isNull())
4790 return compositeType
;
4793 // Handle block pointer types.
4794 if (LHSTy
->isBlockPointerType() || RHSTy
->isBlockPointerType()) {
4795 if (!LHSTy
->isBlockPointerType() || !RHSTy
->isBlockPointerType()) {
4796 if (LHSTy
->isVoidPointerType() || RHSTy
->isVoidPointerType()) {
4797 QualType destType
= Context
.getPointerType(Context
.VoidTy
);
4798 ImpCastExprToType(LHS
, destType
, CK_BitCast
);
4799 ImpCastExprToType(RHS
, destType
, CK_BitCast
);
4802 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands
)
4803 << LHSTy
<< RHSTy
<< LHS
->getSourceRange() << RHS
->getSourceRange();
4806 // We have 2 block pointer types.
4807 if (Context
.getCanonicalType(LHSTy
) == Context
.getCanonicalType(RHSTy
)) {
4808 // Two identical block pointer types are always compatible.
4811 // The block pointer types aren't identical, continue checking.
4812 QualType lhptee
= LHSTy
->getAs
<BlockPointerType
>()->getPointeeType();
4813 QualType rhptee
= RHSTy
->getAs
<BlockPointerType
>()->getPointeeType();
4815 if (!Context
.typesAreCompatible(lhptee
.getUnqualifiedType(),
4816 rhptee
.getUnqualifiedType())) {
4817 Diag(QuestionLoc
, diag::warn_typecheck_cond_incompatible_pointers
)
4818 << LHSTy
<< RHSTy
<< LHS
->getSourceRange() << RHS
->getSourceRange();
4819 // In this situation, we assume void* type. No especially good
4820 // reason, but this is what gcc does, and we do have to pick
4821 // to get a consistent AST.
4822 QualType incompatTy
= Context
.getPointerType(Context
.VoidTy
);
4823 ImpCastExprToType(LHS
, incompatTy
, CK_BitCast
);
4824 ImpCastExprToType(RHS
, incompatTy
, CK_BitCast
);
4827 // The block pointer types are compatible.
4828 ImpCastExprToType(LHS
, LHSTy
, CK_BitCast
);
4829 ImpCastExprToType(RHS
, LHSTy
, CK_BitCast
);
4833 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4834 if (LHSTy
->isPointerType() && RHSTy
->isPointerType()) {
4835 // get the "pointed to" types
4836 QualType lhptee
= LHSTy
->getAs
<PointerType
>()->getPointeeType();
4837 QualType rhptee
= RHSTy
->getAs
<PointerType
>()->getPointeeType();
4839 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4840 if (lhptee
->isVoidType() && rhptee
->isIncompleteOrObjectType()) {
4841 // Figure out necessary qualifiers (C99 6.5.15p6)
4842 QualType destPointee
4843 = Context
.getQualifiedType(lhptee
, rhptee
.getQualifiers());
4844 QualType destType
= Context
.getPointerType(destPointee
);
4845 // Add qualifiers if necessary.
4846 ImpCastExprToType(LHS
, destType
, CK_NoOp
);
4847 // Promote to void*.
4848 ImpCastExprToType(RHS
, destType
, CK_BitCast
);
4851 if (rhptee
->isVoidType() && lhptee
->isIncompleteOrObjectType()) {
4852 QualType destPointee
4853 = Context
.getQualifiedType(rhptee
, lhptee
.getQualifiers());
4854 QualType destType
= Context
.getPointerType(destPointee
);
4855 // Add qualifiers if necessary.
4856 ImpCastExprToType(RHS
, destType
, CK_NoOp
);
4857 // Promote to void*.
4858 ImpCastExprToType(LHS
, destType
, CK_BitCast
);
4862 if (Context
.getCanonicalType(LHSTy
) == Context
.getCanonicalType(RHSTy
)) {
4863 // Two identical pointer types are always compatible.
4866 if (!Context
.typesAreCompatible(lhptee
.getUnqualifiedType(),
4867 rhptee
.getUnqualifiedType())) {
4868 Diag(QuestionLoc
, diag::warn_typecheck_cond_incompatible_pointers
)
4869 << LHSTy
<< RHSTy
<< LHS
->getSourceRange() << RHS
->getSourceRange();
4870 // In this situation, we assume void* type. No especially good
4871 // reason, but this is what gcc does, and we do have to pick
4872 // to get a consistent AST.
4873 QualType incompatTy
= Context
.getPointerType(Context
.VoidTy
);
4874 ImpCastExprToType(LHS
, incompatTy
, CK_BitCast
);
4875 ImpCastExprToType(RHS
, incompatTy
, CK_BitCast
);
4878 // The pointer types are compatible.
4879 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4880 // differently qualified versions of compatible types, the result type is
4881 // a pointer to an appropriately qualified version of the *composite*
4883 // FIXME: Need to calculate the composite type.
4884 // FIXME: Need to add qualifiers
4885 ImpCastExprToType(LHS
, LHSTy
, CK_BitCast
);
4886 ImpCastExprToType(RHS
, LHSTy
, CK_BitCast
);
4890 // GCC compatibility: soften pointer/integer mismatch. Note that
4891 // null pointers have been filtered out by this point.
4892 if (RHSTy
->isPointerType() && LHSTy
->isIntegerType()) {
4893 Diag(QuestionLoc
, diag::warn_typecheck_cond_pointer_integer_mismatch
)
4894 << LHSTy
<< RHSTy
<< LHS
->getSourceRange() << RHS
->getSourceRange();
4895 ImpCastExprToType(LHS
, RHSTy
, CK_IntegralToPointer
);
4898 if (LHSTy
->isPointerType() && RHSTy
->isIntegerType()) {
4899 Diag(QuestionLoc
, diag::warn_typecheck_cond_pointer_integer_mismatch
)
4900 << LHSTy
<< RHSTy
<< LHS
->getSourceRange() << RHS
->getSourceRange();
4901 ImpCastExprToType(RHS
, LHSTy
, CK_IntegralToPointer
);
4905 // Otherwise, the operands are not compatible.
4906 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands
)
4907 << LHSTy
<< RHSTy
<< LHS
->getSourceRange() << RHS
->getSourceRange();
4911 /// FindCompositeObjCPointerType - Helper method to find composite type of
4912 /// two objective-c pointer types of the two input expressions.
4913 QualType
Sema::FindCompositeObjCPointerType(Expr
*&LHS
, Expr
*&RHS
,
4914 SourceLocation QuestionLoc
) {
4915 QualType LHSTy
= LHS
->getType();
4916 QualType RHSTy
= RHS
->getType();
4918 // Handle things like Class and struct objc_class*. Here we case the result
4919 // to the pseudo-builtin, because that will be implicitly cast back to the
4920 // redefinition type if an attempt is made to access its fields.
4921 if (LHSTy
->isObjCClassType() &&
4922 (RHSTy
.getDesugaredType() == Context
.ObjCClassRedefinitionType
)) {
4923 ImpCastExprToType(RHS
, LHSTy
, CK_BitCast
);
4926 if (RHSTy
->isObjCClassType() &&
4927 (LHSTy
.getDesugaredType() == Context
.ObjCClassRedefinitionType
)) {
4928 ImpCastExprToType(LHS
, RHSTy
, CK_BitCast
);
4931 // And the same for struct objc_object* / id
4932 if (LHSTy
->isObjCIdType() &&
4933 (RHSTy
.getDesugaredType() == Context
.ObjCIdRedefinitionType
)) {
4934 ImpCastExprToType(RHS
, LHSTy
, CK_BitCast
);
4937 if (RHSTy
->isObjCIdType() &&
4938 (LHSTy
.getDesugaredType() == Context
.ObjCIdRedefinitionType
)) {
4939 ImpCastExprToType(LHS
, RHSTy
, CK_BitCast
);
4942 // And the same for struct objc_selector* / SEL
4943 if (Context
.isObjCSelType(LHSTy
) &&
4944 (RHSTy
.getDesugaredType() == Context
.ObjCSelRedefinitionType
)) {
4945 ImpCastExprToType(RHS
, LHSTy
, CK_BitCast
);
4948 if (Context
.isObjCSelType(RHSTy
) &&
4949 (LHSTy
.getDesugaredType() == Context
.ObjCSelRedefinitionType
)) {
4950 ImpCastExprToType(LHS
, RHSTy
, CK_BitCast
);
4953 // Check constraints for Objective-C object pointers types.
4954 if (LHSTy
->isObjCObjectPointerType() && RHSTy
->isObjCObjectPointerType()) {
4956 if (Context
.getCanonicalType(LHSTy
) == Context
.getCanonicalType(RHSTy
)) {
4957 // Two identical object pointer types are always compatible.
4960 const ObjCObjectPointerType
*LHSOPT
= LHSTy
->getAs
<ObjCObjectPointerType
>();
4961 const ObjCObjectPointerType
*RHSOPT
= RHSTy
->getAs
<ObjCObjectPointerType
>();
4962 QualType compositeType
= LHSTy
;
4964 // If both operands are interfaces and either operand can be
4965 // assigned to the other, use that type as the composite
4966 // type. This allows
4967 // xxx ? (A*) a : (B*) b
4968 // where B is a subclass of A.
4970 // Additionally, as for assignment, if either type is 'id'
4971 // allow silent coercion. Finally, if the types are
4972 // incompatible then make sure to use 'id' as the composite
4973 // type so the result is acceptable for sending messages to.
4975 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4976 // It could return the composite type.
4977 if (Context
.canAssignObjCInterfaces(LHSOPT
, RHSOPT
)) {
4978 compositeType
= RHSOPT
->isObjCBuiltinType() ? RHSTy
: LHSTy
;
4979 } else if (Context
.canAssignObjCInterfaces(RHSOPT
, LHSOPT
)) {
4980 compositeType
= LHSOPT
->isObjCBuiltinType() ? LHSTy
: RHSTy
;
4981 } else if ((LHSTy
->isObjCQualifiedIdType() ||
4982 RHSTy
->isObjCQualifiedIdType()) &&
4983 Context
.ObjCQualifiedIdTypesAreCompatible(LHSTy
, RHSTy
, true)) {
4984 // Need to handle "id<xx>" explicitly.
4985 // GCC allows qualified id and any Objective-C type to devolve to
4986 // id. Currently localizing to here until clear this should be
4987 // part of ObjCQualifiedIdTypesAreCompatible.
4988 compositeType
= Context
.getObjCIdType();
4989 } else if (LHSTy
->isObjCIdType() || RHSTy
->isObjCIdType()) {
4990 compositeType
= Context
.getObjCIdType();
4991 } else if (!(compositeType
=
4992 Context
.areCommonBaseCompatible(LHSOPT
, RHSOPT
)).isNull())
4995 Diag(QuestionLoc
, diag::ext_typecheck_cond_incompatible_operands
)
4997 << LHS
->getSourceRange() << RHS
->getSourceRange();
4998 QualType incompatTy
= Context
.getObjCIdType();
4999 ImpCastExprToType(LHS
, incompatTy
, CK_BitCast
);
5000 ImpCastExprToType(RHS
, incompatTy
, CK_BitCast
);
5003 // The object pointer types are compatible.
5004 ImpCastExprToType(LHS
, compositeType
, CK_BitCast
);
5005 ImpCastExprToType(RHS
, compositeType
, CK_BitCast
);
5006 return compositeType
;
5008 // Check Objective-C object pointer types and 'void *'
5009 if (LHSTy
->isVoidPointerType() && RHSTy
->isObjCObjectPointerType()) {
5010 QualType lhptee
= LHSTy
->getAs
<PointerType
>()->getPointeeType();
5011 QualType rhptee
= RHSTy
->getAs
<ObjCObjectPointerType
>()->getPointeeType();
5012 QualType destPointee
5013 = Context
.getQualifiedType(lhptee
, rhptee
.getQualifiers());
5014 QualType destType
= Context
.getPointerType(destPointee
);
5015 // Add qualifiers if necessary.
5016 ImpCastExprToType(LHS
, destType
, CK_NoOp
);
5017 // Promote to void*.
5018 ImpCastExprToType(RHS
, destType
, CK_BitCast
);
5021 if (LHSTy
->isObjCObjectPointerType() && RHSTy
->isVoidPointerType()) {
5022 QualType lhptee
= LHSTy
->getAs
<ObjCObjectPointerType
>()->getPointeeType();
5023 QualType rhptee
= RHSTy
->getAs
<PointerType
>()->getPointeeType();
5024 QualType destPointee
5025 = Context
.getQualifiedType(rhptee
, lhptee
.getQualifiers());
5026 QualType destType
= Context
.getPointerType(destPointee
);
5027 // Add qualifiers if necessary.
5028 ImpCastExprToType(RHS
, destType
, CK_NoOp
);
5029 // Promote to void*.
5030 ImpCastExprToType(LHS
, destType
, CK_BitCast
);
5036 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5037 /// in the case of a the GNU conditional expr extension.
5038 ExprResult
Sema::ActOnConditionalOp(SourceLocation QuestionLoc
,
5039 SourceLocation ColonLoc
,
5040 Expr
*CondExpr
, Expr
*LHSExpr
,
5042 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5043 // was the condition.
5044 bool isLHSNull
= LHSExpr
== 0;
5047 LHSExpr
= SAVEExpr
= CondExpr
;
5050 QualType result
= CheckConditionalOperands(CondExpr
, LHSExpr
, RHSExpr
,
5051 SAVEExpr
, QuestionLoc
);
5052 if (result
.isNull())
5055 return Owned(new (Context
) ConditionalOperator(CondExpr
, QuestionLoc
,
5061 // CheckPointerTypesForAssignment - This is a very tricky routine (despite
5062 // being closely modeled after the C99 spec:-). The odd characteristic of this
5063 // routine is it effectively iqnores the qualifiers on the top level pointee.
5064 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5065 // FIXME: add a couple examples in this comment.
5066 Sema::AssignConvertType
5067 Sema::CheckPointerTypesForAssignment(QualType lhsType
, QualType rhsType
) {
5068 QualType lhptee
, rhptee
;
5070 if ((lhsType
->isObjCClassType() &&
5071 (rhsType
.getDesugaredType() == Context
.ObjCClassRedefinitionType
)) ||
5072 (rhsType
->isObjCClassType() &&
5073 (lhsType
.getDesugaredType() == Context
.ObjCClassRedefinitionType
))) {
5077 // get the "pointed to" type (ignoring qualifiers at the top level)
5078 lhptee
= lhsType
->getAs
<PointerType
>()->getPointeeType();
5079 rhptee
= rhsType
->getAs
<PointerType
>()->getPointeeType();
5081 // make sure we operate on the canonical type
5082 lhptee
= Context
.getCanonicalType(lhptee
);
5083 rhptee
= Context
.getCanonicalType(rhptee
);
5085 AssignConvertType ConvTy
= Compatible
;
5087 // C99 6.5.16.1p1: This following citation is common to constraints
5088 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5089 // qualifiers of the type *pointed to* by the right;
5090 // FIXME: Handle ExtQualType
5091 if (!lhptee
.isAtLeastAsQualifiedAs(rhptee
))
5092 ConvTy
= CompatiblePointerDiscardsQualifiers
;
5094 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5095 // incomplete type and the other is a pointer to a qualified or unqualified
5096 // version of void...
5097 if (lhptee
->isVoidType()) {
5098 if (rhptee
->isIncompleteOrObjectType())
5101 // As an extension, we allow cast to/from void* to function pointer.
5102 assert(rhptee
->isFunctionType());
5103 return FunctionVoidPointer
;
5106 if (rhptee
->isVoidType()) {
5107 if (lhptee
->isIncompleteOrObjectType())
5110 // As an extension, we allow cast to/from void* to function pointer.
5111 assert(lhptee
->isFunctionType());
5112 return FunctionVoidPointer
;
5114 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5115 // unqualified versions of compatible types, ...
5116 lhptee
= lhptee
.getUnqualifiedType();
5117 rhptee
= rhptee
.getUnqualifiedType();
5118 if (!Context
.typesAreCompatible(lhptee
, rhptee
)) {
5119 // Check if the pointee types are compatible ignoring the sign.
5120 // We explicitly check for char so that we catch "char" vs
5121 // "unsigned char" on systems where "char" is unsigned.
5122 if (lhptee
->isCharType())
5123 lhptee
= Context
.UnsignedCharTy
;
5124 else if (lhptee
->hasSignedIntegerRepresentation())
5125 lhptee
= Context
.getCorrespondingUnsignedType(lhptee
);
5127 if (rhptee
->isCharType())
5128 rhptee
= Context
.UnsignedCharTy
;
5129 else if (rhptee
->hasSignedIntegerRepresentation())
5130 rhptee
= Context
.getCorrespondingUnsignedType(rhptee
);
5132 if (lhptee
== rhptee
) {
5133 // Types are compatible ignoring the sign. Qualifier incompatibility
5134 // takes priority over sign incompatibility because the sign
5135 // warning can be disabled.
5136 if (ConvTy
!= Compatible
)
5138 return IncompatiblePointerSign
;
5141 // If we are a multi-level pointer, it's possible that our issue is simply
5142 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5143 // the eventual target type is the same and the pointers have the same
5144 // level of indirection, this must be the issue.
5145 if (lhptee
->isPointerType() && rhptee
->isPointerType()) {
5147 lhptee
= lhptee
->getAs
<PointerType
>()->getPointeeType();
5148 rhptee
= rhptee
->getAs
<PointerType
>()->getPointeeType();
5150 lhptee
= Context
.getCanonicalType(lhptee
);
5151 rhptee
= Context
.getCanonicalType(rhptee
);
5152 } while (lhptee
->isPointerType() && rhptee
->isPointerType());
5154 if (Context
.hasSameUnqualifiedType(lhptee
, rhptee
))
5155 return IncompatibleNestedPointerQualifiers
;
5158 // General pointer incompatibility takes priority over qualifiers.
5159 return IncompatiblePointer
;
5164 /// CheckBlockPointerTypesForAssignment - This routine determines whether two
5165 /// block pointer types are compatible or whether a block and normal pointer
5166 /// are compatible. It is more restrict than comparing two function pointer
5168 Sema::AssignConvertType
5169 Sema::CheckBlockPointerTypesForAssignment(QualType lhsType
,
5171 QualType lhptee
, rhptee
;
5173 // get the "pointed to" type (ignoring qualifiers at the top level)
5174 lhptee
= lhsType
->getAs
<BlockPointerType
>()->getPointeeType();
5175 rhptee
= rhsType
->getAs
<BlockPointerType
>()->getPointeeType();
5177 // make sure we operate on the canonical type
5178 lhptee
= Context
.getCanonicalType(lhptee
);
5179 rhptee
= Context
.getCanonicalType(rhptee
);
5181 AssignConvertType ConvTy
= Compatible
;
5183 // For blocks we enforce that qualifiers are identical.
5184 if (lhptee
.getLocalCVRQualifiers() != rhptee
.getLocalCVRQualifiers())
5185 ConvTy
= CompatiblePointerDiscardsQualifiers
;
5187 if (!getLangOptions().CPlusPlus
) {
5188 if (!Context
.typesAreBlockPointerCompatible(lhsType
, rhsType
))
5189 return IncompatibleBlockPointer
;
5191 else if (!Context
.typesAreCompatible(lhptee
, rhptee
))
5192 return IncompatibleBlockPointer
;
5196 /// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
5197 /// for assignment compatibility.
5198 Sema::AssignConvertType
5199 Sema::CheckObjCPointerTypesForAssignment(QualType lhsType
, QualType rhsType
) {
5200 if (lhsType
->isObjCBuiltinType()) {
5201 // Class is not compatible with ObjC object pointers.
5202 if (lhsType
->isObjCClassType() && !rhsType
->isObjCBuiltinType() &&
5203 !rhsType
->isObjCQualifiedClassType())
5204 return IncompatiblePointer
;
5207 if (rhsType
->isObjCBuiltinType()) {
5208 // Class is not compatible with ObjC object pointers.
5209 if (rhsType
->isObjCClassType() && !lhsType
->isObjCBuiltinType() &&
5210 !lhsType
->isObjCQualifiedClassType())
5211 return IncompatiblePointer
;
5215 lhsType
->getAs
<ObjCObjectPointerType
>()->getPointeeType();
5217 rhsType
->getAs
<ObjCObjectPointerType
>()->getPointeeType();
5218 // make sure we operate on the canonical type
5219 lhptee
= Context
.getCanonicalType(lhptee
);
5220 rhptee
= Context
.getCanonicalType(rhptee
);
5221 if (!lhptee
.isAtLeastAsQualifiedAs(rhptee
))
5222 return CompatiblePointerDiscardsQualifiers
;
5224 if (Context
.typesAreCompatible(lhsType
, rhsType
))
5226 if (lhsType
->isObjCQualifiedIdType() || rhsType
->isObjCQualifiedIdType())
5227 return IncompatibleObjCQualifiedId
;
5228 return IncompatiblePointer
;
5231 Sema::AssignConvertType
5232 Sema::CheckAssignmentConstraints(QualType lhsType
, QualType rhsType
) {
5233 // Fake up an opaque expression. We don't actually care about what
5234 // cast operations are required, so if CheckAssignmentConstraints
5235 // adds casts to this they'll be wasted, but fortunately that doesn't
5236 // usually happen on valid code.
5237 OpaqueValueExpr
rhs(rhsType
, VK_RValue
);
5238 Expr
*rhsPtr
= &rhs
;
5239 CastKind K
= CK_Invalid
;
5241 return CheckAssignmentConstraints(lhsType
, rhsPtr
, K
);
5244 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5245 /// has code to accommodate several GCC extensions when type checking
5246 /// pointers. Here are some objectionable examples that GCC considers warnings:
5250 /// struct foo *pfoo;
5252 /// pint = pshort; // warning: assignment from incompatible pointer type
5253 /// a = pint; // warning: assignment makes integer from pointer without a cast
5254 /// pint = a; // warning: assignment makes pointer from integer without a cast
5255 /// pint = pfoo; // warning: assignment from incompatible pointer type
5257 /// As a result, the code for dealing with pointers is more complex than the
5258 /// C99 spec dictates.
5260 /// Sets 'Kind' for any result kind except Incompatible.
5261 Sema::AssignConvertType
5262 Sema::CheckAssignmentConstraints(QualType lhsType
, Expr
*&rhs
,
5264 QualType rhsType
= rhs
->getType();
5266 // Get canonical types. We're not formatting these types, just comparing
5268 lhsType
= Context
.getCanonicalType(lhsType
).getUnqualifiedType();
5269 rhsType
= Context
.getCanonicalType(rhsType
).getUnqualifiedType();
5271 if (lhsType
== rhsType
) {
5273 return Compatible
; // Common case: fast path an exact match.
5276 if ((lhsType
->isObjCClassType() &&
5277 (rhsType
.getDesugaredType() == Context
.ObjCClassRedefinitionType
)) ||
5278 (rhsType
->isObjCClassType() &&
5279 (lhsType
.getDesugaredType() == Context
.ObjCClassRedefinitionType
))) {
5284 // If the left-hand side is a reference type, then we are in a
5285 // (rare!) case where we've allowed the use of references in C,
5286 // e.g., as a parameter type in a built-in function. In this case,
5287 // just make sure that the type referenced is compatible with the
5288 // right-hand side type. The caller is responsible for adjusting
5289 // lhsType so that the resulting expression does not have reference
5291 if (const ReferenceType
*lhsTypeRef
= lhsType
->getAs
<ReferenceType
>()) {
5292 if (Context
.typesAreCompatible(lhsTypeRef
->getPointeeType(), rhsType
)) {
5293 Kind
= CK_LValueBitCast
;
5296 return Incompatible
;
5298 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5299 // to the same ExtVector type.
5300 if (lhsType
->isExtVectorType()) {
5301 if (rhsType
->isExtVectorType())
5302 return Incompatible
;
5303 if (rhsType
->isArithmeticType()) {
5304 // CK_VectorSplat does T -> vector T, so first cast to the
5306 QualType elType
= cast
<ExtVectorType
>(lhsType
)->getElementType();
5307 if (elType
!= rhsType
) {
5308 Kind
= PrepareScalarCast(*this, rhs
, elType
);
5309 ImpCastExprToType(rhs
, elType
, Kind
);
5311 Kind
= CK_VectorSplat
;
5316 if (lhsType
->isVectorType() || rhsType
->isVectorType()) {
5317 if (lhsType
->isVectorType() && rhsType
->isVectorType()) {
5318 // If we are allowing lax vector conversions, and LHS and RHS are both
5319 // vectors, the total size only needs to be the same. This is a bitcast;
5320 // no bits are changed but the result type is different.
5321 if (getLangOptions().LaxVectorConversions
&&
5322 (Context
.getTypeSize(lhsType
) == Context
.getTypeSize(rhsType
))) {
5324 return IncompatibleVectors
;
5327 // Allow assignments of an AltiVec vector type to an equivalent GCC
5328 // vector type and vice versa
5329 if (Context
.areCompatibleVectorTypes(lhsType
, rhsType
)) {
5334 return Incompatible
;
5337 if (lhsType
->isArithmeticType() && rhsType
->isArithmeticType() &&
5338 !(getLangOptions().CPlusPlus
&& lhsType
->isEnumeralType())) {
5339 Kind
= PrepareScalarCast(*this, rhs
, lhsType
);
5343 if (isa
<PointerType
>(lhsType
)) {
5344 if (rhsType
->isIntegerType()) {
5345 Kind
= CK_IntegralToPointer
; // FIXME: null?
5346 return IntToPointer
;
5349 if (isa
<PointerType
>(rhsType
)) {
5351 return CheckPointerTypesForAssignment(lhsType
, rhsType
);
5354 // In general, C pointers are not compatible with ObjC object pointers.
5355 if (isa
<ObjCObjectPointerType
>(rhsType
)) {
5356 Kind
= CK_AnyPointerToObjCPointerCast
;
5357 if (lhsType
->isVoidPointerType()) // an exception to the rule.
5359 return IncompatiblePointer
;
5361 if (rhsType
->getAs
<BlockPointerType
>()) {
5362 if (lhsType
->getAs
<PointerType
>()->getPointeeType()->isVoidType()) {
5367 // Treat block pointers as objects.
5368 if (getLangOptions().ObjC1
&& lhsType
->isObjCIdType()) {
5369 Kind
= CK_AnyPointerToObjCPointerCast
;
5373 return Incompatible
;
5376 if (isa
<BlockPointerType
>(lhsType
)) {
5377 if (rhsType
->isIntegerType()) {
5378 Kind
= CK_IntegralToPointer
; // FIXME: null
5379 return IntToBlockPointer
;
5382 Kind
= CK_AnyPointerToObjCPointerCast
;
5384 // Treat block pointers as objects.
5385 if (getLangOptions().ObjC1
&& rhsType
->isObjCIdType())
5388 if (rhsType
->isBlockPointerType())
5389 return CheckBlockPointerTypesForAssignment(lhsType
, rhsType
);
5391 if (const PointerType
*RHSPT
= rhsType
->getAs
<PointerType
>())
5392 if (RHSPT
->getPointeeType()->isVoidType())
5395 return Incompatible
;
5398 if (isa
<ObjCObjectPointerType
>(lhsType
)) {
5399 if (rhsType
->isIntegerType()) {
5400 Kind
= CK_IntegralToPointer
; // FIXME: null
5401 return IntToPointer
;
5406 // In general, C pointers are not compatible with ObjC object pointers.
5407 if (isa
<PointerType
>(rhsType
)) {
5408 if (rhsType
->isVoidPointerType()) // an exception to the rule.
5410 return IncompatiblePointer
;
5412 if (rhsType
->isObjCObjectPointerType()) {
5413 return CheckObjCPointerTypesForAssignment(lhsType
, rhsType
);
5415 if (const PointerType
*RHSPT
= rhsType
->getAs
<PointerType
>()) {
5416 if (RHSPT
->getPointeeType()->isVoidType())
5419 // Treat block pointers as objects.
5420 if (rhsType
->isBlockPointerType())
5422 return Incompatible
;
5424 if (isa
<PointerType
>(rhsType
)) {
5425 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
5426 if (lhsType
== Context
.BoolTy
) {
5427 Kind
= CK_PointerToBoolean
;
5431 if (lhsType
->isIntegerType()) {
5432 Kind
= CK_PointerToIntegral
;
5433 return PointerToInt
;
5436 if (isa
<BlockPointerType
>(lhsType
) &&
5437 rhsType
->getAs
<PointerType
>()->getPointeeType()->isVoidType()) {
5438 Kind
= CK_AnyPointerToBlockPointerCast
;
5441 return Incompatible
;
5443 if (isa
<ObjCObjectPointerType
>(rhsType
)) {
5444 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
5445 if (lhsType
== Context
.BoolTy
) {
5446 Kind
= CK_PointerToBoolean
;
5450 if (lhsType
->isIntegerType()) {
5451 Kind
= CK_PointerToIntegral
;
5452 return PointerToInt
;
5457 // In general, C pointers are not compatible with ObjC object pointers.
5458 if (isa
<PointerType
>(lhsType
)) {
5459 if (lhsType
->isVoidPointerType()) // an exception to the rule.
5461 return IncompatiblePointer
;
5463 if (isa
<BlockPointerType
>(lhsType
) &&
5464 rhsType
->getAs
<PointerType
>()->getPointeeType()->isVoidType()) {
5465 Kind
= CK_AnyPointerToBlockPointerCast
;
5468 return Incompatible
;
5471 if (isa
<TagType
>(lhsType
) && isa
<TagType
>(rhsType
)) {
5472 if (Context
.typesAreCompatible(lhsType
, rhsType
)) {
5477 return Incompatible
;
5480 /// \brief Constructs a transparent union from an expression that is
5481 /// used to initialize the transparent union.
5482 static void ConstructTransparentUnion(ASTContext
&C
, Expr
*&E
,
5483 QualType UnionType
, FieldDecl
*Field
) {
5484 // Build an initializer list that designates the appropriate member
5485 // of the transparent union.
5486 InitListExpr
*Initializer
= new (C
) InitListExpr(C
, SourceLocation(),
5489 Initializer
->setType(UnionType
);
5490 Initializer
->setInitializedFieldInUnion(Field
);
5492 // Build a compound literal constructing a value of the transparent
5493 // union type from this initializer list.
5494 TypeSourceInfo
*unionTInfo
= C
.getTrivialTypeSourceInfo(UnionType
);
5495 E
= new (C
) CompoundLiteralExpr(SourceLocation(), unionTInfo
, UnionType
,
5496 Initializer
, false);
5499 Sema::AssignConvertType
5500 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType
, Expr
*&rExpr
) {
5501 QualType FromType
= rExpr
->getType();
5503 // If the ArgType is a Union type, we want to handle a potential
5504 // transparent_union GCC extension.
5505 const RecordType
*UT
= ArgType
->getAsUnionType();
5506 if (!UT
|| !UT
->getDecl()->hasAttr
<TransparentUnionAttr
>())
5507 return Incompatible
;
5509 // The field to initialize within the transparent union.
5510 RecordDecl
*UD
= UT
->getDecl();
5511 FieldDecl
*InitField
= 0;
5512 // It's compatible if the expression matches any of the fields.
5513 for (RecordDecl::field_iterator it
= UD
->field_begin(),
5514 itend
= UD
->field_end();
5515 it
!= itend
; ++it
) {
5516 if (it
->getType()->isPointerType()) {
5517 // If the transparent union contains a pointer type, we allow:
5519 // 2) null pointer constant
5520 if (FromType
->isPointerType())
5521 if (FromType
->getAs
<PointerType
>()->getPointeeType()->isVoidType()) {
5522 ImpCastExprToType(rExpr
, it
->getType(), CK_BitCast
);
5527 if (rExpr
->isNullPointerConstant(Context
,
5528 Expr::NPC_ValueDependentIsNull
)) {
5529 ImpCastExprToType(rExpr
, it
->getType(), CK_NullToPointer
);
5536 CastKind Kind
= CK_Invalid
;
5537 if (CheckAssignmentConstraints(it
->getType(), rhs
, Kind
)
5539 ImpCastExprToType(rhs
, it
->getType(), Kind
);
5547 return Incompatible
;
5549 ConstructTransparentUnion(Context
, rExpr
, ArgType
, InitField
);
5553 Sema::AssignConvertType
5554 Sema::CheckSingleAssignmentConstraints(QualType lhsType
, Expr
*&rExpr
) {
5555 if (getLangOptions().CPlusPlus
) {
5556 if (!lhsType
->isRecordType()) {
5557 // C++ 5.17p3: If the left operand is not of class type, the
5558 // expression is implicitly converted (C++ 4) to the
5559 // cv-unqualified type of the left operand.
5560 if (PerformImplicitConversion(rExpr
, lhsType
.getUnqualifiedType(),
5562 return Incompatible
;
5566 // FIXME: Currently, we fall through and treat C++ classes like C
5570 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5571 // a null pointer constant.
5572 if ((lhsType
->isPointerType() ||
5573 lhsType
->isObjCObjectPointerType() ||
5574 lhsType
->isBlockPointerType())
5575 && rExpr
->isNullPointerConstant(Context
,
5576 Expr::NPC_ValueDependentIsNull
)) {
5577 ImpCastExprToType(rExpr
, lhsType
, CK_NullToPointer
);
5581 // This check seems unnatural, however it is necessary to ensure the proper
5582 // conversion of functions/arrays. If the conversion were done for all
5583 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5584 // expressions that suppress this implicit conversion (&, sizeof).
5586 // Suppress this for references: C++ 8.5.3p5.
5587 if (!lhsType
->isReferenceType())
5588 DefaultFunctionArrayLvalueConversion(rExpr
);
5590 CastKind Kind
= CK_Invalid
;
5591 Sema::AssignConvertType result
=
5592 CheckAssignmentConstraints(lhsType
, rExpr
, Kind
);
5594 // C99 6.5.16.1p2: The value of the right operand is converted to the
5595 // type of the assignment expression.
5596 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5597 // so that we can use references in built-in functions even in C.
5598 // The getNonReferenceType() call makes sure that the resulting expression
5599 // does not have reference type.
5600 if (result
!= Incompatible
&& rExpr
->getType() != lhsType
)
5601 ImpCastExprToType(rExpr
, lhsType
.getNonLValueExprType(Context
), Kind
);
5605 QualType
Sema::InvalidOperands(SourceLocation Loc
, Expr
*&lex
, Expr
*&rex
) {
5606 Diag(Loc
, diag::err_typecheck_invalid_operands
)
5607 << lex
->getType() << rex
->getType()
5608 << lex
->getSourceRange() << rex
->getSourceRange();
5612 QualType
Sema::CheckVectorOperands(SourceLocation Loc
, Expr
*&lex
, Expr
*&rex
) {
5613 // For conversion purposes, we ignore any qualifiers.
5614 // For example, "const float" and "float" are equivalent.
5616 Context
.getCanonicalType(lex
->getType()).getUnqualifiedType();
5618 Context
.getCanonicalType(rex
->getType()).getUnqualifiedType();
5620 // If the vector types are identical, return.
5621 if (lhsType
== rhsType
)
5624 // Handle the case of a vector & extvector type of the same size and element
5625 // type. It would be nice if we only had one vector type someday.
5626 if (getLangOptions().LaxVectorConversions
) {
5627 if (const VectorType
*LV
= lhsType
->getAs
<VectorType
>()) {
5628 if (const VectorType
*RV
= rhsType
->getAs
<VectorType
>()) {
5629 if (LV
->getElementType() == RV
->getElementType() &&
5630 LV
->getNumElements() == RV
->getNumElements()) {
5631 if (lhsType
->isExtVectorType()) {
5632 ImpCastExprToType(rex
, lhsType
, CK_BitCast
);
5636 ImpCastExprToType(lex
, rhsType
, CK_BitCast
);
5638 } else if (Context
.getTypeSize(lhsType
) ==Context
.getTypeSize(rhsType
)){
5639 // If we are allowing lax vector conversions, and LHS and RHS are both
5640 // vectors, the total size only needs to be the same. This is a
5641 // bitcast; no bits are changed but the result type is different.
5642 ImpCastExprToType(rex
, lhsType
, CK_BitCast
);
5649 // Handle the case of equivalent AltiVec and GCC vector types
5650 if (lhsType
->isVectorType() && rhsType
->isVectorType() &&
5651 Context
.areCompatibleVectorTypes(lhsType
, rhsType
)) {
5652 ImpCastExprToType(lex
, rhsType
, CK_BitCast
);
5656 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5657 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5658 bool swapped
= false;
5659 if (rhsType
->isExtVectorType()) {
5661 std::swap(rex
, lex
);
5662 std::swap(rhsType
, lhsType
);
5665 // Handle the case of an ext vector and scalar.
5666 if (const ExtVectorType
*LV
= lhsType
->getAs
<ExtVectorType
>()) {
5667 QualType EltTy
= LV
->getElementType();
5668 if (EltTy
->isIntegralType(Context
) && rhsType
->isIntegralType(Context
)) {
5669 int order
= Context
.getIntegerTypeOrder(EltTy
, rhsType
);
5671 ImpCastExprToType(rex
, EltTy
, CK_IntegralCast
);
5673 ImpCastExprToType(rex
, lhsType
, CK_VectorSplat
);
5674 if (swapped
) std::swap(rex
, lex
);
5678 if (EltTy
->isRealFloatingType() && rhsType
->isScalarType() &&
5679 rhsType
->isRealFloatingType()) {
5680 int order
= Context
.getFloatingTypeOrder(EltTy
, rhsType
);
5682 ImpCastExprToType(rex
, EltTy
, CK_FloatingCast
);
5684 ImpCastExprToType(rex
, lhsType
, CK_VectorSplat
);
5685 if (swapped
) std::swap(rex
, lex
);
5691 // Vectors of different size or scalar and non-ext-vector are errors.
5692 Diag(Loc
, diag::err_typecheck_vector_not_convertable
)
5693 << lex
->getType() << rex
->getType()
5694 << lex
->getSourceRange() << rex
->getSourceRange();
5698 QualType
Sema::CheckMultiplyDivideOperands(
5699 Expr
*&lex
, Expr
*&rex
, SourceLocation Loc
, bool isCompAssign
, bool isDiv
) {
5700 if (lex
->getType()->isVectorType() || rex
->getType()->isVectorType())
5701 return CheckVectorOperands(Loc
, lex
, rex
);
5703 QualType compType
= UsualArithmeticConversions(lex
, rex
, isCompAssign
);
5705 if (!lex
->getType()->isArithmeticType() ||
5706 !rex
->getType()->isArithmeticType())
5707 return InvalidOperands(Loc
, lex
, rex
);
5709 // Check for division by zero.
5711 rex
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNotNull
))
5712 DiagRuntimeBehavior(Loc
, PDiag(diag::warn_division_by_zero
)
5713 << rex
->getSourceRange());
5718 QualType
Sema::CheckRemainderOperands(
5719 Expr
*&lex
, Expr
*&rex
, SourceLocation Loc
, bool isCompAssign
) {
5720 if (lex
->getType()->isVectorType() || rex
->getType()->isVectorType()) {
5721 if (lex
->getType()->hasIntegerRepresentation() &&
5722 rex
->getType()->hasIntegerRepresentation())
5723 return CheckVectorOperands(Loc
, lex
, rex
);
5724 return InvalidOperands(Loc
, lex
, rex
);
5727 QualType compType
= UsualArithmeticConversions(lex
, rex
, isCompAssign
);
5729 if (!lex
->getType()->isIntegerType() || !rex
->getType()->isIntegerType())
5730 return InvalidOperands(Loc
, lex
, rex
);
5732 // Check for remainder by zero.
5733 if (rex
->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNotNull
))
5734 DiagRuntimeBehavior(Loc
, PDiag(diag::warn_remainder_by_zero
)
5735 << rex
->getSourceRange());
5740 QualType
Sema::CheckAdditionOperands( // C99 6.5.6
5741 Expr
*&lex
, Expr
*&rex
, SourceLocation Loc
, QualType
* CompLHSTy
) {
5742 if (lex
->getType()->isVectorType() || rex
->getType()->isVectorType()) {
5743 QualType compType
= CheckVectorOperands(Loc
, lex
, rex
);
5744 if (CompLHSTy
) *CompLHSTy
= compType
;
5748 QualType compType
= UsualArithmeticConversions(lex
, rex
, CompLHSTy
);
5750 // handle the common case first (both operands are arithmetic).
5751 if (lex
->getType()->isArithmeticType() &&
5752 rex
->getType()->isArithmeticType()) {
5753 if (CompLHSTy
) *CompLHSTy
= compType
;
5757 // Put any potential pointer into PExp
5758 Expr
* PExp
= lex
, *IExp
= rex
;
5759 if (IExp
->getType()->isAnyPointerType())
5760 std::swap(PExp
, IExp
);
5762 if (PExp
->getType()->isAnyPointerType()) {
5764 if (IExp
->getType()->isIntegerType()) {
5765 QualType PointeeTy
= PExp
->getType()->getPointeeType();
5767 // Check for arithmetic on pointers to incomplete types.
5768 if (PointeeTy
->isVoidType()) {
5769 if (getLangOptions().CPlusPlus
) {
5770 Diag(Loc
, diag::err_typecheck_pointer_arith_void_type
)
5771 << lex
->getSourceRange() << rex
->getSourceRange();
5775 // GNU extension: arithmetic on pointer to void
5776 Diag(Loc
, diag::ext_gnu_void_ptr
)
5777 << lex
->getSourceRange() << rex
->getSourceRange();
5778 } else if (PointeeTy
->isFunctionType()) {
5779 if (getLangOptions().CPlusPlus
) {
5780 Diag(Loc
, diag::err_typecheck_pointer_arith_function_type
)
5781 << lex
->getType() << lex
->getSourceRange();
5785 // GNU extension: arithmetic on pointer to function
5786 Diag(Loc
, diag::ext_gnu_ptr_func_arith
)
5787 << lex
->getType() << lex
->getSourceRange();
5789 // Check if we require a complete type.
5790 if (((PExp
->getType()->isPointerType() &&
5791 !PExp
->getType()->isDependentType()) ||
5792 PExp
->getType()->isObjCObjectPointerType()) &&
5793 RequireCompleteType(Loc
, PointeeTy
,
5794 PDiag(diag::err_typecheck_arithmetic_incomplete_type
)
5795 << PExp
->getSourceRange()
5796 << PExp
->getType()))
5799 // Diagnose bad cases where we step over interface counts.
5800 if (PointeeTy
->isObjCObjectType() && LangOpts
.ObjCNonFragileABI
) {
5801 Diag(Loc
, diag::err_arithmetic_nonfragile_interface
)
5802 << PointeeTy
<< PExp
->getSourceRange();
5807 QualType LHSTy
= Context
.isPromotableBitField(lex
);
5808 if (LHSTy
.isNull()) {
5809 LHSTy
= lex
->getType();
5810 if (LHSTy
->isPromotableIntegerType())
5811 LHSTy
= Context
.getPromotedIntegerType(LHSTy
);
5815 return PExp
->getType();
5819 return InvalidOperands(Loc
, lex
, rex
);
5823 QualType
Sema::CheckSubtractionOperands(Expr
*&lex
, Expr
*&rex
,
5824 SourceLocation Loc
, QualType
* CompLHSTy
) {
5825 if (lex
->getType()->isVectorType() || rex
->getType()->isVectorType()) {
5826 QualType compType
= CheckVectorOperands(Loc
, lex
, rex
);
5827 if (CompLHSTy
) *CompLHSTy
= compType
;
5831 QualType compType
= UsualArithmeticConversions(lex
, rex
, CompLHSTy
);
5833 // Enforce type constraints: C99 6.5.6p3.
5835 // Handle the common case first (both operands are arithmetic).
5836 if (lex
->getType()->isArithmeticType()
5837 && rex
->getType()->isArithmeticType()) {
5838 if (CompLHSTy
) *CompLHSTy
= compType
;
5842 // Either ptr - int or ptr - ptr.
5843 if (lex
->getType()->isAnyPointerType()) {
5844 QualType lpointee
= lex
->getType()->getPointeeType();
5846 // The LHS must be an completely-defined object type.
5848 bool ComplainAboutVoid
= false;
5849 Expr
*ComplainAboutFunc
= 0;
5850 if (lpointee
->isVoidType()) {
5851 if (getLangOptions().CPlusPlus
) {
5852 Diag(Loc
, diag::err_typecheck_pointer_arith_void_type
)
5853 << lex
->getSourceRange() << rex
->getSourceRange();
5857 // GNU C extension: arithmetic on pointer to void
5858 ComplainAboutVoid
= true;
5859 } else if (lpointee
->isFunctionType()) {
5860 if (getLangOptions().CPlusPlus
) {
5861 Diag(Loc
, diag::err_typecheck_pointer_arith_function_type
)
5862 << lex
->getType() << lex
->getSourceRange();
5866 // GNU C extension: arithmetic on pointer to function
5867 ComplainAboutFunc
= lex
;
5868 } else if (!lpointee
->isDependentType() &&
5869 RequireCompleteType(Loc
, lpointee
,
5870 PDiag(diag::err_typecheck_sub_ptr_object
)
5871 << lex
->getSourceRange()
5875 // Diagnose bad cases where we step over interface counts.
5876 if (lpointee
->isObjCObjectType() && LangOpts
.ObjCNonFragileABI
) {
5877 Diag(Loc
, diag::err_arithmetic_nonfragile_interface
)
5878 << lpointee
<< lex
->getSourceRange();
5882 // The result type of a pointer-int computation is the pointer type.
5883 if (rex
->getType()->isIntegerType()) {
5884 if (ComplainAboutVoid
)
5885 Diag(Loc
, diag::ext_gnu_void_ptr
)
5886 << lex
->getSourceRange() << rex
->getSourceRange();
5887 if (ComplainAboutFunc
)
5888 Diag(Loc
, diag::ext_gnu_ptr_func_arith
)
5889 << ComplainAboutFunc
->getType()
5890 << ComplainAboutFunc
->getSourceRange();
5892 if (CompLHSTy
) *CompLHSTy
= lex
->getType();
5893 return lex
->getType();
5896 // Handle pointer-pointer subtractions.
5897 if (const PointerType
*RHSPTy
= rex
->getType()->getAs
<PointerType
>()) {
5898 QualType rpointee
= RHSPTy
->getPointeeType();
5900 // RHS must be a completely-type object type.
5901 // Handle the GNU void* extension.
5902 if (rpointee
->isVoidType()) {
5903 if (getLangOptions().CPlusPlus
) {
5904 Diag(Loc
, diag::err_typecheck_pointer_arith_void_type
)
5905 << lex
->getSourceRange() << rex
->getSourceRange();
5909 ComplainAboutVoid
= true;
5910 } else if (rpointee
->isFunctionType()) {
5911 if (getLangOptions().CPlusPlus
) {
5912 Diag(Loc
, diag::err_typecheck_pointer_arith_function_type
)
5913 << rex
->getType() << rex
->getSourceRange();
5917 // GNU extension: arithmetic on pointer to function
5918 if (!ComplainAboutFunc
)
5919 ComplainAboutFunc
= rex
;
5920 } else if (!rpointee
->isDependentType() &&
5921 RequireCompleteType(Loc
, rpointee
,
5922 PDiag(diag::err_typecheck_sub_ptr_object
)
5923 << rex
->getSourceRange()
5927 if (getLangOptions().CPlusPlus
) {
5928 // Pointee types must be the same: C++ [expr.add]
5929 if (!Context
.hasSameUnqualifiedType(lpointee
, rpointee
)) {
5930 Diag(Loc
, diag::err_typecheck_sub_ptr_compatible
)
5931 << lex
->getType() << rex
->getType()
5932 << lex
->getSourceRange() << rex
->getSourceRange();
5936 // Pointee types must be compatible C99 6.5.6p3
5937 if (!Context
.typesAreCompatible(
5938 Context
.getCanonicalType(lpointee
).getUnqualifiedType(),
5939 Context
.getCanonicalType(rpointee
).getUnqualifiedType())) {
5940 Diag(Loc
, diag::err_typecheck_sub_ptr_compatible
)
5941 << lex
->getType() << rex
->getType()
5942 << lex
->getSourceRange() << rex
->getSourceRange();
5947 if (ComplainAboutVoid
)
5948 Diag(Loc
, diag::ext_gnu_void_ptr
)
5949 << lex
->getSourceRange() << rex
->getSourceRange();
5950 if (ComplainAboutFunc
)
5951 Diag(Loc
, diag::ext_gnu_ptr_func_arith
)
5952 << ComplainAboutFunc
->getType()
5953 << ComplainAboutFunc
->getSourceRange();
5955 if (CompLHSTy
) *CompLHSTy
= lex
->getType();
5956 return Context
.getPointerDiffType();
5960 return InvalidOperands(Loc
, lex
, rex
);
5963 static bool isScopedEnumerationType(QualType T
) {
5964 if (const EnumType
*ET
= dyn_cast
<EnumType
>(T
))
5965 return ET
->getDecl()->isScoped();
5970 QualType
Sema::CheckShiftOperands(Expr
*&lex
, Expr
*&rex
, SourceLocation Loc
,
5971 bool isCompAssign
) {
5972 // C99 6.5.7p2: Each of the operands shall have integer type.
5973 if (!lex
->getType()->hasIntegerRepresentation() ||
5974 !rex
->getType()->hasIntegerRepresentation())
5975 return InvalidOperands(Loc
, lex
, rex
);
5977 // C++0x: Don't allow scoped enums. FIXME: Use something better than
5978 // hasIntegerRepresentation() above instead of this.
5979 if (isScopedEnumerationType(lex
->getType()) ||
5980 isScopedEnumerationType(rex
->getType())) {
5981 return InvalidOperands(Loc
, lex
, rex
);
5984 // Vector shifts promote their scalar inputs to vector type.
5985 if (lex
->getType()->isVectorType() || rex
->getType()->isVectorType())
5986 return CheckVectorOperands(Loc
, lex
, rex
);
5988 // Shifts don't perform usual arithmetic conversions, they just do integer
5989 // promotions on each operand. C99 6.5.7p3
5990 QualType LHSTy
= Context
.isPromotableBitField(lex
);
5991 if (LHSTy
.isNull()) {
5992 LHSTy
= lex
->getType();
5993 if (LHSTy
->isPromotableIntegerType())
5994 LHSTy
= Context
.getPromotedIntegerType(LHSTy
);
5997 ImpCastExprToType(lex
, LHSTy
, CK_IntegralCast
);
5999 UsualUnaryConversions(rex
);
6001 // Sanity-check shift operands
6003 // Check right/shifter operand
6004 if (!rex
->isValueDependent() &&
6005 rex
->isIntegerConstantExpr(Right
, Context
)) {
6006 if (Right
.isNegative())
6007 Diag(Loc
, diag::warn_shift_negative
) << rex
->getSourceRange();
6009 llvm::APInt
LeftBits(Right
.getBitWidth(),
6010 Context
.getTypeSize(lex
->getType()));
6011 if (Right
.uge(LeftBits
))
6012 Diag(Loc
, diag::warn_shift_gt_typewidth
) << rex
->getSourceRange();
6016 // "The type of the result is that of the promoted left operand."
6020 static bool IsWithinTemplateSpecialization(Decl
*D
) {
6021 if (DeclContext
*DC
= D
->getDeclContext()) {
6022 if (isa
<ClassTemplateSpecializationDecl
>(DC
))
6024 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(DC
))
6025 return FD
->isFunctionTemplateSpecialization();
6030 // C99 6.5.8, C++ [expr.rel]
6031 QualType
Sema::CheckCompareOperands(Expr
*&lex
, Expr
*&rex
, SourceLocation Loc
,
6032 unsigned OpaqueOpc
, bool isRelational
) {
6033 BinaryOperatorKind Opc
= (BinaryOperatorKind
) OpaqueOpc
;
6035 // Handle vector comparisons separately.
6036 if (lex
->getType()->isVectorType() || rex
->getType()->isVectorType())
6037 return CheckVectorCompareOperands(lex
, rex
, Loc
, isRelational
);
6039 QualType lType
= lex
->getType();
6040 QualType rType
= rex
->getType();
6042 if (!lType
->hasFloatingRepresentation() &&
6043 !(lType
->isBlockPointerType() && isRelational
) &&
6044 !lex
->getLocStart().isMacroID() &&
6045 !rex
->getLocStart().isMacroID()) {
6046 // For non-floating point types, check for self-comparisons of the form
6047 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6048 // often indicate logic errors in the program.
6050 // NOTE: Don't warn about comparison expressions resulting from macro
6051 // expansion. Also don't warn about comparisons which are only self
6052 // comparisons within a template specialization. The warnings should catch
6053 // obvious cases in the definition of the template anyways. The idea is to
6054 // warn when the typed comparison operator will always evaluate to the same
6056 Expr
*LHSStripped
= lex
->IgnoreParens();
6057 Expr
*RHSStripped
= rex
->IgnoreParens();
6058 if (DeclRefExpr
* DRL
= dyn_cast
<DeclRefExpr
>(LHSStripped
)) {
6059 if (DeclRefExpr
* DRR
= dyn_cast
<DeclRefExpr
>(RHSStripped
)) {
6060 if (DRL
->getDecl() == DRR
->getDecl() &&
6061 !IsWithinTemplateSpecialization(DRL
->getDecl())) {
6062 DiagRuntimeBehavior(Loc
, PDiag(diag::warn_comparison_always
)
6067 } else if (lType
->isArrayType() && rType
->isArrayType() &&
6068 !DRL
->getDecl()->getType()->isReferenceType() &&
6069 !DRR
->getDecl()->getType()->isReferenceType()) {
6070 // what is it always going to eval to?
6071 char always_evals_to
;
6073 case BO_EQ
: // e.g. array1 == array2
6074 always_evals_to
= 0; // false
6076 case BO_NE
: // e.g. array1 != array2
6077 always_evals_to
= 1; // true
6080 // best we can say is 'a constant'
6081 always_evals_to
= 2; // e.g. array1 <= array2
6084 DiagRuntimeBehavior(Loc
, PDiag(diag::warn_comparison_always
)
6086 << always_evals_to
);
6091 if (isa
<CastExpr
>(LHSStripped
))
6092 LHSStripped
= LHSStripped
->IgnoreParenCasts();
6093 if (isa
<CastExpr
>(RHSStripped
))
6094 RHSStripped
= RHSStripped
->IgnoreParenCasts();
6096 // Warn about comparisons against a string constant (unless the other
6097 // operand is null), the user probably wants strcmp.
6098 Expr
*literalString
= 0;
6099 Expr
*literalStringStripped
= 0;
6100 if ((isa
<StringLiteral
>(LHSStripped
) || isa
<ObjCEncodeExpr
>(LHSStripped
)) &&
6101 !RHSStripped
->isNullPointerConstant(Context
,
6102 Expr::NPC_ValueDependentIsNull
)) {
6103 literalString
= lex
;
6104 literalStringStripped
= LHSStripped
;
6105 } else if ((isa
<StringLiteral
>(RHSStripped
) ||
6106 isa
<ObjCEncodeExpr
>(RHSStripped
)) &&
6107 !LHSStripped
->isNullPointerConstant(Context
,
6108 Expr::NPC_ValueDependentIsNull
)) {
6109 literalString
= rex
;
6110 literalStringStripped
= RHSStripped
;
6113 if (literalString
) {
6114 std::string resultComparison
;
6116 case BO_LT
: resultComparison
= ") < 0"; break;
6117 case BO_GT
: resultComparison
= ") > 0"; break;
6118 case BO_LE
: resultComparison
= ") <= 0"; break;
6119 case BO_GE
: resultComparison
= ") >= 0"; break;
6120 case BO_EQ
: resultComparison
= ") == 0"; break;
6121 case BO_NE
: resultComparison
= ") != 0"; break;
6122 default: assert(false && "Invalid comparison operator");
6125 DiagRuntimeBehavior(Loc
,
6126 PDiag(diag::warn_stringcompare
)
6127 << isa
<ObjCEncodeExpr
>(literalStringStripped
)
6128 << literalString
->getSourceRange());
6132 // C99 6.5.8p3 / C99 6.5.9p4
6133 if (lex
->getType()->isArithmeticType() && rex
->getType()->isArithmeticType())
6134 UsualArithmeticConversions(lex
, rex
);
6136 UsualUnaryConversions(lex
);
6137 UsualUnaryConversions(rex
);
6140 lType
= lex
->getType();
6141 rType
= rex
->getType();
6143 // The result of comparisons is 'bool' in C++, 'int' in C.
6144 QualType ResultTy
= getLangOptions().CPlusPlus
? Context
.BoolTy
:Context
.IntTy
;
6147 if (lType
->isRealType() && rType
->isRealType())
6150 // Check for comparisons of floating point operands using != and ==.
6151 if (lType
->hasFloatingRepresentation())
6152 CheckFloatComparison(Loc
,lex
,rex
);
6154 if (lType
->isArithmeticType() && rType
->isArithmeticType())
6158 bool LHSIsNull
= lex
->isNullPointerConstant(Context
,
6159 Expr::NPC_ValueDependentIsNull
);
6160 bool RHSIsNull
= rex
->isNullPointerConstant(Context
,
6161 Expr::NPC_ValueDependentIsNull
);
6163 // All of the following pointer-related warnings are GCC extensions, except
6164 // when handling null pointer constants.
6165 if (lType
->isPointerType() && rType
->isPointerType()) { // C99 6.5.8p2
6166 QualType LCanPointeeTy
=
6167 Context
.getCanonicalType(lType
->getAs
<PointerType
>()->getPointeeType());
6168 QualType RCanPointeeTy
=
6169 Context
.getCanonicalType(rType
->getAs
<PointerType
>()->getPointeeType());
6171 if (getLangOptions().CPlusPlus
) {
6172 if (LCanPointeeTy
== RCanPointeeTy
)
6174 if (!isRelational
&&
6175 (LCanPointeeTy
->isVoidType() || RCanPointeeTy
->isVoidType())) {
6176 // Valid unless comparison between non-null pointer and function pointer
6177 // This is a gcc extension compatibility comparison.
6178 // In a SFINAE context, we treat this as a hard error to maintain
6179 // conformance with the C++ standard.
6180 if ((LCanPointeeTy
->isFunctionType() || RCanPointeeTy
->isFunctionType())
6181 && !LHSIsNull
&& !RHSIsNull
) {
6184 diag::err_typecheck_comparison_of_fptr_to_void
6185 : diag::ext_typecheck_comparison_of_fptr_to_void
)
6186 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6188 if (isSFINAEContext())
6191 ImpCastExprToType(rex
, lType
, CK_BitCast
);
6196 // C++ [expr.rel]p2:
6197 // [...] Pointer conversions (4.10) and qualification
6198 // conversions (4.4) are performed on pointer operands (or on
6199 // a pointer operand and a null pointer constant) to bring
6200 // them to their composite pointer type. [...]
6202 // C++ [expr.eq]p1 uses the same notion for (in)equality
6203 // comparisons of pointers.
6204 bool NonStandardCompositeType
= false;
6205 QualType T
= FindCompositePointerType(Loc
, lex
, rex
,
6206 isSFINAEContext()? 0 : &NonStandardCompositeType
);
6208 Diag(Loc
, diag::err_typecheck_comparison_of_distinct_pointers
)
6209 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6211 } else if (NonStandardCompositeType
) {
6213 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard
)
6214 << lType
<< rType
<< T
6215 << lex
->getSourceRange() << rex
->getSourceRange();
6218 ImpCastExprToType(lex
, T
, CK_BitCast
);
6219 ImpCastExprToType(rex
, T
, CK_BitCast
);
6222 // C99 6.5.9p2 and C99 6.5.8p2
6223 if (Context
.typesAreCompatible(LCanPointeeTy
.getUnqualifiedType(),
6224 RCanPointeeTy
.getUnqualifiedType())) {
6225 // Valid unless a relational comparison of function pointers
6226 if (isRelational
&& LCanPointeeTy
->isFunctionType()) {
6227 Diag(Loc
, diag::ext_typecheck_ordered_comparison_of_function_pointers
)
6228 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6230 } else if (!isRelational
&&
6231 (LCanPointeeTy
->isVoidType() || RCanPointeeTy
->isVoidType())) {
6232 // Valid unless comparison between non-null pointer and function pointer
6233 if ((LCanPointeeTy
->isFunctionType() || RCanPointeeTy
->isFunctionType())
6234 && !LHSIsNull
&& !RHSIsNull
) {
6235 Diag(Loc
, diag::ext_typecheck_comparison_of_fptr_to_void
)
6236 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6240 Diag(Loc
, diag::ext_typecheck_comparison_of_distinct_pointers
)
6241 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6243 if (LCanPointeeTy
!= RCanPointeeTy
)
6244 ImpCastExprToType(rex
, lType
, CK_BitCast
);
6248 if (getLangOptions().CPlusPlus
) {
6249 // Comparison of nullptr_t with itself.
6250 if (lType
->isNullPtrType() && rType
->isNullPtrType())
6253 // Comparison of pointers with null pointer constants and equality
6254 // comparisons of member pointers to null pointer constants.
6256 ((lType
->isPointerType() || lType
->isNullPtrType()) ||
6257 (!isRelational
&& lType
->isMemberPointerType()))) {
6258 ImpCastExprToType(rex
, lType
,
6259 lType
->isMemberPointerType()
6260 ? CK_NullToMemberPointer
6261 : CK_NullToPointer
);
6265 ((rType
->isPointerType() || rType
->isNullPtrType()) ||
6266 (!isRelational
&& rType
->isMemberPointerType()))) {
6267 ImpCastExprToType(lex
, rType
,
6268 rType
->isMemberPointerType()
6269 ? CK_NullToMemberPointer
6270 : CK_NullToPointer
);
6274 // Comparison of member pointers.
6275 if (!isRelational
&&
6276 lType
->isMemberPointerType() && rType
->isMemberPointerType()) {
6278 // In addition, pointers to members can be compared, or a pointer to
6279 // member and a null pointer constant. Pointer to member conversions
6280 // (4.11) and qualification conversions (4.4) are performed to bring
6281 // them to a common type. If one operand is a null pointer constant,
6282 // the common type is the type of the other operand. Otherwise, the
6283 // common type is a pointer to member type similar (4.4) to the type
6284 // of one of the operands, with a cv-qualification signature (4.4)
6285 // that is the union of the cv-qualification signatures of the operand
6287 bool NonStandardCompositeType
= false;
6288 QualType T
= FindCompositePointerType(Loc
, lex
, rex
,
6289 isSFINAEContext()? 0 : &NonStandardCompositeType
);
6291 Diag(Loc
, diag::err_typecheck_comparison_of_distinct_pointers
)
6292 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6294 } else if (NonStandardCompositeType
) {
6296 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard
)
6297 << lType
<< rType
<< T
6298 << lex
->getSourceRange() << rex
->getSourceRange();
6301 ImpCastExprToType(lex
, T
, CK_BitCast
);
6302 ImpCastExprToType(rex
, T
, CK_BitCast
);
6307 // Handle block pointer types.
6308 if (!isRelational
&& lType
->isBlockPointerType() && rType
->isBlockPointerType()) {
6309 QualType lpointee
= lType
->getAs
<BlockPointerType
>()->getPointeeType();
6310 QualType rpointee
= rType
->getAs
<BlockPointerType
>()->getPointeeType();
6312 if (!LHSIsNull
&& !RHSIsNull
&&
6313 !Context
.typesAreCompatible(lpointee
, rpointee
)) {
6314 Diag(Loc
, diag::err_typecheck_comparison_of_distinct_blocks
)
6315 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6317 ImpCastExprToType(rex
, lType
, CK_BitCast
);
6320 // Allow block pointers to be compared with null pointer constants.
6322 && ((lType
->isBlockPointerType() && rType
->isPointerType())
6323 || (lType
->isPointerType() && rType
->isBlockPointerType()))) {
6324 if (!LHSIsNull
&& !RHSIsNull
) {
6325 if (!((rType
->isPointerType() && rType
->getAs
<PointerType
>()
6326 ->getPointeeType()->isVoidType())
6327 || (lType
->isPointerType() && lType
->getAs
<PointerType
>()
6328 ->getPointeeType()->isVoidType())))
6329 Diag(Loc
, diag::err_typecheck_comparison_of_distinct_blocks
)
6330 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6332 ImpCastExprToType(rex
, lType
, CK_BitCast
);
6336 if ((lType
->isObjCObjectPointerType() || rType
->isObjCObjectPointerType())) {
6337 if (lType
->isPointerType() || rType
->isPointerType()) {
6338 const PointerType
*LPT
= lType
->getAs
<PointerType
>();
6339 const PointerType
*RPT
= rType
->getAs
<PointerType
>();
6340 bool LPtrToVoid
= LPT
?
6341 Context
.getCanonicalType(LPT
->getPointeeType())->isVoidType() : false;
6342 bool RPtrToVoid
= RPT
?
6343 Context
.getCanonicalType(RPT
->getPointeeType())->isVoidType() : false;
6345 if (!LPtrToVoid
&& !RPtrToVoid
&&
6346 !Context
.typesAreCompatible(lType
, rType
)) {
6347 Diag(Loc
, diag::ext_typecheck_comparison_of_distinct_pointers
)
6348 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6350 ImpCastExprToType(rex
, lType
, CK_BitCast
);
6353 if (lType
->isObjCObjectPointerType() && rType
->isObjCObjectPointerType()) {
6354 if (!Context
.areComparableObjCPointerTypes(lType
, rType
))
6355 Diag(Loc
, diag::ext_typecheck_comparison_of_distinct_pointers
)
6356 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6357 ImpCastExprToType(rex
, lType
, CK_BitCast
);
6361 if ((lType
->isAnyPointerType() && rType
->isIntegerType()) ||
6362 (lType
->isIntegerType() && rType
->isAnyPointerType())) {
6363 unsigned DiagID
= 0;
6364 bool isError
= false;
6365 if ((LHSIsNull
&& lType
->isIntegerType()) ||
6366 (RHSIsNull
&& rType
->isIntegerType())) {
6367 if (isRelational
&& !getLangOptions().CPlusPlus
)
6368 DiagID
= diag::ext_typecheck_ordered_comparison_of_pointer_and_zero
;
6369 } else if (isRelational
&& !getLangOptions().CPlusPlus
)
6370 DiagID
= diag::ext_typecheck_ordered_comparison_of_pointer_integer
;
6371 else if (getLangOptions().CPlusPlus
) {
6372 DiagID
= diag::err_typecheck_comparison_of_pointer_integer
;
6375 DiagID
= diag::ext_typecheck_comparison_of_pointer_integer
;
6379 << lType
<< rType
<< lex
->getSourceRange() << rex
->getSourceRange();
6384 if (lType
->isIntegerType())
6385 ImpCastExprToType(lex
, rType
,
6386 LHSIsNull
? CK_NullToPointer
: CK_IntegralToPointer
);
6388 ImpCastExprToType(rex
, lType
,
6389 RHSIsNull
? CK_NullToPointer
: CK_IntegralToPointer
);
6393 // Handle block pointers.
6394 if (!isRelational
&& RHSIsNull
6395 && lType
->isBlockPointerType() && rType
->isIntegerType()) {
6396 ImpCastExprToType(rex
, lType
, CK_NullToPointer
);
6399 if (!isRelational
&& LHSIsNull
6400 && lType
->isIntegerType() && rType
->isBlockPointerType()) {
6401 ImpCastExprToType(lex
, rType
, CK_NullToPointer
);
6404 return InvalidOperands(Loc
, lex
, rex
);
6407 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
6408 /// operates on extended vector types. Instead of producing an IntTy result,
6409 /// like a scalar comparison, a vector comparison produces a vector of integer
6411 QualType
Sema::CheckVectorCompareOperands(Expr
*&lex
, Expr
*&rex
,
6413 bool isRelational
) {
6414 // Check to make sure we're operating on vectors of the same type and width,
6415 // Allowing one side to be a scalar of element type.
6416 QualType vType
= CheckVectorOperands(Loc
, lex
, rex
);
6420 QualType lType
= lex
->getType();
6421 QualType rType
= rex
->getType();
6423 // For non-floating point types, check for self-comparisons of the form
6424 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6425 // often indicate logic errors in the program.
6426 if (!lType
->hasFloatingRepresentation()) {
6427 if (DeclRefExpr
* DRL
= dyn_cast
<DeclRefExpr
>(lex
->IgnoreParens()))
6428 if (DeclRefExpr
* DRR
= dyn_cast
<DeclRefExpr
>(rex
->IgnoreParens()))
6429 if (DRL
->getDecl() == DRR
->getDecl())
6430 DiagRuntimeBehavior(Loc
,
6431 PDiag(diag::warn_comparison_always
)
6433 << 2 // "a constant"
6437 // Check for comparisons of floating point operands using != and ==.
6438 if (!isRelational
&& lType
->hasFloatingRepresentation()) {
6439 assert (rType
->hasFloatingRepresentation());
6440 CheckFloatComparison(Loc
,lex
,rex
);
6443 // Return the type for the comparison, which is the same as vector type for
6444 // integer vectors, or an integer type of identical size and number of
6445 // elements for floating point vectors.
6446 if (lType
->hasIntegerRepresentation())
6449 const VectorType
*VTy
= lType
->getAs
<VectorType
>();
6450 unsigned TypeSize
= Context
.getTypeSize(VTy
->getElementType());
6451 if (TypeSize
== Context
.getTypeSize(Context
.IntTy
))
6452 return Context
.getExtVectorType(Context
.IntTy
, VTy
->getNumElements());
6453 if (TypeSize
== Context
.getTypeSize(Context
.LongTy
))
6454 return Context
.getExtVectorType(Context
.LongTy
, VTy
->getNumElements());
6456 assert(TypeSize
== Context
.getTypeSize(Context
.LongLongTy
) &&
6457 "Unhandled vector element size in vector compare");
6458 return Context
.getExtVectorType(Context
.LongLongTy
, VTy
->getNumElements());
6461 inline QualType
Sema::CheckBitwiseOperands(
6462 Expr
*&lex
, Expr
*&rex
, SourceLocation Loc
, bool isCompAssign
) {
6463 if (lex
->getType()->isVectorType() || rex
->getType()->isVectorType()) {
6464 if (lex
->getType()->hasIntegerRepresentation() &&
6465 rex
->getType()->hasIntegerRepresentation())
6466 return CheckVectorOperands(Loc
, lex
, rex
);
6468 return InvalidOperands(Loc
, lex
, rex
);
6471 QualType compType
= UsualArithmeticConversions(lex
, rex
, isCompAssign
);
6473 if (lex
->getType()->isIntegralOrUnscopedEnumerationType() &&
6474 rex
->getType()->isIntegralOrUnscopedEnumerationType())
6476 return InvalidOperands(Loc
, lex
, rex
);
6479 inline QualType
Sema::CheckLogicalOperands( // C99 6.5.[13,14]
6480 Expr
*&lex
, Expr
*&rex
, SourceLocation Loc
, unsigned Opc
) {
6482 // Diagnose cases where the user write a logical and/or but probably meant a
6483 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6485 if (lex
->getType()->isIntegerType() && !lex
->getType()->isBooleanType() &&
6486 rex
->getType()->isIntegerType() && !rex
->isValueDependent() &&
6487 // Don't warn in macros.
6489 // If the RHS can be constant folded, and if it constant folds to something
6490 // that isn't 0 or 1 (which indicate a potential logical operation that
6491 // happened to fold to true/false) then warn.
6492 Expr::EvalResult Result
;
6493 if (rex
->Evaluate(Result
, Context
) && !Result
.HasSideEffects
&&
6494 Result
.Val
.getInt() != 0 && Result
.Val
.getInt() != 1) {
6495 Diag(Loc
, diag::warn_logical_instead_of_bitwise
)
6496 << rex
->getSourceRange()
6497 << (Opc
== BO_LAnd
? "&&" : "||")
6498 << (Opc
== BO_LAnd
? "&" : "|");
6502 if (!Context
.getLangOptions().CPlusPlus
) {
6503 UsualUnaryConversions(lex
);
6504 UsualUnaryConversions(rex
);
6506 if (!lex
->getType()->isScalarType() || !rex
->getType()->isScalarType())
6507 return InvalidOperands(Loc
, lex
, rex
);
6509 return Context
.IntTy
;
6512 // The following is safe because we only use this method for
6513 // non-overloadable operands.
6515 // C++ [expr.log.and]p1
6516 // C++ [expr.log.or]p1
6517 // The operands are both contextually converted to type bool.
6518 if (PerformContextuallyConvertToBool(lex
) ||
6519 PerformContextuallyConvertToBool(rex
))
6520 return InvalidOperands(Loc
, lex
, rex
);
6522 // C++ [expr.log.and]p2
6523 // C++ [expr.log.or]p2
6524 // The result is a bool.
6525 return Context
.BoolTy
;
6528 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6529 /// is a read-only property; return true if so. A readonly property expression
6530 /// depends on various declarations and thus must be treated specially.
6532 static bool IsReadonlyProperty(Expr
*E
, Sema
&S
) {
6533 if (E
->getStmtClass() == Expr::ObjCPropertyRefExprClass
) {
6534 const ObjCPropertyRefExpr
* PropExpr
= cast
<ObjCPropertyRefExpr
>(E
);
6535 if (ObjCPropertyDecl
*PDecl
= PropExpr
->getProperty()) {
6536 QualType BaseType
= PropExpr
->isSuperReceiver() ?
6537 PropExpr
->getSuperType() :
6538 PropExpr
->getBase()->getType();
6540 if (const ObjCObjectPointerType
*OPT
=
6541 BaseType
->getAsObjCInterfacePointerType())
6542 if (ObjCInterfaceDecl
*IFace
= OPT
->getInterfaceDecl())
6543 if (S
.isPropertyReadonly(PDecl
, IFace
))
6550 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6551 /// emit an error and return true. If so, return false.
6552 static bool CheckForModifiableLvalue(Expr
*E
, SourceLocation Loc
, Sema
&S
) {
6553 SourceLocation OrigLoc
= Loc
;
6554 Expr::isModifiableLvalueResult IsLV
= E
->isModifiableLvalue(S
.Context
,
6556 if (IsLV
== Expr::MLV_Valid
&& IsReadonlyProperty(E
, S
))
6557 IsLV
= Expr::MLV_ReadonlyProperty
;
6558 if (IsLV
== Expr::MLV_Valid
)
6562 bool NeedType
= false;
6563 switch (IsLV
) { // C99 6.5.16p2
6564 case Expr::MLV_ConstQualified
: Diag
= diag::err_typecheck_assign_const
; break;
6565 case Expr::MLV_ArrayType
:
6566 Diag
= diag::err_typecheck_array_not_modifiable_lvalue
;
6569 case Expr::MLV_NotObjectType
:
6570 Diag
= diag::err_typecheck_non_object_not_modifiable_lvalue
;
6573 case Expr::MLV_LValueCast
:
6574 Diag
= diag::err_typecheck_lvalue_casts_not_supported
;
6576 case Expr::MLV_Valid
:
6577 llvm_unreachable("did not take early return for MLV_Valid");
6578 case Expr::MLV_InvalidExpression
:
6579 case Expr::MLV_MemberFunction
:
6580 case Expr::MLV_ClassTemporary
:
6581 Diag
= diag::err_typecheck_expression_not_modifiable_lvalue
;
6583 case Expr::MLV_IncompleteType
:
6584 case Expr::MLV_IncompleteVoidType
:
6585 return S
.RequireCompleteType(Loc
, E
->getType(),
6586 S
.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue
)
6587 << E
->getSourceRange());
6588 case Expr::MLV_DuplicateVectorComponents
:
6589 Diag
= diag::err_typecheck_duplicate_vector_components_not_mlvalue
;
6591 case Expr::MLV_NotBlockQualified
:
6592 Diag
= diag::err_block_decl_ref_not_modifiable_lvalue
;
6594 case Expr::MLV_ReadonlyProperty
:
6595 Diag
= diag::error_readonly_property_assignment
;
6597 case Expr::MLV_NoSetterProperty
:
6598 Diag
= diag::error_nosetter_property_assignment
;
6600 case Expr::MLV_SubObjCPropertySetting
:
6601 Diag
= diag::error_no_subobject_property_setting
;
6607 Assign
= SourceRange(OrigLoc
, OrigLoc
);
6609 S
.Diag(Loc
, Diag
) << E
->getType() << E
->getSourceRange() << Assign
;
6611 S
.Diag(Loc
, Diag
) << E
->getSourceRange() << Assign
;
6618 QualType
Sema::CheckAssignmentOperands(Expr
*LHS
, Expr
*&RHS
,
6620 QualType CompoundType
) {
6621 // Verify that LHS is a modifiable lvalue, and emit error if not.
6622 if (CheckForModifiableLvalue(LHS
, Loc
, *this))
6625 QualType LHSType
= LHS
->getType();
6626 QualType RHSType
= CompoundType
.isNull() ? RHS
->getType() : CompoundType
;
6627 AssignConvertType ConvTy
;
6628 if (CompoundType
.isNull()) {
6629 QualType
LHSTy(LHSType
);
6630 // Simple assignment "x = y".
6631 ConvertPropertyAssignment(LHS
, RHS
, LHSTy
);
6632 ConvTy
= CheckSingleAssignmentConstraints(LHSTy
, RHS
);
6633 // Special case of NSObject attributes on c-style pointer types.
6634 if (ConvTy
== IncompatiblePointer
&&
6635 ((Context
.isObjCNSObjectType(LHSType
) &&
6636 RHSType
->isObjCObjectPointerType()) ||
6637 (Context
.isObjCNSObjectType(RHSType
) &&
6638 LHSType
->isObjCObjectPointerType())))
6639 ConvTy
= Compatible
;
6641 // If the RHS is a unary plus or minus, check to see if they = and + are
6642 // right next to each other. If so, the user may have typo'd "x =+ 4"
6643 // instead of "x += 4".
6644 Expr
*RHSCheck
= RHS
;
6645 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(RHSCheck
))
6646 RHSCheck
= ICE
->getSubExpr();
6647 if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(RHSCheck
)) {
6648 if ((UO
->getOpcode() == UO_Plus
||
6649 UO
->getOpcode() == UO_Minus
) &&
6650 Loc
.isFileID() && UO
->getOperatorLoc().isFileID() &&
6651 // Only if the two operators are exactly adjacent.
6652 Loc
.getFileLocWithOffset(1) == UO
->getOperatorLoc() &&
6653 // And there is a space or other character before the subexpr of the
6654 // unary +/-. We don't want to warn on "x=-1".
6655 Loc
.getFileLocWithOffset(2) != UO
->getSubExpr()->getLocStart() &&
6656 UO
->getSubExpr()->getLocStart().isFileID()) {
6657 Diag(Loc
, diag::warn_not_compound_assign
)
6658 << (UO
->getOpcode() == UO_Plus
? "+" : "-")
6659 << SourceRange(UO
->getOperatorLoc(), UO
->getOperatorLoc());
6663 // Compound assignment "x += y"
6664 ConvTy
= CheckAssignmentConstraints(LHSType
, RHSType
);
6667 if (DiagnoseAssignmentResult(ConvTy
, Loc
, LHSType
, RHSType
,
6672 // Check to see if the destination operand is a dereferenced null pointer. If
6673 // so, and if not volatile-qualified, this is undefined behavior that the
6674 // optimizer will delete, so warn about it. People sometimes try to use this
6675 // to get a deterministic trap and are surprised by clang's behavior. This
6676 // only handles the pattern "*null = whatever", which is a very syntactic
6678 if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(LHS
->IgnoreParenCasts()))
6679 if (UO
->getOpcode() == UO_Deref
&&
6680 UO
->getSubExpr()->IgnoreParenCasts()->
6681 isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNotNull
) &&
6682 !UO
->getType().isVolatileQualified()) {
6683 Diag(UO
->getOperatorLoc(), diag::warn_indirection_through_null
)
6684 << UO
->getSubExpr()->getSourceRange();
6685 Diag(UO
->getOperatorLoc(), diag::note_indirection_through_null
);
6688 // C99 6.5.16p3: The type of an assignment expression is the type of the
6689 // left operand unless the left operand has qualified type, in which case
6690 // it is the unqualified version of the type of the left operand.
6691 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
6692 // is converted to the type of the assignment expression (above).
6693 // C++ 5.17p1: the type of the assignment expression is that of its left
6695 return (getLangOptions().CPlusPlus
6696 ? LHSType
: LHSType
.getUnqualifiedType());
6700 QualType
Sema::CheckCommaOperands(Expr
*LHS
, Expr
*&RHS
, SourceLocation Loc
) {
6701 DiagnoseUnusedExprResult(LHS
);
6703 ExprResult LHSResult
= CheckPlaceholderExpr(LHS
, Loc
);
6704 if (LHSResult
.isInvalid())
6707 ExprResult RHSResult
= CheckPlaceholderExpr(RHS
, Loc
);
6708 if (RHSResult
.isInvalid())
6710 RHS
= RHSResult
.take();
6712 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
6713 // operands, but not unary promotions.
6714 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
6715 if (!getLangOptions().CPlusPlus
) {
6716 DefaultFunctionArrayLvalueConversion(LHS
);
6717 if (!LHS
->getType()->isVoidType())
6718 RequireCompleteType(Loc
, LHS
->getType(), diag::err_incomplete_type
);
6720 DefaultFunctionArrayLvalueConversion(RHS
);
6721 if (!RHS
->getType()->isVoidType())
6722 RequireCompleteType(Loc
, RHS
->getType(), diag::err_incomplete_type
);
6725 return RHS
->getType();
6728 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
6729 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
6730 QualType
Sema::CheckIncrementDecrementOperand(Expr
*Op
, SourceLocation OpLoc
,
6731 bool isInc
, bool isPrefix
) {
6732 if (Op
->isTypeDependent())
6733 return Context
.DependentTy
;
6735 QualType ResType
= Op
->getType();
6736 assert(!ResType
.isNull() && "no type for increment/decrement expression");
6738 if (getLangOptions().CPlusPlus
&& ResType
->isBooleanType()) {
6739 // Decrement of bool is not allowed.
6741 Diag(OpLoc
, diag::err_decrement_bool
) << Op
->getSourceRange();
6744 // Increment of bool sets it to true, but is deprecated.
6745 Diag(OpLoc
, diag::warn_increment_bool
) << Op
->getSourceRange();
6746 } else if (ResType
->isRealType()) {
6748 } else if (ResType
->isAnyPointerType()) {
6749 QualType PointeeTy
= ResType
->getPointeeType();
6751 // C99 6.5.2.4p2, 6.5.6p2
6752 if (PointeeTy
->isVoidType()) {
6753 if (getLangOptions().CPlusPlus
) {
6754 Diag(OpLoc
, diag::err_typecheck_pointer_arith_void_type
)
6755 << Op
->getSourceRange();
6759 // Pointer to void is a GNU extension in C.
6760 Diag(OpLoc
, diag::ext_gnu_void_ptr
) << Op
->getSourceRange();
6761 } else if (PointeeTy
->isFunctionType()) {
6762 if (getLangOptions().CPlusPlus
) {
6763 Diag(OpLoc
, diag::err_typecheck_pointer_arith_function_type
)
6764 << Op
->getType() << Op
->getSourceRange();
6768 Diag(OpLoc
, diag::ext_gnu_ptr_func_arith
)
6769 << ResType
<< Op
->getSourceRange();
6770 } else if (RequireCompleteType(OpLoc
, PointeeTy
,
6771 PDiag(diag::err_typecheck_arithmetic_incomplete_type
)
6772 << Op
->getSourceRange()
6775 // Diagnose bad cases where we step over interface counts.
6776 else if (PointeeTy
->isObjCObjectType() && LangOpts
.ObjCNonFragileABI
) {
6777 Diag(OpLoc
, diag::err_arithmetic_nonfragile_interface
)
6778 << PointeeTy
<< Op
->getSourceRange();
6781 } else if (ResType
->isAnyComplexType()) {
6782 // C99 does not support ++/-- on complex types, we allow as an extension.
6783 Diag(OpLoc
, diag::ext_integer_increment_complex
)
6784 << ResType
<< Op
->getSourceRange();
6785 } else if (ResType
->isPlaceholderType()) {
6786 ExprResult PR
= CheckPlaceholderExpr(Op
, OpLoc
);
6787 if (PR
.isInvalid()) return QualType();
6788 return CheckIncrementDecrementOperand(PR
.take(), OpLoc
, isInc
, isPrefix
);
6790 Diag(OpLoc
, diag::err_typecheck_illegal_increment_decrement
)
6791 << ResType
<< int(isInc
) << Op
->getSourceRange();
6794 // At this point, we know we have a real, complex or pointer type.
6795 // Now make sure the operand is a modifiable lvalue.
6796 if (CheckForModifiableLvalue(Op
, OpLoc
, *this))
6798 // In C++, a prefix increment is the same type as the operand. Otherwise
6799 // (in C or with postfix), the increment is the unqualified type of the
6801 return isPrefix
&& getLangOptions().CPlusPlus
6802 ? ResType
: ResType
.getUnqualifiedType();
6805 void Sema::ConvertPropertyAssignment(Expr
*LHS
, Expr
*&RHS
, QualType
& LHSTy
) {
6806 bool copyInit
= false;
6807 if (const ObjCImplicitSetterGetterRefExpr
*OISGE
=
6808 dyn_cast
<ObjCImplicitSetterGetterRefExpr
>(LHS
)) {
6809 // If using property-dot syntax notation for assignment, and there is a
6810 // setter, RHS expression is being passed to the setter argument. So,
6811 // type conversion (and comparison) is RHS to setter's argument type.
6812 if (const ObjCMethodDecl
*SetterMD
= OISGE
->getSetterMethod()) {
6813 ObjCMethodDecl::param_iterator P
= SetterMD
->param_begin();
6814 LHSTy
= (*P
)->getType();
6816 copyInit
= (getLangOptions().CPlusPlus
&& LHSTy
->isRecordType());
6819 copyInit
= (getLangOptions().CPlusPlus
&& isa
<ObjCPropertyRefExpr
>(LHS
) &&
6820 LHSTy
->isRecordType());
6822 InitializedEntity Entity
=
6823 InitializedEntity::InitializeParameter(Context
, LHSTy
);
6825 ExprResult ArgE
= PerformCopyInitialization(Entity
, SourceLocation(),
6827 if (!ArgE
.isInvalid())
6828 RHS
= ArgE
.takeAs
<Expr
>();
6833 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
6834 /// This routine allows us to typecheck complex/recursive expressions
6835 /// where the declaration is needed for type checking. We only need to
6836 /// handle cases when the expression references a function designator
6837 /// or is an lvalue. Here are some examples:
6839 /// - &*****f => f for f a function designator.
6841 /// - &s.zz[1].yy -> s, if zz is an array
6842 /// - *(x + 1) -> x, if x is an array
6843 /// - &"123"[2] -> 0
6844 /// - & __real__ x -> x
6845 static NamedDecl
*getPrimaryDecl(Expr
*E
) {
6846 switch (E
->getStmtClass()) {
6847 case Stmt::DeclRefExprClass
:
6848 return cast
<DeclRefExpr
>(E
)->getDecl();
6849 case Stmt::MemberExprClass
:
6850 // If this is an arrow operator, the address is an offset from
6851 // the base's value, so the object the base refers to is
6853 if (cast
<MemberExpr
>(E
)->isArrow())
6855 // Otherwise, the expression refers to a part of the base
6856 return getPrimaryDecl(cast
<MemberExpr
>(E
)->getBase());
6857 case Stmt::ArraySubscriptExprClass
: {
6858 // FIXME: This code shouldn't be necessary! We should catch the implicit
6859 // promotion of register arrays earlier.
6860 Expr
* Base
= cast
<ArraySubscriptExpr
>(E
)->getBase();
6861 if (ImplicitCastExpr
* ICE
= dyn_cast
<ImplicitCastExpr
>(Base
)) {
6862 if (ICE
->getSubExpr()->getType()->isArrayType())
6863 return getPrimaryDecl(ICE
->getSubExpr());
6867 case Stmt::UnaryOperatorClass
: {
6868 UnaryOperator
*UO
= cast
<UnaryOperator
>(E
);
6870 switch(UO
->getOpcode()) {
6874 return getPrimaryDecl(UO
->getSubExpr());
6879 case Stmt::ParenExprClass
:
6880 return getPrimaryDecl(cast
<ParenExpr
>(E
)->getSubExpr());
6881 case Stmt::ImplicitCastExprClass
:
6882 // If the result of an implicit cast is an l-value, we care about
6883 // the sub-expression; otherwise, the result here doesn't matter.
6884 return getPrimaryDecl(cast
<ImplicitCastExpr
>(E
)->getSubExpr());
6890 /// CheckAddressOfOperand - The operand of & must be either a function
6891 /// designator or an lvalue designating an object. If it is an lvalue, the
6892 /// object cannot be declared with storage class register or be a bit field.
6893 /// Note: The usual conversions are *not* applied to the operand of the &
6894 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
6895 /// In C++, the operand might be an overloaded function name, in which case
6896 /// we allow the '&' but retain the overloaded-function type.
6897 QualType
Sema::CheckAddressOfOperand(Expr
*OrigOp
, SourceLocation OpLoc
) {
6898 if (OrigOp
->isTypeDependent())
6899 return Context
.DependentTy
;
6900 if (OrigOp
->getType() == Context
.OverloadTy
)
6901 return Context
.OverloadTy
;
6903 ExprResult PR
= CheckPlaceholderExpr(OrigOp
, OpLoc
);
6904 if (PR
.isInvalid()) return QualType();
6907 // Make sure to ignore parentheses in subsequent checks
6908 Expr
*op
= OrigOp
->IgnoreParens();
6910 if (getLangOptions().C99
) {
6911 // Implement C99-only parts of addressof rules.
6912 if (UnaryOperator
* uOp
= dyn_cast
<UnaryOperator
>(op
)) {
6913 if (uOp
->getOpcode() == UO_Deref
)
6914 // Per C99 6.5.3.2, the address of a deref always returns a valid result
6915 // (assuming the deref expression is valid).
6916 return uOp
->getSubExpr()->getType();
6918 // Technically, there should be a check for array subscript
6919 // expressions here, but the result of one is always an lvalue anyway.
6921 NamedDecl
*dcl
= getPrimaryDecl(op
);
6922 Expr::isLvalueResult lval
= op
->isLvalue(Context
);
6924 if (lval
== Expr::LV_ClassTemporary
) {
6925 Diag(OpLoc
, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6926 : diag::ext_typecheck_addrof_class_temporary
)
6927 << op
->getType() << op
->getSourceRange();
6928 if (isSFINAEContext())
6930 } else if (isa
<ObjCSelectorExpr
>(op
)) {
6931 return Context
.getPointerType(op
->getType());
6932 } else if (lval
== Expr::LV_MemberFunction
) {
6933 // If it's an instance method, make a member pointer.
6934 // The expression must have exactly the form &A::foo.
6936 // If the underlying expression isn't a decl ref, give up.
6937 if (!isa
<DeclRefExpr
>(op
)) {
6938 Diag(OpLoc
, diag::err_invalid_form_pointer_member_function
)
6939 << OrigOp
->getSourceRange();
6942 DeclRefExpr
*DRE
= cast
<DeclRefExpr
>(op
);
6943 CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(DRE
->getDecl());
6945 // The id-expression was parenthesized.
6946 if (OrigOp
!= DRE
) {
6947 Diag(OpLoc
, diag::err_parens_pointer_member_function
)
6948 << OrigOp
->getSourceRange();
6950 // The method was named without a qualifier.
6951 } else if (!DRE
->getQualifier()) {
6952 Diag(OpLoc
, diag::err_unqualified_pointer_member_function
)
6953 << op
->getSourceRange();
6956 return Context
.getMemberPointerType(op
->getType(),
6957 Context
.getTypeDeclType(MD
->getParent()).getTypePtr());
6958 } else if (lval
!= Expr::LV_Valid
&& lval
!= Expr::LV_IncompleteVoidType
) {
6960 // The operand must be either an l-value or a function designator
6961 if (!op
->getType()->isFunctionType()) {
6962 // FIXME: emit more specific diag...
6963 Diag(OpLoc
, diag::err_typecheck_invalid_lvalue_addrof
)
6964 << op
->getSourceRange();
6967 } else if (op
->getBitField()) { // C99 6.5.3.2p1
6968 // The operand cannot be a bit-field
6969 Diag(OpLoc
, diag::err_typecheck_address_of
)
6970 << "bit-field" << op
->getSourceRange();
6972 } else if (op
->refersToVectorElement()) {
6973 // The operand cannot be an element of a vector
6974 Diag(OpLoc
, diag::err_typecheck_address_of
)
6975 << "vector element" << op
->getSourceRange();
6977 } else if (isa
<ObjCPropertyRefExpr
>(op
)) {
6978 // cannot take address of a property expression.
6979 Diag(OpLoc
, diag::err_typecheck_address_of
)
6980 << "property expression" << op
->getSourceRange();
6982 } else if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(op
)) {
6983 // FIXME: Can LHS ever be null here?
6984 if (!CheckAddressOfOperand(CO
->getTrueExpr(), OpLoc
).isNull())
6985 return CheckAddressOfOperand(CO
->getFalseExpr(), OpLoc
);
6986 } else if (dcl
) { // C99 6.5.3.2p1
6987 // We have an lvalue with a decl. Make sure the decl is not declared
6988 // with the register storage-class specifier.
6989 if (const VarDecl
*vd
= dyn_cast
<VarDecl
>(dcl
)) {
6990 // in C++ it is not error to take address of a register
6991 // variable (c++03 7.1.1P3)
6992 if (vd
->getStorageClass() == SC_Register
&&
6993 !getLangOptions().CPlusPlus
) {
6994 Diag(OpLoc
, diag::err_typecheck_address_of
)
6995 << "register variable" << op
->getSourceRange();
6998 } else if (isa
<FunctionTemplateDecl
>(dcl
)) {
6999 return Context
.OverloadTy
;
7000 } else if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(dcl
)) {
7001 // Okay: we can take the address of a field.
7002 // Could be a pointer to member, though, if there is an explicit
7003 // scope qualifier for the class.
7004 if (isa
<DeclRefExpr
>(op
) && cast
<DeclRefExpr
>(op
)->getQualifier()) {
7005 DeclContext
*Ctx
= dcl
->getDeclContext();
7006 if (Ctx
&& Ctx
->isRecord()) {
7007 if (FD
->getType()->isReferenceType()) {
7009 diag::err_cannot_form_pointer_to_member_of_reference_type
)
7010 << FD
->getDeclName() << FD
->getType();
7014 return Context
.getMemberPointerType(op
->getType(),
7015 Context
.getTypeDeclType(cast
<RecordDecl
>(Ctx
)).getTypePtr());
7018 } else if (!isa
<FunctionDecl
>(dcl
))
7019 assert(0 && "Unknown/unexpected decl type");
7022 if (lval
== Expr::LV_IncompleteVoidType
) {
7023 // Taking the address of a void variable is technically illegal, but we
7024 // allow it in cases which are otherwise valid.
7025 // Example: "extern void x; void* y = &x;".
7026 Diag(OpLoc
, diag::ext_typecheck_addrof_void
) << op
->getSourceRange();
7029 // If the operand has type "type", the result has type "pointer to type".
7030 if (op
->getType()->isObjCObjectType())
7031 return Context
.getObjCObjectPointerType(op
->getType());
7032 return Context
.getPointerType(op
->getType());
7035 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
7036 QualType
Sema::CheckIndirectionOperand(Expr
*Op
, SourceLocation OpLoc
) {
7037 if (Op
->isTypeDependent())
7038 return Context
.DependentTy
;
7040 UsualUnaryConversions(Op
);
7041 QualType OpTy
= Op
->getType();
7044 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7045 // is an incomplete type or void. It would be possible to warn about
7046 // dereferencing a void pointer, but it's completely well-defined, and such a
7047 // warning is unlikely to catch any mistakes.
7048 if (const PointerType
*PT
= OpTy
->getAs
<PointerType
>())
7049 Result
= PT
->getPointeeType();
7050 else if (const ObjCObjectPointerType
*OPT
=
7051 OpTy
->getAs
<ObjCObjectPointerType
>())
7052 Result
= OPT
->getPointeeType();
7054 ExprResult PR
= CheckPlaceholderExpr(Op
, OpLoc
);
7055 if (PR
.isInvalid()) return QualType();
7056 if (PR
.take() != Op
) return CheckIndirectionOperand(PR
.take(), OpLoc
);
7059 if (Result
.isNull()) {
7060 Diag(OpLoc
, diag::err_typecheck_indirection_requires_pointer
)
7061 << OpTy
<< Op
->getSourceRange();
7068 static inline BinaryOperatorKind
ConvertTokenKindToBinaryOpcode(
7069 tok::TokenKind Kind
) {
7070 BinaryOperatorKind Opc
;
7072 default: assert(0 && "Unknown binop!");
7073 case tok::periodstar
: Opc
= BO_PtrMemD
; break;
7074 case tok::arrowstar
: Opc
= BO_PtrMemI
; break;
7075 case tok::star
: Opc
= BO_Mul
; break;
7076 case tok::slash
: Opc
= BO_Div
; break;
7077 case tok::percent
: Opc
= BO_Rem
; break;
7078 case tok::plus
: Opc
= BO_Add
; break;
7079 case tok::minus
: Opc
= BO_Sub
; break;
7080 case tok::lessless
: Opc
= BO_Shl
; break;
7081 case tok::greatergreater
: Opc
= BO_Shr
; break;
7082 case tok::lessequal
: Opc
= BO_LE
; break;
7083 case tok::less
: Opc
= BO_LT
; break;
7084 case tok::greaterequal
: Opc
= BO_GE
; break;
7085 case tok::greater
: Opc
= BO_GT
; break;
7086 case tok::exclaimequal
: Opc
= BO_NE
; break;
7087 case tok::equalequal
: Opc
= BO_EQ
; break;
7088 case tok::amp
: Opc
= BO_And
; break;
7089 case tok::caret
: Opc
= BO_Xor
; break;
7090 case tok::pipe
: Opc
= BO_Or
; break;
7091 case tok::ampamp
: Opc
= BO_LAnd
; break;
7092 case tok::pipepipe
: Opc
= BO_LOr
; break;
7093 case tok::equal
: Opc
= BO_Assign
; break;
7094 case tok::starequal
: Opc
= BO_MulAssign
; break;
7095 case tok::slashequal
: Opc
= BO_DivAssign
; break;
7096 case tok::percentequal
: Opc
= BO_RemAssign
; break;
7097 case tok::plusequal
: Opc
= BO_AddAssign
; break;
7098 case tok::minusequal
: Opc
= BO_SubAssign
; break;
7099 case tok::lesslessequal
: Opc
= BO_ShlAssign
; break;
7100 case tok::greatergreaterequal
: Opc
= BO_ShrAssign
; break;
7101 case tok::ampequal
: Opc
= BO_AndAssign
; break;
7102 case tok::caretequal
: Opc
= BO_XorAssign
; break;
7103 case tok::pipeequal
: Opc
= BO_OrAssign
; break;
7104 case tok::comma
: Opc
= BO_Comma
; break;
7109 static inline UnaryOperatorKind
ConvertTokenKindToUnaryOpcode(
7110 tok::TokenKind Kind
) {
7111 UnaryOperatorKind Opc
;
7113 default: assert(0 && "Unknown unary op!");
7114 case tok::plusplus
: Opc
= UO_PreInc
; break;
7115 case tok::minusminus
: Opc
= UO_PreDec
; break;
7116 case tok::amp
: Opc
= UO_AddrOf
; break;
7117 case tok::star
: Opc
= UO_Deref
; break;
7118 case tok::plus
: Opc
= UO_Plus
; break;
7119 case tok::minus
: Opc
= UO_Minus
; break;
7120 case tok::tilde
: Opc
= UO_Not
; break;
7121 case tok::exclaim
: Opc
= UO_LNot
; break;
7122 case tok::kw___real
: Opc
= UO_Real
; break;
7123 case tok::kw___imag
: Opc
= UO_Imag
; break;
7124 case tok::kw___extension__
: Opc
= UO_Extension
; break;
7129 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7130 /// operator @p Opc at location @c TokLoc. This routine only supports
7131 /// built-in operations; ActOnBinOp handles overloaded operators.
7132 ExprResult
Sema::CreateBuiltinBinOp(SourceLocation OpLoc
,
7134 Expr
*lhs
, Expr
*rhs
) {
7135 QualType ResultTy
; // Result type of the binary operator.
7136 BinaryOperatorKind Opc
= (BinaryOperatorKind
) Op
;
7137 // The following two variables are used for compound assignment operators
7138 QualType CompLHSTy
; // Type of LHS after promotions for computation
7139 QualType CompResultTy
; // Type of computation result
7143 ResultTy
= CheckAssignmentOperands(lhs
, rhs
, OpLoc
, QualType());
7147 ResultTy
= CheckPointerToMemberOperands(lhs
, rhs
, OpLoc
,
7152 ResultTy
= CheckMultiplyDivideOperands(lhs
, rhs
, OpLoc
, false,
7156 ResultTy
= CheckRemainderOperands(lhs
, rhs
, OpLoc
);
7159 ResultTy
= CheckAdditionOperands(lhs
, rhs
, OpLoc
);
7162 ResultTy
= CheckSubtractionOperands(lhs
, rhs
, OpLoc
);
7166 ResultTy
= CheckShiftOperands(lhs
, rhs
, OpLoc
);
7172 ResultTy
= CheckCompareOperands(lhs
, rhs
, OpLoc
, Opc
, true);
7176 ResultTy
= CheckCompareOperands(lhs
, rhs
, OpLoc
, Opc
, false);
7181 ResultTy
= CheckBitwiseOperands(lhs
, rhs
, OpLoc
);
7185 ResultTy
= CheckLogicalOperands(lhs
, rhs
, OpLoc
, Opc
);
7189 CompResultTy
= CheckMultiplyDivideOperands(lhs
, rhs
, OpLoc
, true,
7190 Opc
== BO_DivAssign
);
7191 CompLHSTy
= CompResultTy
;
7192 if (!CompResultTy
.isNull())
7193 ResultTy
= CheckAssignmentOperands(lhs
, rhs
, OpLoc
, CompResultTy
);
7196 CompResultTy
= CheckRemainderOperands(lhs
, rhs
, OpLoc
, true);
7197 CompLHSTy
= CompResultTy
;
7198 if (!CompResultTy
.isNull())
7199 ResultTy
= CheckAssignmentOperands(lhs
, rhs
, OpLoc
, CompResultTy
);
7202 CompResultTy
= CheckAdditionOperands(lhs
, rhs
, OpLoc
, &CompLHSTy
);
7203 if (!CompResultTy
.isNull())
7204 ResultTy
= CheckAssignmentOperands(lhs
, rhs
, OpLoc
, CompResultTy
);
7207 CompResultTy
= CheckSubtractionOperands(lhs
, rhs
, OpLoc
, &CompLHSTy
);
7208 if (!CompResultTy
.isNull())
7209 ResultTy
= CheckAssignmentOperands(lhs
, rhs
, OpLoc
, CompResultTy
);
7213 CompResultTy
= CheckShiftOperands(lhs
, rhs
, OpLoc
, true);
7214 CompLHSTy
= CompResultTy
;
7215 if (!CompResultTy
.isNull())
7216 ResultTy
= CheckAssignmentOperands(lhs
, rhs
, OpLoc
, CompResultTy
);
7221 CompResultTy
= CheckBitwiseOperands(lhs
, rhs
, OpLoc
, true);
7222 CompLHSTy
= CompResultTy
;
7223 if (!CompResultTy
.isNull())
7224 ResultTy
= CheckAssignmentOperands(lhs
, rhs
, OpLoc
, CompResultTy
);
7227 ResultTy
= CheckCommaOperands(lhs
, rhs
, OpLoc
);
7230 if (ResultTy
.isNull())
7232 if (ResultTy
->isObjCObjectType() && LangOpts
.ObjCNonFragileABI
) {
7233 if (Opc
>= BO_Assign
&& Opc
<= BO_OrAssign
)
7234 Diag(OpLoc
, diag::err_assignment_requires_nonfragile_object
)
7237 if (CompResultTy
.isNull())
7238 return Owned(new (Context
) BinaryOperator(lhs
, rhs
, Opc
, ResultTy
, OpLoc
));
7240 return Owned(new (Context
) CompoundAssignOperator(lhs
, rhs
, Opc
, ResultTy
,
7241 CompLHSTy
, CompResultTy
,
7245 /// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7246 /// ParenRange in parentheses.
7247 static void SuggestParentheses(Sema
&Self
, SourceLocation Loc
,
7248 const PartialDiagnostic
&PD
,
7249 const PartialDiagnostic
&FirstNote
,
7250 SourceRange FirstParenRange
,
7251 const PartialDiagnostic
&SecondNote
,
7252 SourceRange SecondParenRange
) {
7255 if (!FirstNote
.getDiagID())
7258 SourceLocation EndLoc
= Self
.PP
.getLocForEndOfToken(FirstParenRange
.getEnd());
7259 if (!FirstParenRange
.getEnd().isFileID() || EndLoc
.isInvalid()) {
7260 // We can't display the parentheses, so just return.
7264 Self
.Diag(Loc
, FirstNote
)
7265 << FixItHint::CreateInsertion(FirstParenRange
.getBegin(), "(")
7266 << FixItHint::CreateInsertion(EndLoc
, ")");
7268 if (!SecondNote
.getDiagID())
7271 EndLoc
= Self
.PP
.getLocForEndOfToken(SecondParenRange
.getEnd());
7272 if (!SecondParenRange
.getEnd().isFileID() || EndLoc
.isInvalid()) {
7273 // We can't display the parentheses, so just dig the
7274 // warning/error and return.
7275 Self
.Diag(Loc
, SecondNote
);
7279 Self
.Diag(Loc
, SecondNote
)
7280 << FixItHint::CreateInsertion(SecondParenRange
.getBegin(), "(")
7281 << FixItHint::CreateInsertion(EndLoc
, ")");
7284 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7285 /// operators are mixed in a way that suggests that the programmer forgot that
7286 /// comparison operators have higher precedence. The most typical example of
7287 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
7288 static void DiagnoseBitwisePrecedence(Sema
&Self
, BinaryOperatorKind Opc
,
7289 SourceLocation OpLoc
,Expr
*lhs
,Expr
*rhs
){
7290 typedef BinaryOperator BinOp
;
7291 BinOp::Opcode lhsopc
= static_cast<BinOp::Opcode
>(-1),
7292 rhsopc
= static_cast<BinOp::Opcode
>(-1);
7293 if (BinOp
*BO
= dyn_cast
<BinOp
>(lhs
))
7294 lhsopc
= BO
->getOpcode();
7295 if (BinOp
*BO
= dyn_cast
<BinOp
>(rhs
))
7296 rhsopc
= BO
->getOpcode();
7298 // Subs are not binary operators.
7299 if (lhsopc
== -1 && rhsopc
== -1)
7302 // Bitwise operations are sometimes used as eager logical ops.
7303 // Don't diagnose this.
7304 if ((BinOp::isComparisonOp(lhsopc
) || BinOp::isBitwiseOp(lhsopc
)) &&
7305 (BinOp::isComparisonOp(rhsopc
) || BinOp::isBitwiseOp(rhsopc
)))
7308 if (BinOp::isComparisonOp(lhsopc
))
7309 SuggestParentheses(Self
, OpLoc
,
7310 Self
.PDiag(diag::warn_precedence_bitwise_rel
)
7311 << SourceRange(lhs
->getLocStart(), OpLoc
)
7312 << BinOp::getOpcodeStr(Opc
) << BinOp::getOpcodeStr(lhsopc
),
7313 Self
.PDiag(diag::note_precedence_bitwise_first
)
7314 << BinOp::getOpcodeStr(Opc
),
7315 SourceRange(cast
<BinOp
>(lhs
)->getRHS()->getLocStart(), rhs
->getLocEnd()),
7316 Self
.PDiag(diag::note_precedence_bitwise_silence
)
7317 << BinOp::getOpcodeStr(lhsopc
),
7318 lhs
->getSourceRange());
7319 else if (BinOp::isComparisonOp(rhsopc
))
7320 SuggestParentheses(Self
, OpLoc
,
7321 Self
.PDiag(diag::warn_precedence_bitwise_rel
)
7322 << SourceRange(OpLoc
, rhs
->getLocEnd())
7323 << BinOp::getOpcodeStr(Opc
) << BinOp::getOpcodeStr(rhsopc
),
7324 Self
.PDiag(diag::note_precedence_bitwise_first
)
7325 << BinOp::getOpcodeStr(Opc
),
7326 SourceRange(lhs
->getLocEnd(), cast
<BinOp
>(rhs
)->getLHS()->getLocStart()),
7327 Self
.PDiag(diag::note_precedence_bitwise_silence
)
7328 << BinOp::getOpcodeStr(rhsopc
),
7329 rhs
->getSourceRange());
7332 /// \brief It accepts a '&&' expr that is inside a '||' one.
7333 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7336 EmitDiagnosticForLogicalAndInLogicalOr(Sema
&Self
, SourceLocation OpLoc
,
7338 assert(isa
<BinaryOperator
>(E
) &&
7339 cast
<BinaryOperator
>(E
)->getOpcode() == BO_LAnd
);
7340 SuggestParentheses(Self
, OpLoc
,
7341 Self
.PDiag(diag::warn_logical_and_in_logical_or
)
7342 << E
->getSourceRange(),
7343 Self
.PDiag(diag::note_logical_and_in_logical_or_silence
),
7344 E
->getSourceRange(),
7345 Self
.PDiag(0), SourceRange());
7348 /// \brief Returns true if the given expression can be evaluated as a constant
7350 static bool EvaluatesAsTrue(Sema
&S
, Expr
*E
) {
7352 return E
->EvaluateAsBooleanCondition(Res
, S
.getASTContext()) && Res
;
7355 /// \brief Look for '&&' in the left hand of a '||' expr.
7356 static void DiagnoseLogicalAndInLogicalOrLHS(Sema
&S
, SourceLocation OpLoc
,
7358 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(E
)) {
7359 if (Bop
->getOpcode() == BO_LAnd
) {
7360 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7361 if (!EvaluatesAsTrue(S
, Bop
->getLHS()))
7362 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, Bop
);
7363 } else if (Bop
->getOpcode() == BO_LOr
) {
7364 if (BinaryOperator
*RBop
= dyn_cast
<BinaryOperator
>(Bop
->getRHS())) {
7365 // If it's "a || b && 1 || c" we didn't warn earlier for
7366 // "a || b && 1", but warn now.
7367 if (RBop
->getOpcode() == BO_LAnd
&& EvaluatesAsTrue(S
, RBop
->getRHS()))
7368 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, RBop
);
7374 /// \brief Look for '&&' in the right hand of a '||' expr.
7375 static void DiagnoseLogicalAndInLogicalOrRHS(Sema
&S
, SourceLocation OpLoc
,
7377 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(E
)) {
7378 if (Bop
->getOpcode() == BO_LAnd
) {
7379 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7380 if (!EvaluatesAsTrue(S
, Bop
->getRHS()))
7381 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, Bop
);
7386 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
7388 static void DiagnoseBinOpPrecedence(Sema
&Self
, BinaryOperatorKind Opc
,
7389 SourceLocation OpLoc
, Expr
*lhs
, Expr
*rhs
){
7390 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
7391 if (BinaryOperator::isBitwiseOp(Opc
))
7392 return DiagnoseBitwisePrecedence(Self
, Opc
, OpLoc
, lhs
, rhs
);
7394 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7395 // We don't warn for 'assert(a || b && "bad")' since this is safe.
7396 if (Opc
== BO_LOr
&& !OpLoc
.isMacroID()/* Don't warn in macros. */) {
7397 DiagnoseLogicalAndInLogicalOrLHS(Self
, OpLoc
, lhs
);
7398 DiagnoseLogicalAndInLogicalOrRHS(Self
, OpLoc
, rhs
);
7402 // Binary Operators. 'Tok' is the token for the operator.
7403 ExprResult
Sema::ActOnBinOp(Scope
*S
, SourceLocation TokLoc
,
7404 tok::TokenKind Kind
,
7405 Expr
*lhs
, Expr
*rhs
) {
7406 BinaryOperatorKind Opc
= ConvertTokenKindToBinaryOpcode(Kind
);
7407 assert((lhs
!= 0) && "ActOnBinOp(): missing left expression");
7408 assert((rhs
!= 0) && "ActOnBinOp(): missing right expression");
7410 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7411 DiagnoseBinOpPrecedence(*this, Opc
, TokLoc
, lhs
, rhs
);
7413 return BuildBinOp(S
, TokLoc
, Opc
, lhs
, rhs
);
7416 ExprResult
Sema::BuildBinOp(Scope
*S
, SourceLocation OpLoc
,
7417 BinaryOperatorKind Opc
,
7418 Expr
*lhs
, Expr
*rhs
) {
7419 if (getLangOptions().CPlusPlus
&&
7420 ((!isa
<ObjCImplicitSetterGetterRefExpr
>(lhs
) &&
7421 !isa
<ObjCPropertyRefExpr
>(lhs
))
7422 || rhs
->isTypeDependent() || Opc
!= BO_Assign
) &&
7423 (lhs
->getType()->isOverloadableType() ||
7424 rhs
->getType()->isOverloadableType())) {
7425 // Find all of the overloaded operators visible from this
7426 // point. We perform both an operator-name lookup from the local
7427 // scope and an argument-dependent lookup based on the types of
7429 UnresolvedSet
<16> Functions
;
7430 OverloadedOperatorKind OverOp
= BinaryOperator::getOverloadedOperator(Opc
);
7431 if (S
&& OverOp
!= OO_None
)
7432 LookupOverloadedOperatorName(OverOp
, S
, lhs
->getType(), rhs
->getType(),
7435 // Build the (potentially-overloaded, potentially-dependent)
7436 // binary operation.
7437 return CreateOverloadedBinOp(OpLoc
, Opc
, Functions
, lhs
, rhs
);
7440 // Build a built-in binary operation.
7441 return CreateBuiltinBinOp(OpLoc
, Opc
, lhs
, rhs
);
7444 ExprResult
Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc
,
7447 UnaryOperatorKind Opc
= static_cast<UnaryOperatorKind
>(OpcIn
);
7449 QualType resultType
;
7455 resultType
= CheckIncrementDecrementOperand(Input
, OpLoc
,
7462 resultType
= CheckAddressOfOperand(Input
, OpLoc
);
7465 DefaultFunctionArrayLvalueConversion(Input
);
7466 resultType
= CheckIndirectionOperand(Input
, OpLoc
);
7470 UsualUnaryConversions(Input
);
7471 resultType
= Input
->getType();
7472 if (resultType
->isDependentType())
7474 if (resultType
->isArithmeticType() || // C99 6.5.3.3p1
7475 resultType
->isVectorType())
7477 else if (getLangOptions().CPlusPlus
&& // C++ [expr.unary.op]p6-7
7478 resultType
->isEnumeralType())
7480 else if (getLangOptions().CPlusPlus
&& // C++ [expr.unary.op]p6
7482 resultType
->isPointerType())
7484 else if (resultType
->isPlaceholderType()) {
7485 ExprResult PR
= CheckPlaceholderExpr(Input
, OpLoc
);
7486 if (PR
.isInvalid()) return ExprError();
7487 return CreateBuiltinUnaryOp(OpLoc
, OpcIn
, PR
.take());
7490 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
7491 << resultType
<< Input
->getSourceRange());
7492 case UO_Not
: // bitwise complement
7493 UsualUnaryConversions(Input
);
7494 resultType
= Input
->getType();
7495 if (resultType
->isDependentType())
7497 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7498 if (resultType
->isComplexType() || resultType
->isComplexIntegerType())
7499 // C99 does not support '~' for complex conjugation.
7500 Diag(OpLoc
, diag::ext_integer_complement_complex
)
7501 << resultType
<< Input
->getSourceRange();
7502 else if (resultType
->hasIntegerRepresentation())
7504 else if (resultType
->isPlaceholderType()) {
7505 ExprResult PR
= CheckPlaceholderExpr(Input
, OpLoc
);
7506 if (PR
.isInvalid()) return ExprError();
7507 return CreateBuiltinUnaryOp(OpLoc
, OpcIn
, PR
.take());
7509 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
7510 << resultType
<< Input
->getSourceRange());
7513 case UO_LNot
: // logical negation
7514 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
7515 DefaultFunctionArrayLvalueConversion(Input
);
7516 resultType
= Input
->getType();
7517 if (resultType
->isDependentType())
7519 if (resultType
->isScalarType()) { // C99 6.5.3.3p1
7521 } else if (resultType
->isPlaceholderType()) {
7522 ExprResult PR
= CheckPlaceholderExpr(Input
, OpLoc
);
7523 if (PR
.isInvalid()) return ExprError();
7524 return CreateBuiltinUnaryOp(OpLoc
, OpcIn
, PR
.take());
7526 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
7527 << resultType
<< Input
->getSourceRange());
7530 // LNot always has type int. C99 6.5.3.3p5.
7531 // In C++, it's bool. C++ 5.3.1p8
7532 resultType
= getLangOptions().CPlusPlus
? Context
.BoolTy
: Context
.IntTy
;
7536 resultType
= CheckRealImagOperand(Input
, OpLoc
, Opc
== UO_Real
);
7539 resultType
= Input
->getType();
7542 if (resultType
.isNull())
7545 return Owned(new (Context
) UnaryOperator(Input
, Opc
, resultType
, OpLoc
));
7548 ExprResult
Sema::BuildUnaryOp(Scope
*S
, SourceLocation OpLoc
,
7549 UnaryOperatorKind Opc
,
7551 if (getLangOptions().CPlusPlus
&& Input
->getType()->isOverloadableType() &&
7552 UnaryOperator::getOverloadedOperator(Opc
) != OO_None
) {
7553 // Find all of the overloaded operators visible from this
7554 // point. We perform both an operator-name lookup from the local
7555 // scope and an argument-dependent lookup based on the types of
7557 UnresolvedSet
<16> Functions
;
7558 OverloadedOperatorKind OverOp
= UnaryOperator::getOverloadedOperator(Opc
);
7559 if (S
&& OverOp
!= OO_None
)
7560 LookupOverloadedOperatorName(OverOp
, S
, Input
->getType(), QualType(),
7563 return CreateOverloadedUnaryOp(OpLoc
, Opc
, Functions
, Input
);
7566 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
);
7569 // Unary Operators. 'Tok' is the token for the operator.
7570 ExprResult
Sema::ActOnUnaryOp(Scope
*S
, SourceLocation OpLoc
,
7571 tok::TokenKind Op
, Expr
*Input
) {
7572 return BuildUnaryOp(S
, OpLoc
, ConvertTokenKindToUnaryOpcode(Op
), Input
);
7575 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
7576 ExprResult
Sema::ActOnAddrLabel(SourceLocation OpLoc
,
7577 SourceLocation LabLoc
,
7578 IdentifierInfo
*LabelII
) {
7579 // Look up the record for this label identifier.
7580 LabelStmt
*&LabelDecl
= getCurFunction()->LabelMap
[LabelII
];
7582 // If we haven't seen this label yet, create a forward reference. It
7583 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
7585 LabelDecl
= new (Context
) LabelStmt(LabLoc
, LabelII
, 0);
7587 LabelDecl
->setUsed();
7588 // Create the AST node. The address of a label always has type 'void*'.
7589 return Owned(new (Context
) AddrLabelExpr(OpLoc
, LabLoc
, LabelDecl
,
7590 Context
.getPointerType(Context
.VoidTy
)));
7594 Sema::ActOnStmtExpr(SourceLocation LPLoc
, Stmt
*SubStmt
,
7595 SourceLocation RPLoc
) { // "({..})"
7596 assert(SubStmt
&& isa
<CompoundStmt
>(SubStmt
) && "Invalid action invocation!");
7597 CompoundStmt
*Compound
= cast
<CompoundStmt
>(SubStmt
);
7600 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
7602 return ExprError(Diag(LPLoc
, diag::err_stmtexpr_file_scope
));
7604 // FIXME: there are a variety of strange constraints to enforce here, for
7605 // example, it is not possible to goto into a stmt expression apparently.
7606 // More semantic analysis is needed.
7608 // If there are sub stmts in the compound stmt, take the type of the last one
7609 // as the type of the stmtexpr.
7610 QualType Ty
= Context
.VoidTy
;
7611 bool StmtExprMayBindToTemp
= false;
7612 if (!Compound
->body_empty()) {
7613 Stmt
*LastStmt
= Compound
->body_back();
7614 LabelStmt
*LastLabelStmt
= 0;
7615 // If LastStmt is a label, skip down through into the body.
7616 while (LabelStmt
*Label
= dyn_cast
<LabelStmt
>(LastStmt
)) {
7617 LastLabelStmt
= Label
;
7618 LastStmt
= Label
->getSubStmt();
7620 if (Expr
*LastExpr
= dyn_cast
<Expr
>(LastStmt
)) {
7621 DefaultFunctionArrayLvalueConversion(LastExpr
);
7622 Ty
= LastExpr
->getType();
7623 if (!Ty
->isDependentType() && !LastExpr
->isTypeDependent()) {
7624 ExprResult Res
= PerformCopyInitialization(
7625 InitializedEntity::InitializeResult(LPLoc
,
7630 if (Res
.isInvalid())
7632 if ((LastExpr
= Res
.takeAs
<Expr
>())) {
7634 Compound
->setLastStmt(LastExpr
);
7636 LastLabelStmt
->setSubStmt(LastExpr
);
7637 StmtExprMayBindToTemp
= true;
7643 // FIXME: Check that expression type is complete/non-abstract; statement
7644 // expressions are not lvalues.
7645 Expr
*ResStmtExpr
= new (Context
) StmtExpr(Compound
, Ty
, LPLoc
, RPLoc
);
7646 if (StmtExprMayBindToTemp
)
7647 return MaybeBindToTemporary(ResStmtExpr
);
7648 return Owned(ResStmtExpr
);
7651 ExprResult
Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc
,
7652 TypeSourceInfo
*TInfo
,
7653 OffsetOfComponent
*CompPtr
,
7654 unsigned NumComponents
,
7655 SourceLocation RParenLoc
) {
7656 QualType ArgTy
= TInfo
->getType();
7657 bool Dependent
= ArgTy
->isDependentType();
7658 SourceRange TypeRange
= TInfo
->getTypeLoc().getLocalSourceRange();
7660 // We must have at least one component that refers to the type, and the first
7661 // one is known to be a field designator. Verify that the ArgTy represents
7662 // a struct/union/class.
7663 if (!Dependent
&& !ArgTy
->isRecordType())
7664 return ExprError(Diag(BuiltinLoc
, diag::err_offsetof_record_type
)
7665 << ArgTy
<< TypeRange
);
7667 // Type must be complete per C99 7.17p3 because a declaring a variable
7668 // with an incomplete type would be ill-formed.
7670 && RequireCompleteType(BuiltinLoc
, ArgTy
,
7671 PDiag(diag::err_offsetof_incomplete_type
)
7675 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
7676 // GCC extension, diagnose them.
7677 // FIXME: This diagnostic isn't actually visible because the location is in
7679 if (NumComponents
!= 1)
7680 Diag(BuiltinLoc
, diag::ext_offsetof_extended_field_designator
)
7681 << SourceRange(CompPtr
[1].LocStart
, CompPtr
[NumComponents
-1].LocEnd
);
7683 bool DidWarnAboutNonPOD
= false;
7684 QualType CurrentType
= ArgTy
;
7685 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode
;
7686 llvm::SmallVector
<OffsetOfNode
, 4> Comps
;
7687 llvm::SmallVector
<Expr
*, 4> Exprs
;
7688 for (unsigned i
= 0; i
!= NumComponents
; ++i
) {
7689 const OffsetOfComponent
&OC
= CompPtr
[i
];
7690 if (OC
.isBrackets
) {
7691 // Offset of an array sub-field. TODO: Should we allow vector elements?
7692 if (!CurrentType
->isDependentType()) {
7693 const ArrayType
*AT
= Context
.getAsArrayType(CurrentType
);
7695 return ExprError(Diag(OC
.LocEnd
, diag::err_offsetof_array_type
)
7697 CurrentType
= AT
->getElementType();
7699 CurrentType
= Context
.DependentTy
;
7701 // The expression must be an integral expression.
7702 // FIXME: An integral constant expression?
7703 Expr
*Idx
= static_cast<Expr
*>(OC
.U
.E
);
7704 if (!Idx
->isTypeDependent() && !Idx
->isValueDependent() &&
7705 !Idx
->getType()->isIntegerType())
7706 return ExprError(Diag(Idx
->getLocStart(),
7707 diag::err_typecheck_subscript_not_integer
)
7708 << Idx
->getSourceRange());
7710 // Record this array index.
7711 Comps
.push_back(OffsetOfNode(OC
.LocStart
, Exprs
.size(), OC
.LocEnd
));
7712 Exprs
.push_back(Idx
);
7716 // Offset of a field.
7717 if (CurrentType
->isDependentType()) {
7718 // We have the offset of a field, but we can't look into the dependent
7719 // type. Just record the identifier of the field.
7720 Comps
.push_back(OffsetOfNode(OC
.LocStart
, OC
.U
.IdentInfo
, OC
.LocEnd
));
7721 CurrentType
= Context
.DependentTy
;
7725 // We need to have a complete type to look into.
7726 if (RequireCompleteType(OC
.LocStart
, CurrentType
,
7727 diag::err_offsetof_incomplete_type
))
7730 // Look for the designated field.
7731 const RecordType
*RC
= CurrentType
->getAs
<RecordType
>();
7733 return ExprError(Diag(OC
.LocEnd
, diag::err_offsetof_record_type
)
7735 RecordDecl
*RD
= RC
->getDecl();
7737 // C++ [lib.support.types]p5:
7738 // The macro offsetof accepts a restricted set of type arguments in this
7739 // International Standard. type shall be a POD structure or a POD union
7741 if (CXXRecordDecl
*CRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
7742 if (!CRD
->isPOD() && !DidWarnAboutNonPOD
&&
7743 DiagRuntimeBehavior(BuiltinLoc
,
7744 PDiag(diag::warn_offsetof_non_pod_type
)
7745 << SourceRange(CompPtr
[0].LocStart
, OC
.LocEnd
)
7747 DidWarnAboutNonPOD
= true;
7750 // Look for the field.
7751 LookupResult
R(*this, OC
.U
.IdentInfo
, OC
.LocStart
, LookupMemberName
);
7752 LookupQualifiedName(R
, RD
);
7753 FieldDecl
*MemberDecl
= R
.getAsSingle
<FieldDecl
>();
7755 return ExprError(Diag(BuiltinLoc
, diag::err_no_member
)
7756 << OC
.U
.IdentInfo
<< RD
<< SourceRange(OC
.LocStart
,
7760 // (If the specified member is a bit-field, the behavior is undefined.)
7762 // We diagnose this as an error.
7763 if (MemberDecl
->getBitWidth()) {
7764 Diag(OC
.LocEnd
, diag::err_offsetof_bitfield
)
7765 << MemberDecl
->getDeclName()
7766 << SourceRange(BuiltinLoc
, RParenLoc
);
7767 Diag(MemberDecl
->getLocation(), diag::note_bitfield_decl
);
7771 RecordDecl
*Parent
= MemberDecl
->getParent();
7772 bool AnonStructUnion
= Parent
->isAnonymousStructOrUnion();
7773 if (AnonStructUnion
) {
7775 Parent
= cast
<RecordDecl
>(Parent
->getParent());
7776 } while (Parent
->isAnonymousStructOrUnion());
7779 // If the member was found in a base class, introduce OffsetOfNodes for
7780 // the base class indirections.
7781 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
7782 /*DetectVirtual=*/false);
7783 if (IsDerivedFrom(CurrentType
, Context
.getTypeDeclType(Parent
), Paths
)) {
7784 CXXBasePath
&Path
= Paths
.front();
7785 for (CXXBasePath::iterator B
= Path
.begin(), BEnd
= Path
.end();
7787 Comps
.push_back(OffsetOfNode(B
->Base
));
7790 if (AnonStructUnion
) {
7791 llvm::SmallVector
<FieldDecl
*, 4> Path
;
7792 BuildAnonymousStructUnionMemberPath(MemberDecl
, Path
);
7793 unsigned n
= Path
.size();
7794 for (int j
= n
- 1; j
> -1; --j
)
7795 Comps
.push_back(OffsetOfNode(OC
.LocStart
, Path
[j
], OC
.LocEnd
));
7797 Comps
.push_back(OffsetOfNode(OC
.LocStart
, MemberDecl
, OC
.LocEnd
));
7799 CurrentType
= MemberDecl
->getType().getNonReferenceType();
7802 return Owned(OffsetOfExpr::Create(Context
, Context
.getSizeType(), BuiltinLoc
,
7803 TInfo
, Comps
.data(), Comps
.size(),
7804 Exprs
.data(), Exprs
.size(), RParenLoc
));
7807 ExprResult
Sema::ActOnBuiltinOffsetOf(Scope
*S
,
7808 SourceLocation BuiltinLoc
,
7809 SourceLocation TypeLoc
,
7811 OffsetOfComponent
*CompPtr
,
7812 unsigned NumComponents
,
7813 SourceLocation RPLoc
) {
7815 TypeSourceInfo
*ArgTInfo
;
7816 QualType ArgTy
= GetTypeFromParser(argty
, &ArgTInfo
);
7821 ArgTInfo
= Context
.getTrivialTypeSourceInfo(ArgTy
, TypeLoc
);
7823 return BuildBuiltinOffsetOf(BuiltinLoc
, ArgTInfo
, CompPtr
, NumComponents
,
7828 ExprResult
Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc
,
7829 ParsedType arg1
, ParsedType arg2
,
7830 SourceLocation RPLoc
) {
7831 TypeSourceInfo
*argTInfo1
;
7832 QualType argT1
= GetTypeFromParser(arg1
, &argTInfo1
);
7833 TypeSourceInfo
*argTInfo2
;
7834 QualType argT2
= GetTypeFromParser(arg2
, &argTInfo2
);
7836 assert((!argT1
.isNull() && !argT2
.isNull()) && "Missing type argument(s)");
7838 return BuildTypesCompatibleExpr(BuiltinLoc
, argTInfo1
, argTInfo2
, RPLoc
);
7842 Sema::BuildTypesCompatibleExpr(SourceLocation BuiltinLoc
,
7843 TypeSourceInfo
*argTInfo1
,
7844 TypeSourceInfo
*argTInfo2
,
7845 SourceLocation RPLoc
) {
7846 if (getLangOptions().CPlusPlus
) {
7847 Diag(BuiltinLoc
, diag::err_types_compatible_p_in_cplusplus
)
7848 << SourceRange(BuiltinLoc
, RPLoc
);
7852 return Owned(new (Context
) TypesCompatibleExpr(Context
.IntTy
, BuiltinLoc
,
7853 argTInfo1
, argTInfo2
, RPLoc
));
7857 ExprResult
Sema::ActOnChooseExpr(SourceLocation BuiltinLoc
,
7859 Expr
*LHSExpr
, Expr
*RHSExpr
,
7860 SourceLocation RPLoc
) {
7861 assert((CondExpr
&& LHSExpr
&& RHSExpr
) && "Missing type argument(s)");
7864 bool ValueDependent
= false;
7865 if (CondExpr
->isTypeDependent() || CondExpr
->isValueDependent()) {
7866 resType
= Context
.DependentTy
;
7867 ValueDependent
= true;
7869 // The conditional expression is required to be a constant expression.
7870 llvm::APSInt
condEval(32);
7871 SourceLocation ExpLoc
;
7872 if (!CondExpr
->isIntegerConstantExpr(condEval
, Context
, &ExpLoc
))
7873 return ExprError(Diag(ExpLoc
,
7874 diag::err_typecheck_choose_expr_requires_constant
)
7875 << CondExpr
->getSourceRange());
7877 // If the condition is > zero, then the AST type is the same as the LSHExpr.
7878 resType
= condEval
.getZExtValue() ? LHSExpr
->getType() : RHSExpr
->getType();
7879 ValueDependent
= condEval
.getZExtValue() ? LHSExpr
->isValueDependent()
7880 : RHSExpr
->isValueDependent();
7883 return Owned(new (Context
) ChooseExpr(BuiltinLoc
, CondExpr
, LHSExpr
, RHSExpr
,
7885 resType
->isDependentType(),
7889 //===----------------------------------------------------------------------===//
7890 // Clang Extensions.
7891 //===----------------------------------------------------------------------===//
7893 /// ActOnBlockStart - This callback is invoked when a block literal is started.
7894 void Sema::ActOnBlockStart(SourceLocation CaretLoc
, Scope
*BlockScope
) {
7895 BlockDecl
*Block
= BlockDecl::Create(Context
, CurContext
, CaretLoc
);
7896 PushBlockScope(BlockScope
, Block
);
7897 CurContext
->addDecl(Block
);
7899 PushDeclContext(BlockScope
, Block
);
7904 void Sema::ActOnBlockArguments(Declarator
&ParamInfo
, Scope
*CurScope
) {
7905 assert(ParamInfo
.getIdentifier()==0 && "block-id should have no identifier!");
7906 BlockScopeInfo
*CurBlock
= getCurBlock();
7908 TypeSourceInfo
*Sig
= GetTypeForDeclarator(ParamInfo
, CurScope
);
7909 CurBlock
->TheDecl
->setSignatureAsWritten(Sig
);
7910 QualType T
= Sig
->getType();
7914 if (const FunctionType
*Fn
= T
->getAs
<FunctionType
>()) {
7915 CurBlock
->FunctionType
= T
;
7916 RetTy
= Fn
->getResultType();
7918 !isa
<FunctionProtoType
>(Fn
) || cast
<FunctionProtoType
>(Fn
)->isVariadic();
7924 CurBlock
->TheDecl
->setIsVariadic(isVariadic
);
7926 // Don't allow returning an array by value.
7927 if (RetTy
->isArrayType()) {
7928 Diag(ParamInfo
.getSourceRange().getBegin(), diag::err_block_returns_array
);
7932 // Don't allow returning a objc interface by value.
7933 if (RetTy
->isObjCObjectType()) {
7934 Diag(ParamInfo
.getSourceRange().getBegin(),
7935 diag::err_object_cannot_be_passed_returned_by_value
) << 0 << RetTy
;
7939 // Context.DependentTy is used as a placeholder for a missing block
7940 // return type. TODO: what should we do with declarators like:
7942 // If the answer is "apply template argument deduction"....
7943 if (RetTy
!= Context
.DependentTy
)
7944 CurBlock
->ReturnType
= RetTy
;
7946 // Push block parameters from the declarator if we had them.
7947 llvm::SmallVector
<ParmVarDecl
*, 8> Params
;
7948 if (isa
<FunctionProtoType
>(T
)) {
7949 FunctionProtoTypeLoc TL
= cast
<FunctionProtoTypeLoc
>(Sig
->getTypeLoc());
7950 for (unsigned I
= 0, E
= TL
.getNumArgs(); I
!= E
; ++I
) {
7951 ParmVarDecl
*Param
= TL
.getArg(I
);
7952 if (Param
->getIdentifier() == 0 &&
7953 !Param
->isImplicit() &&
7954 !Param
->isInvalidDecl() &&
7955 !getLangOptions().CPlusPlus
)
7956 Diag(Param
->getLocation(), diag::err_parameter_name_omitted
);
7957 Params
.push_back(Param
);
7960 // Fake up parameter variables if we have a typedef, like
7962 } else if (const FunctionProtoType
*Fn
= T
->getAs
<FunctionProtoType
>()) {
7963 for (FunctionProtoType::arg_type_iterator
7964 I
= Fn
->arg_type_begin(), E
= Fn
->arg_type_end(); I
!= E
; ++I
) {
7965 ParmVarDecl
*Param
=
7966 BuildParmVarDeclForTypedef(CurBlock
->TheDecl
,
7967 ParamInfo
.getSourceRange().getBegin(),
7969 Params
.push_back(Param
);
7973 // Set the parameters on the block decl.
7974 if (!Params
.empty()) {
7975 CurBlock
->TheDecl
->setParams(Params
.data(), Params
.size());
7976 CheckParmsForFunctionDef(CurBlock
->TheDecl
->param_begin(),
7977 CurBlock
->TheDecl
->param_end(),
7978 /*CheckParameterNames=*/false);
7981 // Finally we can process decl attributes.
7982 ProcessDeclAttributes(CurScope
, CurBlock
->TheDecl
, ParamInfo
);
7984 if (!isVariadic
&& CurBlock
->TheDecl
->getAttr
<SentinelAttr
>()) {
7985 Diag(ParamInfo
.getAttributes()->getLoc(),
7986 diag::warn_attribute_sentinel_not_variadic
) << 1;
7987 // FIXME: remove the attribute.
7990 // Put the parameter variables in scope. We can bail out immediately
7991 // if we don't have any.
7995 bool ShouldCheckShadow
=
7996 Diags
.getDiagnosticLevel(diag::warn_decl_shadow
) != Diagnostic::Ignored
;
7998 for (BlockDecl::param_iterator AI
= CurBlock
->TheDecl
->param_begin(),
7999 E
= CurBlock
->TheDecl
->param_end(); AI
!= E
; ++AI
) {
8000 (*AI
)->setOwningFunction(CurBlock
->TheDecl
);
8002 // If this has an identifier, add it to the scope stack.
8003 if ((*AI
)->getIdentifier()) {
8004 if (ShouldCheckShadow
)
8005 CheckShadow(CurBlock
->TheScope
, *AI
);
8007 PushOnScopeChains(*AI
, CurBlock
->TheScope
);
8012 /// ActOnBlockError - If there is an error parsing a block, this callback
8013 /// is invoked to pop the information about the block from the action impl.
8014 void Sema::ActOnBlockError(SourceLocation CaretLoc
, Scope
*CurScope
) {
8015 // Pop off CurBlock, handle nested blocks.
8017 PopFunctionOrBlockScope();
8020 /// ActOnBlockStmtExpr - This is called when the body of a block statement
8021 /// literal was successfully completed. ^(int x){...}
8022 ExprResult
Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc
,
8023 Stmt
*Body
, Scope
*CurScope
) {
8024 // If blocks are disabled, emit an error.
8025 if (!LangOpts
.Blocks
)
8026 Diag(CaretLoc
, diag::err_blocks_disable
);
8028 BlockScopeInfo
*BSI
= cast
<BlockScopeInfo
>(FunctionScopes
.back());
8032 QualType RetTy
= Context
.VoidTy
;
8033 if (!BSI
->ReturnType
.isNull())
8034 RetTy
= BSI
->ReturnType
;
8036 bool NoReturn
= BSI
->TheDecl
->getAttr
<NoReturnAttr
>();
8039 // If the user wrote a function type in some form, try to use that.
8040 if (!BSI
->FunctionType
.isNull()) {
8041 const FunctionType
*FTy
= BSI
->FunctionType
->getAs
<FunctionType
>();
8043 FunctionType::ExtInfo Ext
= FTy
->getExtInfo();
8044 if (NoReturn
&& !Ext
.getNoReturn()) Ext
= Ext
.withNoReturn(true);
8046 // Turn protoless block types into nullary block types.
8047 if (isa
<FunctionNoProtoType
>(FTy
)) {
8048 BlockTy
= Context
.getFunctionType(RetTy
, 0, 0, false, 0,
8049 false, false, 0, 0, Ext
);
8051 // Otherwise, if we don't need to change anything about the function type,
8052 // preserve its sugar structure.
8053 } else if (FTy
->getResultType() == RetTy
&&
8054 (!NoReturn
|| FTy
->getNoReturnAttr())) {
8055 BlockTy
= BSI
->FunctionType
;
8057 // Otherwise, make the minimal modifications to the function type.
8059 const FunctionProtoType
*FPT
= cast
<FunctionProtoType
>(FTy
);
8060 BlockTy
= Context
.getFunctionType(RetTy
,
8061 FPT
->arg_type_begin(),
8065 FPT
->hasExceptionSpec(),
8066 FPT
->hasAnyExceptionSpec(),
8067 FPT
->getNumExceptions(),
8068 FPT
->exception_begin(),
8072 // If we don't have a function type, just build one from nothing.
8074 BlockTy
= Context
.getFunctionType(RetTy
, 0, 0, false, 0,
8076 FunctionType::ExtInfo(NoReturn
, 0, CC_Default
));
8079 DiagnoseUnusedParameters(BSI
->TheDecl
->param_begin(),
8080 BSI
->TheDecl
->param_end());
8081 BlockTy
= Context
.getBlockPointerType(BlockTy
);
8083 // If needed, diagnose invalid gotos and switches in the block.
8084 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
8085 DiagnoseInvalidJumps(cast
<CompoundStmt
>(Body
));
8087 BSI
->TheDecl
->setBody(cast
<CompoundStmt
>(Body
));
8090 // Check goto/label use.
8091 for (llvm::DenseMap
<IdentifierInfo
*, LabelStmt
*>::iterator
8092 I
= BSI
->LabelMap
.begin(), E
= BSI
->LabelMap
.end(); I
!= E
; ++I
) {
8093 LabelStmt
*L
= I
->second
;
8095 // Verify that we have no forward references left. If so, there was a goto
8096 // or address of a label taken, but no definition of it.
8097 if (L
->getSubStmt() != 0) {
8099 Diag(L
->getIdentLoc(), diag::warn_unused_label
) << L
->getName();
8104 Diag(L
->getIdentLoc(), diag::err_undeclared_label_use
) << L
->getName();
8108 PopFunctionOrBlockScope();
8112 BlockExpr
*Result
= new (Context
) BlockExpr(BSI
->TheDecl
, BlockTy
,
8113 BSI
->hasBlockDeclRefExprs
);
8115 // Issue any analysis-based warnings.
8116 const sema::AnalysisBasedWarnings::Policy
&WP
=
8117 AnalysisWarnings
.getDefaultPolicy();
8118 AnalysisWarnings
.IssueWarnings(WP
, Result
);
8120 PopFunctionOrBlockScope();
8121 return Owned(Result
);
8124 ExprResult
Sema::ActOnVAArg(SourceLocation BuiltinLoc
,
8125 Expr
*expr
, ParsedType type
,
8126 SourceLocation RPLoc
) {
8127 TypeSourceInfo
*TInfo
;
8128 QualType T
= GetTypeFromParser(type
, &TInfo
);
8129 return BuildVAArgExpr(BuiltinLoc
, expr
, TInfo
, RPLoc
);
8132 ExprResult
Sema::BuildVAArgExpr(SourceLocation BuiltinLoc
,
8133 Expr
*E
, TypeSourceInfo
*TInfo
,
8134 SourceLocation RPLoc
) {
8137 // Get the va_list type
8138 QualType VaListType
= Context
.getBuiltinVaListType();
8139 if (VaListType
->isArrayType()) {
8140 // Deal with implicit array decay; for example, on x86-64,
8141 // va_list is an array, but it's supposed to decay to
8142 // a pointer for va_arg.
8143 VaListType
= Context
.getArrayDecayedType(VaListType
);
8144 // Make sure the input expression also decays appropriately.
8145 UsualUnaryConversions(E
);
8147 // Otherwise, the va_list argument must be an l-value because
8148 // it is modified by va_arg.
8149 if (!E
->isTypeDependent() &&
8150 CheckForModifiableLvalue(E
, BuiltinLoc
, *this))
8154 if (!E
->isTypeDependent() &&
8155 !Context
.hasSameType(VaListType
, E
->getType())) {
8156 return ExprError(Diag(E
->getLocStart(),
8157 diag::err_first_argument_to_va_arg_not_of_type_va_list
)
8158 << OrigExpr
->getType() << E
->getSourceRange());
8161 // FIXME: Check that type is complete/non-abstract
8162 // FIXME: Warn if a non-POD type is passed in.
8164 QualType T
= TInfo
->getType().getNonLValueExprType(Context
);
8165 return Owned(new (Context
) VAArgExpr(BuiltinLoc
, E
, TInfo
, RPLoc
, T
));
8168 ExprResult
Sema::ActOnGNUNullExpr(SourceLocation TokenLoc
) {
8169 // The type of __null will be int or long, depending on the size of
8170 // pointers on the target.
8172 if (Context
.Target
.getPointerWidth(0) == Context
.Target
.getIntWidth())
8175 Ty
= Context
.LongTy
;
8177 return Owned(new (Context
) GNUNullExpr(Ty
, TokenLoc
));
8180 static void MakeObjCStringLiteralFixItHint(Sema
& SemaRef
, QualType DstType
,
8181 Expr
*SrcExpr
, FixItHint
&Hint
) {
8182 if (!SemaRef
.getLangOptions().ObjC1
)
8185 const ObjCObjectPointerType
*PT
= DstType
->getAs
<ObjCObjectPointerType
>();
8189 // Check if the destination is of type 'id'.
8190 if (!PT
->isObjCIdType()) {
8191 // Check if the destination is the 'NSString' interface.
8192 const ObjCInterfaceDecl
*ID
= PT
->getInterfaceDecl();
8193 if (!ID
|| !ID
->getIdentifier()->isStr("NSString"))
8197 // Strip off any parens and casts.
8198 StringLiteral
*SL
= dyn_cast
<StringLiteral
>(SrcExpr
->IgnoreParenCasts());
8199 if (!SL
|| SL
->isWide())
8202 Hint
= FixItHint::CreateInsertion(SL
->getLocStart(), "@");
8205 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy
,
8207 QualType DstType
, QualType SrcType
,
8208 Expr
*SrcExpr
, AssignmentAction Action
,
8211 *Complained
= false;
8213 // Decode the result (notice that AST's are still created for extensions).
8214 bool isInvalid
= false;
8219 default: assert(0 && "Unknown conversion type");
8220 case Compatible
: return false;
8222 DiagKind
= diag::ext_typecheck_convert_pointer_int
;
8225 DiagKind
= diag::ext_typecheck_convert_int_pointer
;
8227 case IncompatiblePointer
:
8228 MakeObjCStringLiteralFixItHint(*this, DstType
, SrcExpr
, Hint
);
8229 DiagKind
= diag::ext_typecheck_convert_incompatible_pointer
;
8231 case IncompatiblePointerSign
:
8232 DiagKind
= diag::ext_typecheck_convert_incompatible_pointer_sign
;
8234 case FunctionVoidPointer
:
8235 DiagKind
= diag::ext_typecheck_convert_pointer_void_func
;
8237 case CompatiblePointerDiscardsQualifiers
:
8238 // If the qualifiers lost were because we were applying the
8239 // (deprecated) C++ conversion from a string literal to a char*
8240 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8241 // Ideally, this check would be performed in
8242 // CheckPointerTypesForAssignment. However, that would require a
8243 // bit of refactoring (so that the second argument is an
8244 // expression, rather than a type), which should be done as part
8245 // of a larger effort to fix CheckPointerTypesForAssignment for
8247 if (getLangOptions().CPlusPlus
&&
8248 IsStringLiteralToNonConstPointerConversion(SrcExpr
, DstType
))
8250 DiagKind
= diag::ext_typecheck_convert_discards_qualifiers
;
8252 case IncompatibleNestedPointerQualifiers
:
8253 DiagKind
= diag::ext_nested_pointer_qualifier_mismatch
;
8255 case IntToBlockPointer
:
8256 DiagKind
= diag::err_int_to_block_pointer
;
8258 case IncompatibleBlockPointer
:
8259 DiagKind
= diag::err_typecheck_convert_incompatible_block_pointer
;
8261 case IncompatibleObjCQualifiedId
:
8262 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
8263 // it can give a more specific diagnostic.
8264 DiagKind
= diag::warn_incompatible_qualified_id
;
8266 case IncompatibleVectors
:
8267 DiagKind
= diag::warn_incompatible_vectors
;
8270 DiagKind
= diag::err_typecheck_convert_incompatible
;
8275 QualType FirstType
, SecondType
;
8278 case AA_Initializing
:
8279 // The destination type comes first.
8280 FirstType
= DstType
;
8281 SecondType
= SrcType
;
8289 // The source type comes first.
8290 FirstType
= SrcType
;
8291 SecondType
= DstType
;
8295 Diag(Loc
, DiagKind
) << FirstType
<< SecondType
<< Action
8296 << SrcExpr
->getSourceRange() << Hint
;
8302 bool Sema::VerifyIntegerConstantExpression(const Expr
*E
, llvm::APSInt
*Result
){
8303 llvm::APSInt ICEResult
;
8304 if (E
->isIntegerConstantExpr(ICEResult
, Context
)) {
8306 *Result
= ICEResult
;
8310 Expr::EvalResult EvalResult
;
8312 if (!E
->Evaluate(EvalResult
, Context
) || !EvalResult
.Val
.isInt() ||
8313 EvalResult
.HasSideEffects
) {
8314 Diag(E
->getExprLoc(), diag::err_expr_not_ice
) << E
->getSourceRange();
8316 if (EvalResult
.Diag
) {
8317 // We only show the note if it's not the usual "invalid subexpression"
8318 // or if it's actually in a subexpression.
8319 if (EvalResult
.Diag
!= diag::note_invalid_subexpr_in_ice
||
8320 E
->IgnoreParens() != EvalResult
.DiagExpr
->IgnoreParens())
8321 Diag(EvalResult
.DiagLoc
, EvalResult
.Diag
);
8327 Diag(E
->getExprLoc(), diag::ext_expr_not_ice
) <<
8328 E
->getSourceRange();
8330 if (EvalResult
.Diag
&&
8331 Diags
.getDiagnosticLevel(diag::ext_expr_not_ice
) != Diagnostic::Ignored
)
8332 Diag(EvalResult
.DiagLoc
, EvalResult
.Diag
);
8335 *Result
= EvalResult
.Val
.getInt();
8340 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext
) {
8341 ExprEvalContexts
.push_back(
8342 ExpressionEvaluationContextRecord(NewContext
, ExprTemporaries
.size()));
8346 Sema::PopExpressionEvaluationContext() {
8347 // Pop the current expression evaluation context off the stack.
8348 ExpressionEvaluationContextRecord Rec
= ExprEvalContexts
.back();
8349 ExprEvalContexts
.pop_back();
8351 if (Rec
.Context
== PotentiallyPotentiallyEvaluated
) {
8352 if (Rec
.PotentiallyReferenced
) {
8353 // Mark any remaining declarations in the current position of the stack
8354 // as "referenced". If they were not meant to be referenced, semantic
8355 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
8356 for (PotentiallyReferencedDecls::iterator
8357 I
= Rec
.PotentiallyReferenced
->begin(),
8358 IEnd
= Rec
.PotentiallyReferenced
->end();
8360 MarkDeclarationReferenced(I
->first
, I
->second
);
8363 if (Rec
.PotentiallyDiagnosed
) {
8364 // Emit any pending diagnostics.
8365 for (PotentiallyEmittedDiagnostics::iterator
8366 I
= Rec
.PotentiallyDiagnosed
->begin(),
8367 IEnd
= Rec
.PotentiallyDiagnosed
->end();
8369 Diag(I
->first
, I
->second
);
8373 // When are coming out of an unevaluated context, clear out any
8374 // temporaries that we may have created as part of the evaluation of
8375 // the expression in that context: they aren't relevant because they
8376 // will never be constructed.
8377 if (Rec
.Context
== Unevaluated
&&
8378 ExprTemporaries
.size() > Rec
.NumTemporaries
)
8379 ExprTemporaries
.erase(ExprTemporaries
.begin() + Rec
.NumTemporaries
,
8380 ExprTemporaries
.end());
8382 // Destroy the popped expression evaluation record.
8386 /// \brief Note that the given declaration was referenced in the source code.
8388 /// This routine should be invoke whenever a given declaration is referenced
8389 /// in the source code, and where that reference occurred. If this declaration
8390 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8391 /// C99 6.9p3), then the declaration will be marked as used.
8393 /// \param Loc the location where the declaration was referenced.
8395 /// \param D the declaration that has been referenced by the source code.
8396 void Sema::MarkDeclarationReferenced(SourceLocation Loc
, Decl
*D
) {
8397 assert(D
&& "No declaration?");
8399 if (D
->isUsed(false))
8402 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8403 // template or not. The reason for this is that unevaluated expressions
8404 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8405 // -Wunused-parameters)
8406 if (isa
<ParmVarDecl
>(D
) ||
8407 (isa
<VarDecl
>(D
) && D
->getDeclContext()->isFunctionOrMethod())) {
8412 if (!isa
<VarDecl
>(D
) && !isa
<FunctionDecl
>(D
))
8415 // Do not mark anything as "used" within a dependent context; wait for
8416 // an instantiation.
8417 if (CurContext
->isDependentContext())
8420 switch (ExprEvalContexts
.back().Context
) {
8422 // We are in an expression that is not potentially evaluated; do nothing.
8425 case PotentiallyEvaluated
:
8426 // We are in a potentially-evaluated expression, so this declaration is
8427 // "used"; handle this below.
8430 case PotentiallyPotentiallyEvaluated
:
8431 // We are in an expression that may be potentially evaluated; queue this
8432 // declaration reference until we know whether the expression is
8433 // potentially evaluated.
8434 ExprEvalContexts
.back().addReferencedDecl(Loc
, D
);
8437 case PotentiallyEvaluatedIfUsed
:
8438 // Referenced declarations will only be used if the construct in the
8439 // containing expression is used.
8443 // Note that this declaration has been used.
8444 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(D
)) {
8446 if (Constructor
->isImplicit() && Constructor
->isDefaultConstructor()) {
8447 if (Constructor
->getParent()->hasTrivialConstructor())
8449 if (!Constructor
->isUsed(false))
8450 DefineImplicitDefaultConstructor(Loc
, Constructor
);
8451 } else if (Constructor
->isImplicit() &&
8452 Constructor
->isCopyConstructor(TypeQuals
)) {
8453 if (!Constructor
->isUsed(false))
8454 DefineImplicitCopyConstructor(Loc
, Constructor
, TypeQuals
);
8457 MarkVTableUsed(Loc
, Constructor
->getParent());
8458 } else if (CXXDestructorDecl
*Destructor
= dyn_cast
<CXXDestructorDecl
>(D
)) {
8459 if (Destructor
->isImplicit() && !Destructor
->isUsed(false))
8460 DefineImplicitDestructor(Loc
, Destructor
);
8461 if (Destructor
->isVirtual())
8462 MarkVTableUsed(Loc
, Destructor
->getParent());
8463 } else if (CXXMethodDecl
*MethodDecl
= dyn_cast
<CXXMethodDecl
>(D
)) {
8464 if (MethodDecl
->isImplicit() && MethodDecl
->isOverloadedOperator() &&
8465 MethodDecl
->getOverloadedOperator() == OO_Equal
) {
8466 if (!MethodDecl
->isUsed(false))
8467 DefineImplicitCopyAssignment(Loc
, MethodDecl
);
8468 } else if (MethodDecl
->isVirtual())
8469 MarkVTableUsed(Loc
, MethodDecl
->getParent());
8471 if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(D
)) {
8472 // Implicit instantiation of function templates and member functions of
8474 if (Function
->isImplicitlyInstantiable()) {
8475 bool AlreadyInstantiated
= false;
8476 if (FunctionTemplateSpecializationInfo
*SpecInfo
8477 = Function
->getTemplateSpecializationInfo()) {
8478 if (SpecInfo
->getPointOfInstantiation().isInvalid())
8479 SpecInfo
->setPointOfInstantiation(Loc
);
8480 else if (SpecInfo
->getTemplateSpecializationKind()
8481 == TSK_ImplicitInstantiation
)
8482 AlreadyInstantiated
= true;
8483 } else if (MemberSpecializationInfo
*MSInfo
8484 = Function
->getMemberSpecializationInfo()) {
8485 if (MSInfo
->getPointOfInstantiation().isInvalid())
8486 MSInfo
->setPointOfInstantiation(Loc
);
8487 else if (MSInfo
->getTemplateSpecializationKind()
8488 == TSK_ImplicitInstantiation
)
8489 AlreadyInstantiated
= true;
8492 if (!AlreadyInstantiated
) {
8493 if (isa
<CXXRecordDecl
>(Function
->getDeclContext()) &&
8494 cast
<CXXRecordDecl
>(Function
->getDeclContext())->isLocalClass())
8495 PendingLocalImplicitInstantiations
.push_back(std::make_pair(Function
,
8498 PendingInstantiations
.push_back(std::make_pair(Function
, Loc
));
8500 } else // Walk redefinitions, as some of them may be instantiable.
8501 for (FunctionDecl::redecl_iterator
i(Function
->redecls_begin()),
8502 e(Function
->redecls_end()); i
!= e
; ++i
) {
8503 if (!i
->isUsed(false) && i
->isImplicitlyInstantiable())
8504 MarkDeclarationReferenced(Loc
, *i
);
8507 // FIXME: keep track of references to static functions
8509 // Recursive functions should be marked when used from another function.
8510 if (CurContext
!= Function
)
8511 Function
->setUsed(true);
8516 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(D
)) {
8517 // Implicit instantiation of static data members of class templates.
8518 if (Var
->isStaticDataMember() &&
8519 Var
->getInstantiatedFromStaticDataMember()) {
8520 MemberSpecializationInfo
*MSInfo
= Var
->getMemberSpecializationInfo();
8521 assert(MSInfo
&& "Missing member specialization information?");
8522 if (MSInfo
->getPointOfInstantiation().isInvalid() &&
8523 MSInfo
->getTemplateSpecializationKind()== TSK_ImplicitInstantiation
) {
8524 MSInfo
->setPointOfInstantiation(Loc
);
8525 PendingInstantiations
.push_back(std::make_pair(Var
, Loc
));
8529 // FIXME: keep track of references to static data?
8537 // Mark all of the declarations referenced
8538 // FIXME: Not fully implemented yet! We need to have a better understanding
8539 // of when we're entering
8540 class MarkReferencedDecls
: public RecursiveASTVisitor
<MarkReferencedDecls
> {
8545 typedef RecursiveASTVisitor
<MarkReferencedDecls
> Inherited
;
8547 MarkReferencedDecls(Sema
&S
, SourceLocation Loc
) : S(S
), Loc(Loc
) { }
8549 bool TraverseTemplateArgument(const TemplateArgument
&Arg
);
8550 bool TraverseRecordType(RecordType
*T
);
8554 bool MarkReferencedDecls::TraverseTemplateArgument(
8555 const TemplateArgument
&Arg
) {
8556 if (Arg
.getKind() == TemplateArgument::Declaration
) {
8557 S
.MarkDeclarationReferenced(Loc
, Arg
.getAsDecl());
8560 return Inherited::TraverseTemplateArgument(Arg
);
8563 bool MarkReferencedDecls::TraverseRecordType(RecordType
*T
) {
8564 if (ClassTemplateSpecializationDecl
*Spec
8565 = dyn_cast
<ClassTemplateSpecializationDecl
>(T
->getDecl())) {
8566 const TemplateArgumentList
&Args
= Spec
->getTemplateArgs();
8567 return TraverseTemplateArguments(Args
.data(), Args
.size());
8573 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc
, QualType T
) {
8574 MarkReferencedDecls
Marker(*this, Loc
);
8575 Marker
.TraverseType(Context
.getCanonicalType(T
));
8579 /// \brief Helper class that marks all of the declarations referenced by
8580 /// potentially-evaluated subexpressions as "referenced".
8581 class EvaluatedExprMarker
: public EvaluatedExprVisitor
<EvaluatedExprMarker
> {
8585 typedef EvaluatedExprVisitor
<EvaluatedExprMarker
> Inherited
;
8587 explicit EvaluatedExprMarker(Sema
&S
) : Inherited(S
.Context
), S(S
) { }
8589 void VisitDeclRefExpr(DeclRefExpr
*E
) {
8590 S
.MarkDeclarationReferenced(E
->getLocation(), E
->getDecl());
8593 void VisitMemberExpr(MemberExpr
*E
) {
8594 S
.MarkDeclarationReferenced(E
->getMemberLoc(), E
->getMemberDecl());
8595 Inherited::VisitMemberExpr(E
);
8598 void VisitCXXNewExpr(CXXNewExpr
*E
) {
8599 if (E
->getConstructor())
8600 S
.MarkDeclarationReferenced(E
->getLocStart(), E
->getConstructor());
8601 if (E
->getOperatorNew())
8602 S
.MarkDeclarationReferenced(E
->getLocStart(), E
->getOperatorNew());
8603 if (E
->getOperatorDelete())
8604 S
.MarkDeclarationReferenced(E
->getLocStart(), E
->getOperatorDelete());
8605 Inherited::VisitCXXNewExpr(E
);
8608 void VisitCXXDeleteExpr(CXXDeleteExpr
*E
) {
8609 if (E
->getOperatorDelete())
8610 S
.MarkDeclarationReferenced(E
->getLocStart(), E
->getOperatorDelete());
8611 QualType Destroyed
= S
.Context
.getBaseElementType(E
->getDestroyedType());
8612 if (const RecordType
*DestroyedRec
= Destroyed
->getAs
<RecordType
>()) {
8613 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(DestroyedRec
->getDecl());
8614 S
.MarkDeclarationReferenced(E
->getLocStart(),
8615 S
.LookupDestructor(Record
));
8618 Inherited::VisitCXXDeleteExpr(E
);
8621 void VisitCXXConstructExpr(CXXConstructExpr
*E
) {
8622 S
.MarkDeclarationReferenced(E
->getLocStart(), E
->getConstructor());
8623 Inherited::VisitCXXConstructExpr(E
);
8626 void VisitBlockDeclRefExpr(BlockDeclRefExpr
*E
) {
8627 S
.MarkDeclarationReferenced(E
->getLocation(), E
->getDecl());
8630 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr
*E
) {
8631 Visit(E
->getExpr());
8636 /// \brief Mark any declarations that appear within this expression or any
8637 /// potentially-evaluated subexpressions as "referenced".
8638 void Sema::MarkDeclarationsReferencedInExpr(Expr
*E
) {
8639 EvaluatedExprMarker(*this).Visit(E
);
8642 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
8643 /// of the program being compiled.
8645 /// This routine emits the given diagnostic when the code currently being
8646 /// type-checked is "potentially evaluated", meaning that there is a
8647 /// possibility that the code will actually be executable. Code in sizeof()
8648 /// expressions, code used only during overload resolution, etc., are not
8649 /// potentially evaluated. This routine will suppress such diagnostics or,
8650 /// in the absolutely nutty case of potentially potentially evaluated
8651 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
8654 /// This routine should be used for all diagnostics that describe the run-time
8655 /// behavior of a program, such as passing a non-POD value through an ellipsis.
8656 /// Failure to do so will likely result in spurious diagnostics or failures
8657 /// during overload resolution or within sizeof/alignof/typeof/typeid.
8658 bool Sema::DiagRuntimeBehavior(SourceLocation Loc
,
8659 const PartialDiagnostic
&PD
) {
8660 switch (ExprEvalContexts
.back().Context
) {
8662 // The argument will never be evaluated, so don't complain.
8665 case PotentiallyEvaluated
:
8666 case PotentiallyEvaluatedIfUsed
:
8670 case PotentiallyPotentiallyEvaluated
:
8671 ExprEvalContexts
.back().addDiagnostic(Loc
, PD
);
8678 bool Sema::CheckCallReturnType(QualType ReturnType
, SourceLocation Loc
,
8679 CallExpr
*CE
, FunctionDecl
*FD
) {
8680 if (ReturnType
->isVoidType() || !ReturnType
->isIncompleteType())
8683 PartialDiagnostic Note
=
8684 FD
? PDiag(diag::note_function_with_incomplete_return_type_declared_here
)
8685 << FD
->getDeclName() : PDiag();
8686 SourceLocation NoteLoc
= FD
? FD
->getLocation() : SourceLocation();
8688 if (RequireCompleteType(Loc
, ReturnType
,
8690 PDiag(diag::err_call_function_incomplete_return
)
8691 << CE
->getSourceRange() << FD
->getDeclName() :
8692 PDiag(diag::err_call_incomplete_return
)
8693 << CE
->getSourceRange(),
8694 std::make_pair(NoteLoc
, Note
)))
8700 // Diagnose the common s/=/==/ typo. Note that adding parentheses
8701 // will prevent this condition from triggering, which is what we want.
8702 void Sema::DiagnoseAssignmentAsCondition(Expr
*E
) {
8705 unsigned diagnostic
= diag::warn_condition_is_assignment
;
8707 if (isa
<BinaryOperator
>(E
)) {
8708 BinaryOperator
*Op
= cast
<BinaryOperator
>(E
);
8709 if (Op
->getOpcode() != BO_Assign
)
8712 // Greylist some idioms by putting them into a warning subcategory.
8713 if (ObjCMessageExpr
*ME
8714 = dyn_cast
<ObjCMessageExpr
>(Op
->getRHS()->IgnoreParenCasts())) {
8715 Selector Sel
= ME
->getSelector();
8717 // self = [<foo> init...]
8718 if (isSelfExpr(Op
->getLHS())
8719 && Sel
.getIdentifierInfoForSlot(0)->getName().startswith("init"))
8720 diagnostic
= diag::warn_condition_is_idiomatic_assignment
;
8722 // <foo> = [<bar> nextObject]
8723 else if (Sel
.isUnarySelector() &&
8724 Sel
.getIdentifierInfoForSlot(0)->getName() == "nextObject")
8725 diagnostic
= diag::warn_condition_is_idiomatic_assignment
;
8728 Loc
= Op
->getOperatorLoc();
8729 } else if (isa
<CXXOperatorCallExpr
>(E
)) {
8730 CXXOperatorCallExpr
*Op
= cast
<CXXOperatorCallExpr
>(E
);
8731 if (Op
->getOperator() != OO_Equal
)
8734 Loc
= Op
->getOperatorLoc();
8736 // Not an assignment.
8740 SourceLocation Open
= E
->getSourceRange().getBegin();
8741 SourceLocation Close
= PP
.getLocForEndOfToken(E
->getSourceRange().getEnd());
8743 Diag(Loc
, diagnostic
) << E
->getSourceRange();
8744 Diag(Loc
, diag::note_condition_assign_to_comparison
)
8745 << FixItHint::CreateReplacement(Loc
, "==");
8746 Diag(Loc
, diag::note_condition_assign_silence
)
8747 << FixItHint::CreateInsertion(Open
, "(")
8748 << FixItHint::CreateInsertion(Close
, ")");
8751 bool Sema::CheckBooleanCondition(Expr
*&E
, SourceLocation Loc
) {
8752 DiagnoseAssignmentAsCondition(E
);
8754 if (!E
->isTypeDependent()) {
8755 if (E
->isBoundMemberFunction(Context
))
8756 return Diag(E
->getLocStart(), diag::err_invalid_use_of_bound_member_func
)
8757 << E
->getSourceRange();
8759 DefaultFunctionArrayLvalueConversion(E
);
8761 QualType T
= E
->getType();
8763 if (getLangOptions().CPlusPlus
) {
8764 if (CheckCXXBooleanCondition(E
)) // C++ 6.4p4
8766 } else if (!T
->isScalarType()) { // C99 6.8.4.1p1
8767 Diag(Loc
, diag::err_typecheck_statement_requires_scalar
)
8768 << T
<< E
->getSourceRange();
8776 ExprResult
Sema::ActOnBooleanCondition(Scope
*S
, SourceLocation Loc
,
8781 if (CheckBooleanCondition(Sub
, Loc
))
8787 /// Check for operands with placeholder types and complain if found.
8788 /// Returns true if there was an error and no recovery was possible.
8789 ExprResult
Sema::CheckPlaceholderExpr(Expr
*E
, SourceLocation Loc
) {
8790 const BuiltinType
*BT
= E
->getType()->getAs
<BuiltinType
>();
8791 if (!BT
|| !BT
->isPlaceholderType()) return Owned(E
);
8793 // If this is overload, check for a single overload.
8794 if (BT
->getKind() == BuiltinType::Overload
) {
8795 if (FunctionDecl
*Specialization
8796 = ResolveSingleFunctionTemplateSpecialization(E
)) {
8797 // The access doesn't really matter in this case.
8798 DeclAccessPair Found
= DeclAccessPair::make(Specialization
,
8799 Specialization
->getAccess());
8800 E
= FixOverloadedFunctionReference(E
, Found
, Specialization
);
8801 if (!E
) return ExprError();
8805 Diag(Loc
, diag::err_ovl_unresolvable
) << E
->getSourceRange();
8809 // Otherwise it's a use of undeduced auto.
8810 assert(BT
->getKind() == BuiltinType::UndeducedAuto
);
8812 DeclRefExpr
*DRE
= cast
<DeclRefExpr
>(E
->IgnoreParens());
8813 Diag(Loc
, diag::err_auto_variable_cannot_appear_in_own_initializer
)
8814 << DRE
->getDecl() << E
->getSourceRange();