Allow resolving headers from a PCH even after headers+PCH were moved to another path.
[clang.git] / lib / Sema / SemaExpr.cpp
blobb0c337149d9c8a8f3b0e009ce9f1962a242809ce
1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/AnalysisBasedWarnings.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/DeclSpec.h"
34 #include "clang/Sema/Designator.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/ParsedTemplate.h"
38 #include "clang/Sema/Template.h"
39 using namespace clang;
40 using namespace sema;
43 /// \brief Determine whether the use of this declaration is valid, and
44 /// emit any corresponding diagnostics.
45 ///
46 /// This routine diagnoses various problems with referencing
47 /// declarations that can occur when using a declaration. For example,
48 /// it might warn if a deprecated or unavailable declaration is being
49 /// used, or produce an error (and return true) if a C++0x deleted
50 /// function is being used.
51 ///
52 /// If IgnoreDeprecated is set to true, this should not warn about deprecated
53 /// decls.
54 ///
55 /// \returns true if there was an error (this declaration cannot be
56 /// referenced), false otherwise.
57 ///
58 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
59 bool UnknownObjCClass) {
60 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
61 // If there were any diagnostics suppressed by template argument deduction,
62 // emit them now.
63 llvm::DenseMap<Decl *, llvm::SmallVector<PartialDiagnosticAt, 1> >::iterator
64 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
65 if (Pos != SuppressedDiagnostics.end()) {
66 llvm::SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
67 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
68 Diag(Suppressed[I].first, Suppressed[I].second);
70 // Clear out the list of suppressed diagnostics, so that we don't emit
71 // them again for this specialization. However, we don't remove this
72 // entry from the table, because we want to avoid ever emitting these
73 // diagnostics again.
74 Suppressed.clear();
78 // See if the decl is deprecated.
79 if (const DeprecatedAttr *DA = D->getAttr<DeprecatedAttr>())
80 EmitDeprecationWarning(D, DA->getMessage(), Loc, UnknownObjCClass);
82 // See if the decl is unavailable
83 if (const UnavailableAttr *UA = D->getAttr<UnavailableAttr>()) {
84 if (UA->getMessage().empty()) {
85 if (!UnknownObjCClass)
86 Diag(Loc, diag::err_unavailable) << D->getDeclName();
87 else
88 Diag(Loc, diag::warn_unavailable_fwdclass_message)
89 << D->getDeclName();
91 else
92 Diag(Loc, diag::err_unavailable_message)
93 << D->getDeclName() << UA->getMessage();
94 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
97 // See if this is a deleted function.
98 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
99 if (FD->isDeleted()) {
100 Diag(Loc, diag::err_deleted_function_use);
101 Diag(D->getLocation(), diag::note_unavailable_here) << true;
102 return true;
106 // Warn if this is used but marked unused.
107 if (D->hasAttr<UnusedAttr>())
108 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
110 return false;
113 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
114 /// (and other functions in future), which have been declared with sentinel
115 /// attribute. It warns if call does not have the sentinel argument.
117 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
118 Expr **Args, unsigned NumArgs) {
119 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
120 if (!attr)
121 return;
123 // FIXME: In C++0x, if any of the arguments are parameter pack
124 // expansions, we can't check for the sentinel now.
125 int sentinelPos = attr->getSentinel();
126 int nullPos = attr->getNullPos();
128 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
129 // base class. Then we won't be needing two versions of the same code.
130 unsigned int i = 0;
131 bool warnNotEnoughArgs = false;
132 int isMethod = 0;
133 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
134 // skip over named parameters.
135 ObjCMethodDecl::param_iterator P, E = MD->param_end();
136 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
137 if (nullPos)
138 --nullPos;
139 else
140 ++i;
142 warnNotEnoughArgs = (P != E || i >= NumArgs);
143 isMethod = 1;
144 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
145 // skip over named parameters.
146 ObjCMethodDecl::param_iterator P, E = FD->param_end();
147 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
148 if (nullPos)
149 --nullPos;
150 else
151 ++i;
153 warnNotEnoughArgs = (P != E || i >= NumArgs);
154 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
155 // block or function pointer call.
156 QualType Ty = V->getType();
157 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
158 const FunctionType *FT = Ty->isFunctionPointerType()
159 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
160 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
161 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
162 unsigned NumArgsInProto = Proto->getNumArgs();
163 unsigned k;
164 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
165 if (nullPos)
166 --nullPos;
167 else
168 ++i;
170 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
172 if (Ty->isBlockPointerType())
173 isMethod = 2;
174 } else
175 return;
176 } else
177 return;
179 if (warnNotEnoughArgs) {
180 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
181 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
182 return;
184 int sentinel = i;
185 while (sentinelPos > 0 && i < NumArgs-1) {
186 --sentinelPos;
187 ++i;
189 if (sentinelPos > 0) {
190 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
191 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
192 return;
194 while (i < NumArgs-1) {
195 ++i;
196 ++sentinel;
198 Expr *sentinelExpr = Args[sentinel];
199 if (!sentinelExpr) return;
200 if (sentinelExpr->isTypeDependent()) return;
201 if (sentinelExpr->isValueDependent()) return;
203 // nullptr_t is always treated as null.
204 if (sentinelExpr->getType()->isNullPtrType()) return;
206 if (sentinelExpr->getType()->isAnyPointerType() &&
207 sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
208 Expr::NPC_ValueDependentIsNull))
209 return;
211 // Unfortunately, __null has type 'int'.
212 if (isa<GNUNullExpr>(sentinelExpr)) return;
214 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
215 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
218 SourceRange Sema::getExprRange(ExprTy *E) const {
219 Expr *Ex = (Expr *)E;
220 return Ex? Ex->getSourceRange() : SourceRange();
223 //===----------------------------------------------------------------------===//
224 // Standard Promotions and Conversions
225 //===----------------------------------------------------------------------===//
227 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
228 void Sema::DefaultFunctionArrayConversion(Expr *&E) {
229 QualType Ty = E->getType();
230 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
232 if (Ty->isFunctionType())
233 ImpCastExprToType(E, Context.getPointerType(Ty),
234 CK_FunctionToPointerDecay);
235 else if (Ty->isArrayType()) {
236 // In C90 mode, arrays only promote to pointers if the array expression is
237 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
238 // type 'array of type' is converted to an expression that has type 'pointer
239 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
240 // that has type 'array of type' ...". The relevant change is "an lvalue"
241 // (C90) to "an expression" (C99).
243 // C++ 4.2p1:
244 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
245 // T" can be converted to an rvalue of type "pointer to T".
247 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
248 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
249 CK_ArrayToPointerDecay);
253 void Sema::DefaultLvalueConversion(Expr *&E) {
254 // C++ [conv.lval]p1:
255 // A glvalue of a non-function, non-array type T can be
256 // converted to a prvalue.
257 if (!E->isGLValue()) return;
259 QualType T = E->getType();
260 assert(!T.isNull() && "r-value conversion on typeless expression?");
262 // Create a load out of an ObjCProperty l-value, if necessary.
263 if (E->getObjectKind() == OK_ObjCProperty) {
264 ConvertPropertyForRValue(E);
265 if (!E->isGLValue())
266 return;
269 // We don't want to throw lvalue-to-rvalue casts on top of
270 // expressions of certain types in C++.
271 if (getLangOptions().CPlusPlus &&
272 (E->getType() == Context.OverloadTy ||
273 T->isDependentType() ||
274 T->isRecordType()))
275 return;
277 // The C standard is actually really unclear on this point, and
278 // DR106 tells us what the result should be but not why. It's
279 // generally best to say that void types just doesn't undergo
280 // lvalue-to-rvalue at all. Note that expressions of unqualified
281 // 'void' type are never l-values, but qualified void can be.
282 if (T->isVoidType())
283 return;
285 // C++ [conv.lval]p1:
286 // [...] If T is a non-class type, the type of the prvalue is the
287 // cv-unqualified version of T. Otherwise, the type of the
288 // rvalue is T.
290 // C99 6.3.2.1p2:
291 // If the lvalue has qualified type, the value has the unqualified
292 // version of the type of the lvalue; otherwise, the value has the
293 // type of the lvalue.
294 if (T.hasQualifiers())
295 T = T.getUnqualifiedType();
297 E = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
298 E, 0, VK_RValue);
301 void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
302 DefaultFunctionArrayConversion(E);
303 DefaultLvalueConversion(E);
307 /// UsualUnaryConversions - Performs various conversions that are common to most
308 /// operators (C99 6.3). The conversions of array and function types are
309 /// sometimes surpressed. For example, the array->pointer conversion doesn't
310 /// apply if the array is an argument to the sizeof or address (&) operators.
311 /// In these instances, this routine should *not* be called.
312 Expr *Sema::UsualUnaryConversions(Expr *&E) {
313 // First, convert to an r-value.
314 DefaultFunctionArrayLvalueConversion(E);
316 QualType Ty = E->getType();
317 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
319 // Try to perform integral promotions if the object has a theoretically
320 // promotable type.
321 if (Ty->isIntegralOrUnscopedEnumerationType()) {
322 // C99 6.3.1.1p2:
324 // The following may be used in an expression wherever an int or
325 // unsigned int may be used:
326 // - an object or expression with an integer type whose integer
327 // conversion rank is less than or equal to the rank of int
328 // and unsigned int.
329 // - A bit-field of type _Bool, int, signed int, or unsigned int.
331 // If an int can represent all values of the original type, the
332 // value is converted to an int; otherwise, it is converted to an
333 // unsigned int. These are called the integer promotions. All
334 // other types are unchanged by the integer promotions.
336 QualType PTy = Context.isPromotableBitField(E);
337 if (!PTy.isNull()) {
338 ImpCastExprToType(E, PTy, CK_IntegralCast);
339 return E;
341 if (Ty->isPromotableIntegerType()) {
342 QualType PT = Context.getPromotedIntegerType(Ty);
343 ImpCastExprToType(E, PT, CK_IntegralCast);
344 return E;
348 return E;
351 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
352 /// do not have a prototype. Arguments that have type float are promoted to
353 /// double. All other argument types are converted by UsualUnaryConversions().
354 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
355 QualType Ty = Expr->getType();
356 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
358 UsualUnaryConversions(Expr);
360 // If this is a 'float' (CVR qualified or typedef) promote to double.
361 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
362 return ImpCastExprToType(Expr, Context.DoubleTy, CK_FloatingCast);
365 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
366 /// will warn if the resulting type is not a POD type, and rejects ObjC
367 /// interfaces passed by value. This returns true if the argument type is
368 /// completely illegal.
369 bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
370 FunctionDecl *FDecl) {
371 DefaultArgumentPromotion(Expr);
373 // __builtin_va_start takes the second argument as a "varargs" argument, but
374 // it doesn't actually do anything with it. It doesn't need to be non-pod
375 // etc.
376 if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
377 return false;
379 if (Expr->getType()->isObjCObjectType() &&
380 DiagRuntimeBehavior(Expr->getLocStart(),
381 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
382 << Expr->getType() << CT))
383 return true;
385 if (!Expr->getType()->isPODType() &&
386 DiagRuntimeBehavior(Expr->getLocStart(),
387 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
388 << Expr->getType() << CT))
389 return true;
391 return false;
394 /// UsualArithmeticConversions - Performs various conversions that are common to
395 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
396 /// routine returns the first non-arithmetic type found. The client is
397 /// responsible for emitting appropriate error diagnostics.
398 /// FIXME: verify the conversion rules for "complex int" are consistent with
399 /// GCC.
400 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
401 bool isCompAssign) {
402 if (!isCompAssign)
403 UsualUnaryConversions(lhsExpr);
405 UsualUnaryConversions(rhsExpr);
407 // For conversion purposes, we ignore any qualifiers.
408 // For example, "const float" and "float" are equivalent.
409 QualType lhs =
410 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
411 QualType rhs =
412 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
414 // If both types are identical, no conversion is needed.
415 if (lhs == rhs)
416 return lhs;
418 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
419 // The caller can deal with this (e.g. pointer + int).
420 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
421 return lhs;
423 // Apply unary and bitfield promotions to the LHS's type.
424 QualType lhs_unpromoted = lhs;
425 if (lhs->isPromotableIntegerType())
426 lhs = Context.getPromotedIntegerType(lhs);
427 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
428 if (!LHSBitfieldPromoteTy.isNull())
429 lhs = LHSBitfieldPromoteTy;
430 if (lhs != lhs_unpromoted && !isCompAssign)
431 ImpCastExprToType(lhsExpr, lhs, CK_IntegralCast);
433 // If both types are identical, no conversion is needed.
434 if (lhs == rhs)
435 return lhs;
437 // At this point, we have two different arithmetic types.
439 // Handle complex types first (C99 6.3.1.8p1).
440 bool LHSComplexFloat = lhs->isComplexType();
441 bool RHSComplexFloat = rhs->isComplexType();
442 if (LHSComplexFloat || RHSComplexFloat) {
443 // if we have an integer operand, the result is the complex type.
445 if (!RHSComplexFloat && !rhs->isRealFloatingType()) {
446 if (rhs->isIntegerType()) {
447 QualType fp = cast<ComplexType>(lhs)->getElementType();
448 ImpCastExprToType(rhsExpr, fp, CK_IntegralToFloating);
449 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
450 } else {
451 assert(rhs->isComplexIntegerType());
452 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexToFloatingComplex);
454 return lhs;
457 if (!LHSComplexFloat && !lhs->isRealFloatingType()) {
458 if (!isCompAssign) {
459 // int -> float -> _Complex float
460 if (lhs->isIntegerType()) {
461 QualType fp = cast<ComplexType>(rhs)->getElementType();
462 ImpCastExprToType(lhsExpr, fp, CK_IntegralToFloating);
463 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
464 } else {
465 assert(lhs->isComplexIntegerType());
466 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexToFloatingComplex);
469 return rhs;
472 // This handles complex/complex, complex/float, or float/complex.
473 // When both operands are complex, the shorter operand is converted to the
474 // type of the longer, and that is the type of the result. This corresponds
475 // to what is done when combining two real floating-point operands.
476 // The fun begins when size promotion occur across type domains.
477 // From H&S 6.3.4: When one operand is complex and the other is a real
478 // floating-point type, the less precise type is converted, within it's
479 // real or complex domain, to the precision of the other type. For example,
480 // when combining a "long double" with a "double _Complex", the
481 // "double _Complex" is promoted to "long double _Complex".
482 int order = Context.getFloatingTypeOrder(lhs, rhs);
484 // If both are complex, just cast to the more precise type.
485 if (LHSComplexFloat && RHSComplexFloat) {
486 if (order > 0) {
487 // _Complex float -> _Complex double
488 ImpCastExprToType(rhsExpr, lhs, CK_FloatingComplexCast);
489 return lhs;
491 } else if (order < 0) {
492 // _Complex float -> _Complex double
493 if (!isCompAssign)
494 ImpCastExprToType(lhsExpr, rhs, CK_FloatingComplexCast);
495 return rhs;
497 return lhs;
500 // If just the LHS is complex, the RHS needs to be converted,
501 // and the LHS might need to be promoted.
502 if (LHSComplexFloat) {
503 if (order > 0) { // LHS is wider
504 // float -> _Complex double
505 QualType fp = cast<ComplexType>(lhs)->getElementType();
506 ImpCastExprToType(rhsExpr, fp, CK_FloatingCast);
507 ImpCastExprToType(rhsExpr, lhs, CK_FloatingRealToComplex);
508 return lhs;
511 // RHS is at least as wide. Find its corresponding complex type.
512 QualType result = (order == 0 ? lhs : Context.getComplexType(rhs));
514 // double -> _Complex double
515 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
517 // _Complex float -> _Complex double
518 if (!isCompAssign && order < 0)
519 ImpCastExprToType(lhsExpr, result, CK_FloatingComplexCast);
521 return result;
524 // Just the RHS is complex, so the LHS needs to be converted
525 // and the RHS might need to be promoted.
526 assert(RHSComplexFloat);
528 if (order < 0) { // RHS is wider
529 // float -> _Complex double
530 if (!isCompAssign) {
531 QualType fp = cast<ComplexType>(rhs)->getElementType();
532 ImpCastExprToType(lhsExpr, fp, CK_FloatingCast);
533 ImpCastExprToType(lhsExpr, rhs, CK_FloatingRealToComplex);
535 return rhs;
538 // LHS is at least as wide. Find its corresponding complex type.
539 QualType result = (order == 0 ? rhs : Context.getComplexType(lhs));
541 // double -> _Complex double
542 if (!isCompAssign)
543 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
545 // _Complex float -> _Complex double
546 if (order > 0)
547 ImpCastExprToType(rhsExpr, result, CK_FloatingComplexCast);
549 return result;
552 // Now handle "real" floating types (i.e. float, double, long double).
553 bool LHSFloat = lhs->isRealFloatingType();
554 bool RHSFloat = rhs->isRealFloatingType();
555 if (LHSFloat || RHSFloat) {
556 // If we have two real floating types, convert the smaller operand
557 // to the bigger result.
558 if (LHSFloat && RHSFloat) {
559 int order = Context.getFloatingTypeOrder(lhs, rhs);
560 if (order > 0) {
561 ImpCastExprToType(rhsExpr, lhs, CK_FloatingCast);
562 return lhs;
565 assert(order < 0 && "illegal float comparison");
566 if (!isCompAssign)
567 ImpCastExprToType(lhsExpr, rhs, CK_FloatingCast);
568 return rhs;
571 // If we have an integer operand, the result is the real floating type.
572 if (LHSFloat) {
573 if (rhs->isIntegerType()) {
574 // Convert rhs to the lhs floating point type.
575 ImpCastExprToType(rhsExpr, lhs, CK_IntegralToFloating);
576 return lhs;
579 // Convert both sides to the appropriate complex float.
580 assert(rhs->isComplexIntegerType());
581 QualType result = Context.getComplexType(lhs);
583 // _Complex int -> _Complex float
584 ImpCastExprToType(rhsExpr, result, CK_IntegralComplexToFloatingComplex);
586 // float -> _Complex float
587 if (!isCompAssign)
588 ImpCastExprToType(lhsExpr, result, CK_FloatingRealToComplex);
590 return result;
593 assert(RHSFloat);
594 if (lhs->isIntegerType()) {
595 // Convert lhs to the rhs floating point type.
596 if (!isCompAssign)
597 ImpCastExprToType(lhsExpr, rhs, CK_IntegralToFloating);
598 return rhs;
601 // Convert both sides to the appropriate complex float.
602 assert(lhs->isComplexIntegerType());
603 QualType result = Context.getComplexType(rhs);
605 // _Complex int -> _Complex float
606 if (!isCompAssign)
607 ImpCastExprToType(lhsExpr, result, CK_IntegralComplexToFloatingComplex);
609 // float -> _Complex float
610 ImpCastExprToType(rhsExpr, result, CK_FloatingRealToComplex);
612 return result;
615 // Handle GCC complex int extension.
616 // FIXME: if the operands are (int, _Complex long), we currently
617 // don't promote the complex. Also, signedness?
618 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
619 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
620 if (lhsComplexInt && rhsComplexInt) {
621 int order = Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
622 rhsComplexInt->getElementType());
623 assert(order && "inequal types with equal element ordering");
624 if (order > 0) {
625 // _Complex int -> _Complex long
626 ImpCastExprToType(rhsExpr, lhs, CK_IntegralComplexCast);
627 return lhs;
630 if (!isCompAssign)
631 ImpCastExprToType(lhsExpr, rhs, CK_IntegralComplexCast);
632 return rhs;
633 } else if (lhsComplexInt) {
634 // int -> _Complex int
635 ImpCastExprToType(rhsExpr, lhs, CK_IntegralRealToComplex);
636 return lhs;
637 } else if (rhsComplexInt) {
638 // int -> _Complex int
639 if (!isCompAssign)
640 ImpCastExprToType(lhsExpr, rhs, CK_IntegralRealToComplex);
641 return rhs;
644 // Finally, we have two differing integer types.
645 // The rules for this case are in C99 6.3.1.8
646 int compare = Context.getIntegerTypeOrder(lhs, rhs);
647 bool lhsSigned = lhs->hasSignedIntegerRepresentation(),
648 rhsSigned = rhs->hasSignedIntegerRepresentation();
649 if (lhsSigned == rhsSigned) {
650 // Same signedness; use the higher-ranked type
651 if (compare >= 0) {
652 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
653 return lhs;
654 } else if (!isCompAssign)
655 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
656 return rhs;
657 } else if (compare != (lhsSigned ? 1 : -1)) {
658 // The unsigned type has greater than or equal rank to the
659 // signed type, so use the unsigned type
660 if (rhsSigned) {
661 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
662 return lhs;
663 } else if (!isCompAssign)
664 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
665 return rhs;
666 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
667 // The two types are different widths; if we are here, that
668 // means the signed type is larger than the unsigned type, so
669 // use the signed type.
670 if (lhsSigned) {
671 ImpCastExprToType(rhsExpr, lhs, CK_IntegralCast);
672 return lhs;
673 } else if (!isCompAssign)
674 ImpCastExprToType(lhsExpr, rhs, CK_IntegralCast);
675 return rhs;
676 } else {
677 // The signed type is higher-ranked than the unsigned type,
678 // but isn't actually any bigger (like unsigned int and long
679 // on most 32-bit systems). Use the unsigned type corresponding
680 // to the signed type.
681 QualType result =
682 Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
683 ImpCastExprToType(rhsExpr, result, CK_IntegralCast);
684 if (!isCompAssign)
685 ImpCastExprToType(lhsExpr, result, CK_IntegralCast);
686 return result;
690 //===----------------------------------------------------------------------===//
691 // Semantic Analysis for various Expression Types
692 //===----------------------------------------------------------------------===//
695 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
696 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
697 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
698 /// multiple tokens. However, the common case is that StringToks points to one
699 /// string.
701 ExprResult
702 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
703 assert(NumStringToks && "Must have at least one string!");
705 StringLiteralParser Literal(StringToks, NumStringToks, PP);
706 if (Literal.hadError)
707 return ExprError();
709 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
710 for (unsigned i = 0; i != NumStringToks; ++i)
711 StringTokLocs.push_back(StringToks[i].getLocation());
713 QualType StrTy = Context.CharTy;
714 if (Literal.AnyWide) StrTy = Context.getWCharType();
715 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
717 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
718 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
719 StrTy.addConst();
721 // Get an array type for the string, according to C99 6.4.5. This includes
722 // the nul terminator character as well as the string length for pascal
723 // strings.
724 StrTy = Context.getConstantArrayType(StrTy,
725 llvm::APInt(32, Literal.GetNumStringChars()+1),
726 ArrayType::Normal, 0);
728 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
729 return Owned(StringLiteral::Create(Context, Literal.GetString(),
730 Literal.GetStringLength(),
731 Literal.AnyWide, StrTy,
732 &StringTokLocs[0],
733 StringTokLocs.size()));
736 enum CaptureResult {
737 /// No capture is required.
738 CR_NoCapture,
740 /// A capture is required.
741 CR_Capture,
743 /// A by-ref capture is required.
744 CR_CaptureByRef,
746 /// An error occurred when trying to capture the given variable.
747 CR_Error
750 /// Diagnose an uncapturable value reference.
752 /// \param var - the variable referenced
753 /// \param DC - the context which we couldn't capture through
754 static CaptureResult
755 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
756 VarDecl *var, DeclContext *DC) {
757 switch (S.ExprEvalContexts.back().Context) {
758 case Sema::Unevaluated:
759 // The argument will never be evaluated, so don't complain.
760 return CR_NoCapture;
762 case Sema::PotentiallyEvaluated:
763 case Sema::PotentiallyEvaluatedIfUsed:
764 break;
766 case Sema::PotentiallyPotentiallyEvaluated:
767 // FIXME: delay these!
768 break;
771 // Don't diagnose about capture if we're not actually in code right
772 // now; in general, there are more appropriate places that will
773 // diagnose this.
774 if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
776 // This particular madness can happen in ill-formed default
777 // arguments; claim it's okay and let downstream code handle it.
778 if (isa<ParmVarDecl>(var) &&
779 S.CurContext == var->getDeclContext()->getParent())
780 return CR_NoCapture;
782 DeclarationName functionName;
783 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
784 functionName = fn->getDeclName();
785 // FIXME: variable from enclosing block that we couldn't capture from!
787 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
788 << var->getIdentifier() << functionName;
789 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
790 << var->getIdentifier();
792 return CR_Error;
795 /// There is a well-formed capture at a particular scope level;
796 /// propagate it through all the nested blocks.
797 static CaptureResult propagateCapture(Sema &S, unsigned validScopeIndex,
798 const BlockDecl::Capture &capture) {
799 VarDecl *var = capture.getVariable();
801 // Update all the inner blocks with the capture information.
802 for (unsigned i = validScopeIndex + 1, e = S.FunctionScopes.size();
803 i != e; ++i) {
804 BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
805 innerBlock->Captures.push_back(
806 BlockDecl::Capture(capture.getVariable(), capture.isByRef(),
807 /*nested*/ true, capture.getCopyExpr()));
808 innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
811 return capture.isByRef() ? CR_CaptureByRef : CR_Capture;
814 /// shouldCaptureValueReference - Determine if a reference to the
815 /// given value in the current context requires a variable capture.
817 /// This also keeps the captures set in the BlockScopeInfo records
818 /// up-to-date.
819 static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
820 ValueDecl *value) {
821 // Only variables ever require capture.
822 VarDecl *var = dyn_cast<VarDecl>(value);
823 if (!var) return CR_NoCapture;
825 // Fast path: variables from the current context never require capture.
826 DeclContext *DC = S.CurContext;
827 if (var->getDeclContext() == DC) return CR_NoCapture;
829 // Only variables with local storage require capture.
830 // FIXME: What about 'const' variables in C++?
831 if (!var->hasLocalStorage()) return CR_NoCapture;
833 // Otherwise, we need to capture.
835 unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
836 do {
837 // Only blocks (and eventually C++0x closures) can capture; other
838 // scopes don't work.
839 if (!isa<BlockDecl>(DC))
840 return diagnoseUncapturableValueReference(S, loc, var, DC);
842 BlockScopeInfo *blockScope =
843 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
844 assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
846 // Check whether we've already captured it in this block. If so,
847 // we're done.
848 if (unsigned indexPlus1 = blockScope->CaptureMap[var])
849 return propagateCapture(S, functionScopesIndex,
850 blockScope->Captures[indexPlus1 - 1]);
852 functionScopesIndex--;
853 DC = cast<BlockDecl>(DC)->getDeclContext();
854 } while (var->getDeclContext() != DC);
856 // Okay, we descended all the way to the block that defines the variable.
857 // Actually try to capture it.
858 QualType type = var->getType();
860 // Prohibit variably-modified types.
861 if (type->isVariablyModifiedType()) {
862 S.Diag(loc, diag::err_ref_vm_type);
863 S.Diag(var->getLocation(), diag::note_declared_at);
864 return CR_Error;
867 // Prohibit arrays, even in __block variables, but not references to
868 // them.
869 if (type->isArrayType()) {
870 S.Diag(loc, diag::err_ref_array_type);
871 S.Diag(var->getLocation(), diag::note_declared_at);
872 return CR_Error;
875 S.MarkDeclarationReferenced(loc, var);
877 // The BlocksAttr indicates the variable is bound by-reference.
878 bool byRef = var->hasAttr<BlocksAttr>();
880 // Build a copy expression.
881 Expr *copyExpr = 0;
882 if (!byRef && S.getLangOptions().CPlusPlus &&
883 !type->isDependentType() && type->isStructureOrClassType()) {
884 // According to the blocks spec, the capture of a variable from
885 // the stack requires a const copy constructor. This is not true
886 // of the copy/move done to move a __block variable to the heap.
887 type.addConst();
889 Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
890 ExprResult result =
891 S.PerformCopyInitialization(
892 InitializedEntity::InitializeBlock(var->getLocation(),
893 type, false),
894 loc, S.Owned(declRef));
896 // Build a full-expression copy expression if initialization
897 // succeeded and used a non-trivial constructor. Recover from
898 // errors by pretending that the copy isn't necessary.
899 if (!result.isInvalid() &&
900 !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
901 result = S.MaybeCreateExprWithCleanups(result);
902 copyExpr = result.take();
906 // We're currently at the declarer; go back to the closure.
907 functionScopesIndex++;
908 BlockScopeInfo *blockScope =
909 cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
911 // Build a valid capture in this scope.
912 blockScope->Captures.push_back(
913 BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
914 blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
916 // Propagate that to inner captures if necessary.
917 return propagateCapture(S, functionScopesIndex,
918 blockScope->Captures.back());
921 static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *vd,
922 const DeclarationNameInfo &NameInfo,
923 bool byRef) {
924 assert(isa<VarDecl>(vd) && "capturing non-variable");
926 VarDecl *var = cast<VarDecl>(vd);
927 assert(var->hasLocalStorage() && "capturing non-local");
928 assert(byRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
930 QualType exprType = var->getType().getNonReferenceType();
932 BlockDeclRefExpr *BDRE;
933 if (!byRef) {
934 // The variable will be bound by copy; make it const within the
935 // closure, but record that this was done in the expression.
936 bool constAdded = !exprType.isConstQualified();
937 exprType.addConst();
939 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
940 NameInfo.getLoc(), false,
941 constAdded);
942 } else {
943 BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
944 NameInfo.getLoc(), true);
947 return S.Owned(BDRE);
950 ExprResult
951 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
952 SourceLocation Loc,
953 const CXXScopeSpec *SS) {
954 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
955 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
958 /// BuildDeclRefExpr - Build an expression that references a
959 /// declaration that does not require a closure capture.
960 ExprResult
961 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
962 const DeclarationNameInfo &NameInfo,
963 const CXXScopeSpec *SS) {
964 if (Ty == Context.UndeducedAutoTy) {
965 Diag(NameInfo.getLoc(),
966 diag::err_auto_variable_cannot_appear_in_own_initializer)
967 << D->getDeclName();
968 return ExprError();
971 MarkDeclarationReferenced(NameInfo.getLoc(), D);
973 Expr *E = DeclRefExpr::Create(Context,
974 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
975 SS? SS->getRange() : SourceRange(),
976 D, NameInfo, Ty, VK);
978 // Just in case we're building an illegal pointer-to-member.
979 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
980 E->setObjectKind(OK_BitField);
982 return Owned(E);
985 static ExprResult
986 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
987 const CXXScopeSpec &SS, FieldDecl *Field,
988 DeclAccessPair FoundDecl,
989 const DeclarationNameInfo &MemberNameInfo);
991 ExprResult
992 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
993 SourceLocation loc,
994 IndirectFieldDecl *indirectField,
995 Expr *baseObjectExpr,
996 SourceLocation opLoc) {
997 // First, build the expression that refers to the base object.
999 bool baseObjectIsPointer = false;
1000 Qualifiers baseQuals;
1002 // Case 1: the base of the indirect field is not a field.
1003 VarDecl *baseVariable = indirectField->getVarDecl();
1004 if (baseVariable) {
1005 assert(baseVariable->getType()->isRecordType());
1007 // In principle we could have a member access expression that
1008 // accesses an anonymous struct/union that's a static member of
1009 // the base object's class. However, under the current standard,
1010 // static data members cannot be anonymous structs or unions.
1011 // Supporting this is as easy as building a MemberExpr here.
1012 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
1014 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
1016 ExprResult result =
1017 BuildDeclarationNameExpr(SS, baseNameInfo, baseVariable);
1018 if (result.isInvalid()) return ExprError();
1020 baseObjectExpr = result.take();
1021 baseObjectIsPointer = false;
1022 baseQuals = baseObjectExpr->getType().getQualifiers();
1024 // Case 2: the base of the indirect field is a field and the user
1025 // wrote a member expression.
1026 } else if (baseObjectExpr) {
1027 // The caller provided the base object expression. Determine
1028 // whether its a pointer and whether it adds any qualifiers to the
1029 // anonymous struct/union fields we're looking into.
1030 QualType objectType = baseObjectExpr->getType();
1032 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
1033 baseObjectIsPointer = true;
1034 objectType = ptr->getPointeeType();
1035 } else {
1036 baseObjectIsPointer = false;
1038 baseQuals = objectType.getQualifiers();
1040 // Case 3: the base of the indirect field is a field and we should
1041 // build an implicit member access.
1042 } else {
1043 // We've found a member of an anonymous struct/union that is
1044 // inside a non-anonymous struct/union, so in a well-formed
1045 // program our base object expression is "this".
1046 CXXMethodDecl *method = tryCaptureCXXThis();
1047 if (!method) {
1048 Diag(loc, diag::err_invalid_member_use_in_static_method)
1049 << indirectField->getDeclName();
1050 return ExprError();
1053 // Our base object expression is "this".
1054 baseObjectExpr =
1055 new (Context) CXXThisExpr(loc, method->getThisType(Context),
1056 /*isImplicit=*/ true);
1057 baseObjectIsPointer = true;
1058 baseQuals = Qualifiers::fromCVRMask(method->getTypeQualifiers());
1061 // Build the implicit member references to the field of the
1062 // anonymous struct/union.
1063 Expr *result = baseObjectExpr;
1064 IndirectFieldDecl::chain_iterator
1065 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
1067 // Build the first member access in the chain with full information.
1068 if (!baseVariable) {
1069 FieldDecl *field = cast<FieldDecl>(*FI);
1071 // FIXME: use the real found-decl info!
1072 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1074 // Make a nameInfo that properly uses the anonymous name.
1075 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1077 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
1078 SS, field, foundDecl,
1079 memberNameInfo).take();
1080 baseObjectIsPointer = false;
1082 // FIXME: check qualified member access
1085 // In all cases, we should now skip the first declaration in the chain.
1086 ++FI;
1088 for (; FI != FEnd; FI++) {
1089 FieldDecl *field = cast<FieldDecl>(*FI);
1091 // FIXME: these are somewhat meaningless
1092 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
1093 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
1094 CXXScopeSpec memberSS;
1096 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
1097 memberSS, field, foundDecl, memberNameInfo)
1098 .take();
1101 return Owned(result);
1104 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1105 /// possibly a list of template arguments.
1107 /// If this produces template arguments, it is permitted to call
1108 /// DecomposeTemplateName.
1110 /// This actually loses a lot of source location information for
1111 /// non-standard name kinds; we should consider preserving that in
1112 /// some way.
1113 static void DecomposeUnqualifiedId(Sema &SemaRef,
1114 const UnqualifiedId &Id,
1115 TemplateArgumentListInfo &Buffer,
1116 DeclarationNameInfo &NameInfo,
1117 const TemplateArgumentListInfo *&TemplateArgs) {
1118 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1119 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1120 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1122 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
1123 Id.TemplateId->getTemplateArgs(),
1124 Id.TemplateId->NumArgs);
1125 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
1126 TemplateArgsPtr.release();
1128 TemplateName TName = Id.TemplateId->Template.get();
1129 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1130 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
1131 TemplateArgs = &Buffer;
1132 } else {
1133 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
1134 TemplateArgs = 0;
1138 /// Determines if the given class is provably not derived from all of
1139 /// the prospective base classes.
1140 static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1141 CXXRecordDecl *Record,
1142 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
1143 if (Bases.count(Record->getCanonicalDecl()))
1144 return false;
1146 RecordDecl *RD = Record->getDefinition();
1147 if (!RD) return false;
1148 Record = cast<CXXRecordDecl>(RD);
1150 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1151 E = Record->bases_end(); I != E; ++I) {
1152 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1153 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1154 if (!BaseRT) return false;
1156 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
1157 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1158 return false;
1161 return true;
1164 enum IMAKind {
1165 /// The reference is definitely not an instance member access.
1166 IMA_Static,
1168 /// The reference may be an implicit instance member access.
1169 IMA_Mixed,
1171 /// The reference may be to an instance member, but it is invalid if
1172 /// so, because the context is not an instance method.
1173 IMA_Mixed_StaticContext,
1175 /// The reference may be to an instance member, but it is invalid if
1176 /// so, because the context is from an unrelated class.
1177 IMA_Mixed_Unrelated,
1179 /// The reference is definitely an implicit instance member access.
1180 IMA_Instance,
1182 /// The reference may be to an unresolved using declaration.
1183 IMA_Unresolved,
1185 /// The reference may be to an unresolved using declaration and the
1186 /// context is not an instance method.
1187 IMA_Unresolved_StaticContext,
1189 /// All possible referrents are instance members and the current
1190 /// context is not an instance method.
1191 IMA_Error_StaticContext,
1193 /// All possible referrents are instance members of an unrelated
1194 /// class.
1195 IMA_Error_Unrelated
1198 /// The given lookup names class member(s) and is not being used for
1199 /// an address-of-member expression. Classify the type of access
1200 /// according to whether it's possible that this reference names an
1201 /// instance member. This is best-effort; it is okay to
1202 /// conservatively answer "yes", in which case some errors will simply
1203 /// not be caught until template-instantiation.
1204 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1205 const LookupResult &R) {
1206 assert(!R.empty() && (*R.begin())->isCXXClassMember());
1208 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
1209 bool isStaticContext =
1210 (!isa<CXXMethodDecl>(DC) ||
1211 cast<CXXMethodDecl>(DC)->isStatic());
1213 if (R.isUnresolvableResult())
1214 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1216 // Collect all the declaring classes of instance members we find.
1217 bool hasNonInstance = false;
1218 bool hasField = false;
1219 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1220 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1221 NamedDecl *D = *I;
1223 if (D->isCXXInstanceMember()) {
1224 if (dyn_cast<FieldDecl>(D))
1225 hasField = true;
1227 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
1228 Classes.insert(R->getCanonicalDecl());
1230 else
1231 hasNonInstance = true;
1234 // If we didn't find any instance members, it can't be an implicit
1235 // member reference.
1236 if (Classes.empty())
1237 return IMA_Static;
1239 // If the current context is not an instance method, it can't be
1240 // an implicit member reference.
1241 if (isStaticContext) {
1242 if (hasNonInstance)
1243 return IMA_Mixed_StaticContext;
1245 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1246 // C++0x [expr.prim.general]p10:
1247 // An id-expression that denotes a non-static data member or non-static
1248 // member function of a class can only be used:
1249 // (...)
1250 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1251 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1252 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1253 if (isUnevaluatedExpression)
1254 return IMA_Mixed_StaticContext;
1257 return IMA_Error_StaticContext;
1260 // If we can prove that the current context is unrelated to all the
1261 // declaring classes, it can't be an implicit member reference (in
1262 // which case it's an error if any of those members are selected).
1263 if (IsProvablyNotDerivedFrom(SemaRef,
1264 cast<CXXMethodDecl>(DC)->getParent(),
1265 Classes))
1266 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1268 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1271 /// Diagnose a reference to a field with no object available.
1272 static void DiagnoseInstanceReference(Sema &SemaRef,
1273 const CXXScopeSpec &SS,
1274 NamedDecl *rep,
1275 const DeclarationNameInfo &nameInfo) {
1276 SourceLocation Loc = nameInfo.getLoc();
1277 SourceRange Range(Loc);
1278 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1280 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
1281 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1282 if (MD->isStatic()) {
1283 // "invalid use of member 'x' in static member function"
1284 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1285 << Range << nameInfo.getName();
1286 return;
1290 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1291 << nameInfo.getName() << Range;
1292 return;
1295 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
1298 /// Diagnose an empty lookup.
1300 /// \return false if new lookup candidates were found
1301 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1302 CorrectTypoContext CTC) {
1303 DeclarationName Name = R.getLookupName();
1305 unsigned diagnostic = diag::err_undeclared_var_use;
1306 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1307 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1308 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1309 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1310 diagnostic = diag::err_undeclared_use;
1311 diagnostic_suggest = diag::err_undeclared_use_suggest;
1314 // If the original lookup was an unqualified lookup, fake an
1315 // unqualified lookup. This is useful when (for example) the
1316 // original lookup would not have found something because it was a
1317 // dependent name.
1318 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1319 DC; DC = DC->getParent()) {
1320 if (isa<CXXRecordDecl>(DC)) {
1321 LookupQualifiedName(R, DC);
1323 if (!R.empty()) {
1324 // Don't give errors about ambiguities in this lookup.
1325 R.suppressDiagnostics();
1327 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1328 bool isInstance = CurMethod &&
1329 CurMethod->isInstance() &&
1330 DC == CurMethod->getParent();
1332 // Give a code modification hint to insert 'this->'.
1333 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1334 // Actually quite difficult!
1335 if (isInstance) {
1336 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1337 CallsUndergoingInstantiation.back()->getCallee());
1338 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
1339 CurMethod->getInstantiatedFromMemberFunction());
1340 if (DepMethod) {
1341 Diag(R.getNameLoc(), diagnostic) << Name
1342 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1343 QualType DepThisType = DepMethod->getThisType(Context);
1344 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1345 R.getNameLoc(), DepThisType, false);
1346 TemplateArgumentListInfo TList;
1347 if (ULE->hasExplicitTemplateArgs())
1348 ULE->copyTemplateArgumentsInto(TList);
1349 CXXDependentScopeMemberExpr *DepExpr =
1350 CXXDependentScopeMemberExpr::Create(
1351 Context, DepThis, DepThisType, true, SourceLocation(),
1352 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1353 R.getLookupNameInfo(), &TList);
1354 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1355 } else {
1356 // FIXME: we should be able to handle this case too. It is correct
1357 // to add this-> here. This is a workaround for PR7947.
1358 Diag(R.getNameLoc(), diagnostic) << Name;
1360 } else {
1361 Diag(R.getNameLoc(), diagnostic) << Name;
1364 // Do we really want to note all of these?
1365 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1366 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1368 // Tell the callee to try to recover.
1369 return false;
1372 R.clear();
1376 // We didn't find anything, so try to correct for a typo.
1377 DeclarationName Corrected;
1378 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
1379 if (!R.empty()) {
1380 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1381 if (SS.isEmpty())
1382 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1383 << FixItHint::CreateReplacement(R.getNameLoc(),
1384 R.getLookupName().getAsString());
1385 else
1386 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1387 << Name << computeDeclContext(SS, false) << R.getLookupName()
1388 << SS.getRange()
1389 << FixItHint::CreateReplacement(R.getNameLoc(),
1390 R.getLookupName().getAsString());
1391 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1392 Diag(ND->getLocation(), diag::note_previous_decl)
1393 << ND->getDeclName();
1395 // Tell the callee to try to recover.
1396 return false;
1399 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1400 // FIXME: If we ended up with a typo for a type name or
1401 // Objective-C class name, we're in trouble because the parser
1402 // is in the wrong place to recover. Suggest the typo
1403 // correction, but don't make it a fix-it since we're not going
1404 // to recover well anyway.
1405 if (SS.isEmpty())
1406 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1407 else
1408 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1409 << Name << computeDeclContext(SS, false) << R.getLookupName()
1410 << SS.getRange();
1412 // Don't try to recover; it won't work.
1413 return true;
1415 } else {
1416 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1417 // because we aren't able to recover.
1418 if (SS.isEmpty())
1419 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
1420 else
1421 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1422 << Name << computeDeclContext(SS, false) << Corrected
1423 << SS.getRange();
1424 return true;
1426 R.clear();
1429 // Emit a special diagnostic for failed member lookups.
1430 // FIXME: computing the declaration context might fail here (?)
1431 if (!SS.isEmpty()) {
1432 Diag(R.getNameLoc(), diag::err_no_member)
1433 << Name << computeDeclContext(SS, false)
1434 << SS.getRange();
1435 return true;
1438 // Give up, we can't recover.
1439 Diag(R.getNameLoc(), diagnostic) << Name;
1440 return true;
1443 ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1444 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1445 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1446 if (!IDecl)
1447 return 0;
1448 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1449 if (!ClassImpDecl)
1450 return 0;
1451 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
1452 if (!property)
1453 return 0;
1454 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1455 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1456 PIDecl->getPropertyIvarDecl())
1457 return 0;
1458 return property;
1461 bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1462 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1463 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1464 if (!IDecl)
1465 return false;
1466 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1467 if (!ClassImpDecl)
1468 return false;
1469 if (ObjCPropertyImplDecl *PIDecl
1470 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1471 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1472 PIDecl->getPropertyIvarDecl())
1473 return false;
1475 return true;
1478 static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
1479 LookupResult &Lookup,
1480 IdentifierInfo *II,
1481 SourceLocation NameLoc) {
1482 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1483 bool LookForIvars;
1484 if (Lookup.empty())
1485 LookForIvars = true;
1486 else if (CurMeth->isClassMethod())
1487 LookForIvars = false;
1488 else
1489 LookForIvars = (Lookup.isSingleResult() &&
1490 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1491 (Lookup.getAsSingle<VarDecl>() != 0));
1492 if (!LookForIvars)
1493 return 0;
1495 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1496 if (!IDecl)
1497 return 0;
1498 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1499 if (!ClassImpDecl)
1500 return 0;
1501 bool DynamicImplSeen = false;
1502 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1503 if (!property)
1504 return 0;
1505 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
1506 DynamicImplSeen =
1507 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1508 // property implementation has a designated ivar. No need to assume a new
1509 // one.
1510 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1511 return 0;
1513 if (!DynamicImplSeen) {
1514 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1515 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
1516 NameLoc,
1517 II, PropType, /*Dinfo=*/0,
1518 ObjCIvarDecl::Private,
1519 (Expr *)0, true);
1520 ClassImpDecl->addDecl(Ivar);
1521 IDecl->makeDeclVisibleInContext(Ivar, false);
1522 property->setPropertyIvarDecl(Ivar);
1523 return Ivar;
1525 return 0;
1528 ExprResult Sema::ActOnIdExpression(Scope *S,
1529 CXXScopeSpec &SS,
1530 UnqualifiedId &Id,
1531 bool HasTrailingLParen,
1532 bool isAddressOfOperand) {
1533 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1534 "cannot be direct & operand and have a trailing lparen");
1536 if (SS.isInvalid())
1537 return ExprError();
1539 TemplateArgumentListInfo TemplateArgsBuffer;
1541 // Decompose the UnqualifiedId into the following data.
1542 DeclarationNameInfo NameInfo;
1543 const TemplateArgumentListInfo *TemplateArgs;
1544 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1546 DeclarationName Name = NameInfo.getName();
1547 IdentifierInfo *II = Name.getAsIdentifierInfo();
1548 SourceLocation NameLoc = NameInfo.getLoc();
1550 // C++ [temp.dep.expr]p3:
1551 // An id-expression is type-dependent if it contains:
1552 // -- an identifier that was declared with a dependent type,
1553 // (note: handled after lookup)
1554 // -- a template-id that is dependent,
1555 // (note: handled in BuildTemplateIdExpr)
1556 // -- a conversion-function-id that specifies a dependent type,
1557 // -- a nested-name-specifier that contains a class-name that
1558 // names a dependent type.
1559 // Determine whether this is a member of an unknown specialization;
1560 // we need to handle these differently.
1561 bool DependentID = false;
1562 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1563 Name.getCXXNameType()->isDependentType()) {
1564 DependentID = true;
1565 } else if (SS.isSet()) {
1566 DeclContext *DC = computeDeclContext(SS, false);
1567 if (DC) {
1568 if (RequireCompleteDeclContext(SS, DC))
1569 return ExprError();
1570 } else {
1571 DependentID = true;
1575 if (DependentID) {
1576 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1577 TemplateArgs);
1579 bool IvarLookupFollowUp = false;
1580 // Perform the required lookup.
1581 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1582 if (TemplateArgs) {
1583 // Lookup the template name again to correctly establish the context in
1584 // which it was found. This is really unfortunate as we already did the
1585 // lookup to determine that it was a template name in the first place. If
1586 // this becomes a performance hit, we can work harder to preserve those
1587 // results until we get here but it's likely not worth it.
1588 bool MemberOfUnknownSpecialization;
1589 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1590 MemberOfUnknownSpecialization);
1592 if (MemberOfUnknownSpecialization ||
1593 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1594 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1595 TemplateArgs);
1596 } else {
1597 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1598 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1600 // If the result might be in a dependent base class, this is a dependent
1601 // id-expression.
1602 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1603 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1604 TemplateArgs);
1606 // If this reference is in an Objective-C method, then we need to do
1607 // some special Objective-C lookup, too.
1608 if (IvarLookupFollowUp) {
1609 ExprResult E(LookupInObjCMethod(R, S, II, true));
1610 if (E.isInvalid())
1611 return ExprError();
1613 Expr *Ex = E.takeAs<Expr>();
1614 if (Ex) return Owned(Ex);
1615 // Synthesize ivars lazily
1616 if (getLangOptions().ObjCDefaultSynthProperties &&
1617 getLangOptions().ObjCNonFragileABI2) {
1618 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1619 if (const ObjCPropertyDecl *Property =
1620 canSynthesizeProvisionalIvar(II)) {
1621 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1622 Diag(Property->getLocation(), diag::note_property_declare);
1624 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1625 isAddressOfOperand);
1628 // for further use, this must be set to false if in class method.
1629 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
1633 if (R.isAmbiguous())
1634 return ExprError();
1636 // Determine whether this name might be a candidate for
1637 // argument-dependent lookup.
1638 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1640 if (R.empty() && !ADL) {
1641 // Otherwise, this could be an implicitly declared function reference (legal
1642 // in C90, extension in C99, forbidden in C++).
1643 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1644 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1645 if (D) R.addDecl(D);
1648 // If this name wasn't predeclared and if this is not a function
1649 // call, diagnose the problem.
1650 if (R.empty()) {
1651 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1652 return ExprError();
1654 assert(!R.empty() &&
1655 "DiagnoseEmptyLookup returned false but added no results");
1657 // If we found an Objective-C instance variable, let
1658 // LookupInObjCMethod build the appropriate expression to
1659 // reference the ivar.
1660 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1661 R.clear();
1662 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1663 assert(E.isInvalid() || E.get());
1664 return move(E);
1669 // This is guaranteed from this point on.
1670 assert(!R.empty() || ADL);
1672 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
1673 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
1674 !(getLangOptions().ObjCDefaultSynthProperties &&
1675 getLangOptions().ObjCNonFragileABI2) &&
1676 Var->isFileVarDecl()) {
1677 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
1678 if (Property) {
1679 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1680 Diag(Property->getLocation(), diag::note_property_declare);
1681 Diag(Var->getLocation(), diag::note_global_declared_at);
1686 // Check whether this might be a C++ implicit instance member access.
1687 // C++ [class.mfct.non-static]p3:
1688 // When an id-expression that is not part of a class member access
1689 // syntax and not used to form a pointer to member is used in the
1690 // body of a non-static member function of class X, if name lookup
1691 // resolves the name in the id-expression to a non-static non-type
1692 // member of some class C, the id-expression is transformed into a
1693 // class member access expression using (*this) as the
1694 // postfix-expression to the left of the . operator.
1696 // But we don't actually need to do this for '&' operands if R
1697 // resolved to a function or overloaded function set, because the
1698 // expression is ill-formed if it actually works out to be a
1699 // non-static member function:
1701 // C++ [expr.ref]p4:
1702 // Otherwise, if E1.E2 refers to a non-static member function. . .
1703 // [t]he expression can be used only as the left-hand operand of a
1704 // member function call.
1706 // There are other safeguards against such uses, but it's important
1707 // to get this right here so that we don't end up making a
1708 // spuriously dependent expression if we're inside a dependent
1709 // instance method.
1710 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1711 bool MightBeImplicitMember;
1712 if (!isAddressOfOperand)
1713 MightBeImplicitMember = true;
1714 else if (!SS.isEmpty())
1715 MightBeImplicitMember = false;
1716 else if (R.isOverloadedResult())
1717 MightBeImplicitMember = false;
1718 else if (R.isUnresolvableResult())
1719 MightBeImplicitMember = true;
1720 else
1721 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1722 isa<IndirectFieldDecl>(R.getFoundDecl());
1724 if (MightBeImplicitMember)
1725 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1728 if (TemplateArgs)
1729 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1731 return BuildDeclarationNameExpr(SS, R, ADL);
1734 /// Builds an expression which might be an implicit member expression.
1735 ExprResult
1736 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1737 LookupResult &R,
1738 const TemplateArgumentListInfo *TemplateArgs) {
1739 switch (ClassifyImplicitMemberAccess(*this, R)) {
1740 case IMA_Instance:
1741 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1743 case IMA_Mixed:
1744 case IMA_Mixed_Unrelated:
1745 case IMA_Unresolved:
1746 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1748 case IMA_Static:
1749 case IMA_Mixed_StaticContext:
1750 case IMA_Unresolved_StaticContext:
1751 if (TemplateArgs)
1752 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1753 return BuildDeclarationNameExpr(SS, R, false);
1755 case IMA_Error_StaticContext:
1756 case IMA_Error_Unrelated:
1757 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
1758 R.getLookupNameInfo());
1759 return ExprError();
1762 llvm_unreachable("unexpected instance member access kind");
1763 return ExprError();
1766 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1767 /// declaration name, generally during template instantiation.
1768 /// There's a large number of things which don't need to be done along
1769 /// this path.
1770 ExprResult
1771 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1772 const DeclarationNameInfo &NameInfo) {
1773 DeclContext *DC;
1774 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1775 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
1777 if (RequireCompleteDeclContext(SS, DC))
1778 return ExprError();
1780 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1781 LookupQualifiedName(R, DC);
1783 if (R.isAmbiguous())
1784 return ExprError();
1786 if (R.empty()) {
1787 Diag(NameInfo.getLoc(), diag::err_no_member)
1788 << NameInfo.getName() << DC << SS.getRange();
1789 return ExprError();
1792 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1795 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1796 /// detected that we're currently inside an ObjC method. Perform some
1797 /// additional lookup.
1799 /// Ideally, most of this would be done by lookup, but there's
1800 /// actually quite a lot of extra work involved.
1802 /// Returns a null sentinel to indicate trivial success.
1803 ExprResult
1804 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1805 IdentifierInfo *II, bool AllowBuiltinCreation) {
1806 SourceLocation Loc = Lookup.getNameLoc();
1807 ObjCMethodDecl *CurMethod = getCurMethodDecl();
1809 // There are two cases to handle here. 1) scoped lookup could have failed,
1810 // in which case we should look for an ivar. 2) scoped lookup could have
1811 // found a decl, but that decl is outside the current instance method (i.e.
1812 // a global variable). In these two cases, we do a lookup for an ivar with
1813 // this name, if the lookup sucedes, we replace it our current decl.
1815 // If we're in a class method, we don't normally want to look for
1816 // ivars. But if we don't find anything else, and there's an
1817 // ivar, that's an error.
1818 bool IsClassMethod = CurMethod->isClassMethod();
1820 bool LookForIvars;
1821 if (Lookup.empty())
1822 LookForIvars = true;
1823 else if (IsClassMethod)
1824 LookForIvars = false;
1825 else
1826 LookForIvars = (Lookup.isSingleResult() &&
1827 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1828 ObjCInterfaceDecl *IFace = 0;
1829 if (LookForIvars) {
1830 IFace = CurMethod->getClassInterface();
1831 ObjCInterfaceDecl *ClassDeclared;
1832 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1833 // Diagnose using an ivar in a class method.
1834 if (IsClassMethod)
1835 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1836 << IV->getDeclName());
1838 // If we're referencing an invalid decl, just return this as a silent
1839 // error node. The error diagnostic was already emitted on the decl.
1840 if (IV->isInvalidDecl())
1841 return ExprError();
1843 // Check if referencing a field with __attribute__((deprecated)).
1844 if (DiagnoseUseOfDecl(IV, Loc))
1845 return ExprError();
1847 // Diagnose the use of an ivar outside of the declaring class.
1848 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1849 ClassDeclared != IFace)
1850 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1852 // FIXME: This should use a new expr for a direct reference, don't
1853 // turn this into Self->ivar, just return a BareIVarExpr or something.
1854 IdentifierInfo &II = Context.Idents.get("self");
1855 UnqualifiedId SelfName;
1856 SelfName.setIdentifier(&II, SourceLocation());
1857 CXXScopeSpec SelfScopeSpec;
1858 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1859 SelfName, false, false);
1860 if (SelfExpr.isInvalid())
1861 return ExprError();
1863 Expr *SelfE = SelfExpr.take();
1864 DefaultLvalueConversion(SelfE);
1866 MarkDeclarationReferenced(Loc, IV);
1867 return Owned(new (Context)
1868 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1869 SelfE, true, true));
1871 } else if (CurMethod->isInstanceMethod()) {
1872 // We should warn if a local variable hides an ivar.
1873 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
1874 ObjCInterfaceDecl *ClassDeclared;
1875 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1876 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1877 IFace == ClassDeclared)
1878 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1882 if (Lookup.empty() && II && AllowBuiltinCreation) {
1883 // FIXME. Consolidate this with similar code in LookupName.
1884 if (unsigned BuiltinID = II->getBuiltinID()) {
1885 if (!(getLangOptions().CPlusPlus &&
1886 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1887 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1888 S, Lookup.isForRedeclaration(),
1889 Lookup.getNameLoc());
1890 if (D) Lookup.addDecl(D);
1894 // Sentinel value saying that we didn't do anything special.
1895 return Owned((Expr*) 0);
1898 /// \brief Cast a base object to a member's actual type.
1900 /// Logically this happens in three phases:
1902 /// * First we cast from the base type to the naming class.
1903 /// The naming class is the class into which we were looking
1904 /// when we found the member; it's the qualifier type if a
1905 /// qualifier was provided, and otherwise it's the base type.
1907 /// * Next we cast from the naming class to the declaring class.
1908 /// If the member we found was brought into a class's scope by
1909 /// a using declaration, this is that class; otherwise it's
1910 /// the class declaring the member.
1912 /// * Finally we cast from the declaring class to the "true"
1913 /// declaring class of the member. This conversion does not
1914 /// obey access control.
1915 bool
1916 Sema::PerformObjectMemberConversion(Expr *&From,
1917 NestedNameSpecifier *Qualifier,
1918 NamedDecl *FoundDecl,
1919 NamedDecl *Member) {
1920 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1921 if (!RD)
1922 return false;
1924 QualType DestRecordType;
1925 QualType DestType;
1926 QualType FromRecordType;
1927 QualType FromType = From->getType();
1928 bool PointerConversions = false;
1929 if (isa<FieldDecl>(Member)) {
1930 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
1932 if (FromType->getAs<PointerType>()) {
1933 DestType = Context.getPointerType(DestRecordType);
1934 FromRecordType = FromType->getPointeeType();
1935 PointerConversions = true;
1936 } else {
1937 DestType = DestRecordType;
1938 FromRecordType = FromType;
1940 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1941 if (Method->isStatic())
1942 return false;
1944 DestType = Method->getThisType(Context);
1945 DestRecordType = DestType->getPointeeType();
1947 if (FromType->getAs<PointerType>()) {
1948 FromRecordType = FromType->getPointeeType();
1949 PointerConversions = true;
1950 } else {
1951 FromRecordType = FromType;
1952 DestType = DestRecordType;
1954 } else {
1955 // No conversion necessary.
1956 return false;
1959 if (DestType->isDependentType() || FromType->isDependentType())
1960 return false;
1962 // If the unqualified types are the same, no conversion is necessary.
1963 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1964 return false;
1966 SourceRange FromRange = From->getSourceRange();
1967 SourceLocation FromLoc = FromRange.getBegin();
1969 ExprValueKind VK = CastCategory(From);
1971 // C++ [class.member.lookup]p8:
1972 // [...] Ambiguities can often be resolved by qualifying a name with its
1973 // class name.
1975 // If the member was a qualified name and the qualified referred to a
1976 // specific base subobject type, we'll cast to that intermediate type
1977 // first and then to the object in which the member is declared. That allows
1978 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1980 // class Base { public: int x; };
1981 // class Derived1 : public Base { };
1982 // class Derived2 : public Base { };
1983 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1985 // void VeryDerived::f() {
1986 // x = 17; // error: ambiguous base subobjects
1987 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1988 // }
1989 if (Qualifier) {
1990 QualType QType = QualType(Qualifier->getAsType(), 0);
1991 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1992 assert(QType->isRecordType() && "lookup done with non-record type");
1994 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1996 // In C++98, the qualifier type doesn't actually have to be a base
1997 // type of the object type, in which case we just ignore it.
1998 // Otherwise build the appropriate casts.
1999 if (IsDerivedFrom(FromRecordType, QRecordType)) {
2000 CXXCastPath BasePath;
2001 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2002 FromLoc, FromRange, &BasePath))
2003 return true;
2005 if (PointerConversions)
2006 QType = Context.getPointerType(QType);
2007 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2008 VK, &BasePath);
2010 FromType = QType;
2011 FromRecordType = QRecordType;
2013 // If the qualifier type was the same as the destination type,
2014 // we're done.
2015 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2016 return false;
2020 bool IgnoreAccess = false;
2022 // If we actually found the member through a using declaration, cast
2023 // down to the using declaration's type.
2025 // Pointer equality is fine here because only one declaration of a
2026 // class ever has member declarations.
2027 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2028 assert(isa<UsingShadowDecl>(FoundDecl));
2029 QualType URecordType = Context.getTypeDeclType(
2030 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2032 // We only need to do this if the naming-class to declaring-class
2033 // conversion is non-trivial.
2034 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2035 assert(IsDerivedFrom(FromRecordType, URecordType));
2036 CXXCastPath BasePath;
2037 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2038 FromLoc, FromRange, &BasePath))
2039 return true;
2041 QualType UType = URecordType;
2042 if (PointerConversions)
2043 UType = Context.getPointerType(UType);
2044 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2045 VK, &BasePath);
2046 FromType = UType;
2047 FromRecordType = URecordType;
2050 // We don't do access control for the conversion from the
2051 // declaring class to the true declaring class.
2052 IgnoreAccess = true;
2055 CXXCastPath BasePath;
2056 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2057 FromLoc, FromRange, &BasePath,
2058 IgnoreAccess))
2059 return true;
2061 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2062 VK, &BasePath);
2063 return false;
2066 /// \brief Build a MemberExpr AST node.
2067 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
2068 const CXXScopeSpec &SS, ValueDecl *Member,
2069 DeclAccessPair FoundDecl,
2070 const DeclarationNameInfo &MemberNameInfo,
2071 QualType Ty,
2072 ExprValueKind VK, ExprObjectKind OK,
2073 const TemplateArgumentListInfo *TemplateArgs = 0) {
2074 NestedNameSpecifier *Qualifier = 0;
2075 SourceRange QualifierRange;
2076 if (SS.isSet()) {
2077 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
2078 QualifierRange = SS.getRange();
2081 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
2082 Member, FoundDecl, MemberNameInfo,
2083 TemplateArgs, Ty, VK, OK);
2086 static ExprResult
2087 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
2088 const CXXScopeSpec &SS, FieldDecl *Field,
2089 DeclAccessPair FoundDecl,
2090 const DeclarationNameInfo &MemberNameInfo) {
2091 // x.a is an l-value if 'a' has a reference type. Otherwise:
2092 // x.a is an l-value/x-value/pr-value if the base is (and note
2093 // that *x is always an l-value), except that if the base isn't
2094 // an ordinary object then we must have an rvalue.
2095 ExprValueKind VK = VK_LValue;
2096 ExprObjectKind OK = OK_Ordinary;
2097 if (!IsArrow) {
2098 if (BaseExpr->getObjectKind() == OK_Ordinary)
2099 VK = BaseExpr->getValueKind();
2100 else
2101 VK = VK_RValue;
2103 if (VK != VK_RValue && Field->isBitField())
2104 OK = OK_BitField;
2106 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2107 QualType MemberType = Field->getType();
2108 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
2109 MemberType = Ref->getPointeeType();
2110 VK = VK_LValue;
2111 } else {
2112 QualType BaseType = BaseExpr->getType();
2113 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2115 Qualifiers BaseQuals = BaseType.getQualifiers();
2117 // GC attributes are never picked up by members.
2118 BaseQuals.removeObjCGCAttr();
2120 // CVR attributes from the base are picked up by members,
2121 // except that 'mutable' members don't pick up 'const'.
2122 if (Field->isMutable()) BaseQuals.removeConst();
2124 Qualifiers MemberQuals
2125 = S.Context.getCanonicalType(MemberType).getQualifiers();
2127 // TR 18037 does not allow fields to be declared with address spaces.
2128 assert(!MemberQuals.hasAddressSpace());
2130 Qualifiers Combined = BaseQuals + MemberQuals;
2131 if (Combined != MemberQuals)
2132 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2135 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2136 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2137 FoundDecl, Field))
2138 return ExprError();
2139 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2140 Field, FoundDecl, MemberNameInfo,
2141 MemberType, VK, OK));
2144 /// Builds an implicit member access expression. The current context
2145 /// is known to be an instance method, and the given unqualified lookup
2146 /// set is known to contain only instance members, at least one of which
2147 /// is from an appropriate type.
2148 ExprResult
2149 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2150 LookupResult &R,
2151 const TemplateArgumentListInfo *TemplateArgs,
2152 bool IsKnownInstance) {
2153 assert(!R.empty() && !R.isAmbiguous());
2155 SourceLocation loc = R.getNameLoc();
2157 // We may have found a field within an anonymous union or struct
2158 // (C++ [class.union]).
2159 // FIXME: template-ids inside anonymous structs?
2160 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2161 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
2163 // If this is known to be an instance access, go ahead and build an
2164 // implicit 'this' expression now.
2165 // 'this' expression now.
2166 CXXMethodDecl *method = tryCaptureCXXThis();
2167 assert(method && "didn't correctly pre-flight capture of 'this'");
2169 QualType thisType = method->getThisType(Context);
2170 Expr *baseExpr = 0; // null signifies implicit access
2171 if (IsKnownInstance) {
2172 SourceLocation Loc = R.getNameLoc();
2173 if (SS.getRange().isValid())
2174 Loc = SS.getRange().getBegin();
2175 baseExpr = new (Context) CXXThisExpr(loc, thisType, /*isImplicit=*/true);
2178 return BuildMemberReferenceExpr(baseExpr, thisType,
2179 /*OpLoc*/ SourceLocation(),
2180 /*IsArrow*/ true,
2182 /*FirstQualifierInScope*/ 0,
2183 R, TemplateArgs);
2186 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2187 const LookupResult &R,
2188 bool HasTrailingLParen) {
2189 // Only when used directly as the postfix-expression of a call.
2190 if (!HasTrailingLParen)
2191 return false;
2193 // Never if a scope specifier was provided.
2194 if (SS.isSet())
2195 return false;
2197 // Only in C++ or ObjC++.
2198 if (!getLangOptions().CPlusPlus)
2199 return false;
2201 // Turn off ADL when we find certain kinds of declarations during
2202 // normal lookup:
2203 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2204 NamedDecl *D = *I;
2206 // C++0x [basic.lookup.argdep]p3:
2207 // -- a declaration of a class member
2208 // Since using decls preserve this property, we check this on the
2209 // original decl.
2210 if (D->isCXXClassMember())
2211 return false;
2213 // C++0x [basic.lookup.argdep]p3:
2214 // -- a block-scope function declaration that is not a
2215 // using-declaration
2216 // NOTE: we also trigger this for function templates (in fact, we
2217 // don't check the decl type at all, since all other decl types
2218 // turn off ADL anyway).
2219 if (isa<UsingShadowDecl>(D))
2220 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2221 else if (D->getDeclContext()->isFunctionOrMethod())
2222 return false;
2224 // C++0x [basic.lookup.argdep]p3:
2225 // -- a declaration that is neither a function or a function
2226 // template
2227 // And also for builtin functions.
2228 if (isa<FunctionDecl>(D)) {
2229 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2231 // But also builtin functions.
2232 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2233 return false;
2234 } else if (!isa<FunctionTemplateDecl>(D))
2235 return false;
2238 return true;
2242 /// Diagnoses obvious problems with the use of the given declaration
2243 /// as an expression. This is only actually called for lookups that
2244 /// were not overloaded, and it doesn't promise that the declaration
2245 /// will in fact be used.
2246 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2247 if (isa<TypedefDecl>(D)) {
2248 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2249 return true;
2252 if (isa<ObjCInterfaceDecl>(D)) {
2253 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2254 return true;
2257 if (isa<NamespaceDecl>(D)) {
2258 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2259 return true;
2262 return false;
2265 ExprResult
2266 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2267 LookupResult &R,
2268 bool NeedsADL) {
2269 // If this is a single, fully-resolved result and we don't need ADL,
2270 // just build an ordinary singleton decl ref.
2271 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2272 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2273 R.getFoundDecl());
2275 // We only need to check the declaration if there's exactly one
2276 // result, because in the overloaded case the results can only be
2277 // functions and function templates.
2278 if (R.isSingleResult() &&
2279 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2280 return ExprError();
2282 // Otherwise, just build an unresolved lookup expression. Suppress
2283 // any lookup-related diagnostics; we'll hash these out later, when
2284 // we've picked a target.
2285 R.suppressDiagnostics();
2287 UnresolvedLookupExpr *ULE
2288 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2289 (NestedNameSpecifier*) SS.getScopeRep(),
2290 SS.getRange(), R.getLookupNameInfo(),
2291 NeedsADL, R.isOverloadedResult(),
2292 R.begin(), R.end());
2294 return Owned(ULE);
2297 /// \brief Complete semantic analysis for a reference to the given declaration.
2298 ExprResult
2299 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2300 const DeclarationNameInfo &NameInfo,
2301 NamedDecl *D) {
2302 assert(D && "Cannot refer to a NULL declaration");
2303 assert(!isa<FunctionTemplateDecl>(D) &&
2304 "Cannot refer unambiguously to a function template");
2306 SourceLocation Loc = NameInfo.getLoc();
2307 if (CheckDeclInExpr(*this, Loc, D))
2308 return ExprError();
2310 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2311 // Specifically diagnose references to class templates that are missing
2312 // a template argument list.
2313 Diag(Loc, diag::err_template_decl_ref)
2314 << Template << SS.getRange();
2315 Diag(Template->getLocation(), diag::note_template_decl_here);
2316 return ExprError();
2319 // Make sure that we're referring to a value.
2320 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2321 if (!VD) {
2322 Diag(Loc, diag::err_ref_non_value)
2323 << D << SS.getRange();
2324 Diag(D->getLocation(), diag::note_declared_at);
2325 return ExprError();
2328 // Check whether this declaration can be used. Note that we suppress
2329 // this check when we're going to perform argument-dependent lookup
2330 // on this function name, because this might not be the function
2331 // that overload resolution actually selects.
2332 if (DiagnoseUseOfDecl(VD, Loc))
2333 return ExprError();
2335 // Only create DeclRefExpr's for valid Decl's.
2336 if (VD->isInvalidDecl())
2337 return ExprError();
2339 // Handle members of anonymous structs and unions. If we got here,
2340 // and the reference is to a class member indirect field, then this
2341 // must be the subject of a pointer-to-member expression.
2342 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2343 if (!indirectField->isCXXClassMember())
2344 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2345 indirectField);
2347 // If the identifier reference is inside a block, and it refers to a value
2348 // that is outside the block, create a BlockDeclRefExpr instead of a
2349 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2350 // the block is formed.
2352 // We do not do this for things like enum constants, global variables, etc,
2353 // as they do not get snapshotted.
2355 switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
2356 case CR_Error:
2357 return ExprError();
2359 case CR_Capture:
2360 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2361 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2363 case CR_CaptureByRef:
2364 assert(!SS.isSet() && "referenced local variable with scope specifier?");
2365 return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
2367 case CR_NoCapture: {
2368 // If this reference is not in a block or if the referenced
2369 // variable is within the block, create a normal DeclRefExpr.
2371 QualType type = VD->getType();
2372 ExprValueKind valueKind = VK_RValue;
2374 switch (D->getKind()) {
2375 // Ignore all the non-ValueDecl kinds.
2376 #define ABSTRACT_DECL(kind)
2377 #define VALUE(type, base)
2378 #define DECL(type, base) \
2379 case Decl::type:
2380 #include "clang/AST/DeclNodes.inc"
2381 llvm_unreachable("invalid value decl kind");
2382 return ExprError();
2384 // These shouldn't make it here.
2385 case Decl::ObjCAtDefsField:
2386 case Decl::ObjCIvar:
2387 llvm_unreachable("forming non-member reference to ivar?");
2388 return ExprError();
2390 // Enum constants are always r-values and never references.
2391 // Unresolved using declarations are dependent.
2392 case Decl::EnumConstant:
2393 case Decl::UnresolvedUsingValue:
2394 valueKind = VK_RValue;
2395 break;
2397 // Fields and indirect fields that got here must be for
2398 // pointer-to-member expressions; we just call them l-values for
2399 // internal consistency, because this subexpression doesn't really
2400 // exist in the high-level semantics.
2401 case Decl::Field:
2402 case Decl::IndirectField:
2403 assert(getLangOptions().CPlusPlus &&
2404 "building reference to field in C?");
2406 // These can't have reference type in well-formed programs, but
2407 // for internal consistency we do this anyway.
2408 type = type.getNonReferenceType();
2409 valueKind = VK_LValue;
2410 break;
2412 // Non-type template parameters are either l-values or r-values
2413 // depending on the type.
2414 case Decl::NonTypeTemplateParm: {
2415 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2416 type = reftype->getPointeeType();
2417 valueKind = VK_LValue; // even if the parameter is an r-value reference
2418 break;
2421 // For non-references, we need to strip qualifiers just in case
2422 // the template parameter was declared as 'const int' or whatever.
2423 valueKind = VK_RValue;
2424 type = type.getUnqualifiedType();
2425 break;
2428 case Decl::Var:
2429 // In C, "extern void blah;" is valid and is an r-value.
2430 if (!getLangOptions().CPlusPlus &&
2431 !type.hasQualifiers() &&
2432 type->isVoidType()) {
2433 valueKind = VK_RValue;
2434 break;
2436 // fallthrough
2438 case Decl::ImplicitParam:
2439 case Decl::ParmVar:
2440 // These are always l-values.
2441 valueKind = VK_LValue;
2442 type = type.getNonReferenceType();
2443 break;
2445 case Decl::Function: {
2446 // Functions are l-values in C++.
2447 if (getLangOptions().CPlusPlus) {
2448 valueKind = VK_LValue;
2449 break;
2452 // C99 DR 316 says that, if a function type comes from a
2453 // function definition (without a prototype), that type is only
2454 // used for checking compatibility. Therefore, when referencing
2455 // the function, we pretend that we don't have the full function
2456 // type.
2457 if (!cast<FunctionDecl>(VD)->hasPrototype())
2458 if (const FunctionProtoType *proto = type->getAs<FunctionProtoType>())
2459 type = Context.getFunctionNoProtoType(proto->getResultType(),
2460 proto->getExtInfo());
2462 // Functions are r-values in C.
2463 valueKind = VK_RValue;
2464 break;
2467 case Decl::CXXMethod:
2468 // C++ methods are l-values if static, r-values if non-static.
2469 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2470 valueKind = VK_LValue;
2471 break;
2473 // fallthrough
2475 case Decl::CXXConversion:
2476 case Decl::CXXDestructor:
2477 case Decl::CXXConstructor:
2478 valueKind = VK_RValue;
2479 break;
2482 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2487 llvm_unreachable("unknown capture result");
2488 return ExprError();
2491 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
2492 tok::TokenKind Kind) {
2493 PredefinedExpr::IdentType IT;
2495 switch (Kind) {
2496 default: assert(0 && "Unknown simple primary expr!");
2497 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2498 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2499 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2502 // Pre-defined identifiers are of type char[x], where x is the length of the
2503 // string.
2505 Decl *currentDecl = getCurFunctionOrMethodDecl();
2506 if (!currentDecl && getCurBlock())
2507 currentDecl = getCurBlock()->TheDecl;
2508 if (!currentDecl) {
2509 Diag(Loc, diag::ext_predef_outside_function);
2510 currentDecl = Context.getTranslationUnitDecl();
2513 QualType ResTy;
2514 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2515 ResTy = Context.DependentTy;
2516 } else {
2517 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2519 llvm::APInt LengthI(32, Length + 1);
2520 ResTy = Context.CharTy.withConst();
2521 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2523 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2526 ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
2527 llvm::SmallString<16> CharBuffer;
2528 bool Invalid = false;
2529 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2530 if (Invalid)
2531 return ExprError();
2533 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2534 PP);
2535 if (Literal.hadError())
2536 return ExprError();
2538 QualType Ty;
2539 if (!getLangOptions().CPlusPlus)
2540 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2541 else if (Literal.isWide())
2542 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
2543 else if (Literal.isMultiChar())
2544 Ty = Context.IntTy; // 'wxyz' -> int in C++.
2545 else
2546 Ty = Context.CharTy; // 'x' -> char in C++
2548 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2549 Literal.isWide(),
2550 Ty, Tok.getLocation()));
2553 ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
2554 // Fast path for a single digit (which is quite common). A single digit
2555 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2556 if (Tok.getLength() == 1) {
2557 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2558 unsigned IntSize = Context.Target.getIntWidth();
2559 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
2560 Context.IntTy, Tok.getLocation()));
2563 llvm::SmallString<512> IntegerBuffer;
2564 // Add padding so that NumericLiteralParser can overread by one character.
2565 IntegerBuffer.resize(Tok.getLength()+1);
2566 const char *ThisTokBegin = &IntegerBuffer[0];
2568 // Get the spelling of the token, which eliminates trigraphs, etc.
2569 bool Invalid = false;
2570 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2571 if (Invalid)
2572 return ExprError();
2574 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2575 Tok.getLocation(), PP);
2576 if (Literal.hadError)
2577 return ExprError();
2579 Expr *Res;
2581 if (Literal.isFloatingLiteral()) {
2582 QualType Ty;
2583 if (Literal.isFloat)
2584 Ty = Context.FloatTy;
2585 else if (!Literal.isLong)
2586 Ty = Context.DoubleTy;
2587 else
2588 Ty = Context.LongDoubleTy;
2590 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2592 using llvm::APFloat;
2593 APFloat Val(Format);
2595 APFloat::opStatus result = Literal.GetFloatValue(Val);
2597 // Overflow is always an error, but underflow is only an error if
2598 // we underflowed to zero (APFloat reports denormals as underflow).
2599 if ((result & APFloat::opOverflow) ||
2600 ((result & APFloat::opUnderflow) && Val.isZero())) {
2601 unsigned diagnostic;
2602 llvm::SmallString<20> buffer;
2603 if (result & APFloat::opOverflow) {
2604 diagnostic = diag::warn_float_overflow;
2605 APFloat::getLargest(Format).toString(buffer);
2606 } else {
2607 diagnostic = diag::warn_float_underflow;
2608 APFloat::getSmallest(Format).toString(buffer);
2611 Diag(Tok.getLocation(), diagnostic)
2612 << Ty
2613 << llvm::StringRef(buffer.data(), buffer.size());
2616 bool isExact = (result == APFloat::opOK);
2617 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
2619 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2620 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2622 } else if (!Literal.isIntegerLiteral()) {
2623 return ExprError();
2624 } else {
2625 QualType Ty;
2627 // long long is a C99 feature.
2628 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
2629 Literal.isLongLong)
2630 Diag(Tok.getLocation(), diag::ext_longlong);
2632 // Get the value in the widest-possible width.
2633 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
2635 if (Literal.GetIntegerValue(ResultVal)) {
2636 // If this value didn't fit into uintmax_t, warn and force to ull.
2637 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2638 Ty = Context.UnsignedLongLongTy;
2639 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2640 "long long is not intmax_t?");
2641 } else {
2642 // If this value fits into a ULL, try to figure out what else it fits into
2643 // according to the rules of C99 6.4.4.1p5.
2645 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2646 // be an unsigned int.
2647 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2649 // Check from smallest to largest, picking the smallest type we can.
2650 unsigned Width = 0;
2651 if (!Literal.isLong && !Literal.isLongLong) {
2652 // Are int/unsigned possibilities?
2653 unsigned IntSize = Context.Target.getIntWidth();
2655 // Does it fit in a unsigned int?
2656 if (ResultVal.isIntN(IntSize)) {
2657 // Does it fit in a signed int?
2658 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2659 Ty = Context.IntTy;
2660 else if (AllowUnsigned)
2661 Ty = Context.UnsignedIntTy;
2662 Width = IntSize;
2666 // Are long/unsigned long possibilities?
2667 if (Ty.isNull() && !Literal.isLongLong) {
2668 unsigned LongSize = Context.Target.getLongWidth();
2670 // Does it fit in a unsigned long?
2671 if (ResultVal.isIntN(LongSize)) {
2672 // Does it fit in a signed long?
2673 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2674 Ty = Context.LongTy;
2675 else if (AllowUnsigned)
2676 Ty = Context.UnsignedLongTy;
2677 Width = LongSize;
2681 // Finally, check long long if needed.
2682 if (Ty.isNull()) {
2683 unsigned LongLongSize = Context.Target.getLongLongWidth();
2685 // Does it fit in a unsigned long long?
2686 if (ResultVal.isIntN(LongLongSize)) {
2687 // Does it fit in a signed long long?
2688 // To be compatible with MSVC, hex integer literals ending with the
2689 // LL or i64 suffix are always signed in Microsoft mode.
2690 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2691 (getLangOptions().Microsoft && Literal.isLongLong)))
2692 Ty = Context.LongLongTy;
2693 else if (AllowUnsigned)
2694 Ty = Context.UnsignedLongLongTy;
2695 Width = LongLongSize;
2699 // If we still couldn't decide a type, we probably have something that
2700 // does not fit in a signed long long, but has no U suffix.
2701 if (Ty.isNull()) {
2702 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2703 Ty = Context.UnsignedLongLongTy;
2704 Width = Context.Target.getLongLongWidth();
2707 if (ResultVal.getBitWidth() != Width)
2708 ResultVal = ResultVal.trunc(Width);
2710 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2713 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2714 if (Literal.isImaginary)
2715 Res = new (Context) ImaginaryLiteral(Res,
2716 Context.getComplexType(Res->getType()));
2718 return Owned(Res);
2721 ExprResult Sema::ActOnParenExpr(SourceLocation L,
2722 SourceLocation R, Expr *E) {
2723 assert((E != 0) && "ActOnParenExpr() missing expr");
2724 return Owned(new (Context) ParenExpr(L, R, E));
2727 /// The UsualUnaryConversions() function is *not* called by this routine.
2728 /// See C99 6.3.2.1p[2-4] for more details.
2729 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
2730 SourceLocation OpLoc,
2731 SourceRange ExprRange,
2732 bool isSizeof) {
2733 if (exprType->isDependentType())
2734 return false;
2736 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2737 // the result is the size of the referenced type."
2738 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2739 // result shall be the alignment of the referenced type."
2740 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2741 exprType = Ref->getPointeeType();
2743 // C99 6.5.3.4p1:
2744 if (exprType->isFunctionType()) {
2745 // alignof(function) is allowed as an extension.
2746 if (isSizeof)
2747 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2748 return false;
2751 // Allow sizeof(void)/alignof(void) as an extension.
2752 if (exprType->isVoidType()) {
2753 Diag(OpLoc, diag::ext_sizeof_void_type)
2754 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
2755 return false;
2758 if (RequireCompleteType(OpLoc, exprType,
2759 PDiag(diag::err_sizeof_alignof_incomplete_type)
2760 << int(!isSizeof) << ExprRange))
2761 return true;
2763 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2764 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
2765 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
2766 << exprType << isSizeof << ExprRange;
2767 return true;
2770 return false;
2773 static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2774 SourceRange ExprRange) {
2775 E = E->IgnoreParens();
2777 // alignof decl is always ok.
2778 if (isa<DeclRefExpr>(E))
2779 return false;
2781 // Cannot know anything else if the expression is dependent.
2782 if (E->isTypeDependent())
2783 return false;
2785 if (E->getBitField()) {
2786 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2787 return true;
2790 // Alignment of a field access is always okay, so long as it isn't a
2791 // bit-field.
2792 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2793 if (isa<FieldDecl>(ME->getMemberDecl()))
2794 return false;
2796 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2799 /// \brief Build a sizeof or alignof expression given a type operand.
2800 ExprResult
2801 Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
2802 SourceLocation OpLoc,
2803 bool isSizeOf, SourceRange R) {
2804 if (!TInfo)
2805 return ExprError();
2807 QualType T = TInfo->getType();
2809 if (!T->isDependentType() &&
2810 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2811 return ExprError();
2813 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2814 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
2815 Context.getSizeType(), OpLoc,
2816 R.getEnd()));
2819 /// \brief Build a sizeof or alignof expression given an expression
2820 /// operand.
2821 ExprResult
2822 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
2823 bool isSizeOf, SourceRange R) {
2824 // Verify that the operand is valid.
2825 bool isInvalid = false;
2826 if (E->isTypeDependent()) {
2827 // Delay type-checking for type-dependent expressions.
2828 } else if (!isSizeOf) {
2829 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
2830 } else if (E->getBitField()) { // C99 6.5.3.4p1.
2831 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2832 isInvalid = true;
2833 } else if (E->getType()->isPlaceholderType()) {
2834 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2835 if (PE.isInvalid()) return ExprError();
2836 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
2837 } else {
2838 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2841 if (isInvalid)
2842 return ExprError();
2844 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2845 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2846 Context.getSizeType(), OpLoc,
2847 R.getEnd()));
2850 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2851 /// the same for @c alignof and @c __alignof
2852 /// Note that the ArgRange is invalid if isType is false.
2853 ExprResult
2854 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2855 void *TyOrEx, const SourceRange &ArgRange) {
2856 // If error parsing type, ignore.
2857 if (TyOrEx == 0) return ExprError();
2859 if (isType) {
2860 TypeSourceInfo *TInfo;
2861 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
2862 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
2865 Expr *ArgEx = (Expr *)TyOrEx;
2866 ExprResult Result
2867 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2869 return move(Result);
2872 static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2873 bool isReal) {
2874 if (V->isTypeDependent())
2875 return S.Context.DependentTy;
2877 // _Real and _Imag are only l-values for normal l-values.
2878 if (V->getObjectKind() != OK_Ordinary)
2879 S.DefaultLvalueConversion(V);
2881 // These operators return the element type of a complex type.
2882 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
2883 return CT->getElementType();
2885 // Otherwise they pass through real integer and floating point types here.
2886 if (V->getType()->isArithmeticType())
2887 return V->getType();
2889 // Test for placeholders.
2890 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
2891 if (PR.isInvalid()) return QualType();
2892 if (PR.take() != V) {
2893 V = PR.take();
2894 return CheckRealImagOperand(S, V, Loc, isReal);
2897 // Reject anything else.
2898 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2899 << (isReal ? "__real" : "__imag");
2900 return QualType();
2905 ExprResult
2906 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2907 tok::TokenKind Kind, Expr *Input) {
2908 UnaryOperatorKind Opc;
2909 switch (Kind) {
2910 default: assert(0 && "Unknown unary op!");
2911 case tok::plusplus: Opc = UO_PostInc; break;
2912 case tok::minusminus: Opc = UO_PostDec; break;
2915 return BuildUnaryOp(S, OpLoc, Opc, Input);
2918 /// Expressions of certain arbitrary types are forbidden by C from
2919 /// having l-value type. These are:
2920 /// - 'void', but not qualified void
2921 /// - function types
2923 /// The exact rule here is C99 6.3.2.1:
2924 /// An lvalue is an expression with an object type or an incomplete
2925 /// type other than void.
2926 static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2927 return ((T->isVoidType() && !T.hasQualifiers()) ||
2928 T->isFunctionType());
2931 ExprResult
2932 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2933 Expr *Idx, SourceLocation RLoc) {
2934 // Since this might be a postfix expression, get rid of ParenListExprs.
2935 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
2936 if (Result.isInvalid()) return ExprError();
2937 Base = Result.take();
2939 Expr *LHSExp = Base, *RHSExp = Idx;
2941 if (getLangOptions().CPlusPlus &&
2942 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2943 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2944 Context.DependentTy,
2945 VK_LValue, OK_Ordinary,
2946 RLoc));
2949 if (getLangOptions().CPlusPlus &&
2950 (LHSExp->getType()->isRecordType() ||
2951 LHSExp->getType()->isEnumeralType() ||
2952 RHSExp->getType()->isRecordType() ||
2953 RHSExp->getType()->isEnumeralType())) {
2954 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
2957 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
2961 ExprResult
2962 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2963 Expr *Idx, SourceLocation RLoc) {
2964 Expr *LHSExp = Base;
2965 Expr *RHSExp = Idx;
2967 // Perform default conversions.
2968 if (!LHSExp->getType()->getAs<VectorType>())
2969 DefaultFunctionArrayLvalueConversion(LHSExp);
2970 DefaultFunctionArrayLvalueConversion(RHSExp);
2972 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
2973 ExprValueKind VK = VK_LValue;
2974 ExprObjectKind OK = OK_Ordinary;
2976 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
2977 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
2978 // in the subscript position. As a result, we need to derive the array base
2979 // and index from the expression types.
2980 Expr *BaseExpr, *IndexExpr;
2981 QualType ResultType;
2982 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2983 BaseExpr = LHSExp;
2984 IndexExpr = RHSExp;
2985 ResultType = Context.DependentTy;
2986 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
2987 BaseExpr = LHSExp;
2988 IndexExpr = RHSExp;
2989 ResultType = PTy->getPointeeType();
2990 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
2991 // Handle the uncommon case of "123[Ptr]".
2992 BaseExpr = RHSExp;
2993 IndexExpr = LHSExp;
2994 ResultType = PTy->getPointeeType();
2995 } else if (const ObjCObjectPointerType *PTy =
2996 LHSTy->getAs<ObjCObjectPointerType>()) {
2997 BaseExpr = LHSExp;
2998 IndexExpr = RHSExp;
2999 ResultType = PTy->getPointeeType();
3000 } else if (const ObjCObjectPointerType *PTy =
3001 RHSTy->getAs<ObjCObjectPointerType>()) {
3002 // Handle the uncommon case of "123[Ptr]".
3003 BaseExpr = RHSExp;
3004 IndexExpr = LHSExp;
3005 ResultType = PTy->getPointeeType();
3006 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3007 BaseExpr = LHSExp; // vectors: V[123]
3008 IndexExpr = RHSExp;
3009 VK = LHSExp->getValueKind();
3010 if (VK != VK_RValue)
3011 OK = OK_VectorComponent;
3013 // FIXME: need to deal with const...
3014 ResultType = VTy->getElementType();
3015 } else if (LHSTy->isArrayType()) {
3016 // If we see an array that wasn't promoted by
3017 // DefaultFunctionArrayLvalueConversion, it must be an array that
3018 // wasn't promoted because of the C90 rule that doesn't
3019 // allow promoting non-lvalue arrays. Warn, then
3020 // force the promotion here.
3021 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3022 LHSExp->getSourceRange();
3023 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3024 CK_ArrayToPointerDecay);
3025 LHSTy = LHSExp->getType();
3027 BaseExpr = LHSExp;
3028 IndexExpr = RHSExp;
3029 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3030 } else if (RHSTy->isArrayType()) {
3031 // Same as previous, except for 123[f().a] case
3032 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3033 RHSExp->getSourceRange();
3034 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3035 CK_ArrayToPointerDecay);
3036 RHSTy = RHSExp->getType();
3038 BaseExpr = RHSExp;
3039 IndexExpr = LHSExp;
3040 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3041 } else {
3042 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3043 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3045 // C99 6.5.2.1p1
3046 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3047 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3048 << IndexExpr->getSourceRange());
3050 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3051 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3052 && !IndexExpr->isTypeDependent())
3053 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3055 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3056 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3057 // type. Note that Functions are not objects, and that (in C99 parlance)
3058 // incomplete types are not object types.
3059 if (ResultType->isFunctionType()) {
3060 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3061 << ResultType << BaseExpr->getSourceRange();
3062 return ExprError();
3065 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3066 // GNU extension: subscripting on pointer to void
3067 Diag(LLoc, diag::ext_gnu_void_ptr)
3068 << BaseExpr->getSourceRange();
3070 // C forbids expressions of unqualified void type from being l-values.
3071 // See IsCForbiddenLValueType.
3072 if (!ResultType.hasQualifiers()) VK = VK_RValue;
3073 } else if (!ResultType->isDependentType() &&
3074 RequireCompleteType(LLoc, ResultType,
3075 PDiag(diag::err_subscript_incomplete_type)
3076 << BaseExpr->getSourceRange()))
3077 return ExprError();
3079 // Diagnose bad cases where we step over interface counts.
3080 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
3081 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3082 << ResultType << BaseExpr->getSourceRange();
3083 return ExprError();
3086 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3087 !IsCForbiddenLValueType(Context, ResultType));
3089 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3090 ResultType, VK, OK, RLoc));
3093 /// Check an ext-vector component access expression.
3095 /// VK should be set in advance to the value kind of the base
3096 /// expression.
3097 static QualType
3098 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
3099 SourceLocation OpLoc, const IdentifierInfo *CompName,
3100 SourceLocation CompLoc) {
3101 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
3102 // see FIXME there.
3104 // FIXME: This logic can be greatly simplified by splitting it along
3105 // halving/not halving and reworking the component checking.
3106 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
3108 // The vector accessor can't exceed the number of elements.
3109 const char *compStr = CompName->getNameStart();
3111 // This flag determines whether or not the component is one of the four
3112 // special names that indicate a subset of exactly half the elements are
3113 // to be selected.
3114 bool HalvingSwizzle = false;
3116 // This flag determines whether or not CompName has an 's' char prefix,
3117 // indicating that it is a string of hex values to be used as vector indices.
3118 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
3120 bool HasRepeated = false;
3121 bool HasIndex[16] = {};
3123 int Idx;
3125 // Check that we've found one of the special components, or that the component
3126 // names must come from the same set.
3127 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
3128 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
3129 HalvingSwizzle = true;
3130 } else if (!HexSwizzle &&
3131 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
3132 do {
3133 if (HasIndex[Idx]) HasRepeated = true;
3134 HasIndex[Idx] = true;
3135 compStr++;
3136 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
3137 } else {
3138 if (HexSwizzle) compStr++;
3139 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
3140 if (HasIndex[Idx]) HasRepeated = true;
3141 HasIndex[Idx] = true;
3142 compStr++;
3146 if (!HalvingSwizzle && *compStr) {
3147 // We didn't get to the end of the string. This means the component names
3148 // didn't come from the same set *or* we encountered an illegal name.
3149 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
3150 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
3151 return QualType();
3154 // Ensure no component accessor exceeds the width of the vector type it
3155 // operates on.
3156 if (!HalvingSwizzle) {
3157 compStr = CompName->getNameStart();
3159 if (HexSwizzle)
3160 compStr++;
3162 while (*compStr) {
3163 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
3164 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
3165 << baseType << SourceRange(CompLoc);
3166 return QualType();
3171 // The component accessor looks fine - now we need to compute the actual type.
3172 // The vector type is implied by the component accessor. For example,
3173 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
3174 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
3175 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
3176 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
3177 : CompName->getLength();
3178 if (HexSwizzle)
3179 CompSize--;
3181 if (CompSize == 1)
3182 return vecType->getElementType();
3184 if (HasRepeated) VK = VK_RValue;
3186 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
3187 // Now look up the TypeDefDecl from the vector type. Without this,
3188 // diagostics look bad. We want extended vector types to appear built-in.
3189 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3190 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3191 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
3193 return VT; // should never get here (a typedef type should always be found).
3196 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
3197 IdentifierInfo *Member,
3198 const Selector &Sel,
3199 ASTContext &Context) {
3200 if (Member)
3201 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3202 return PD;
3203 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
3204 return OMD;
3206 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3207 E = PDecl->protocol_end(); I != E; ++I) {
3208 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3209 Context))
3210 return D;
3212 return 0;
3215 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3216 IdentifierInfo *Member,
3217 const Selector &Sel,
3218 ASTContext &Context) {
3219 // Check protocols on qualified interfaces.
3220 Decl *GDecl = 0;
3221 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3222 E = QIdTy->qual_end(); I != E; ++I) {
3223 if (Member)
3224 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3225 GDecl = PD;
3226 break;
3228 // Also must look for a getter or setter name which uses property syntax.
3229 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
3230 GDecl = OMD;
3231 break;
3234 if (!GDecl) {
3235 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3236 E = QIdTy->qual_end(); I != E; ++I) {
3237 // Search in the protocol-qualifier list of current protocol.
3238 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3239 Context);
3240 if (GDecl)
3241 return GDecl;
3244 return GDecl;
3247 ExprResult
3248 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
3249 bool IsArrow, SourceLocation OpLoc,
3250 const CXXScopeSpec &SS,
3251 NamedDecl *FirstQualifierInScope,
3252 const DeclarationNameInfo &NameInfo,
3253 const TemplateArgumentListInfo *TemplateArgs) {
3254 // Even in dependent contexts, try to diagnose base expressions with
3255 // obviously wrong types, e.g.:
3257 // T* t;
3258 // t.f;
3260 // In Obj-C++, however, the above expression is valid, since it could be
3261 // accessing the 'f' property if T is an Obj-C interface. The extra check
3262 // allows this, while still reporting an error if T is a struct pointer.
3263 if (!IsArrow) {
3264 const PointerType *PT = BaseType->getAs<PointerType>();
3265 if (PT && (!getLangOptions().ObjC1 ||
3266 PT->getPointeeType()->isRecordType())) {
3267 assert(BaseExpr && "cannot happen with implicit member accesses");
3268 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
3269 << BaseType << BaseExpr->getSourceRange();
3270 return ExprError();
3274 assert(BaseType->isDependentType() ||
3275 NameInfo.getName().isDependentName() ||
3276 isDependentScopeSpecifier(SS));
3278 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3279 // must have pointer type, and the accessed type is the pointee.
3280 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
3281 IsArrow, OpLoc,
3282 SS.getScopeRep(),
3283 SS.getRange(),
3284 FirstQualifierInScope,
3285 NameInfo, TemplateArgs));
3288 /// We know that the given qualified member reference points only to
3289 /// declarations which do not belong to the static type of the base
3290 /// expression. Diagnose the problem.
3291 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3292 Expr *BaseExpr,
3293 QualType BaseType,
3294 const CXXScopeSpec &SS,
3295 NamedDecl *rep,
3296 const DeclarationNameInfo &nameInfo) {
3297 // If this is an implicit member access, use a different set of
3298 // diagnostics.
3299 if (!BaseExpr)
3300 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
3302 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
3303 << SS.getRange() << rep << BaseType;
3306 // Check whether the declarations we found through a nested-name
3307 // specifier in a member expression are actually members of the base
3308 // type. The restriction here is:
3310 // C++ [expr.ref]p2:
3311 // ... In these cases, the id-expression shall name a
3312 // member of the class or of one of its base classes.
3314 // So it's perfectly legitimate for the nested-name specifier to name
3315 // an unrelated class, and for us to find an overload set including
3316 // decls from classes which are not superclasses, as long as the decl
3317 // we actually pick through overload resolution is from a superclass.
3318 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3319 QualType BaseType,
3320 const CXXScopeSpec &SS,
3321 const LookupResult &R) {
3322 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3323 if (!BaseRT) {
3324 // We can't check this yet because the base type is still
3325 // dependent.
3326 assert(BaseType->isDependentType());
3327 return false;
3329 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
3331 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3332 // If this is an implicit member reference and we find a
3333 // non-instance member, it's not an error.
3334 if (!BaseExpr && !(*I)->isCXXInstanceMember())
3335 return false;
3337 // Note that we use the DC of the decl, not the underlying decl.
3338 DeclContext *DC = (*I)->getDeclContext();
3339 while (DC->isTransparentContext())
3340 DC = DC->getParent();
3342 if (!DC->isRecord())
3343 continue;
3345 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
3346 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
3348 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3349 return false;
3352 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
3353 R.getRepresentativeDecl(),
3354 R.getLookupNameInfo());
3355 return true;
3358 static bool
3359 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3360 SourceRange BaseRange, const RecordType *RTy,
3361 SourceLocation OpLoc, CXXScopeSpec &SS,
3362 bool HasTemplateArgs) {
3363 RecordDecl *RDecl = RTy->getDecl();
3364 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
3365 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
3366 << BaseRange))
3367 return true;
3369 if (HasTemplateArgs) {
3370 // LookupTemplateName doesn't expect these both to exist simultaneously.
3371 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3373 bool MOUS;
3374 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3375 return false;
3378 DeclContext *DC = RDecl;
3379 if (SS.isSet()) {
3380 // If the member name was a qualified-id, look into the
3381 // nested-name-specifier.
3382 DC = SemaRef.computeDeclContext(SS, false);
3384 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
3385 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3386 << SS.getRange() << DC;
3387 return true;
3390 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
3392 if (!isa<TypeDecl>(DC)) {
3393 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3394 << DC << SS.getRange();
3395 return true;
3399 // The record definition is complete, now look up the member.
3400 SemaRef.LookupQualifiedName(R, DC);
3402 if (!R.empty())
3403 return false;
3405 // We didn't find anything with the given name, so try to correct
3406 // for typos.
3407 DeclarationName Name = R.getLookupName();
3408 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
3409 !R.empty() &&
3410 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3411 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3412 << Name << DC << R.getLookupName() << SS.getRange()
3413 << FixItHint::CreateReplacement(R.getNameLoc(),
3414 R.getLookupName().getAsString());
3415 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3416 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3417 << ND->getDeclName();
3418 return false;
3419 } else {
3420 R.clear();
3421 R.setLookupName(Name);
3424 return false;
3427 ExprResult
3428 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3429 SourceLocation OpLoc, bool IsArrow,
3430 CXXScopeSpec &SS,
3431 NamedDecl *FirstQualifierInScope,
3432 const DeclarationNameInfo &NameInfo,
3433 const TemplateArgumentListInfo *TemplateArgs) {
3434 if (BaseType->isDependentType() ||
3435 (SS.isSet() && isDependentScopeSpecifier(SS)))
3436 return ActOnDependentMemberExpr(Base, BaseType,
3437 IsArrow, OpLoc,
3438 SS, FirstQualifierInScope,
3439 NameInfo, TemplateArgs);
3441 LookupResult R(*this, NameInfo, LookupMemberName);
3443 // Implicit member accesses.
3444 if (!Base) {
3445 QualType RecordTy = BaseType;
3446 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3447 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3448 RecordTy->getAs<RecordType>(),
3449 OpLoc, SS, TemplateArgs != 0))
3450 return ExprError();
3452 // Explicit member accesses.
3453 } else {
3454 ExprResult Result =
3455 LookupMemberExpr(R, Base, IsArrow, OpLoc,
3456 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
3458 if (Result.isInvalid()) {
3459 Owned(Base);
3460 return ExprError();
3463 if (Result.get())
3464 return move(Result);
3466 // LookupMemberExpr can modify Base, and thus change BaseType
3467 BaseType = Base->getType();
3470 return BuildMemberReferenceExpr(Base, BaseType,
3471 OpLoc, IsArrow, SS, FirstQualifierInScope,
3472 R, TemplateArgs);
3475 ExprResult
3476 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
3477 SourceLocation OpLoc, bool IsArrow,
3478 const CXXScopeSpec &SS,
3479 NamedDecl *FirstQualifierInScope,
3480 LookupResult &R,
3481 const TemplateArgumentListInfo *TemplateArgs,
3482 bool SuppressQualifierCheck) {
3483 QualType BaseType = BaseExprType;
3484 if (IsArrow) {
3485 assert(BaseType->isPointerType());
3486 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3488 R.setBaseObjectType(BaseType);
3490 NestedNameSpecifier *Qualifier = SS.getScopeRep();
3491 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3492 DeclarationName MemberName = MemberNameInfo.getName();
3493 SourceLocation MemberLoc = MemberNameInfo.getLoc();
3495 if (R.isAmbiguous())
3496 return ExprError();
3498 if (R.empty()) {
3499 // Rederive where we looked up.
3500 DeclContext *DC = (SS.isSet()
3501 ? computeDeclContext(SS, false)
3502 : BaseType->getAs<RecordType>()->getDecl());
3504 Diag(R.getNameLoc(), diag::err_no_member)
3505 << MemberName << DC
3506 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
3507 return ExprError();
3510 // Diagnose lookups that find only declarations from a non-base
3511 // type. This is possible for either qualified lookups (which may
3512 // have been qualified with an unrelated type) or implicit member
3513 // expressions (which were found with unqualified lookup and thus
3514 // may have come from an enclosing scope). Note that it's okay for
3515 // lookup to find declarations from a non-base type as long as those
3516 // aren't the ones picked by overload resolution.
3517 if ((SS.isSet() || !BaseExpr ||
3518 (isa<CXXThisExpr>(BaseExpr) &&
3519 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
3520 !SuppressQualifierCheck &&
3521 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
3522 return ExprError();
3524 // Construct an unresolved result if we in fact got an unresolved
3525 // result.
3526 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
3527 // Suppress any lookup-related diagnostics; we'll do these when we
3528 // pick a member.
3529 R.suppressDiagnostics();
3531 UnresolvedMemberExpr *MemExpr
3532 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
3533 BaseExpr, BaseExprType,
3534 IsArrow, OpLoc,
3535 Qualifier, SS.getRange(),
3536 MemberNameInfo,
3537 TemplateArgs, R.begin(), R.end());
3539 return Owned(MemExpr);
3542 assert(R.isSingleResult());
3543 DeclAccessPair FoundDecl = R.begin().getPair();
3544 NamedDecl *MemberDecl = R.getFoundDecl();
3546 // FIXME: diagnose the presence of template arguments now.
3548 // If the decl being referenced had an error, return an error for this
3549 // sub-expr without emitting another error, in order to avoid cascading
3550 // error cases.
3551 if (MemberDecl->isInvalidDecl())
3552 return ExprError();
3554 // Handle the implicit-member-access case.
3555 if (!BaseExpr) {
3556 // If this is not an instance member, convert to a non-member access.
3557 if (!MemberDecl->isCXXInstanceMember())
3558 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
3560 SourceLocation Loc = R.getNameLoc();
3561 if (SS.getRange().isValid())
3562 Loc = SS.getRange().getBegin();
3563 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
3566 bool ShouldCheckUse = true;
3567 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3568 // Don't diagnose the use of a virtual member function unless it's
3569 // explicitly qualified.
3570 if (MD->isVirtual() && !SS.isSet())
3571 ShouldCheckUse = false;
3574 // Check the use of this member.
3575 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3576 Owned(BaseExpr);
3577 return ExprError();
3580 // Perform a property load on the base regardless of whether we
3581 // actually need it for the declaration.
3582 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3583 ConvertPropertyForRValue(BaseExpr);
3585 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3586 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3587 SS, FD, FoundDecl, MemberNameInfo);
3589 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3590 // We may have found a field within an anonymous union or struct
3591 // (C++ [class.union]).
3592 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
3593 BaseExpr, OpLoc);
3595 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3596 MarkDeclarationReferenced(MemberLoc, Var);
3597 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3598 Var, FoundDecl, MemberNameInfo,
3599 Var->getType().getNonReferenceType(),
3600 VK_LValue, OK_Ordinary));
3603 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3604 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3605 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3606 MemberFn, FoundDecl, MemberNameInfo,
3607 MemberFn->getType(),
3608 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3609 OK_Ordinary));
3611 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
3613 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3614 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3615 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3616 Enum, FoundDecl, MemberNameInfo,
3617 Enum->getType(), VK_RValue, OK_Ordinary));
3620 Owned(BaseExpr);
3622 // We found something that we didn't expect. Complain.
3623 if (isa<TypeDecl>(MemberDecl))
3624 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
3625 << MemberName << BaseType << int(IsArrow);
3626 else
3627 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3628 << MemberName << BaseType << int(IsArrow);
3630 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3631 << MemberName;
3632 R.suppressDiagnostics();
3633 return ExprError();
3636 /// Given that normal member access failed on the given expression,
3637 /// and given that the expression's type involves builtin-id or
3638 /// builtin-Class, decide whether substituting in the redefinition
3639 /// types would be profitable. The redefinition type is whatever
3640 /// this translation unit tried to typedef to id/Class; we store
3641 /// it to the side and then re-use it in places like this.
3642 static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3643 const ObjCObjectPointerType *opty
3644 = base->getType()->getAs<ObjCObjectPointerType>();
3645 if (!opty) return false;
3647 const ObjCObjectType *ty = opty->getObjectType();
3649 QualType redef;
3650 if (ty->isObjCId()) {
3651 redef = S.Context.ObjCIdRedefinitionType;
3652 } else if (ty->isObjCClass()) {
3653 redef = S.Context.ObjCClassRedefinitionType;
3654 } else {
3655 return false;
3658 // Do the substitution as long as the redefinition type isn't just a
3659 // possibly-qualified pointer to builtin-id or builtin-Class again.
3660 opty = redef->getAs<ObjCObjectPointerType>();
3661 if (opty && !opty->getObjectType()->getInterface() != 0)
3662 return false;
3664 S.ImpCastExprToType(base, redef, CK_BitCast);
3665 return true;
3668 /// Look up the given member of the given non-type-dependent
3669 /// expression. This can return in one of two ways:
3670 /// * If it returns a sentinel null-but-valid result, the caller will
3671 /// assume that lookup was performed and the results written into
3672 /// the provided structure. It will take over from there.
3673 /// * Otherwise, the returned expression will be produced in place of
3674 /// an ordinary member expression.
3676 /// The ObjCImpDecl bit is a gross hack that will need to be properly
3677 /// fixed for ObjC++.
3678 ExprResult
3679 Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
3680 bool &IsArrow, SourceLocation OpLoc,
3681 CXXScopeSpec &SS,
3682 Decl *ObjCImpDecl, bool HasTemplateArgs) {
3683 assert(BaseExpr && "no base expression");
3685 // Perform default conversions.
3686 DefaultFunctionArrayConversion(BaseExpr);
3687 if (IsArrow) DefaultLvalueConversion(BaseExpr);
3689 QualType BaseType = BaseExpr->getType();
3690 assert(!BaseType->isDependentType());
3692 DeclarationName MemberName = R.getLookupName();
3693 SourceLocation MemberLoc = R.getNameLoc();
3695 // For later type-checking purposes, turn arrow accesses into dot
3696 // accesses. The only access type we support that doesn't follow
3697 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3698 // and those never use arrows, so this is unaffected.
3699 if (IsArrow) {
3700 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3701 BaseType = Ptr->getPointeeType();
3702 else if (const ObjCObjectPointerType *Ptr
3703 = BaseType->getAs<ObjCObjectPointerType>())
3704 BaseType = Ptr->getPointeeType();
3705 else if (BaseType->isRecordType()) {
3706 // Recover from arrow accesses to records, e.g.:
3707 // struct MyRecord foo;
3708 // foo->bar
3709 // This is actually well-formed in C++ if MyRecord has an
3710 // overloaded operator->, but that should have been dealt with
3711 // by now.
3712 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3713 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3714 << FixItHint::CreateReplacement(OpLoc, ".");
3715 IsArrow = false;
3716 } else {
3717 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3718 << BaseType << BaseExpr->getSourceRange();
3719 return ExprError();
3723 // Handle field access to simple records.
3724 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3725 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3726 RTy, OpLoc, SS, HasTemplateArgs))
3727 return ExprError();
3729 // Returning valid-but-null is how we indicate to the caller that
3730 // the lookup result was filled in.
3731 return Owned((Expr*) 0);
3734 // Handle ivar access to Objective-C objects.
3735 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
3736 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3738 // There are three cases for the base type:
3739 // - builtin id (qualified or unqualified)
3740 // - builtin Class (qualified or unqualified)
3741 // - an interface
3742 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3743 if (!IDecl) {
3744 // There's an implicit 'isa' ivar on all objects.
3745 // But we only actually find it this way on objects of type 'id',
3746 // apparently.
3747 if (OTy->isObjCId() && Member->isStr("isa"))
3748 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3749 Context.getObjCClassType()));
3751 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3752 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3753 ObjCImpDecl, HasTemplateArgs);
3754 goto fail;
3757 ObjCInterfaceDecl *ClassDeclared;
3758 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3760 if (!IV) {
3761 // Attempt to correct for typos in ivar names.
3762 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3763 LookupMemberName);
3764 if (CorrectTypo(Res, 0, 0, IDecl, false,
3765 IsArrow ? CTC_ObjCIvarLookup
3766 : CTC_ObjCPropertyLookup) &&
3767 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3768 Diag(R.getNameLoc(),
3769 diag::err_typecheck_member_reference_ivar_suggest)
3770 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3771 << FixItHint::CreateReplacement(R.getNameLoc(),
3772 IV->getNameAsString());
3773 Diag(IV->getLocation(), diag::note_previous_decl)
3774 << IV->getDeclName();
3775 } else {
3776 Res.clear();
3777 Res.setLookupName(Member);
3779 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3780 << IDecl->getDeclName() << MemberName
3781 << BaseExpr->getSourceRange();
3782 return ExprError();
3786 // If the decl being referenced had an error, return an error for this
3787 // sub-expr without emitting another error, in order to avoid cascading
3788 // error cases.
3789 if (IV->isInvalidDecl())
3790 return ExprError();
3792 // Check whether we can reference this field.
3793 if (DiagnoseUseOfDecl(IV, MemberLoc))
3794 return ExprError();
3795 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3796 IV->getAccessControl() != ObjCIvarDecl::Package) {
3797 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3798 if (ObjCMethodDecl *MD = getCurMethodDecl())
3799 ClassOfMethodDecl = MD->getClassInterface();
3800 else if (ObjCImpDecl && getCurFunctionDecl()) {
3801 // Case of a c-function declared inside an objc implementation.
3802 // FIXME: For a c-style function nested inside an objc implementation
3803 // class, there is no implementation context available, so we pass
3804 // down the context as argument to this routine. Ideally, this context
3805 // need be passed down in the AST node and somehow calculated from the
3806 // AST for a function decl.
3807 if (ObjCImplementationDecl *IMPD =
3808 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3809 ClassOfMethodDecl = IMPD->getClassInterface();
3810 else if (ObjCCategoryImplDecl* CatImplClass =
3811 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3812 ClassOfMethodDecl = CatImplClass->getClassInterface();
3815 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3816 if (ClassDeclared != IDecl ||
3817 ClassOfMethodDecl != ClassDeclared)
3818 Diag(MemberLoc, diag::error_private_ivar_access)
3819 << IV->getDeclName();
3820 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3821 // @protected
3822 Diag(MemberLoc, diag::error_protected_ivar_access)
3823 << IV->getDeclName();
3826 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3827 MemberLoc, BaseExpr,
3828 IsArrow));
3831 // Objective-C property access.
3832 const ObjCObjectPointerType *OPT;
3833 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3834 // This actually uses the base as an r-value.
3835 DefaultLvalueConversion(BaseExpr);
3836 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3838 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3840 const ObjCObjectType *OT = OPT->getObjectType();
3842 // id, with and without qualifiers.
3843 if (OT->isObjCId()) {
3844 // Check protocols on qualified interfaces.
3845 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3846 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3847 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3848 // Check the use of this declaration
3849 if (DiagnoseUseOfDecl(PD, MemberLoc))
3850 return ExprError();
3852 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3853 VK_LValue,
3854 OK_ObjCProperty,
3855 MemberLoc,
3856 BaseExpr));
3859 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3860 // Check the use of this method.
3861 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3862 return ExprError();
3863 Selector SetterSel =
3864 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3865 PP.getSelectorTable(), Member);
3866 ObjCMethodDecl *SMD = 0;
3867 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3868 SetterSel, Context))
3869 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3870 QualType PType = OMD->getSendResultType();
3872 ExprValueKind VK = VK_LValue;
3873 if (!getLangOptions().CPlusPlus &&
3874 IsCForbiddenLValueType(Context, PType))
3875 VK = VK_RValue;
3876 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3878 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3879 VK, OK,
3880 MemberLoc, BaseExpr));
3884 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3885 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3886 ObjCImpDecl, HasTemplateArgs);
3888 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3889 << MemberName << BaseType);
3892 // 'Class', unqualified only.
3893 if (OT->isObjCClass()) {
3894 // Only works in a method declaration (??!).
3895 ObjCMethodDecl *MD = getCurMethodDecl();
3896 if (!MD) {
3897 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3898 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3899 ObjCImpDecl, HasTemplateArgs);
3901 goto fail;
3904 // Also must look for a getter name which uses property syntax.
3905 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3906 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3907 ObjCMethodDecl *Getter;
3908 if ((Getter = IFace->lookupClassMethod(Sel))) {
3909 // Check the use of this method.
3910 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3911 return ExprError();
3912 } else
3913 Getter = IFace->lookupPrivateMethod(Sel, false);
3914 // If we found a getter then this may be a valid dot-reference, we
3915 // will look for the matching setter, in case it is needed.
3916 Selector SetterSel =
3917 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3918 PP.getSelectorTable(), Member);
3919 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3920 if (!Setter) {
3921 // If this reference is in an @implementation, also check for 'private'
3922 // methods.
3923 Setter = IFace->lookupPrivateMethod(SetterSel, false);
3925 // Look through local category implementations associated with the class.
3926 if (!Setter)
3927 Setter = IFace->getCategoryClassMethod(SetterSel);
3929 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3930 return ExprError();
3932 if (Getter || Setter) {
3933 QualType PType;
3935 ExprValueKind VK = VK_LValue;
3936 if (Getter) {
3937 PType = Getter->getSendResultType();
3938 if (!getLangOptions().CPlusPlus &&
3939 IsCForbiddenLValueType(Context, PType))
3940 VK = VK_RValue;
3941 } else {
3942 // Get the expression type from Setter's incoming parameter.
3943 PType = (*(Setter->param_end() -1))->getType();
3945 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3947 // FIXME: we must check that the setter has property type.
3948 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3949 PType, VK, OK,
3950 MemberLoc, BaseExpr));
3953 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3954 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3955 ObjCImpDecl, HasTemplateArgs);
3957 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3958 << MemberName << BaseType);
3961 // Normal property access.
3962 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3963 SourceLocation(), QualType(), false);
3966 // Handle 'field access' to vectors, such as 'V.xx'.
3967 if (BaseType->isExtVectorType()) {
3968 // FIXME: this expr should store IsArrow.
3969 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3970 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
3971 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3972 Member, MemberLoc);
3973 if (ret.isNull())
3974 return ExprError();
3976 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3977 *Member, MemberLoc));
3980 // Adjust builtin-sel to the appropriate redefinition type if that's
3981 // not just a pointer to builtin-sel again.
3982 if (IsArrow &&
3983 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3984 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3985 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3986 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3987 ObjCImpDecl, HasTemplateArgs);
3990 // Failure cases.
3991 fail:
3993 // There's a possible road to recovery for function types.
3994 const FunctionType *Fun = 0;
3996 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3997 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
3998 // fall out, handled below.
4000 // Recover from dot accesses to pointers, e.g.:
4001 // type *foo;
4002 // foo.bar
4003 // This is actually well-formed in two cases:
4004 // - 'type' is an Objective C type
4005 // - 'bar' is a pseudo-destructor name which happens to refer to
4006 // the appropriate pointer type
4007 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
4008 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
4009 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4010 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
4011 << FixItHint::CreateReplacement(OpLoc, "->");
4013 // Recurse as an -> access.
4014 IsArrow = true;
4015 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4016 ObjCImpDecl, HasTemplateArgs);
4018 } else {
4019 Fun = BaseType->getAs<FunctionType>();
4022 // If the user is trying to apply -> or . to a function pointer
4023 // type, it's probably because they forgot parentheses to call that
4024 // function. Suggest the addition of those parentheses, build the
4025 // call, and continue on.
4026 if (Fun || BaseType == Context.OverloadTy) {
4027 bool TryCall;
4028 if (BaseType == Context.OverloadTy) {
4029 TryCall = true;
4030 } else {
4031 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
4032 TryCall = (FPT->getNumArgs() == 0);
4033 } else {
4034 TryCall = true;
4037 if (TryCall) {
4038 QualType ResultTy = Fun->getResultType();
4039 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
4040 (IsArrow && ResultTy->isPointerType() &&
4041 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
4046 if (TryCall) {
4047 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
4048 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
4049 << QualType(Fun, 0)
4050 << FixItHint::CreateInsertion(Loc, "()");
4052 ExprResult NewBase
4053 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
4054 if (NewBase.isInvalid())
4055 return ExprError();
4056 BaseExpr = NewBase.takeAs<Expr>();
4059 DefaultFunctionArrayConversion(BaseExpr);
4060 BaseType = BaseExpr->getType();
4062 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
4063 ObjCImpDecl, HasTemplateArgs);
4067 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
4068 << BaseType << BaseExpr->getSourceRange();
4070 return ExprError();
4073 /// The main callback when the parser finds something like
4074 /// expression . [nested-name-specifier] identifier
4075 /// expression -> [nested-name-specifier] identifier
4076 /// where 'identifier' encompasses a fairly broad spectrum of
4077 /// possibilities, including destructor and operator references.
4079 /// \param OpKind either tok::arrow or tok::period
4080 /// \param HasTrailingLParen whether the next token is '(', which
4081 /// is used to diagnose mis-uses of special members that can
4082 /// only be called
4083 /// \param ObjCImpDecl the current ObjC @implementation decl;
4084 /// this is an ugly hack around the fact that ObjC @implementations
4085 /// aren't properly put in the context chain
4086 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
4087 SourceLocation OpLoc,
4088 tok::TokenKind OpKind,
4089 CXXScopeSpec &SS,
4090 UnqualifiedId &Id,
4091 Decl *ObjCImpDecl,
4092 bool HasTrailingLParen) {
4093 if (SS.isSet() && SS.isInvalid())
4094 return ExprError();
4096 // Warn about the explicit constructor calls Microsoft extension.
4097 if (getLangOptions().Microsoft &&
4098 Id.getKind() == UnqualifiedId::IK_ConstructorName)
4099 Diag(Id.getSourceRange().getBegin(),
4100 diag::ext_ms_explicit_constructor_call);
4102 TemplateArgumentListInfo TemplateArgsBuffer;
4104 // Decompose the name into its component parts.
4105 DeclarationNameInfo NameInfo;
4106 const TemplateArgumentListInfo *TemplateArgs;
4107 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
4108 NameInfo, TemplateArgs);
4110 DeclarationName Name = NameInfo.getName();
4111 bool IsArrow = (OpKind == tok::arrow);
4113 NamedDecl *FirstQualifierInScope
4114 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
4115 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
4117 // This is a postfix expression, so get rid of ParenListExprs.
4118 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
4119 if (Result.isInvalid()) return ExprError();
4120 Base = Result.take();
4122 if (Base->getType()->isDependentType() || Name.isDependentName() ||
4123 isDependentScopeSpecifier(SS)) {
4124 Result = ActOnDependentMemberExpr(Base, Base->getType(),
4125 IsArrow, OpLoc,
4126 SS, FirstQualifierInScope,
4127 NameInfo, TemplateArgs);
4128 } else {
4129 LookupResult R(*this, NameInfo, LookupMemberName);
4130 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
4131 SS, ObjCImpDecl, TemplateArgs != 0);
4133 if (Result.isInvalid()) {
4134 Owned(Base);
4135 return ExprError();
4138 if (Result.get()) {
4139 // The only way a reference to a destructor can be used is to
4140 // immediately call it, which falls into this case. If the
4141 // next token is not a '(', produce a diagnostic and build the
4142 // call now.
4143 if (!HasTrailingLParen &&
4144 Id.getKind() == UnqualifiedId::IK_DestructorName)
4145 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
4147 return move(Result);
4150 Result = BuildMemberReferenceExpr(Base, Base->getType(),
4151 OpLoc, IsArrow, SS, FirstQualifierInScope,
4152 R, TemplateArgs);
4155 return move(Result);
4158 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4159 FunctionDecl *FD,
4160 ParmVarDecl *Param) {
4161 if (Param->hasUnparsedDefaultArg()) {
4162 Diag(CallLoc,
4163 diag::err_use_of_default_argument_to_function_declared_later) <<
4164 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4165 Diag(UnparsedDefaultArgLocs[Param],
4166 diag::note_default_argument_declared_here);
4167 return ExprError();
4170 if (Param->hasUninstantiatedDefaultArg()) {
4171 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4173 // Instantiate the expression.
4174 MultiLevelTemplateArgumentList ArgList
4175 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
4177 std::pair<const TemplateArgument *, unsigned> Innermost
4178 = ArgList.getInnermost();
4179 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4180 Innermost.second);
4182 ExprResult Result;
4184 // C++ [dcl.fct.default]p5:
4185 // The names in the [default argument] expression are bound, and
4186 // the semantic constraints are checked, at the point where the
4187 // default argument expression appears.
4188 ContextRAII SavedContext(*this, FD);
4189 Result = SubstExpr(UninstExpr, ArgList);
4191 if (Result.isInvalid())
4192 return ExprError();
4194 // Check the expression as an initializer for the parameter.
4195 InitializedEntity Entity
4196 = InitializedEntity::InitializeParameter(Context, Param);
4197 InitializationKind Kind
4198 = InitializationKind::CreateCopy(Param->getLocation(),
4199 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4200 Expr *ResultE = Result.takeAs<Expr>();
4202 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4203 Result = InitSeq.Perform(*this, Entity, Kind,
4204 MultiExprArg(*this, &ResultE, 1));
4205 if (Result.isInvalid())
4206 return ExprError();
4208 // Build the default argument expression.
4209 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4210 Result.takeAs<Expr>()));
4213 // If the default expression creates temporaries, we need to
4214 // push them to the current stack of expression temporaries so they'll
4215 // be properly destroyed.
4216 // FIXME: We should really be rebuilding the default argument with new
4217 // bound temporaries; see the comment in PR5810.
4218 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4219 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4220 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4221 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4222 ExprTemporaries.push_back(Temporary);
4225 // We already type-checked the argument, so we know it works.
4226 // Just mark all of the declarations in this potentially-evaluated expression
4227 // as being "referenced".
4228 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
4229 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
4232 /// ConvertArgumentsForCall - Converts the arguments specified in
4233 /// Args/NumArgs to the parameter types of the function FDecl with
4234 /// function prototype Proto. Call is the call expression itself, and
4235 /// Fn is the function expression. For a C++ member function, this
4236 /// routine does not attempt to convert the object argument. Returns
4237 /// true if the call is ill-formed.
4238 bool
4239 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4240 FunctionDecl *FDecl,
4241 const FunctionProtoType *Proto,
4242 Expr **Args, unsigned NumArgs,
4243 SourceLocation RParenLoc) {
4244 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4245 // assignment, to the types of the corresponding parameter, ...
4246 unsigned NumArgsInProto = Proto->getNumArgs();
4247 bool Invalid = false;
4249 // If too few arguments are available (and we don't have default
4250 // arguments for the remaining parameters), don't make the call.
4251 if (NumArgs < NumArgsInProto) {
4252 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4253 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4254 << Fn->getType()->isBlockPointerType()
4255 << NumArgsInProto << NumArgs << Fn->getSourceRange();
4256 Call->setNumArgs(Context, NumArgsInProto);
4259 // If too many are passed and not variadic, error on the extras and drop
4260 // them.
4261 if (NumArgs > NumArgsInProto) {
4262 if (!Proto->isVariadic()) {
4263 Diag(Args[NumArgsInProto]->getLocStart(),
4264 diag::err_typecheck_call_too_many_args)
4265 << Fn->getType()->isBlockPointerType()
4266 << NumArgsInProto << NumArgs << Fn->getSourceRange()
4267 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4268 Args[NumArgs-1]->getLocEnd());
4269 // This deletes the extra arguments.
4270 Call->setNumArgs(Context, NumArgsInProto);
4271 return true;
4274 llvm::SmallVector<Expr *, 8> AllArgs;
4275 VariadicCallType CallType =
4276 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4277 if (Fn->getType()->isBlockPointerType())
4278 CallType = VariadicBlock; // Block
4279 else if (isa<MemberExpr>(Fn))
4280 CallType = VariadicMethod;
4281 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
4282 Proto, 0, Args, NumArgs, AllArgs, CallType);
4283 if (Invalid)
4284 return true;
4285 unsigned TotalNumArgs = AllArgs.size();
4286 for (unsigned i = 0; i < TotalNumArgs; ++i)
4287 Call->setArg(i, AllArgs[i]);
4289 return false;
4292 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4293 FunctionDecl *FDecl,
4294 const FunctionProtoType *Proto,
4295 unsigned FirstProtoArg,
4296 Expr **Args, unsigned NumArgs,
4297 llvm::SmallVector<Expr *, 8> &AllArgs,
4298 VariadicCallType CallType) {
4299 unsigned NumArgsInProto = Proto->getNumArgs();
4300 unsigned NumArgsToCheck = NumArgs;
4301 bool Invalid = false;
4302 if (NumArgs != NumArgsInProto)
4303 // Use default arguments for missing arguments
4304 NumArgsToCheck = NumArgsInProto;
4305 unsigned ArgIx = 0;
4306 // Continue to check argument types (even if we have too few/many args).
4307 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4308 QualType ProtoArgType = Proto->getArgType(i);
4310 Expr *Arg;
4311 if (ArgIx < NumArgs) {
4312 Arg = Args[ArgIx++];
4314 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4315 ProtoArgType,
4316 PDiag(diag::err_call_incomplete_argument)
4317 << Arg->getSourceRange()))
4318 return true;
4320 // Pass the argument
4321 ParmVarDecl *Param = 0;
4322 if (FDecl && i < FDecl->getNumParams())
4323 Param = FDecl->getParamDecl(i);
4325 InitializedEntity Entity =
4326 Param? InitializedEntity::InitializeParameter(Context, Param)
4327 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
4328 ExprResult ArgE = PerformCopyInitialization(Entity,
4329 SourceLocation(),
4330 Owned(Arg));
4331 if (ArgE.isInvalid())
4332 return true;
4334 Arg = ArgE.takeAs<Expr>();
4335 } else {
4336 ParmVarDecl *Param = FDecl->getParamDecl(i);
4338 ExprResult ArgExpr =
4339 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4340 if (ArgExpr.isInvalid())
4341 return true;
4343 Arg = ArgExpr.takeAs<Expr>();
4345 AllArgs.push_back(Arg);
4348 // If this is a variadic call, handle args passed through "...".
4349 if (CallType != VariadicDoesNotApply) {
4350 // Promote the arguments (C99 6.5.2.2p7).
4351 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4352 Expr *Arg = Args[i];
4353 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
4354 AllArgs.push_back(Arg);
4357 return Invalid;
4360 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4361 /// This provides the location of the left/right parens and a list of comma
4362 /// locations.
4363 ExprResult
4364 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4365 MultiExprArg args, SourceLocation RParenLoc,
4366 Expr *ExecConfig) {
4367 unsigned NumArgs = args.size();
4369 // Since this might be a postfix expression, get rid of ParenListExprs.
4370 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4371 if (Result.isInvalid()) return ExprError();
4372 Fn = Result.take();
4374 Expr **Args = args.release();
4376 if (getLangOptions().CPlusPlus) {
4377 // If this is a pseudo-destructor expression, build the call immediately.
4378 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4379 if (NumArgs > 0) {
4380 // Pseudo-destructor calls should not have any arguments.
4381 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4382 << FixItHint::CreateRemoval(
4383 SourceRange(Args[0]->getLocStart(),
4384 Args[NumArgs-1]->getLocEnd()));
4386 NumArgs = 0;
4389 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
4390 VK_RValue, RParenLoc));
4393 // Determine whether this is a dependent call inside a C++ template,
4394 // in which case we won't do any semantic analysis now.
4395 // FIXME: Will need to cache the results of name lookup (including ADL) in
4396 // Fn.
4397 bool Dependent = false;
4398 if (Fn->isTypeDependent())
4399 Dependent = true;
4400 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4401 Dependent = true;
4403 if (Dependent) {
4404 if (ExecConfig) {
4405 return Owned(new (Context) CUDAKernelCallExpr(
4406 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
4407 Context.DependentTy, VK_RValue, RParenLoc));
4408 } else {
4409 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4410 Context.DependentTy, VK_RValue,
4411 RParenLoc));
4415 // Determine whether this is a call to an object (C++ [over.call.object]).
4416 if (Fn->getType()->isRecordType())
4417 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
4418 RParenLoc));
4420 Expr *NakedFn = Fn->IgnoreParens();
4422 // Determine whether this is a call to an unresolved member function.
4423 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4424 // If lookup was unresolved but not dependent (i.e. didn't find
4425 // an unresolved using declaration), it has to be an overloaded
4426 // function set, which means it must contain either multiple
4427 // declarations (all methods or method templates) or a single
4428 // method template.
4429 assert((MemE->getNumDecls() > 1) ||
4430 isa<FunctionTemplateDecl>(
4431 (*MemE->decls_begin())->getUnderlyingDecl()));
4432 (void)MemE;
4434 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
4435 RParenLoc);
4438 // Determine whether this is a call to a member function.
4439 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
4440 NamedDecl *MemDecl = MemExpr->getMemberDecl();
4441 if (isa<CXXMethodDecl>(MemDecl))
4442 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
4443 RParenLoc);
4446 // Determine whether this is a call to a pointer-to-member function.
4447 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
4448 if (BO->getOpcode() == BO_PtrMemD ||
4449 BO->getOpcode() == BO_PtrMemI) {
4450 if (const FunctionProtoType *FPT
4451 = BO->getType()->getAs<FunctionProtoType>()) {
4452 QualType ResultTy = FPT->getCallResultType(Context);
4453 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
4455 // Check that the object type isn't more qualified than the
4456 // member function we're calling.
4457 Qualifiers FuncQuals = Qualifiers::fromCVRMask(FPT->getTypeQuals());
4458 Qualifiers ObjectQuals
4459 = BO->getOpcode() == BO_PtrMemD
4460 ? BO->getLHS()->getType().getQualifiers()
4461 : BO->getLHS()->getType()->getAs<PointerType>()
4462 ->getPointeeType().getQualifiers();
4464 Qualifiers Difference = ObjectQuals - FuncQuals;
4465 Difference.removeObjCGCAttr();
4466 Difference.removeAddressSpace();
4467 if (Difference) {
4468 std::string QualsString = Difference.getAsString();
4469 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
4470 << BO->getType().getUnqualifiedType()
4471 << QualsString
4472 << (QualsString.find(' ') == std::string::npos? 1 : 2);
4475 CXXMemberCallExpr *TheCall
4476 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
4477 NumArgs, ResultTy, VK,
4478 RParenLoc);
4480 if (CheckCallReturnType(FPT->getResultType(),
4481 BO->getRHS()->getSourceRange().getBegin(),
4482 TheCall, 0))
4483 return ExprError();
4485 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
4486 RParenLoc))
4487 return ExprError();
4489 return MaybeBindToTemporary(TheCall);
4491 return ExprError(Diag(Fn->getLocStart(),
4492 diag::err_typecheck_call_not_function)
4493 << Fn->getType() << Fn->getSourceRange());
4498 // If we're directly calling a function, get the appropriate declaration.
4499 // Also, in C++, keep track of whether we should perform argument-dependent
4500 // lookup and whether there were any explicitly-specified template arguments.
4502 Expr *NakedFn = Fn->IgnoreParens();
4503 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4504 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4505 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4506 RParenLoc, ExecConfig);
4509 NamedDecl *NDecl = 0;
4510 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4511 if (UnOp->getOpcode() == UO_AddrOf)
4512 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4514 if (isa<DeclRefExpr>(NakedFn))
4515 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4517 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
4518 ExecConfig);
4521 ExprResult
4522 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4523 MultiExprArg execConfig, SourceLocation GGGLoc) {
4524 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4525 if (!ConfigDecl)
4526 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4527 << "cudaConfigureCall");
4528 QualType ConfigQTy = ConfigDecl->getType();
4530 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4531 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
4533 return ActOnCallExpr(S, ConfigDR, LLLLoc, execConfig, GGGLoc, 0);
4536 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4537 /// i.e. an expression not of \p OverloadTy. The expression should
4538 /// unary-convert to an expression of function-pointer or
4539 /// block-pointer type.
4541 /// \param NDecl the declaration being called, if available
4542 ExprResult
4543 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4544 SourceLocation LParenLoc,
4545 Expr **Args, unsigned NumArgs,
4546 SourceLocation RParenLoc,
4547 Expr *Config) {
4548 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4550 // Promote the function operand.
4551 UsualUnaryConversions(Fn);
4553 // Make the call expr early, before semantic checks. This guarantees cleanup
4554 // of arguments and function on error.
4555 CallExpr *TheCall;
4556 if (Config) {
4557 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4558 cast<CallExpr>(Config),
4559 Args, NumArgs,
4560 Context.BoolTy,
4561 VK_RValue,
4562 RParenLoc);
4563 } else {
4564 TheCall = new (Context) CallExpr(Context, Fn,
4565 Args, NumArgs,
4566 Context.BoolTy,
4567 VK_RValue,
4568 RParenLoc);
4571 const FunctionType *FuncT;
4572 if (!Fn->getType()->isBlockPointerType()) {
4573 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4574 // have type pointer to function".
4575 const PointerType *PT = Fn->getType()->getAs<PointerType>();
4576 if (PT == 0)
4577 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4578 << Fn->getType() << Fn->getSourceRange());
4579 FuncT = PT->getPointeeType()->getAs<FunctionType>();
4580 } else { // This is a block call.
4581 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
4582 getAs<FunctionType>();
4584 if (FuncT == 0)
4585 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4586 << Fn->getType() << Fn->getSourceRange());
4588 // Check for a valid return type
4589 if (CheckCallReturnType(FuncT->getResultType(),
4590 Fn->getSourceRange().getBegin(), TheCall,
4591 FDecl))
4592 return ExprError();
4594 // We know the result type of the call, set it.
4595 TheCall->setType(FuncT->getCallResultType(Context));
4596 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4598 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
4599 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4600 RParenLoc))
4601 return ExprError();
4602 } else {
4603 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4605 if (FDecl) {
4606 // Check if we have too few/too many template arguments, based
4607 // on our knowledge of the function definition.
4608 const FunctionDecl *Def = 0;
4609 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4610 const FunctionProtoType *Proto
4611 = Def->getType()->getAs<FunctionProtoType>();
4612 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4613 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4614 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4617 // If the function we're calling isn't a function prototype, but we have
4618 // a function prototype from a prior declaratiom, use that prototype.
4619 if (!FDecl->hasPrototype())
4620 Proto = FDecl->getType()->getAs<FunctionProtoType>();
4623 // Promote the arguments (C99 6.5.2.2p6).
4624 for (unsigned i = 0; i != NumArgs; i++) {
4625 Expr *Arg = Args[i];
4627 if (Proto && i < Proto->getNumArgs()) {
4628 InitializedEntity Entity
4629 = InitializedEntity::InitializeParameter(Context,
4630 Proto->getArgType(i));
4631 ExprResult ArgE = PerformCopyInitialization(Entity,
4632 SourceLocation(),
4633 Owned(Arg));
4634 if (ArgE.isInvalid())
4635 return true;
4637 Arg = ArgE.takeAs<Expr>();
4639 } else {
4640 DefaultArgumentPromotion(Arg);
4643 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4644 Arg->getType(),
4645 PDiag(diag::err_call_incomplete_argument)
4646 << Arg->getSourceRange()))
4647 return ExprError();
4649 TheCall->setArg(i, Arg);
4653 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4654 if (!Method->isStatic())
4655 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4656 << Fn->getSourceRange());
4658 // Check for sentinels
4659 if (NDecl)
4660 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4662 // Do special checking on direct calls to functions.
4663 if (FDecl) {
4664 if (CheckFunctionCall(FDecl, TheCall))
4665 return ExprError();
4667 if (unsigned BuiltinID = FDecl->getBuiltinID())
4668 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4669 } else if (NDecl) {
4670 if (CheckBlockCall(NDecl, TheCall))
4671 return ExprError();
4674 return MaybeBindToTemporary(TheCall);
4677 ExprResult
4678 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4679 SourceLocation RParenLoc, Expr *InitExpr) {
4680 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4681 // FIXME: put back this assert when initializers are worked out.
4682 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4684 TypeSourceInfo *TInfo;
4685 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4686 if (!TInfo)
4687 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4689 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4692 ExprResult
4693 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4694 SourceLocation RParenLoc, Expr *literalExpr) {
4695 QualType literalType = TInfo->getType();
4697 if (literalType->isArrayType()) {
4698 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4699 PDiag(diag::err_illegal_decl_array_incomplete_type)
4700 << SourceRange(LParenLoc,
4701 literalExpr->getSourceRange().getEnd())))
4702 return ExprError();
4703 if (literalType->isVariableArrayType())
4704 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4705 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
4706 } else if (!literalType->isDependentType() &&
4707 RequireCompleteType(LParenLoc, literalType,
4708 PDiag(diag::err_typecheck_decl_incomplete_type)
4709 << SourceRange(LParenLoc,
4710 literalExpr->getSourceRange().getEnd())))
4711 return ExprError();
4713 InitializedEntity Entity
4714 = InitializedEntity::InitializeTemporary(literalType);
4715 InitializationKind Kind
4716 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
4717 /*IsCStyleCast=*/true);
4718 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
4719 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4720 MultiExprArg(*this, &literalExpr, 1),
4721 &literalType);
4722 if (Result.isInvalid())
4723 return ExprError();
4724 literalExpr = Result.get();
4726 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4727 if (isFileScope) { // 6.5.2.5p3
4728 if (CheckForConstantInitializer(literalExpr, literalType))
4729 return ExprError();
4732 // In C, compound literals are l-values for some reason.
4733 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4735 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4736 VK, literalExpr, isFileScope));
4739 ExprResult
4740 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
4741 SourceLocation RBraceLoc) {
4742 unsigned NumInit = initlist.size();
4743 Expr **InitList = initlist.release();
4745 // Semantic analysis for initializers is done by ActOnDeclarator() and
4746 // CheckInitializer() - it requires knowledge of the object being intialized.
4748 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4749 NumInit, RBraceLoc);
4750 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4751 return Owned(E);
4754 /// Prepares for a scalar cast, performing all the necessary stages
4755 /// except the final cast and returning the kind required.
4756 static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4757 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4758 // Also, callers should have filtered out the invalid cases with
4759 // pointers. Everything else should be possible.
4761 QualType SrcTy = Src->getType();
4762 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
4763 return CK_NoOp;
4765 switch (SrcTy->getScalarTypeKind()) {
4766 case Type::STK_MemberPointer:
4767 llvm_unreachable("member pointer type in C");
4769 case Type::STK_Pointer:
4770 switch (DestTy->getScalarTypeKind()) {
4771 case Type::STK_Pointer:
4772 return DestTy->isObjCObjectPointerType() ?
4773 CK_AnyPointerToObjCPointerCast :
4774 CK_BitCast;
4775 case Type::STK_Bool:
4776 return CK_PointerToBoolean;
4777 case Type::STK_Integral:
4778 return CK_PointerToIntegral;
4779 case Type::STK_Floating:
4780 case Type::STK_FloatingComplex:
4781 case Type::STK_IntegralComplex:
4782 case Type::STK_MemberPointer:
4783 llvm_unreachable("illegal cast from pointer");
4785 break;
4787 case Type::STK_Bool: // casting from bool is like casting from an integer
4788 case Type::STK_Integral:
4789 switch (DestTy->getScalarTypeKind()) {
4790 case Type::STK_Pointer:
4791 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
4792 return CK_NullToPointer;
4793 return CK_IntegralToPointer;
4794 case Type::STK_Bool:
4795 return CK_IntegralToBoolean;
4796 case Type::STK_Integral:
4797 return CK_IntegralCast;
4798 case Type::STK_Floating:
4799 return CK_IntegralToFloating;
4800 case Type::STK_IntegralComplex:
4801 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4802 CK_IntegralCast);
4803 return CK_IntegralRealToComplex;
4804 case Type::STK_FloatingComplex:
4805 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4806 CK_IntegralToFloating);
4807 return CK_FloatingRealToComplex;
4808 case Type::STK_MemberPointer:
4809 llvm_unreachable("member pointer type in C");
4811 break;
4813 case Type::STK_Floating:
4814 switch (DestTy->getScalarTypeKind()) {
4815 case Type::STK_Floating:
4816 return CK_FloatingCast;
4817 case Type::STK_Bool:
4818 return CK_FloatingToBoolean;
4819 case Type::STK_Integral:
4820 return CK_FloatingToIntegral;
4821 case Type::STK_FloatingComplex:
4822 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4823 CK_FloatingCast);
4824 return CK_FloatingRealToComplex;
4825 case Type::STK_IntegralComplex:
4826 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4827 CK_FloatingToIntegral);
4828 return CK_IntegralRealToComplex;
4829 case Type::STK_Pointer:
4830 llvm_unreachable("valid float->pointer cast?");
4831 case Type::STK_MemberPointer:
4832 llvm_unreachable("member pointer type in C");
4834 break;
4836 case Type::STK_FloatingComplex:
4837 switch (DestTy->getScalarTypeKind()) {
4838 case Type::STK_FloatingComplex:
4839 return CK_FloatingComplexCast;
4840 case Type::STK_IntegralComplex:
4841 return CK_FloatingComplexToIntegralComplex;
4842 case Type::STK_Floating: {
4843 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
4844 if (S.Context.hasSameType(ET, DestTy))
4845 return CK_FloatingComplexToReal;
4846 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4847 return CK_FloatingCast;
4849 case Type::STK_Bool:
4850 return CK_FloatingComplexToBoolean;
4851 case Type::STK_Integral:
4852 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
4853 CK_FloatingComplexToReal);
4854 return CK_FloatingToIntegral;
4855 case Type::STK_Pointer:
4856 llvm_unreachable("valid complex float->pointer cast?");
4857 case Type::STK_MemberPointer:
4858 llvm_unreachable("member pointer type in C");
4860 break;
4862 case Type::STK_IntegralComplex:
4863 switch (DestTy->getScalarTypeKind()) {
4864 case Type::STK_FloatingComplex:
4865 return CK_IntegralComplexToFloatingComplex;
4866 case Type::STK_IntegralComplex:
4867 return CK_IntegralComplexCast;
4868 case Type::STK_Integral: {
4869 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
4870 if (S.Context.hasSameType(ET, DestTy))
4871 return CK_IntegralComplexToReal;
4872 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4873 return CK_IntegralCast;
4875 case Type::STK_Bool:
4876 return CK_IntegralComplexToBoolean;
4877 case Type::STK_Floating:
4878 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
4879 CK_IntegralComplexToReal);
4880 return CK_IntegralToFloating;
4881 case Type::STK_Pointer:
4882 llvm_unreachable("valid complex int->pointer cast?");
4883 case Type::STK_MemberPointer:
4884 llvm_unreachable("member pointer type in C");
4886 break;
4889 llvm_unreachable("Unhandled scalar cast");
4890 return CK_BitCast;
4893 /// CheckCastTypes - Check type constraints for casting between types.
4894 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4895 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4896 CXXCastPath &BasePath, bool FunctionalStyle) {
4897 if (getLangOptions().CPlusPlus)
4898 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4899 castExpr->getLocEnd()),
4900 castType, VK, castExpr, Kind, BasePath,
4901 FunctionalStyle);
4903 // We only support r-value casts in C.
4904 VK = VK_RValue;
4906 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4907 // type needs to be scalar.
4908 if (castType->isVoidType()) {
4909 // We don't necessarily do lvalue-to-rvalue conversions on this.
4910 IgnoredValueConversions(castExpr);
4912 // Cast to void allows any expr type.
4913 Kind = CK_ToVoid;
4914 return false;
4917 DefaultFunctionArrayLvalueConversion(castExpr);
4919 if (RequireCompleteType(TyR.getBegin(), castType,
4920 diag::err_typecheck_cast_to_incomplete))
4921 return true;
4923 if (!castType->isScalarType() && !castType->isVectorType()) {
4924 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
4925 (castType->isStructureType() || castType->isUnionType())) {
4926 // GCC struct/union extension: allow cast to self.
4927 // FIXME: Check that the cast destination type is complete.
4928 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4929 << castType << castExpr->getSourceRange();
4930 Kind = CK_NoOp;
4931 return false;
4934 if (castType->isUnionType()) {
4935 // GCC cast to union extension
4936 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
4937 RecordDecl::field_iterator Field, FieldEnd;
4938 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
4939 Field != FieldEnd; ++Field) {
4940 if (Context.hasSameUnqualifiedType(Field->getType(),
4941 castExpr->getType()) &&
4942 !Field->isUnnamedBitfield()) {
4943 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4944 << castExpr->getSourceRange();
4945 break;
4948 if (Field == FieldEnd)
4949 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4950 << castExpr->getType() << castExpr->getSourceRange();
4951 Kind = CK_ToUnion;
4952 return false;
4955 // Reject any other conversions to non-scalar types.
4956 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4957 << castType << castExpr->getSourceRange();
4960 // The type we're casting to is known to be a scalar or vector.
4962 // Require the operand to be a scalar or vector.
4963 if (!castExpr->getType()->isScalarType() &&
4964 !castExpr->getType()->isVectorType()) {
4965 return Diag(castExpr->getLocStart(),
4966 diag::err_typecheck_expect_scalar_operand)
4967 << castExpr->getType() << castExpr->getSourceRange();
4970 if (castType->isExtVectorType())
4971 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
4973 if (castType->isVectorType())
4974 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4975 if (castExpr->getType()->isVectorType())
4976 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4978 // The source and target types are both scalars, i.e.
4979 // - arithmetic types (fundamental, enum, and complex)
4980 // - all kinds of pointers
4981 // Note that member pointers were filtered out with C++, above.
4983 if (isa<ObjCSelectorExpr>(castExpr))
4984 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4986 // If either type is a pointer, the other type has to be either an
4987 // integer or a pointer.
4988 if (!castType->isArithmeticType()) {
4989 QualType castExprType = castExpr->getType();
4990 if (!castExprType->isIntegralType(Context) &&
4991 castExprType->isArithmeticType())
4992 return Diag(castExpr->getLocStart(),
4993 diag::err_cast_pointer_from_non_pointer_int)
4994 << castExprType << castExpr->getSourceRange();
4995 } else if (!castExpr->getType()->isArithmeticType()) {
4996 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
4997 return Diag(castExpr->getLocStart(),
4998 diag::err_cast_pointer_to_non_pointer_int)
4999 << castType << castExpr->getSourceRange();
5002 Kind = PrepareScalarCast(*this, castExpr, castType);
5004 if (Kind == CK_BitCast)
5005 CheckCastAlign(castExpr, castType, TyR);
5007 return false;
5010 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5011 CastKind &Kind) {
5012 assert(VectorTy->isVectorType() && "Not a vector type!");
5014 if (Ty->isVectorType() || Ty->isIntegerType()) {
5015 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
5016 return Diag(R.getBegin(),
5017 Ty->isVectorType() ?
5018 diag::err_invalid_conversion_between_vectors :
5019 diag::err_invalid_conversion_between_vector_and_integer)
5020 << VectorTy << Ty << R;
5021 } else
5022 return Diag(R.getBegin(),
5023 diag::err_invalid_conversion_between_vector_and_scalar)
5024 << VectorTy << Ty << R;
5026 Kind = CK_BitCast;
5027 return false;
5030 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
5031 CastKind &Kind) {
5032 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5034 QualType SrcTy = CastExpr->getType();
5036 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5037 // an ExtVectorType.
5038 if (SrcTy->isVectorType()) {
5039 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
5040 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5041 << DestTy << SrcTy << R;
5042 Kind = CK_BitCast;
5043 return false;
5046 // All non-pointer scalars can be cast to ExtVector type. The appropriate
5047 // conversion will take place first from scalar to elt type, and then
5048 // splat from elt type to vector.
5049 if (SrcTy->isPointerType())
5050 return Diag(R.getBegin(),
5051 diag::err_invalid_conversion_between_vector_and_scalar)
5052 << DestTy << SrcTy << R;
5054 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5055 ImpCastExprToType(CastExpr, DestElemTy,
5056 PrepareScalarCast(*this, CastExpr, DestElemTy));
5058 Kind = CK_VectorSplat;
5059 return false;
5062 ExprResult
5063 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
5064 SourceLocation RParenLoc, Expr *castExpr) {
5065 assert((Ty != 0) && (castExpr != 0) &&
5066 "ActOnCastExpr(): missing type or expr");
5068 TypeSourceInfo *castTInfo;
5069 QualType castType = GetTypeFromParser(Ty, &castTInfo);
5070 if (!castTInfo)
5071 castTInfo = Context.getTrivialTypeSourceInfo(castType);
5073 // If the Expr being casted is a ParenListExpr, handle it specially.
5074 if (isa<ParenListExpr>(castExpr))
5075 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
5076 castTInfo);
5078 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
5081 ExprResult
5082 Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
5083 SourceLocation RParenLoc, Expr *castExpr) {
5084 CastKind Kind = CK_Invalid;
5085 ExprValueKind VK = VK_RValue;
5086 CXXCastPath BasePath;
5087 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
5088 Kind, VK, BasePath))
5089 return ExprError();
5091 return Owned(CStyleCastExpr::Create(Context,
5092 Ty->getType().getNonLValueExprType(Context),
5093 VK, Kind, castExpr, &BasePath, Ty,
5094 LParenLoc, RParenLoc));
5097 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
5098 /// of comma binary operators.
5099 ExprResult
5100 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
5101 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
5102 if (!E)
5103 return Owned(expr);
5105 ExprResult Result(E->getExpr(0));
5107 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5108 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5109 E->getExpr(i));
5111 if (Result.isInvalid()) return ExprError();
5113 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5116 ExprResult
5117 Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
5118 SourceLocation RParenLoc, Expr *Op,
5119 TypeSourceInfo *TInfo) {
5120 ParenListExpr *PE = cast<ParenListExpr>(Op);
5121 QualType Ty = TInfo->getType();
5122 bool isAltiVecLiteral = false;
5124 // Check for an altivec literal,
5125 // i.e. all the elements are integer constants.
5126 if (getLangOptions().AltiVec && Ty->isVectorType()) {
5127 if (PE->getNumExprs() == 0) {
5128 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
5129 return ExprError();
5131 if (PE->getNumExprs() == 1) {
5132 if (!PE->getExpr(0)->getType()->isVectorType())
5133 isAltiVecLiteral = true;
5135 else
5136 isAltiVecLiteral = true;
5139 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
5140 // then handle it as such.
5141 if (isAltiVecLiteral) {
5142 llvm::SmallVector<Expr *, 8> initExprs;
5143 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
5144 initExprs.push_back(PE->getExpr(i));
5146 // FIXME: This means that pretty-printing the final AST will produce curly
5147 // braces instead of the original commas.
5148 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
5149 &initExprs[0],
5150 initExprs.size(), RParenLoc);
5151 E->setType(Ty);
5152 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
5153 } else {
5154 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5155 // sequence of BinOp comma operators.
5156 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
5157 if (Result.isInvalid()) return ExprError();
5158 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
5162 ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
5163 SourceLocation R,
5164 MultiExprArg Val,
5165 ParsedType TypeOfCast) {
5166 unsigned nexprs = Val.size();
5167 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
5168 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
5169 Expr *expr;
5170 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
5171 expr = new (Context) ParenExpr(L, R, exprs[0]);
5172 else
5173 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
5174 return Owned(expr);
5177 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
5178 /// In that case, lhs = cond.
5179 /// C99 6.5.15
5180 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
5181 Expr *&SAVE, ExprValueKind &VK,
5182 ExprObjectKind &OK,
5183 SourceLocation QuestionLoc) {
5184 // If both LHS and RHS are overloaded functions, try to resolve them.
5185 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
5186 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
5187 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
5188 if (LHSResult.isInvalid())
5189 return QualType();
5191 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
5192 if (RHSResult.isInvalid())
5193 return QualType();
5195 LHS = LHSResult.take();
5196 RHS = RHSResult.take();
5199 // C++ is sufficiently different to merit its own checker.
5200 if (getLangOptions().CPlusPlus)
5201 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
5202 VK, OK, QuestionLoc);
5204 VK = VK_RValue;
5205 OK = OK_Ordinary;
5207 UsualUnaryConversions(Cond);
5208 if (SAVE) {
5209 SAVE = LHS = Cond;
5211 else
5212 UsualUnaryConversions(LHS);
5213 UsualUnaryConversions(RHS);
5214 QualType CondTy = Cond->getType();
5215 QualType LHSTy = LHS->getType();
5216 QualType RHSTy = RHS->getType();
5218 // first, check the condition.
5219 if (!CondTy->isScalarType()) { // C99 6.5.15p2
5220 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
5221 // Throw an error if its not either.
5222 if (getLangOptions().OpenCL) {
5223 if (!CondTy->isVectorType()) {
5224 Diag(Cond->getLocStart(),
5225 diag::err_typecheck_cond_expect_scalar_or_vector)
5226 << CondTy;
5227 return QualType();
5230 else {
5231 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5232 << CondTy;
5233 return QualType();
5237 // Now check the two expressions.
5238 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5239 return CheckVectorOperands(QuestionLoc, LHS, RHS);
5241 // OpenCL: If the condition is a vector, and both operands are scalar,
5242 // attempt to implicity convert them to the vector type to act like the
5243 // built in select.
5244 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5245 // Both operands should be of scalar type.
5246 if (!LHSTy->isScalarType()) {
5247 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5248 << CondTy;
5249 return QualType();
5251 if (!RHSTy->isScalarType()) {
5252 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5253 << CondTy;
5254 return QualType();
5256 // Implicity convert these scalars to the type of the condition.
5257 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5258 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5261 // If both operands have arithmetic type, do the usual arithmetic conversions
5262 // to find a common type: C99 6.5.15p3,5.
5263 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5264 UsualArithmeticConversions(LHS, RHS);
5265 return LHS->getType();
5268 // If both operands are the same structure or union type, the result is that
5269 // type.
5270 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5271 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5272 if (LHSRT->getDecl() == RHSRT->getDecl())
5273 // "If both the operands have structure or union type, the result has
5274 // that type." This implies that CV qualifiers are dropped.
5275 return LHSTy.getUnqualifiedType();
5276 // FIXME: Type of conditional expression must be complete in C mode.
5279 // C99 6.5.15p5: "If both operands have void type, the result has void type."
5280 // The following || allows only one side to be void (a GCC-ism).
5281 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5282 if (!LHSTy->isVoidType())
5283 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5284 << RHS->getSourceRange();
5285 if (!RHSTy->isVoidType())
5286 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5287 << LHS->getSourceRange();
5288 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5289 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
5290 return Context.VoidTy;
5292 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5293 // the type of the other operand."
5294 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
5295 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5296 // promote the null to a pointer.
5297 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
5298 return LHSTy;
5300 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
5301 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5302 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
5303 return RHSTy;
5306 // All objective-c pointer type analysis is done here.
5307 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5308 QuestionLoc);
5309 if (!compositeType.isNull())
5310 return compositeType;
5313 // Handle block pointer types.
5314 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5315 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5316 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5317 QualType destType = Context.getPointerType(Context.VoidTy);
5318 ImpCastExprToType(LHS, destType, CK_BitCast);
5319 ImpCastExprToType(RHS, destType, CK_BitCast);
5320 return destType;
5322 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5323 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5324 return QualType();
5326 // We have 2 block pointer types.
5327 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5328 // Two identical block pointer types are always compatible.
5329 return LHSTy;
5331 // The block pointer types aren't identical, continue checking.
5332 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5333 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
5335 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5336 rhptee.getUnqualifiedType())) {
5337 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5338 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5339 // In this situation, we assume void* type. No especially good
5340 // reason, but this is what gcc does, and we do have to pick
5341 // to get a consistent AST.
5342 QualType incompatTy = Context.getPointerType(Context.VoidTy);
5343 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5344 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5345 return incompatTy;
5347 // The block pointer types are compatible.
5348 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5349 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5350 return LHSTy;
5353 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5354 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5355 // get the "pointed to" types
5356 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5357 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5359 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5360 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5361 // Figure out necessary qualifiers (C99 6.5.15p6)
5362 QualType destPointee
5363 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5364 QualType destType = Context.getPointerType(destPointee);
5365 // Add qualifiers if necessary.
5366 ImpCastExprToType(LHS, destType, CK_NoOp);
5367 // Promote to void*.
5368 ImpCastExprToType(RHS, destType, CK_BitCast);
5369 return destType;
5371 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5372 QualType destPointee
5373 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5374 QualType destType = Context.getPointerType(destPointee);
5375 // Add qualifiers if necessary.
5376 ImpCastExprToType(RHS, destType, CK_NoOp);
5377 // Promote to void*.
5378 ImpCastExprToType(LHS, destType, CK_BitCast);
5379 return destType;
5382 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5383 // Two identical pointer types are always compatible.
5384 return LHSTy;
5386 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5387 rhptee.getUnqualifiedType())) {
5388 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5389 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5390 // In this situation, we assume void* type. No especially good
5391 // reason, but this is what gcc does, and we do have to pick
5392 // to get a consistent AST.
5393 QualType incompatTy = Context.getPointerType(Context.VoidTy);
5394 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5395 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5396 return incompatTy;
5398 // The pointer types are compatible.
5399 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5400 // differently qualified versions of compatible types, the result type is
5401 // a pointer to an appropriately qualified version of the *composite*
5402 // type.
5403 // FIXME: Need to calculate the composite type.
5404 // FIXME: Need to add qualifiers
5405 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5406 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5407 return LHSTy;
5410 // GCC compatibility: soften pointer/integer mismatch. Note that
5411 // null pointers have been filtered out by this point.
5412 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5413 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5414 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5415 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
5416 return RHSTy;
5418 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5419 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5420 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5421 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
5422 return LHSTy;
5425 // Otherwise, the operands are not compatible.
5426 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5427 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5428 return QualType();
5431 /// FindCompositeObjCPointerType - Helper method to find composite type of
5432 /// two objective-c pointer types of the two input expressions.
5433 QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5434 SourceLocation QuestionLoc) {
5435 QualType LHSTy = LHS->getType();
5436 QualType RHSTy = RHS->getType();
5438 // Handle things like Class and struct objc_class*. Here we case the result
5439 // to the pseudo-builtin, because that will be implicitly cast back to the
5440 // redefinition type if an attempt is made to access its fields.
5441 if (LHSTy->isObjCClassType() &&
5442 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
5443 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5444 return LHSTy;
5446 if (RHSTy->isObjCClassType() &&
5447 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
5448 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5449 return RHSTy;
5451 // And the same for struct objc_object* / id
5452 if (LHSTy->isObjCIdType() &&
5453 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
5454 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5455 return LHSTy;
5457 if (RHSTy->isObjCIdType() &&
5458 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
5459 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5460 return RHSTy;
5462 // And the same for struct objc_selector* / SEL
5463 if (Context.isObjCSelType(LHSTy) &&
5464 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
5465 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5466 return LHSTy;
5468 if (Context.isObjCSelType(RHSTy) &&
5469 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
5470 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5471 return RHSTy;
5473 // Check constraints for Objective-C object pointers types.
5474 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5476 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5477 // Two identical object pointer types are always compatible.
5478 return LHSTy;
5480 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5481 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5482 QualType compositeType = LHSTy;
5484 // If both operands are interfaces and either operand can be
5485 // assigned to the other, use that type as the composite
5486 // type. This allows
5487 // xxx ? (A*) a : (B*) b
5488 // where B is a subclass of A.
5490 // Additionally, as for assignment, if either type is 'id'
5491 // allow silent coercion. Finally, if the types are
5492 // incompatible then make sure to use 'id' as the composite
5493 // type so the result is acceptable for sending messages to.
5495 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5496 // It could return the composite type.
5497 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5498 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5499 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5500 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5501 } else if ((LHSTy->isObjCQualifiedIdType() ||
5502 RHSTy->isObjCQualifiedIdType()) &&
5503 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5504 // Need to handle "id<xx>" explicitly.
5505 // GCC allows qualified id and any Objective-C type to devolve to
5506 // id. Currently localizing to here until clear this should be
5507 // part of ObjCQualifiedIdTypesAreCompatible.
5508 compositeType = Context.getObjCIdType();
5509 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5510 compositeType = Context.getObjCIdType();
5511 } else if (!(compositeType =
5512 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5514 else {
5515 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5516 << LHSTy << RHSTy
5517 << LHS->getSourceRange() << RHS->getSourceRange();
5518 QualType incompatTy = Context.getObjCIdType();
5519 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5520 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5521 return incompatTy;
5523 // The object pointer types are compatible.
5524 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5525 ImpCastExprToType(RHS, compositeType, CK_BitCast);
5526 return compositeType;
5528 // Check Objective-C object pointer types and 'void *'
5529 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5530 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5531 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5532 QualType destPointee
5533 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5534 QualType destType = Context.getPointerType(destPointee);
5535 // Add qualifiers if necessary.
5536 ImpCastExprToType(LHS, destType, CK_NoOp);
5537 // Promote to void*.
5538 ImpCastExprToType(RHS, destType, CK_BitCast);
5539 return destType;
5541 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5542 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5543 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5544 QualType destPointee
5545 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5546 QualType destType = Context.getPointerType(destPointee);
5547 // Add qualifiers if necessary.
5548 ImpCastExprToType(RHS, destType, CK_NoOp);
5549 // Promote to void*.
5550 ImpCastExprToType(LHS, destType, CK_BitCast);
5551 return destType;
5553 return QualType();
5556 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5557 /// in the case of a the GNU conditional expr extension.
5558 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5559 SourceLocation ColonLoc,
5560 Expr *CondExpr, Expr *LHSExpr,
5561 Expr *RHSExpr) {
5562 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5563 // was the condition.
5564 bool isLHSNull = LHSExpr == 0;
5565 Expr *SAVEExpr = 0;
5566 if (isLHSNull) {
5567 LHSExpr = SAVEExpr = CondExpr;
5570 ExprValueKind VK = VK_RValue;
5571 ExprObjectKind OK = OK_Ordinary;
5572 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
5573 SAVEExpr, VK, OK, QuestionLoc);
5574 if (result.isNull())
5575 return ExprError();
5577 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5578 LHSExpr, ColonLoc,
5579 RHSExpr, SAVEExpr,
5580 result, VK, OK));
5583 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5584 // being closely modeled after the C99 spec:-). The odd characteristic of this
5585 // routine is it effectively iqnores the qualifiers on the top level pointee.
5586 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5587 // FIXME: add a couple examples in this comment.
5588 static Sema::AssignConvertType
5589 checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5590 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5591 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5593 // get the "pointed to" type (ignoring qualifiers at the top level)
5594 const Type *lhptee, *rhptee;
5595 Qualifiers lhq, rhq;
5596 llvm::tie(lhptee, lhq) = cast<PointerType>(lhsType)->getPointeeType().split();
5597 llvm::tie(rhptee, rhq) = cast<PointerType>(rhsType)->getPointeeType().split();
5599 Sema::AssignConvertType ConvTy = Sema::Compatible;
5601 // C99 6.5.16.1p1: This following citation is common to constraints
5602 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5603 // qualifiers of the type *pointed to* by the right;
5604 Qualifiers lq;
5606 if (!lhq.compatiblyIncludes(rhq)) {
5607 // Treat address-space mismatches as fatal. TODO: address subspaces
5608 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5609 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5611 // For GCC compatibility, other qualifier mismatches are treated
5612 // as still compatible in C.
5613 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5616 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5617 // incomplete type and the other is a pointer to a qualified or unqualified
5618 // version of void...
5619 if (lhptee->isVoidType()) {
5620 if (rhptee->isIncompleteOrObjectType())
5621 return ConvTy;
5623 // As an extension, we allow cast to/from void* to function pointer.
5624 assert(rhptee->isFunctionType());
5625 return Sema::FunctionVoidPointer;
5628 if (rhptee->isVoidType()) {
5629 if (lhptee->isIncompleteOrObjectType())
5630 return ConvTy;
5632 // As an extension, we allow cast to/from void* to function pointer.
5633 assert(lhptee->isFunctionType());
5634 return Sema::FunctionVoidPointer;
5637 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5638 // unqualified versions of compatible types, ...
5639 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5640 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5641 // Check if the pointee types are compatible ignoring the sign.
5642 // We explicitly check for char so that we catch "char" vs
5643 // "unsigned char" on systems where "char" is unsigned.
5644 if (lhptee->isCharType())
5645 ltrans = S.Context.UnsignedCharTy;
5646 else if (lhptee->hasSignedIntegerRepresentation())
5647 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5649 if (rhptee->isCharType())
5650 rtrans = S.Context.UnsignedCharTy;
5651 else if (rhptee->hasSignedIntegerRepresentation())
5652 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5654 if (ltrans == rtrans) {
5655 // Types are compatible ignoring the sign. Qualifier incompatibility
5656 // takes priority over sign incompatibility because the sign
5657 // warning can be disabled.
5658 if (ConvTy != Sema::Compatible)
5659 return ConvTy;
5661 return Sema::IncompatiblePointerSign;
5664 // If we are a multi-level pointer, it's possible that our issue is simply
5665 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5666 // the eventual target type is the same and the pointers have the same
5667 // level of indirection, this must be the issue.
5668 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5669 do {
5670 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5671 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5672 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5674 if (lhptee == rhptee)
5675 return Sema::IncompatibleNestedPointerQualifiers;
5678 // General pointer incompatibility takes priority over qualifiers.
5679 return Sema::IncompatiblePointer;
5681 return ConvTy;
5684 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5685 /// block pointer types are compatible or whether a block and normal pointer
5686 /// are compatible. It is more restrict than comparing two function pointer
5687 // types.
5688 static Sema::AssignConvertType
5689 checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5690 QualType rhsType) {
5691 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5692 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5694 QualType lhptee, rhptee;
5696 // get the "pointed to" type (ignoring qualifiers at the top level)
5697 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5698 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
5700 // In C++, the types have to match exactly.
5701 if (S.getLangOptions().CPlusPlus)
5702 return Sema::IncompatibleBlockPointer;
5704 Sema::AssignConvertType ConvTy = Sema::Compatible;
5706 // For blocks we enforce that qualifiers are identical.
5707 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5708 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5710 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5711 return Sema::IncompatibleBlockPointer;
5713 return ConvTy;
5716 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5717 /// for assignment compatibility.
5718 static Sema::AssignConvertType
5719 checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5720 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5721 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5723 if (lhsType->isObjCBuiltinType()) {
5724 // Class is not compatible with ObjC object pointers.
5725 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5726 !rhsType->isObjCQualifiedClassType())
5727 return Sema::IncompatiblePointer;
5728 return Sema::Compatible;
5730 if (rhsType->isObjCBuiltinType()) {
5731 // Class is not compatible with ObjC object pointers.
5732 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5733 !lhsType->isObjCQualifiedClassType())
5734 return Sema::IncompatiblePointer;
5735 return Sema::Compatible;
5737 QualType lhptee =
5738 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5739 QualType rhptee =
5740 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5742 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5743 return Sema::CompatiblePointerDiscardsQualifiers;
5745 if (S.Context.typesAreCompatible(lhsType, rhsType))
5746 return Sema::Compatible;
5747 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5748 return Sema::IncompatibleObjCQualifiedId;
5749 return Sema::IncompatiblePointer;
5752 Sema::AssignConvertType
5753 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5754 QualType lhsType, QualType rhsType) {
5755 // Fake up an opaque expression. We don't actually care about what
5756 // cast operations are required, so if CheckAssignmentConstraints
5757 // adds casts to this they'll be wasted, but fortunately that doesn't
5758 // usually happen on valid code.
5759 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
5760 Expr *rhsPtr = &rhs;
5761 CastKind K = CK_Invalid;
5763 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5766 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5767 /// has code to accommodate several GCC extensions when type checking
5768 /// pointers. Here are some objectionable examples that GCC considers warnings:
5770 /// int a, *pint;
5771 /// short *pshort;
5772 /// struct foo *pfoo;
5774 /// pint = pshort; // warning: assignment from incompatible pointer type
5775 /// a = pint; // warning: assignment makes integer from pointer without a cast
5776 /// pint = a; // warning: assignment makes pointer from integer without a cast
5777 /// pint = pfoo; // warning: assignment from incompatible pointer type
5779 /// As a result, the code for dealing with pointers is more complex than the
5780 /// C99 spec dictates.
5782 /// Sets 'Kind' for any result kind except Incompatible.
5783 Sema::AssignConvertType
5784 Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
5785 CastKind &Kind) {
5786 QualType rhsType = rhs->getType();
5788 // Get canonical types. We're not formatting these types, just comparing
5789 // them.
5790 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5791 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
5793 // Common case: no conversion required.
5794 if (lhsType == rhsType) {
5795 Kind = CK_NoOp;
5796 return Compatible;
5799 // If the left-hand side is a reference type, then we are in a
5800 // (rare!) case where we've allowed the use of references in C,
5801 // e.g., as a parameter type in a built-in function. In this case,
5802 // just make sure that the type referenced is compatible with the
5803 // right-hand side type. The caller is responsible for adjusting
5804 // lhsType so that the resulting expression does not have reference
5805 // type.
5806 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
5807 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5808 Kind = CK_LValueBitCast;
5809 return Compatible;
5811 return Incompatible;
5814 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5815 // to the same ExtVector type.
5816 if (lhsType->isExtVectorType()) {
5817 if (rhsType->isExtVectorType())
5818 return Incompatible;
5819 if (rhsType->isArithmeticType()) {
5820 // CK_VectorSplat does T -> vector T, so first cast to the
5821 // element type.
5822 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5823 if (elType != rhsType) {
5824 Kind = PrepareScalarCast(*this, rhs, elType);
5825 ImpCastExprToType(rhs, elType, Kind);
5827 Kind = CK_VectorSplat;
5828 return Compatible;
5832 // Conversions to or from vector type.
5833 if (lhsType->isVectorType() || rhsType->isVectorType()) {
5834 if (lhsType->isVectorType() && rhsType->isVectorType()) {
5835 // Allow assignments of an AltiVec vector type to an equivalent GCC
5836 // vector type and vice versa
5837 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5838 Kind = CK_BitCast;
5839 return Compatible;
5842 // If we are allowing lax vector conversions, and LHS and RHS are both
5843 // vectors, the total size only needs to be the same. This is a bitcast;
5844 // no bits are changed but the result type is different.
5845 if (getLangOptions().LaxVectorConversions &&
5846 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
5847 Kind = CK_BitCast;
5848 return IncompatibleVectors;
5851 return Incompatible;
5854 // Arithmetic conversions.
5855 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
5856 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
5857 Kind = PrepareScalarCast(*this, rhs, lhsType);
5858 return Compatible;
5861 // Conversions to normal pointers.
5862 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5863 // U* -> T*
5864 if (isa<PointerType>(rhsType)) {
5865 Kind = CK_BitCast;
5866 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
5869 // int -> T*
5870 if (rhsType->isIntegerType()) {
5871 Kind = CK_IntegralToPointer; // FIXME: null?
5872 return IntToPointer;
5875 // C pointers are not compatible with ObjC object pointers,
5876 // with two exceptions:
5877 if (isa<ObjCObjectPointerType>(rhsType)) {
5878 // - conversions to void*
5879 if (lhsPointer->getPointeeType()->isVoidType()) {
5880 Kind = CK_AnyPointerToObjCPointerCast;
5881 return Compatible;
5884 // - conversions from 'Class' to the redefinition type
5885 if (rhsType->isObjCClassType() &&
5886 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
5887 Kind = CK_BitCast;
5888 return Compatible;
5891 Kind = CK_BitCast;
5892 return IncompatiblePointer;
5895 // U^ -> void*
5896 if (rhsType->getAs<BlockPointerType>()) {
5897 if (lhsPointer->getPointeeType()->isVoidType()) {
5898 Kind = CK_BitCast;
5899 return Compatible;
5903 return Incompatible;
5906 // Conversions to block pointers.
5907 if (isa<BlockPointerType>(lhsType)) {
5908 // U^ -> T^
5909 if (rhsType->isBlockPointerType()) {
5910 Kind = CK_AnyPointerToBlockPointerCast;
5911 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
5914 // int or null -> T^
5915 if (rhsType->isIntegerType()) {
5916 Kind = CK_IntegralToPointer; // FIXME: null
5917 return IntToBlockPointer;
5920 // id -> T^
5921 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5922 Kind = CK_AnyPointerToBlockPointerCast;
5923 return Compatible;
5926 // void* -> T^
5927 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
5928 if (RHSPT->getPointeeType()->isVoidType()) {
5929 Kind = CK_AnyPointerToBlockPointerCast;
5930 return Compatible;
5933 return Incompatible;
5936 // Conversions to Objective-C pointers.
5937 if (isa<ObjCObjectPointerType>(lhsType)) {
5938 // A* -> B*
5939 if (rhsType->isObjCObjectPointerType()) {
5940 Kind = CK_BitCast;
5941 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5944 // int or null -> A*
5945 if (rhsType->isIntegerType()) {
5946 Kind = CK_IntegralToPointer; // FIXME: null
5947 return IntToPointer;
5950 // In general, C pointers are not compatible with ObjC object pointers,
5951 // with two exceptions:
5952 if (isa<PointerType>(rhsType)) {
5953 // - conversions from 'void*'
5954 if (rhsType->isVoidPointerType()) {
5955 Kind = CK_AnyPointerToObjCPointerCast;
5956 return Compatible;
5959 // - conversions to 'Class' from its redefinition type
5960 if (lhsType->isObjCClassType() &&
5961 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5962 Kind = CK_BitCast;
5963 return Compatible;
5966 Kind = CK_AnyPointerToObjCPointerCast;
5967 return IncompatiblePointer;
5970 // T^ -> A*
5971 if (rhsType->isBlockPointerType()) {
5972 Kind = CK_AnyPointerToObjCPointerCast;
5973 return Compatible;
5976 return Incompatible;
5979 // Conversions from pointers that are not covered by the above.
5980 if (isa<PointerType>(rhsType)) {
5981 // T* -> _Bool
5982 if (lhsType == Context.BoolTy) {
5983 Kind = CK_PointerToBoolean;
5984 return Compatible;
5987 // T* -> int
5988 if (lhsType->isIntegerType()) {
5989 Kind = CK_PointerToIntegral;
5990 return PointerToInt;
5993 return Incompatible;
5996 // Conversions from Objective-C pointers that are not covered by the above.
5997 if (isa<ObjCObjectPointerType>(rhsType)) {
5998 // T* -> _Bool
5999 if (lhsType == Context.BoolTy) {
6000 Kind = CK_PointerToBoolean;
6001 return Compatible;
6004 // T* -> int
6005 if (lhsType->isIntegerType()) {
6006 Kind = CK_PointerToIntegral;
6007 return PointerToInt;
6010 return Incompatible;
6013 // struct A -> struct B
6014 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
6015 if (Context.typesAreCompatible(lhsType, rhsType)) {
6016 Kind = CK_NoOp;
6017 return Compatible;
6021 return Incompatible;
6024 /// \brief Constructs a transparent union from an expression that is
6025 /// used to initialize the transparent union.
6026 static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
6027 QualType UnionType, FieldDecl *Field) {
6028 // Build an initializer list that designates the appropriate member
6029 // of the transparent union.
6030 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6031 &E, 1,
6032 SourceLocation());
6033 Initializer->setType(UnionType);
6034 Initializer->setInitializedFieldInUnion(Field);
6036 // Build a compound literal constructing a value of the transparent
6037 // union type from this initializer list.
6038 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6039 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6040 VK_RValue, Initializer, false);
6043 Sema::AssignConvertType
6044 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
6045 QualType FromType = rExpr->getType();
6047 // If the ArgType is a Union type, we want to handle a potential
6048 // transparent_union GCC extension.
6049 const RecordType *UT = ArgType->getAsUnionType();
6050 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6051 return Incompatible;
6053 // The field to initialize within the transparent union.
6054 RecordDecl *UD = UT->getDecl();
6055 FieldDecl *InitField = 0;
6056 // It's compatible if the expression matches any of the fields.
6057 for (RecordDecl::field_iterator it = UD->field_begin(),
6058 itend = UD->field_end();
6059 it != itend; ++it) {
6060 if (it->getType()->isPointerType()) {
6061 // If the transparent union contains a pointer type, we allow:
6062 // 1) void pointer
6063 // 2) null pointer constant
6064 if (FromType->isPointerType())
6065 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
6066 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
6067 InitField = *it;
6068 break;
6071 if (rExpr->isNullPointerConstant(Context,
6072 Expr::NPC_ValueDependentIsNull)) {
6073 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
6074 InitField = *it;
6075 break;
6079 Expr *rhs = rExpr;
6080 CastKind Kind = CK_Invalid;
6081 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
6082 == Compatible) {
6083 ImpCastExprToType(rhs, it->getType(), Kind);
6084 rExpr = rhs;
6085 InitField = *it;
6086 break;
6090 if (!InitField)
6091 return Incompatible;
6093 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
6094 return Compatible;
6097 Sema::AssignConvertType
6098 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
6099 if (getLangOptions().CPlusPlus) {
6100 if (!lhsType->isRecordType()) {
6101 // C++ 5.17p3: If the left operand is not of class type, the
6102 // expression is implicitly converted (C++ 4) to the
6103 // cv-unqualified type of the left operand.
6104 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
6105 AA_Assigning))
6106 return Incompatible;
6107 return Compatible;
6110 // FIXME: Currently, we fall through and treat C++ classes like C
6111 // structures.
6114 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6115 // a null pointer constant.
6116 if ((lhsType->isPointerType() ||
6117 lhsType->isObjCObjectPointerType() ||
6118 lhsType->isBlockPointerType())
6119 && rExpr->isNullPointerConstant(Context,
6120 Expr::NPC_ValueDependentIsNull)) {
6121 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
6122 return Compatible;
6125 // This check seems unnatural, however it is necessary to ensure the proper
6126 // conversion of functions/arrays. If the conversion were done for all
6127 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6128 // expressions that suppress this implicit conversion (&, sizeof).
6130 // Suppress this for references: C++ 8.5.3p5.
6131 if (!lhsType->isReferenceType())
6132 DefaultFunctionArrayLvalueConversion(rExpr);
6134 CastKind Kind = CK_Invalid;
6135 Sema::AssignConvertType result =
6136 CheckAssignmentConstraints(lhsType, rExpr, Kind);
6138 // C99 6.5.16.1p2: The value of the right operand is converted to the
6139 // type of the assignment expression.
6140 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6141 // so that we can use references in built-in functions even in C.
6142 // The getNonReferenceType() call makes sure that the resulting expression
6143 // does not have reference type.
6144 if (result != Incompatible && rExpr->getType() != lhsType)
6145 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
6146 return result;
6149 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
6150 Diag(Loc, diag::err_typecheck_invalid_operands)
6151 << lex->getType() << rex->getType()
6152 << lex->getSourceRange() << rex->getSourceRange();
6153 return QualType();
6156 QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
6157 // For conversion purposes, we ignore any qualifiers.
6158 // For example, "const float" and "float" are equivalent.
6159 QualType lhsType =
6160 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
6161 QualType rhsType =
6162 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
6164 // If the vector types are identical, return.
6165 if (lhsType == rhsType)
6166 return lhsType;
6168 // Handle the case of a vector & extvector type of the same size and element
6169 // type. It would be nice if we only had one vector type someday.
6170 if (getLangOptions().LaxVectorConversions) {
6171 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
6172 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
6173 if (LV->getElementType() == RV->getElementType() &&
6174 LV->getNumElements() == RV->getNumElements()) {
6175 if (lhsType->isExtVectorType()) {
6176 ImpCastExprToType(rex, lhsType, CK_BitCast);
6177 return lhsType;
6180 ImpCastExprToType(lex, rhsType, CK_BitCast);
6181 return rhsType;
6182 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
6183 // If we are allowing lax vector conversions, and LHS and RHS are both
6184 // vectors, the total size only needs to be the same. This is a
6185 // bitcast; no bits are changed but the result type is different.
6186 ImpCastExprToType(rex, lhsType, CK_BitCast);
6187 return lhsType;
6193 // Handle the case of equivalent AltiVec and GCC vector types
6194 if (lhsType->isVectorType() && rhsType->isVectorType() &&
6195 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
6196 ImpCastExprToType(lex, rhsType, CK_BitCast);
6197 return rhsType;
6200 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6201 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6202 bool swapped = false;
6203 if (rhsType->isExtVectorType()) {
6204 swapped = true;
6205 std::swap(rex, lex);
6206 std::swap(rhsType, lhsType);
6209 // Handle the case of an ext vector and scalar.
6210 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
6211 QualType EltTy = LV->getElementType();
6212 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
6213 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
6214 if (order > 0)
6215 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
6216 if (order >= 0) {
6217 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
6218 if (swapped) std::swap(rex, lex);
6219 return lhsType;
6222 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
6223 rhsType->isRealFloatingType()) {
6224 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
6225 if (order > 0)
6226 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
6227 if (order >= 0) {
6228 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
6229 if (swapped) std::swap(rex, lex);
6230 return lhsType;
6235 // Vectors of different size or scalar and non-ext-vector are errors.
6236 Diag(Loc, diag::err_typecheck_vector_not_convertable)
6237 << lex->getType() << rex->getType()
6238 << lex->getSourceRange() << rex->getSourceRange();
6239 return QualType();
6242 QualType Sema::CheckMultiplyDivideOperands(
6243 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6244 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6245 return CheckVectorOperands(Loc, lex, rex);
6247 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6249 if (!lex->getType()->isArithmeticType() ||
6250 !rex->getType()->isArithmeticType())
6251 return InvalidOperands(Loc, lex, rex);
6253 // Check for division by zero.
6254 if (isDiv &&
6255 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6256 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
6257 << rex->getSourceRange());
6259 return compType;
6262 QualType Sema::CheckRemainderOperands(
6263 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
6264 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6265 if (lex->getType()->hasIntegerRepresentation() &&
6266 rex->getType()->hasIntegerRepresentation())
6267 return CheckVectorOperands(Loc, lex, rex);
6268 return InvalidOperands(Loc, lex, rex);
6271 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6273 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6274 return InvalidOperands(Loc, lex, rex);
6276 // Check for remainder by zero.
6277 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6278 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6279 << rex->getSourceRange());
6281 return compType;
6284 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6285 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
6286 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6287 QualType compType = CheckVectorOperands(Loc, lex, rex);
6288 if (CompLHSTy) *CompLHSTy = compType;
6289 return compType;
6292 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
6294 // handle the common case first (both operands are arithmetic).
6295 if (lex->getType()->isArithmeticType() &&
6296 rex->getType()->isArithmeticType()) {
6297 if (CompLHSTy) *CompLHSTy = compType;
6298 return compType;
6301 // Put any potential pointer into PExp
6302 Expr* PExp = lex, *IExp = rex;
6303 if (IExp->getType()->isAnyPointerType())
6304 std::swap(PExp, IExp);
6306 if (PExp->getType()->isAnyPointerType()) {
6308 if (IExp->getType()->isIntegerType()) {
6309 QualType PointeeTy = PExp->getType()->getPointeeType();
6311 // Check for arithmetic on pointers to incomplete types.
6312 if (PointeeTy->isVoidType()) {
6313 if (getLangOptions().CPlusPlus) {
6314 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6315 << lex->getSourceRange() << rex->getSourceRange();
6316 return QualType();
6319 // GNU extension: arithmetic on pointer to void
6320 Diag(Loc, diag::ext_gnu_void_ptr)
6321 << lex->getSourceRange() << rex->getSourceRange();
6322 } else if (PointeeTy->isFunctionType()) {
6323 if (getLangOptions().CPlusPlus) {
6324 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6325 << lex->getType() << lex->getSourceRange();
6326 return QualType();
6329 // GNU extension: arithmetic on pointer to function
6330 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6331 << lex->getType() << lex->getSourceRange();
6332 } else {
6333 // Check if we require a complete type.
6334 if (((PExp->getType()->isPointerType() &&
6335 !PExp->getType()->isDependentType()) ||
6336 PExp->getType()->isObjCObjectPointerType()) &&
6337 RequireCompleteType(Loc, PointeeTy,
6338 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6339 << PExp->getSourceRange()
6340 << PExp->getType()))
6341 return QualType();
6343 // Diagnose bad cases where we step over interface counts.
6344 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6345 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6346 << PointeeTy << PExp->getSourceRange();
6347 return QualType();
6350 if (CompLHSTy) {
6351 QualType LHSTy = Context.isPromotableBitField(lex);
6352 if (LHSTy.isNull()) {
6353 LHSTy = lex->getType();
6354 if (LHSTy->isPromotableIntegerType())
6355 LHSTy = Context.getPromotedIntegerType(LHSTy);
6357 *CompLHSTy = LHSTy;
6359 return PExp->getType();
6363 return InvalidOperands(Loc, lex, rex);
6366 // C99 6.5.6
6367 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
6368 SourceLocation Loc, QualType* CompLHSTy) {
6369 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6370 QualType compType = CheckVectorOperands(Loc, lex, rex);
6371 if (CompLHSTy) *CompLHSTy = compType;
6372 return compType;
6375 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
6377 // Enforce type constraints: C99 6.5.6p3.
6379 // Handle the common case first (both operands are arithmetic).
6380 if (lex->getType()->isArithmeticType()
6381 && rex->getType()->isArithmeticType()) {
6382 if (CompLHSTy) *CompLHSTy = compType;
6383 return compType;
6386 // Either ptr - int or ptr - ptr.
6387 if (lex->getType()->isAnyPointerType()) {
6388 QualType lpointee = lex->getType()->getPointeeType();
6390 // The LHS must be an completely-defined object type.
6392 bool ComplainAboutVoid = false;
6393 Expr *ComplainAboutFunc = 0;
6394 if (lpointee->isVoidType()) {
6395 if (getLangOptions().CPlusPlus) {
6396 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6397 << lex->getSourceRange() << rex->getSourceRange();
6398 return QualType();
6401 // GNU C extension: arithmetic on pointer to void
6402 ComplainAboutVoid = true;
6403 } else if (lpointee->isFunctionType()) {
6404 if (getLangOptions().CPlusPlus) {
6405 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6406 << lex->getType() << lex->getSourceRange();
6407 return QualType();
6410 // GNU C extension: arithmetic on pointer to function
6411 ComplainAboutFunc = lex;
6412 } else if (!lpointee->isDependentType() &&
6413 RequireCompleteType(Loc, lpointee,
6414 PDiag(diag::err_typecheck_sub_ptr_object)
6415 << lex->getSourceRange()
6416 << lex->getType()))
6417 return QualType();
6419 // Diagnose bad cases where we step over interface counts.
6420 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6421 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6422 << lpointee << lex->getSourceRange();
6423 return QualType();
6426 // The result type of a pointer-int computation is the pointer type.
6427 if (rex->getType()->isIntegerType()) {
6428 if (ComplainAboutVoid)
6429 Diag(Loc, diag::ext_gnu_void_ptr)
6430 << lex->getSourceRange() << rex->getSourceRange();
6431 if (ComplainAboutFunc)
6432 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6433 << ComplainAboutFunc->getType()
6434 << ComplainAboutFunc->getSourceRange();
6436 if (CompLHSTy) *CompLHSTy = lex->getType();
6437 return lex->getType();
6440 // Handle pointer-pointer subtractions.
6441 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
6442 QualType rpointee = RHSPTy->getPointeeType();
6444 // RHS must be a completely-type object type.
6445 // Handle the GNU void* extension.
6446 if (rpointee->isVoidType()) {
6447 if (getLangOptions().CPlusPlus) {
6448 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6449 << lex->getSourceRange() << rex->getSourceRange();
6450 return QualType();
6453 ComplainAboutVoid = true;
6454 } else if (rpointee->isFunctionType()) {
6455 if (getLangOptions().CPlusPlus) {
6456 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6457 << rex->getType() << rex->getSourceRange();
6458 return QualType();
6461 // GNU extension: arithmetic on pointer to function
6462 if (!ComplainAboutFunc)
6463 ComplainAboutFunc = rex;
6464 } else if (!rpointee->isDependentType() &&
6465 RequireCompleteType(Loc, rpointee,
6466 PDiag(diag::err_typecheck_sub_ptr_object)
6467 << rex->getSourceRange()
6468 << rex->getType()))
6469 return QualType();
6471 if (getLangOptions().CPlusPlus) {
6472 // Pointee types must be the same: C++ [expr.add]
6473 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6474 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6475 << lex->getType() << rex->getType()
6476 << lex->getSourceRange() << rex->getSourceRange();
6477 return QualType();
6479 } else {
6480 // Pointee types must be compatible C99 6.5.6p3
6481 if (!Context.typesAreCompatible(
6482 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6483 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6484 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6485 << lex->getType() << rex->getType()
6486 << lex->getSourceRange() << rex->getSourceRange();
6487 return QualType();
6491 if (ComplainAboutVoid)
6492 Diag(Loc, diag::ext_gnu_void_ptr)
6493 << lex->getSourceRange() << rex->getSourceRange();
6494 if (ComplainAboutFunc)
6495 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6496 << ComplainAboutFunc->getType()
6497 << ComplainAboutFunc->getSourceRange();
6499 if (CompLHSTy) *CompLHSTy = lex->getType();
6500 return Context.getPointerDiffType();
6504 return InvalidOperands(Loc, lex, rex);
6507 static bool isScopedEnumerationType(QualType T) {
6508 if (const EnumType *ET = dyn_cast<EnumType>(T))
6509 return ET->getDecl()->isScoped();
6510 return false;
6513 // C99 6.5.7
6514 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
6515 bool isCompAssign) {
6516 // C99 6.5.7p2: Each of the operands shall have integer type.
6517 if (!lex->getType()->hasIntegerRepresentation() ||
6518 !rex->getType()->hasIntegerRepresentation())
6519 return InvalidOperands(Loc, lex, rex);
6521 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6522 // hasIntegerRepresentation() above instead of this.
6523 if (isScopedEnumerationType(lex->getType()) ||
6524 isScopedEnumerationType(rex->getType())) {
6525 return InvalidOperands(Loc, lex, rex);
6528 // Vector shifts promote their scalar inputs to vector type.
6529 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6530 return CheckVectorOperands(Loc, lex, rex);
6532 // Shifts don't perform usual arithmetic conversions, they just do integer
6533 // promotions on each operand. C99 6.5.7p3
6535 // For the LHS, do usual unary conversions, but then reset them away
6536 // if this is a compound assignment.
6537 Expr *old_lex = lex;
6538 UsualUnaryConversions(lex);
6539 QualType LHSTy = lex->getType();
6540 if (isCompAssign) lex = old_lex;
6542 // The RHS is simpler.
6543 UsualUnaryConversions(rex);
6545 // Sanity-check shift operands
6546 llvm::APSInt Right;
6547 // Check right/shifter operand
6548 if (!rex->isValueDependent() &&
6549 rex->isIntegerConstantExpr(Right, Context)) {
6550 if (Right.isNegative())
6551 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6552 else {
6553 llvm::APInt LeftBits(Right.getBitWidth(),
6554 Context.getTypeSize(lex->getType()));
6555 if (Right.uge(LeftBits))
6556 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6560 // "The type of the result is that of the promoted left operand."
6561 return LHSTy;
6564 static bool IsWithinTemplateSpecialization(Decl *D) {
6565 if (DeclContext *DC = D->getDeclContext()) {
6566 if (isa<ClassTemplateSpecializationDecl>(DC))
6567 return true;
6568 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6569 return FD->isFunctionTemplateSpecialization();
6571 return false;
6574 // C99 6.5.8, C++ [expr.rel]
6575 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
6576 unsigned OpaqueOpc, bool isRelational) {
6577 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6579 // Handle vector comparisons separately.
6580 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6581 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
6583 QualType lType = lex->getType();
6584 QualType rType = rex->getType();
6586 if (!lType->hasFloatingRepresentation() &&
6587 !(lType->isBlockPointerType() && isRelational) &&
6588 !lex->getLocStart().isMacroID() &&
6589 !rex->getLocStart().isMacroID()) {
6590 // For non-floating point types, check for self-comparisons of the form
6591 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6592 // often indicate logic errors in the program.
6594 // NOTE: Don't warn about comparison expressions resulting from macro
6595 // expansion. Also don't warn about comparisons which are only self
6596 // comparisons within a template specialization. The warnings should catch
6597 // obvious cases in the definition of the template anyways. The idea is to
6598 // warn when the typed comparison operator will always evaluate to the same
6599 // result.
6600 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6601 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6602 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6603 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6604 if (DRL->getDecl() == DRR->getDecl() &&
6605 !IsWithinTemplateSpecialization(DRL->getDecl())) {
6606 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6607 << 0 // self-
6608 << (Opc == BO_EQ
6609 || Opc == BO_LE
6610 || Opc == BO_GE));
6611 } else if (lType->isArrayType() && rType->isArrayType() &&
6612 !DRL->getDecl()->getType()->isReferenceType() &&
6613 !DRR->getDecl()->getType()->isReferenceType()) {
6614 // what is it always going to eval to?
6615 char always_evals_to;
6616 switch(Opc) {
6617 case BO_EQ: // e.g. array1 == array2
6618 always_evals_to = 0; // false
6619 break;
6620 case BO_NE: // e.g. array1 != array2
6621 always_evals_to = 1; // true
6622 break;
6623 default:
6624 // best we can say is 'a constant'
6625 always_evals_to = 2; // e.g. array1 <= array2
6626 break;
6628 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6629 << 1 // array
6630 << always_evals_to);
6635 if (isa<CastExpr>(LHSStripped))
6636 LHSStripped = LHSStripped->IgnoreParenCasts();
6637 if (isa<CastExpr>(RHSStripped))
6638 RHSStripped = RHSStripped->IgnoreParenCasts();
6640 // Warn about comparisons against a string constant (unless the other
6641 // operand is null), the user probably wants strcmp.
6642 Expr *literalString = 0;
6643 Expr *literalStringStripped = 0;
6644 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6645 !RHSStripped->isNullPointerConstant(Context,
6646 Expr::NPC_ValueDependentIsNull)) {
6647 literalString = lex;
6648 literalStringStripped = LHSStripped;
6649 } else if ((isa<StringLiteral>(RHSStripped) ||
6650 isa<ObjCEncodeExpr>(RHSStripped)) &&
6651 !LHSStripped->isNullPointerConstant(Context,
6652 Expr::NPC_ValueDependentIsNull)) {
6653 literalString = rex;
6654 literalStringStripped = RHSStripped;
6657 if (literalString) {
6658 std::string resultComparison;
6659 switch (Opc) {
6660 case BO_LT: resultComparison = ") < 0"; break;
6661 case BO_GT: resultComparison = ") > 0"; break;
6662 case BO_LE: resultComparison = ") <= 0"; break;
6663 case BO_GE: resultComparison = ") >= 0"; break;
6664 case BO_EQ: resultComparison = ") == 0"; break;
6665 case BO_NE: resultComparison = ") != 0"; break;
6666 default: assert(false && "Invalid comparison operator");
6669 DiagRuntimeBehavior(Loc,
6670 PDiag(diag::warn_stringcompare)
6671 << isa<ObjCEncodeExpr>(literalStringStripped)
6672 << literalString->getSourceRange());
6676 // C99 6.5.8p3 / C99 6.5.9p4
6677 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6678 UsualArithmeticConversions(lex, rex);
6679 else {
6680 UsualUnaryConversions(lex);
6681 UsualUnaryConversions(rex);
6684 lType = lex->getType();
6685 rType = rex->getType();
6687 // The result of comparisons is 'bool' in C++, 'int' in C.
6688 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
6690 if (isRelational) {
6691 if (lType->isRealType() && rType->isRealType())
6692 return ResultTy;
6693 } else {
6694 // Check for comparisons of floating point operands using != and ==.
6695 if (lType->hasFloatingRepresentation())
6696 CheckFloatComparison(Loc,lex,rex);
6698 if (lType->isArithmeticType() && rType->isArithmeticType())
6699 return ResultTy;
6702 bool LHSIsNull = lex->isNullPointerConstant(Context,
6703 Expr::NPC_ValueDependentIsNull);
6704 bool RHSIsNull = rex->isNullPointerConstant(Context,
6705 Expr::NPC_ValueDependentIsNull);
6707 // All of the following pointer-related warnings are GCC extensions, except
6708 // when handling null pointer constants.
6709 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
6710 QualType LCanPointeeTy =
6711 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
6712 QualType RCanPointeeTy =
6713 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
6715 if (getLangOptions().CPlusPlus) {
6716 if (LCanPointeeTy == RCanPointeeTy)
6717 return ResultTy;
6718 if (!isRelational &&
6719 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6720 // Valid unless comparison between non-null pointer and function pointer
6721 // This is a gcc extension compatibility comparison.
6722 // In a SFINAE context, we treat this as a hard error to maintain
6723 // conformance with the C++ standard.
6724 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6725 && !LHSIsNull && !RHSIsNull) {
6726 Diag(Loc,
6727 isSFINAEContext()?
6728 diag::err_typecheck_comparison_of_fptr_to_void
6729 : diag::ext_typecheck_comparison_of_fptr_to_void)
6730 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6732 if (isSFINAEContext())
6733 return QualType();
6735 ImpCastExprToType(rex, lType, CK_BitCast);
6736 return ResultTy;
6740 // C++ [expr.rel]p2:
6741 // [...] Pointer conversions (4.10) and qualification
6742 // conversions (4.4) are performed on pointer operands (or on
6743 // a pointer operand and a null pointer constant) to bring
6744 // them to their composite pointer type. [...]
6746 // C++ [expr.eq]p1 uses the same notion for (in)equality
6747 // comparisons of pointers.
6748 bool NonStandardCompositeType = false;
6749 QualType T = FindCompositePointerType(Loc, lex, rex,
6750 isSFINAEContext()? 0 : &NonStandardCompositeType);
6751 if (T.isNull()) {
6752 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6753 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6754 return QualType();
6755 } else if (NonStandardCompositeType) {
6756 Diag(Loc,
6757 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6758 << lType << rType << T
6759 << lex->getSourceRange() << rex->getSourceRange();
6762 ImpCastExprToType(lex, T, CK_BitCast);
6763 ImpCastExprToType(rex, T, CK_BitCast);
6764 return ResultTy;
6766 // C99 6.5.9p2 and C99 6.5.8p2
6767 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6768 RCanPointeeTy.getUnqualifiedType())) {
6769 // Valid unless a relational comparison of function pointers
6770 if (isRelational && LCanPointeeTy->isFunctionType()) {
6771 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6772 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6774 } else if (!isRelational &&
6775 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6776 // Valid unless comparison between non-null pointer and function pointer
6777 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6778 && !LHSIsNull && !RHSIsNull) {
6779 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6780 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6782 } else {
6783 // Invalid
6784 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6785 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6787 if (LCanPointeeTy != RCanPointeeTy)
6788 ImpCastExprToType(rex, lType, CK_BitCast);
6789 return ResultTy;
6792 if (getLangOptions().CPlusPlus) {
6793 // Comparison of nullptr_t with itself.
6794 if (lType->isNullPtrType() && rType->isNullPtrType())
6795 return ResultTy;
6797 // Comparison of pointers with null pointer constants and equality
6798 // comparisons of member pointers to null pointer constants.
6799 if (RHSIsNull &&
6800 ((lType->isPointerType() || lType->isNullPtrType()) ||
6801 (!isRelational && lType->isMemberPointerType()))) {
6802 ImpCastExprToType(rex, lType,
6803 lType->isMemberPointerType()
6804 ? CK_NullToMemberPointer
6805 : CK_NullToPointer);
6806 return ResultTy;
6808 if (LHSIsNull &&
6809 ((rType->isPointerType() || rType->isNullPtrType()) ||
6810 (!isRelational && rType->isMemberPointerType()))) {
6811 ImpCastExprToType(lex, rType,
6812 rType->isMemberPointerType()
6813 ? CK_NullToMemberPointer
6814 : CK_NullToPointer);
6815 return ResultTy;
6818 // Comparison of member pointers.
6819 if (!isRelational &&
6820 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6821 // C++ [expr.eq]p2:
6822 // In addition, pointers to members can be compared, or a pointer to
6823 // member and a null pointer constant. Pointer to member conversions
6824 // (4.11) and qualification conversions (4.4) are performed to bring
6825 // them to a common type. If one operand is a null pointer constant,
6826 // the common type is the type of the other operand. Otherwise, the
6827 // common type is a pointer to member type similar (4.4) to the type
6828 // of one of the operands, with a cv-qualification signature (4.4)
6829 // that is the union of the cv-qualification signatures of the operand
6830 // types.
6831 bool NonStandardCompositeType = false;
6832 QualType T = FindCompositePointerType(Loc, lex, rex,
6833 isSFINAEContext()? 0 : &NonStandardCompositeType);
6834 if (T.isNull()) {
6835 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6836 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6837 return QualType();
6838 } else if (NonStandardCompositeType) {
6839 Diag(Loc,
6840 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6841 << lType << rType << T
6842 << lex->getSourceRange() << rex->getSourceRange();
6845 ImpCastExprToType(lex, T, CK_BitCast);
6846 ImpCastExprToType(rex, T, CK_BitCast);
6847 return ResultTy;
6851 // Handle block pointer types.
6852 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
6853 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6854 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
6856 if (!LHSIsNull && !RHSIsNull &&
6857 !Context.typesAreCompatible(lpointee, rpointee)) {
6858 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6859 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6861 ImpCastExprToType(rex, lType, CK_BitCast);
6862 return ResultTy;
6864 // Allow block pointers to be compared with null pointer constants.
6865 if (!isRelational
6866 && ((lType->isBlockPointerType() && rType->isPointerType())
6867 || (lType->isPointerType() && rType->isBlockPointerType()))) {
6868 if (!LHSIsNull && !RHSIsNull) {
6869 if (!((rType->isPointerType() && rType->getAs<PointerType>()
6870 ->getPointeeType()->isVoidType())
6871 || (lType->isPointerType() && lType->getAs<PointerType>()
6872 ->getPointeeType()->isVoidType())))
6873 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6874 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6876 ImpCastExprToType(rex, lType, CK_BitCast);
6877 return ResultTy;
6880 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
6881 if (lType->isPointerType() || rType->isPointerType()) {
6882 const PointerType *LPT = lType->getAs<PointerType>();
6883 const PointerType *RPT = rType->getAs<PointerType>();
6884 bool LPtrToVoid = LPT ?
6885 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
6886 bool RPtrToVoid = RPT ?
6887 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
6889 if (!LPtrToVoid && !RPtrToVoid &&
6890 !Context.typesAreCompatible(lType, rType)) {
6891 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6892 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6894 ImpCastExprToType(rex, lType, CK_BitCast);
6895 return ResultTy;
6897 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
6898 if (!Context.areComparableObjCPointerTypes(lType, rType))
6899 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6900 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6901 ImpCastExprToType(rex, lType, CK_BitCast);
6902 return ResultTy;
6905 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6906 (lType->isIntegerType() && rType->isAnyPointerType())) {
6907 unsigned DiagID = 0;
6908 bool isError = false;
6909 if ((LHSIsNull && lType->isIntegerType()) ||
6910 (RHSIsNull && rType->isIntegerType())) {
6911 if (isRelational && !getLangOptions().CPlusPlus)
6912 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
6913 } else if (isRelational && !getLangOptions().CPlusPlus)
6914 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
6915 else if (getLangOptions().CPlusPlus) {
6916 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6917 isError = true;
6918 } else
6919 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
6921 if (DiagID) {
6922 Diag(Loc, DiagID)
6923 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6924 if (isError)
6925 return QualType();
6928 if (lType->isIntegerType())
6929 ImpCastExprToType(lex, rType,
6930 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6931 else
6932 ImpCastExprToType(rex, lType,
6933 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6934 return ResultTy;
6937 // Handle block pointers.
6938 if (!isRelational && RHSIsNull
6939 && lType->isBlockPointerType() && rType->isIntegerType()) {
6940 ImpCastExprToType(rex, lType, CK_NullToPointer);
6941 return ResultTy;
6943 if (!isRelational && LHSIsNull
6944 && lType->isIntegerType() && rType->isBlockPointerType()) {
6945 ImpCastExprToType(lex, rType, CK_NullToPointer);
6946 return ResultTy;
6948 return InvalidOperands(Loc, lex, rex);
6951 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
6952 /// operates on extended vector types. Instead of producing an IntTy result,
6953 /// like a scalar comparison, a vector comparison produces a vector of integer
6954 /// types.
6955 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
6956 SourceLocation Loc,
6957 bool isRelational) {
6958 // Check to make sure we're operating on vectors of the same type and width,
6959 // Allowing one side to be a scalar of element type.
6960 QualType vType = CheckVectorOperands(Loc, lex, rex);
6961 if (vType.isNull())
6962 return vType;
6964 // If AltiVec, the comparison results in a numeric type, i.e.
6965 // bool for C++, int for C
6966 if (getLangOptions().AltiVec)
6967 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6969 QualType lType = lex->getType();
6970 QualType rType = rex->getType();
6972 // For non-floating point types, check for self-comparisons of the form
6973 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6974 // often indicate logic errors in the program.
6975 if (!lType->hasFloatingRepresentation()) {
6976 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6977 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6978 if (DRL->getDecl() == DRR->getDecl())
6979 DiagRuntimeBehavior(Loc,
6980 PDiag(diag::warn_comparison_always)
6981 << 0 // self-
6982 << 2 // "a constant"
6986 // Check for comparisons of floating point operands using != and ==.
6987 if (!isRelational && lType->hasFloatingRepresentation()) {
6988 assert (rType->hasFloatingRepresentation());
6989 CheckFloatComparison(Loc,lex,rex);
6992 // Return the type for the comparison, which is the same as vector type for
6993 // integer vectors, or an integer type of identical size and number of
6994 // elements for floating point vectors.
6995 if (lType->hasIntegerRepresentation())
6996 return lType;
6998 const VectorType *VTy = lType->getAs<VectorType>();
6999 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7000 if (TypeSize == Context.getTypeSize(Context.IntTy))
7001 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7002 if (TypeSize == Context.getTypeSize(Context.LongTy))
7003 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7005 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7006 "Unhandled vector element size in vector compare");
7007 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7010 inline QualType Sema::CheckBitwiseOperands(
7011 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
7012 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
7013 if (lex->getType()->hasIntegerRepresentation() &&
7014 rex->getType()->hasIntegerRepresentation())
7015 return CheckVectorOperands(Loc, lex, rex);
7017 return InvalidOperands(Loc, lex, rex);
7020 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
7022 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
7023 rex->getType()->isIntegralOrUnscopedEnumerationType())
7024 return compType;
7025 return InvalidOperands(Loc, lex, rex);
7028 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7029 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
7031 // Diagnose cases where the user write a logical and/or but probably meant a
7032 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7033 // is a constant.
7034 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
7035 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
7036 // Don't warn in macros.
7037 !Loc.isMacroID()) {
7038 // If the RHS can be constant folded, and if it constant folds to something
7039 // that isn't 0 or 1 (which indicate a potential logical operation that
7040 // happened to fold to true/false) then warn.
7041 Expr::EvalResult Result;
7042 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
7043 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
7044 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7045 << rex->getSourceRange()
7046 << (Opc == BO_LAnd ? "&&" : "||")
7047 << (Opc == BO_LAnd ? "&" : "|");
7051 if (!Context.getLangOptions().CPlusPlus) {
7052 UsualUnaryConversions(lex);
7053 UsualUnaryConversions(rex);
7055 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
7056 return InvalidOperands(Loc, lex, rex);
7058 return Context.IntTy;
7061 // The following is safe because we only use this method for
7062 // non-overloadable operands.
7064 // C++ [expr.log.and]p1
7065 // C++ [expr.log.or]p1
7066 // The operands are both contextually converted to type bool.
7067 if (PerformContextuallyConvertToBool(lex) ||
7068 PerformContextuallyConvertToBool(rex))
7069 return InvalidOperands(Loc, lex, rex);
7071 // C++ [expr.log.and]p2
7072 // C++ [expr.log.or]p2
7073 // The result is a bool.
7074 return Context.BoolTy;
7077 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7078 /// is a read-only property; return true if so. A readonly property expression
7079 /// depends on various declarations and thus must be treated specially.
7081 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7082 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
7083 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
7084 if (PropExpr->isImplicitProperty()) return false;
7086 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7087 QualType BaseType = PropExpr->isSuperReceiver() ?
7088 PropExpr->getSuperReceiverType() :
7089 PropExpr->getBase()->getType();
7091 if (const ObjCObjectPointerType *OPT =
7092 BaseType->getAsObjCInterfacePointerType())
7093 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7094 if (S.isPropertyReadonly(PDecl, IFace))
7095 return true;
7097 return false;
7100 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7101 /// emit an error and return true. If so, return false.
7102 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7103 SourceLocation OrigLoc = Loc;
7104 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7105 &Loc);
7106 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7107 IsLV = Expr::MLV_ReadonlyProperty;
7108 if (IsLV == Expr::MLV_Valid)
7109 return false;
7111 unsigned Diag = 0;
7112 bool NeedType = false;
7113 switch (IsLV) { // C99 6.5.16p2
7114 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
7115 case Expr::MLV_ArrayType:
7116 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7117 NeedType = true;
7118 break;
7119 case Expr::MLV_NotObjectType:
7120 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7121 NeedType = true;
7122 break;
7123 case Expr::MLV_LValueCast:
7124 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7125 break;
7126 case Expr::MLV_Valid:
7127 llvm_unreachable("did not take early return for MLV_Valid");
7128 case Expr::MLV_InvalidExpression:
7129 case Expr::MLV_MemberFunction:
7130 case Expr::MLV_ClassTemporary:
7131 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7132 break;
7133 case Expr::MLV_IncompleteType:
7134 case Expr::MLV_IncompleteVoidType:
7135 return S.RequireCompleteType(Loc, E->getType(),
7136 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
7137 << E->getSourceRange());
7138 case Expr::MLV_DuplicateVectorComponents:
7139 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7140 break;
7141 case Expr::MLV_NotBlockQualified:
7142 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7143 break;
7144 case Expr::MLV_ReadonlyProperty:
7145 Diag = diag::error_readonly_property_assignment;
7146 break;
7147 case Expr::MLV_NoSetterProperty:
7148 Diag = diag::error_nosetter_property_assignment;
7149 break;
7150 case Expr::MLV_SubObjCPropertySetting:
7151 Diag = diag::error_no_subobject_property_setting;
7152 break;
7155 SourceRange Assign;
7156 if (Loc != OrigLoc)
7157 Assign = SourceRange(OrigLoc, OrigLoc);
7158 if (NeedType)
7159 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7160 else
7161 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7162 return true;
7167 // C99 6.5.16.1
7168 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
7169 SourceLocation Loc,
7170 QualType CompoundType) {
7171 // Verify that LHS is a modifiable lvalue, and emit error if not.
7172 if (CheckForModifiableLvalue(LHS, Loc, *this))
7173 return QualType();
7175 QualType LHSType = LHS->getType();
7176 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
7177 AssignConvertType ConvTy;
7178 if (CompoundType.isNull()) {
7179 QualType LHSTy(LHSType);
7180 // Simple assignment "x = y".
7181 if (LHS->getObjectKind() == OK_ObjCProperty)
7182 ConvertPropertyForLValue(LHS, RHS, LHSTy);
7183 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7184 // Special case of NSObject attributes on c-style pointer types.
7185 if (ConvTy == IncompatiblePointer &&
7186 ((Context.isObjCNSObjectType(LHSType) &&
7187 RHSType->isObjCObjectPointerType()) ||
7188 (Context.isObjCNSObjectType(RHSType) &&
7189 LHSType->isObjCObjectPointerType())))
7190 ConvTy = Compatible;
7192 if (ConvTy == Compatible &&
7193 getLangOptions().ObjCNonFragileABI &&
7194 LHSType->isObjCObjectType())
7195 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7196 << LHSType;
7198 // If the RHS is a unary plus or minus, check to see if they = and + are
7199 // right next to each other. If so, the user may have typo'd "x =+ 4"
7200 // instead of "x += 4".
7201 Expr *RHSCheck = RHS;
7202 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7203 RHSCheck = ICE->getSubExpr();
7204 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7205 if ((UO->getOpcode() == UO_Plus ||
7206 UO->getOpcode() == UO_Minus) &&
7207 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7208 // Only if the two operators are exactly adjacent.
7209 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
7210 // And there is a space or other character before the subexpr of the
7211 // unary +/-. We don't want to warn on "x=-1".
7212 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7213 UO->getSubExpr()->getLocStart().isFileID()) {
7214 Diag(Loc, diag::warn_not_compound_assign)
7215 << (UO->getOpcode() == UO_Plus ? "+" : "-")
7216 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7219 } else {
7220 // Compound assignment "x += y"
7221 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7224 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7225 RHS, AA_Assigning))
7226 return QualType();
7229 // Check to see if the destination operand is a dereferenced null pointer. If
7230 // so, and if not volatile-qualified, this is undefined behavior that the
7231 // optimizer will delete, so warn about it. People sometimes try to use this
7232 // to get a deterministic trap and are surprised by clang's behavior. This
7233 // only handles the pattern "*null = whatever", which is a very syntactic
7234 // check.
7235 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
7236 if (UO->getOpcode() == UO_Deref &&
7237 UO->getSubExpr()->IgnoreParenCasts()->
7238 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
7239 !UO->getType().isVolatileQualified()) {
7240 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
7241 << UO->getSubExpr()->getSourceRange();
7242 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
7245 // C99 6.5.16p3: The type of an assignment expression is the type of the
7246 // left operand unless the left operand has qualified type, in which case
7247 // it is the unqualified version of the type of the left operand.
7248 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7249 // is converted to the type of the assignment expression (above).
7250 // C++ 5.17p1: the type of the assignment expression is that of its left
7251 // operand.
7252 return (getLangOptions().CPlusPlus
7253 ? LHSType : LHSType.getUnqualifiedType());
7256 // C99 6.5.17
7257 static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
7258 SourceLocation Loc) {
7259 S.DiagnoseUnusedExprResult(LHS);
7261 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
7262 if (LHSResult.isInvalid())
7263 return QualType();
7265 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
7266 if (RHSResult.isInvalid())
7267 return QualType();
7268 RHS = RHSResult.take();
7270 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7271 // operands, but not unary promotions.
7272 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7274 // So we treat the LHS as a ignored value, and in C++ we allow the
7275 // containing site to determine what should be done with the RHS.
7276 S.IgnoredValueConversions(LHS);
7278 if (!S.getLangOptions().CPlusPlus) {
7279 S.DefaultFunctionArrayLvalueConversion(RHS);
7280 if (!RHS->getType()->isVoidType())
7281 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
7284 return RHS->getType();
7287 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7288 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7289 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7290 ExprValueKind &VK,
7291 SourceLocation OpLoc,
7292 bool isInc, bool isPrefix) {
7293 if (Op->isTypeDependent())
7294 return S.Context.DependentTy;
7296 QualType ResType = Op->getType();
7297 assert(!ResType.isNull() && "no type for increment/decrement expression");
7299 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
7300 // Decrement of bool is not allowed.
7301 if (!isInc) {
7302 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7303 return QualType();
7305 // Increment of bool sets it to true, but is deprecated.
7306 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7307 } else if (ResType->isRealType()) {
7308 // OK!
7309 } else if (ResType->isAnyPointerType()) {
7310 QualType PointeeTy = ResType->getPointeeType();
7312 // C99 6.5.2.4p2, 6.5.6p2
7313 if (PointeeTy->isVoidType()) {
7314 if (S.getLangOptions().CPlusPlus) {
7315 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
7316 << Op->getSourceRange();
7317 return QualType();
7320 // Pointer to void is a GNU extension in C.
7321 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
7322 } else if (PointeeTy->isFunctionType()) {
7323 if (S.getLangOptions().CPlusPlus) {
7324 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
7325 << Op->getType() << Op->getSourceRange();
7326 return QualType();
7329 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
7330 << ResType << Op->getSourceRange();
7331 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7332 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
7333 << Op->getSourceRange()
7334 << ResType))
7335 return QualType();
7336 // Diagnose bad cases where we step over interface counts.
7337 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7338 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
7339 << PointeeTy << Op->getSourceRange();
7340 return QualType();
7342 } else if (ResType->isAnyComplexType()) {
7343 // C99 does not support ++/-- on complex types, we allow as an extension.
7344 S.Diag(OpLoc, diag::ext_integer_increment_complex)
7345 << ResType << Op->getSourceRange();
7346 } else if (ResType->isPlaceholderType()) {
7347 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
7348 if (PR.isInvalid()) return QualType();
7349 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7350 isInc, isPrefix);
7351 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7352 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7353 } else {
7354 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7355 << ResType << int(isInc) << Op->getSourceRange();
7356 return QualType();
7358 // At this point, we know we have a real, complex or pointer type.
7359 // Now make sure the operand is a modifiable lvalue.
7360 if (CheckForModifiableLvalue(Op, OpLoc, S))
7361 return QualType();
7362 // In C++, a prefix increment is the same type as the operand. Otherwise
7363 // (in C or with postfix), the increment is the unqualified type of the
7364 // operand.
7365 if (isPrefix && S.getLangOptions().CPlusPlus) {
7366 VK = VK_LValue;
7367 return ResType;
7368 } else {
7369 VK = VK_RValue;
7370 return ResType.getUnqualifiedType();
7374 void Sema::ConvertPropertyForRValue(Expr *&E) {
7375 assert(E->getValueKind() == VK_LValue &&
7376 E->getObjectKind() == OK_ObjCProperty);
7377 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7379 ExprValueKind VK = VK_RValue;
7380 if (PRE->isImplicitProperty()) {
7381 if (const ObjCMethodDecl *GetterMethod =
7382 PRE->getImplicitPropertyGetter()) {
7383 QualType Result = GetterMethod->getResultType();
7384 VK = Expr::getValueKindForType(Result);
7386 else {
7387 Diag(PRE->getLocation(), diag::err_getter_not_found)
7388 << PRE->getBase()->getType();
7392 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7393 E, 0, VK);
7395 ExprResult Result = MaybeBindToTemporary(E);
7396 if (!Result.isInvalid())
7397 E = Result.take();
7400 void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7401 assert(LHS->getValueKind() == VK_LValue &&
7402 LHS->getObjectKind() == OK_ObjCProperty);
7403 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7405 if (PRE->isImplicitProperty()) {
7406 // If using property-dot syntax notation for assignment, and there is a
7407 // setter, RHS expression is being passed to the setter argument. So,
7408 // type conversion (and comparison) is RHS to setter's argument type.
7409 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7410 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7411 LHSTy = (*P)->getType();
7413 // Otherwise, if the getter returns an l-value, just call that.
7414 } else {
7415 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7416 ExprValueKind VK = Expr::getValueKindForType(Result);
7417 if (VK == VK_LValue) {
7418 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7419 CK_GetObjCProperty, LHS, 0, VK);
7420 return;
7425 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
7426 InitializedEntity Entity =
7427 InitializedEntity::InitializeParameter(Context, LHSTy);
7428 Expr *Arg = RHS;
7429 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7430 Owned(Arg));
7431 if (!ArgE.isInvalid())
7432 RHS = ArgE.takeAs<Expr>();
7437 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7438 /// This routine allows us to typecheck complex/recursive expressions
7439 /// where the declaration is needed for type checking. We only need to
7440 /// handle cases when the expression references a function designator
7441 /// or is an lvalue. Here are some examples:
7442 /// - &(x) => x
7443 /// - &*****f => f for f a function designator.
7444 /// - &s.xx => s
7445 /// - &s.zz[1].yy -> s, if zz is an array
7446 /// - *(x + 1) -> x, if x is an array
7447 /// - &"123"[2] -> 0
7448 /// - & __real__ x -> x
7449 static ValueDecl *getPrimaryDecl(Expr *E) {
7450 switch (E->getStmtClass()) {
7451 case Stmt::DeclRefExprClass:
7452 return cast<DeclRefExpr>(E)->getDecl();
7453 case Stmt::MemberExprClass:
7454 // If this is an arrow operator, the address is an offset from
7455 // the base's value, so the object the base refers to is
7456 // irrelevant.
7457 if (cast<MemberExpr>(E)->isArrow())
7458 return 0;
7459 // Otherwise, the expression refers to a part of the base
7460 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7461 case Stmt::ArraySubscriptExprClass: {
7462 // FIXME: This code shouldn't be necessary! We should catch the implicit
7463 // promotion of register arrays earlier.
7464 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7465 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7466 if (ICE->getSubExpr()->getType()->isArrayType())
7467 return getPrimaryDecl(ICE->getSubExpr());
7469 return 0;
7471 case Stmt::UnaryOperatorClass: {
7472 UnaryOperator *UO = cast<UnaryOperator>(E);
7474 switch(UO->getOpcode()) {
7475 case UO_Real:
7476 case UO_Imag:
7477 case UO_Extension:
7478 return getPrimaryDecl(UO->getSubExpr());
7479 default:
7480 return 0;
7483 case Stmt::ParenExprClass:
7484 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7485 case Stmt::ImplicitCastExprClass:
7486 // If the result of an implicit cast is an l-value, we care about
7487 // the sub-expression; otherwise, the result here doesn't matter.
7488 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7489 default:
7490 return 0;
7494 /// CheckAddressOfOperand - The operand of & must be either a function
7495 /// designator or an lvalue designating an object. If it is an lvalue, the
7496 /// object cannot be declared with storage class register or be a bit field.
7497 /// Note: The usual conversions are *not* applied to the operand of the &
7498 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7499 /// In C++, the operand might be an overloaded function name, in which case
7500 /// we allow the '&' but retain the overloaded-function type.
7501 static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7502 SourceLocation OpLoc) {
7503 if (OrigOp->isTypeDependent())
7504 return S.Context.DependentTy;
7505 if (OrigOp->getType() == S.Context.OverloadTy)
7506 return S.Context.OverloadTy;
7508 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
7509 if (PR.isInvalid()) return QualType();
7510 OrigOp = PR.take();
7512 // Make sure to ignore parentheses in subsequent checks
7513 Expr *op = OrigOp->IgnoreParens();
7515 if (S.getLangOptions().C99) {
7516 // Implement C99-only parts of addressof rules.
7517 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7518 if (uOp->getOpcode() == UO_Deref)
7519 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7520 // (assuming the deref expression is valid).
7521 return uOp->getSubExpr()->getType();
7523 // Technically, there should be a check for array subscript
7524 // expressions here, but the result of one is always an lvalue anyway.
7526 ValueDecl *dcl = getPrimaryDecl(op);
7527 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7529 if (lval == Expr::LV_ClassTemporary) {
7530 bool sfinae = S.isSFINAEContext();
7531 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7532 : diag::ext_typecheck_addrof_class_temporary)
7533 << op->getType() << op->getSourceRange();
7534 if (sfinae)
7535 return QualType();
7536 } else if (isa<ObjCSelectorExpr>(op)) {
7537 return S.Context.getPointerType(op->getType());
7538 } else if (lval == Expr::LV_MemberFunction) {
7539 // If it's an instance method, make a member pointer.
7540 // The expression must have exactly the form &A::foo.
7542 // If the underlying expression isn't a decl ref, give up.
7543 if (!isa<DeclRefExpr>(op)) {
7544 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7545 << OrigOp->getSourceRange();
7546 return QualType();
7548 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7549 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7551 // The id-expression was parenthesized.
7552 if (OrigOp != DRE) {
7553 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7554 << OrigOp->getSourceRange();
7556 // The method was named without a qualifier.
7557 } else if (!DRE->getQualifier()) {
7558 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7559 << op->getSourceRange();
7562 return S.Context.getMemberPointerType(op->getType(),
7563 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7564 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7565 // C99 6.5.3.2p1
7566 // The operand must be either an l-value or a function designator
7567 if (!op->getType()->isFunctionType()) {
7568 // FIXME: emit more specific diag...
7569 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7570 << op->getSourceRange();
7571 return QualType();
7573 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7574 // The operand cannot be a bit-field
7575 S.Diag(OpLoc, diag::err_typecheck_address_of)
7576 << "bit-field" << op->getSourceRange();
7577 return QualType();
7578 } else if (op->getObjectKind() == OK_VectorComponent) {
7579 // The operand cannot be an element of a vector
7580 S.Diag(OpLoc, diag::err_typecheck_address_of)
7581 << "vector element" << op->getSourceRange();
7582 return QualType();
7583 } else if (op->getObjectKind() == OK_ObjCProperty) {
7584 // cannot take address of a property expression.
7585 S.Diag(OpLoc, diag::err_typecheck_address_of)
7586 << "property expression" << op->getSourceRange();
7587 return QualType();
7588 } else if (dcl) { // C99 6.5.3.2p1
7589 // We have an lvalue with a decl. Make sure the decl is not declared
7590 // with the register storage-class specifier.
7591 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
7592 // in C++ it is not error to take address of a register
7593 // variable (c++03 7.1.1P3)
7594 if (vd->getStorageClass() == SC_Register &&
7595 !S.getLangOptions().CPlusPlus) {
7596 S.Diag(OpLoc, diag::err_typecheck_address_of)
7597 << "register variable" << op->getSourceRange();
7598 return QualType();
7600 } else if (isa<FunctionTemplateDecl>(dcl)) {
7601 return S.Context.OverloadTy;
7602 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
7603 // Okay: we can take the address of a field.
7604 // Could be a pointer to member, though, if there is an explicit
7605 // scope qualifier for the class.
7606 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
7607 DeclContext *Ctx = dcl->getDeclContext();
7608 if (Ctx && Ctx->isRecord()) {
7609 if (dcl->getType()->isReferenceType()) {
7610 S.Diag(OpLoc,
7611 diag::err_cannot_form_pointer_to_member_of_reference_type)
7612 << dcl->getDeclName() << dcl->getType();
7613 return QualType();
7616 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7617 Ctx = Ctx->getParent();
7618 return S.Context.getMemberPointerType(op->getType(),
7619 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
7622 } else if (!isa<FunctionDecl>(dcl))
7623 assert(0 && "Unknown/unexpected decl type");
7626 if (lval == Expr::LV_IncompleteVoidType) {
7627 // Taking the address of a void variable is technically illegal, but we
7628 // allow it in cases which are otherwise valid.
7629 // Example: "extern void x; void* y = &x;".
7630 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
7633 // If the operand has type "type", the result has type "pointer to type".
7634 if (op->getType()->isObjCObjectType())
7635 return S.Context.getObjCObjectPointerType(op->getType());
7636 return S.Context.getPointerType(op->getType());
7639 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
7640 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7641 SourceLocation OpLoc) {
7642 if (Op->isTypeDependent())
7643 return S.Context.DependentTy;
7645 S.UsualUnaryConversions(Op);
7646 QualType OpTy = Op->getType();
7647 QualType Result;
7649 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7650 // is an incomplete type or void. It would be possible to warn about
7651 // dereferencing a void pointer, but it's completely well-defined, and such a
7652 // warning is unlikely to catch any mistakes.
7653 if (const PointerType *PT = OpTy->getAs<PointerType>())
7654 Result = PT->getPointeeType();
7655 else if (const ObjCObjectPointerType *OPT =
7656 OpTy->getAs<ObjCObjectPointerType>())
7657 Result = OPT->getPointeeType();
7658 else {
7659 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
7660 if (PR.isInvalid()) return QualType();
7661 if (PR.take() != Op)
7662 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
7665 if (Result.isNull()) {
7666 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
7667 << OpTy << Op->getSourceRange();
7668 return QualType();
7671 // Dereferences are usually l-values...
7672 VK = VK_LValue;
7674 // ...except that certain expressions are never l-values in C.
7675 if (!S.getLangOptions().CPlusPlus &&
7676 IsCForbiddenLValueType(S.Context, Result))
7677 VK = VK_RValue;
7679 return Result;
7682 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
7683 tok::TokenKind Kind) {
7684 BinaryOperatorKind Opc;
7685 switch (Kind) {
7686 default: assert(0 && "Unknown binop!");
7687 case tok::periodstar: Opc = BO_PtrMemD; break;
7688 case tok::arrowstar: Opc = BO_PtrMemI; break;
7689 case tok::star: Opc = BO_Mul; break;
7690 case tok::slash: Opc = BO_Div; break;
7691 case tok::percent: Opc = BO_Rem; break;
7692 case tok::plus: Opc = BO_Add; break;
7693 case tok::minus: Opc = BO_Sub; break;
7694 case tok::lessless: Opc = BO_Shl; break;
7695 case tok::greatergreater: Opc = BO_Shr; break;
7696 case tok::lessequal: Opc = BO_LE; break;
7697 case tok::less: Opc = BO_LT; break;
7698 case tok::greaterequal: Opc = BO_GE; break;
7699 case tok::greater: Opc = BO_GT; break;
7700 case tok::exclaimequal: Opc = BO_NE; break;
7701 case tok::equalequal: Opc = BO_EQ; break;
7702 case tok::amp: Opc = BO_And; break;
7703 case tok::caret: Opc = BO_Xor; break;
7704 case tok::pipe: Opc = BO_Or; break;
7705 case tok::ampamp: Opc = BO_LAnd; break;
7706 case tok::pipepipe: Opc = BO_LOr; break;
7707 case tok::equal: Opc = BO_Assign; break;
7708 case tok::starequal: Opc = BO_MulAssign; break;
7709 case tok::slashequal: Opc = BO_DivAssign; break;
7710 case tok::percentequal: Opc = BO_RemAssign; break;
7711 case tok::plusequal: Opc = BO_AddAssign; break;
7712 case tok::minusequal: Opc = BO_SubAssign; break;
7713 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7714 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7715 case tok::ampequal: Opc = BO_AndAssign; break;
7716 case tok::caretequal: Opc = BO_XorAssign; break;
7717 case tok::pipeequal: Opc = BO_OrAssign; break;
7718 case tok::comma: Opc = BO_Comma; break;
7720 return Opc;
7723 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
7724 tok::TokenKind Kind) {
7725 UnaryOperatorKind Opc;
7726 switch (Kind) {
7727 default: assert(0 && "Unknown unary op!");
7728 case tok::plusplus: Opc = UO_PreInc; break;
7729 case tok::minusminus: Opc = UO_PreDec; break;
7730 case tok::amp: Opc = UO_AddrOf; break;
7731 case tok::star: Opc = UO_Deref; break;
7732 case tok::plus: Opc = UO_Plus; break;
7733 case tok::minus: Opc = UO_Minus; break;
7734 case tok::tilde: Opc = UO_Not; break;
7735 case tok::exclaim: Opc = UO_LNot; break;
7736 case tok::kw___real: Opc = UO_Real; break;
7737 case tok::kw___imag: Opc = UO_Imag; break;
7738 case tok::kw___extension__: Opc = UO_Extension; break;
7740 return Opc;
7743 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7744 /// This warning is only emitted for builtin assignment operations. It is also
7745 /// suppressed in the event of macro expansions.
7746 static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7747 SourceLocation OpLoc) {
7748 if (!S.ActiveTemplateInstantiations.empty())
7749 return;
7750 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7751 return;
7752 lhs = lhs->IgnoreParenImpCasts();
7753 rhs = rhs->IgnoreParenImpCasts();
7754 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7755 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7756 if (!LeftDeclRef || !RightDeclRef ||
7757 LeftDeclRef->getLocation().isMacroID() ||
7758 RightDeclRef->getLocation().isMacroID())
7759 return;
7760 const ValueDecl *LeftDecl =
7761 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7762 const ValueDecl *RightDecl =
7763 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7764 if (LeftDecl != RightDecl)
7765 return;
7766 if (LeftDecl->getType().isVolatileQualified())
7767 return;
7768 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7769 if (RefTy->getPointeeType().isVolatileQualified())
7770 return;
7772 S.Diag(OpLoc, diag::warn_self_assignment)
7773 << LeftDeclRef->getType()
7774 << lhs->getSourceRange() << rhs->getSourceRange();
7777 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7778 /// operator @p Opc at location @c TokLoc. This routine only supports
7779 /// built-in operations; ActOnBinOp handles overloaded operators.
7780 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
7781 BinaryOperatorKind Opc,
7782 Expr *lhs, Expr *rhs) {
7783 QualType ResultTy; // Result type of the binary operator.
7784 // The following two variables are used for compound assignment operators
7785 QualType CompLHSTy; // Type of LHS after promotions for computation
7786 QualType CompResultTy; // Type of computation result
7787 ExprValueKind VK = VK_RValue;
7788 ExprObjectKind OK = OK_Ordinary;
7790 switch (Opc) {
7791 case BO_Assign:
7792 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
7793 if (getLangOptions().CPlusPlus &&
7794 lhs->getObjectKind() != OK_ObjCProperty) {
7795 VK = lhs->getValueKind();
7796 OK = lhs->getObjectKind();
7798 if (!ResultTy.isNull())
7799 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
7800 break;
7801 case BO_PtrMemD:
7802 case BO_PtrMemI:
7803 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
7804 Opc == BO_PtrMemI);
7805 break;
7806 case BO_Mul:
7807 case BO_Div:
7808 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
7809 Opc == BO_Div);
7810 break;
7811 case BO_Rem:
7812 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7813 break;
7814 case BO_Add:
7815 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7816 break;
7817 case BO_Sub:
7818 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7819 break;
7820 case BO_Shl:
7821 case BO_Shr:
7822 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7823 break;
7824 case BO_LE:
7825 case BO_LT:
7826 case BO_GE:
7827 case BO_GT:
7828 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
7829 break;
7830 case BO_EQ:
7831 case BO_NE:
7832 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
7833 break;
7834 case BO_And:
7835 case BO_Xor:
7836 case BO_Or:
7837 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7838 break;
7839 case BO_LAnd:
7840 case BO_LOr:
7841 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
7842 break;
7843 case BO_MulAssign:
7844 case BO_DivAssign:
7845 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
7846 Opc == BO_DivAssign);
7847 CompLHSTy = CompResultTy;
7848 if (!CompResultTy.isNull())
7849 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7850 break;
7851 case BO_RemAssign:
7852 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7853 CompLHSTy = CompResultTy;
7854 if (!CompResultTy.isNull())
7855 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7856 break;
7857 case BO_AddAssign:
7858 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7859 if (!CompResultTy.isNull())
7860 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7861 break;
7862 case BO_SubAssign:
7863 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7864 if (!CompResultTy.isNull())
7865 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7866 break;
7867 case BO_ShlAssign:
7868 case BO_ShrAssign:
7869 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7870 CompLHSTy = CompResultTy;
7871 if (!CompResultTy.isNull())
7872 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7873 break;
7874 case BO_AndAssign:
7875 case BO_XorAssign:
7876 case BO_OrAssign:
7877 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7878 CompLHSTy = CompResultTy;
7879 if (!CompResultTy.isNull())
7880 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7881 break;
7882 case BO_Comma:
7883 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
7884 if (getLangOptions().CPlusPlus) {
7885 VK = rhs->getValueKind();
7886 OK = rhs->getObjectKind();
7888 break;
7890 if (ResultTy.isNull())
7891 return ExprError();
7892 if (CompResultTy.isNull())
7893 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7894 VK, OK, OpLoc));
7896 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
7897 VK = VK_LValue;
7898 OK = lhs->getObjectKind();
7900 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7901 VK, OK, CompLHSTy,
7902 CompResultTy, OpLoc));
7905 /// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7906 /// ParenRange in parentheses.
7907 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7908 const PartialDiagnostic &PD,
7909 const PartialDiagnostic &FirstNote,
7910 SourceRange FirstParenRange,
7911 const PartialDiagnostic &SecondNote,
7912 SourceRange SecondParenRange) {
7913 Self.Diag(Loc, PD);
7915 if (!FirstNote.getDiagID())
7916 return;
7918 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7919 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7920 // We can't display the parentheses, so just return.
7921 return;
7924 Self.Diag(Loc, FirstNote)
7925 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
7926 << FixItHint::CreateInsertion(EndLoc, ")");
7928 if (!SecondNote.getDiagID())
7929 return;
7931 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7932 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7933 // We can't display the parentheses, so just dig the
7934 // warning/error and return.
7935 Self.Diag(Loc, SecondNote);
7936 return;
7939 Self.Diag(Loc, SecondNote)
7940 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7941 << FixItHint::CreateInsertion(EndLoc, ")");
7944 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7945 /// operators are mixed in a way that suggests that the programmer forgot that
7946 /// comparison operators have higher precedence. The most typical example of
7947 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
7948 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
7949 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
7950 typedef BinaryOperator BinOp;
7951 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7952 rhsopc = static_cast<BinOp::Opcode>(-1);
7953 if (BinOp *BO = dyn_cast<BinOp>(lhs))
7954 lhsopc = BO->getOpcode();
7955 if (BinOp *BO = dyn_cast<BinOp>(rhs))
7956 rhsopc = BO->getOpcode();
7958 // Subs are not binary operators.
7959 if (lhsopc == -1 && rhsopc == -1)
7960 return;
7962 // Bitwise operations are sometimes used as eager logical ops.
7963 // Don't diagnose this.
7964 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7965 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
7966 return;
7968 if (BinOp::isComparisonOp(lhsopc))
7969 SuggestParentheses(Self, OpLoc,
7970 Self.PDiag(diag::warn_precedence_bitwise_rel)
7971 << SourceRange(lhs->getLocStart(), OpLoc)
7972 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
7973 Self.PDiag(diag::note_precedence_bitwise_first)
7974 << BinOp::getOpcodeStr(Opc),
7975 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7976 Self.PDiag(diag::note_precedence_bitwise_silence)
7977 << BinOp::getOpcodeStr(lhsopc),
7978 lhs->getSourceRange());
7979 else if (BinOp::isComparisonOp(rhsopc))
7980 SuggestParentheses(Self, OpLoc,
7981 Self.PDiag(diag::warn_precedence_bitwise_rel)
7982 << SourceRange(OpLoc, rhs->getLocEnd())
7983 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
7984 Self.PDiag(diag::note_precedence_bitwise_first)
7985 << BinOp::getOpcodeStr(Opc),
7986 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7987 Self.PDiag(diag::note_precedence_bitwise_silence)
7988 << BinOp::getOpcodeStr(rhsopc),
7989 rhs->getSourceRange());
7992 /// \brief It accepts a '&&' expr that is inside a '||' one.
7993 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7994 /// in parentheses.
7995 static void
7996 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7997 Expr *E) {
7998 assert(isa<BinaryOperator>(E) &&
7999 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
8000 SuggestParentheses(Self, OpLoc,
8001 Self.PDiag(diag::warn_logical_and_in_logical_or)
8002 << E->getSourceRange(),
8003 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
8004 E->getSourceRange(),
8005 Self.PDiag(0), SourceRange());
8008 /// \brief Returns true if the given expression can be evaluated as a constant
8009 /// 'true'.
8010 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8011 bool Res;
8012 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8015 /// \brief Returns true if the given expression can be evaluated as a constant
8016 /// 'false'.
8017 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8018 bool Res;
8019 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8022 /// \brief Look for '&&' in the left hand of a '||' expr.
8023 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8024 Expr *OrLHS, Expr *OrRHS) {
8025 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
8026 if (Bop->getOpcode() == BO_LAnd) {
8027 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8028 if (EvaluatesAsFalse(S, OrRHS))
8029 return;
8030 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8031 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8032 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8033 } else if (Bop->getOpcode() == BO_LOr) {
8034 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8035 // If it's "a || b && 1 || c" we didn't warn earlier for
8036 // "a || b && 1", but warn now.
8037 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8038 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8044 /// \brief Look for '&&' in the right hand of a '||' expr.
8045 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8046 Expr *OrLHS, Expr *OrRHS) {
8047 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
8048 if (Bop->getOpcode() == BO_LAnd) {
8049 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8050 if (EvaluatesAsFalse(S, OrLHS))
8051 return;
8052 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8053 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8054 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8059 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8060 /// precedence.
8061 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8062 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
8063 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8064 if (BinaryOperator::isBitwiseOp(Opc))
8065 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
8067 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8068 // We don't warn for 'assert(a || b && "bad")' since this is safe.
8069 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8070 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
8071 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
8075 // Binary Operators. 'Tok' is the token for the operator.
8076 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8077 tok::TokenKind Kind,
8078 Expr *lhs, Expr *rhs) {
8079 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8080 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
8081 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
8083 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8084 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
8086 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
8089 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8090 BinaryOperatorKind Opc,
8091 Expr *lhs, Expr *rhs) {
8092 if (getLangOptions().CPlusPlus) {
8093 bool UseBuiltinOperator;
8095 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
8096 UseBuiltinOperator = false;
8097 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
8098 UseBuiltinOperator = true;
8099 } else {
8100 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
8101 !rhs->getType()->isOverloadableType();
8104 if (!UseBuiltinOperator) {
8105 // Find all of the overloaded operators visible from this
8106 // point. We perform both an operator-name lookup from the local
8107 // scope and an argument-dependent lookup based on the types of
8108 // the arguments.
8109 UnresolvedSet<16> Functions;
8110 OverloadedOperatorKind OverOp
8111 = BinaryOperator::getOverloadedOperator(Opc);
8112 if (S && OverOp != OO_None)
8113 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
8114 Functions);
8116 // Build the (potentially-overloaded, potentially-dependent)
8117 // binary operation.
8118 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
8122 // Build a built-in binary operation.
8123 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
8126 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8127 UnaryOperatorKind Opc,
8128 Expr *Input) {
8129 ExprValueKind VK = VK_RValue;
8130 ExprObjectKind OK = OK_Ordinary;
8131 QualType resultType;
8132 switch (Opc) {
8133 case UO_PreInc:
8134 case UO_PreDec:
8135 case UO_PostInc:
8136 case UO_PostDec:
8137 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
8138 Opc == UO_PreInc ||
8139 Opc == UO_PostInc,
8140 Opc == UO_PreInc ||
8141 Opc == UO_PreDec);
8142 break;
8143 case UO_AddrOf:
8144 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8145 break;
8146 case UO_Deref:
8147 DefaultFunctionArrayLvalueConversion(Input);
8148 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
8149 break;
8150 case UO_Plus:
8151 case UO_Minus:
8152 UsualUnaryConversions(Input);
8153 resultType = Input->getType();
8154 if (resultType->isDependentType())
8155 break;
8156 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8157 resultType->isVectorType())
8158 break;
8159 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8160 resultType->isEnumeralType())
8161 break;
8162 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
8163 Opc == UO_Plus &&
8164 resultType->isPointerType())
8165 break;
8166 else if (resultType->isPlaceholderType()) {
8167 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8168 if (PR.isInvalid()) return ExprError();
8169 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
8172 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8173 << resultType << Input->getSourceRange());
8174 case UO_Not: // bitwise complement
8175 UsualUnaryConversions(Input);
8176 resultType = Input->getType();
8177 if (resultType->isDependentType())
8178 break;
8179 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8180 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8181 // C99 does not support '~' for complex conjugation.
8182 Diag(OpLoc, diag::ext_integer_complement_complex)
8183 << resultType << Input->getSourceRange();
8184 else if (resultType->hasIntegerRepresentation())
8185 break;
8186 else if (resultType->isPlaceholderType()) {
8187 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8188 if (PR.isInvalid()) return ExprError();
8189 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
8190 } else {
8191 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8192 << resultType << Input->getSourceRange());
8194 break;
8195 case UO_LNot: // logical negation
8196 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8197 DefaultFunctionArrayLvalueConversion(Input);
8198 resultType = Input->getType();
8199 if (resultType->isDependentType())
8200 break;
8201 if (resultType->isScalarType()) { // C99 6.5.3.3p1
8202 // ok, fallthrough
8203 } else if (resultType->isPlaceholderType()) {
8204 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
8205 if (PR.isInvalid()) return ExprError();
8206 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
8207 } else {
8208 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8209 << resultType << Input->getSourceRange());
8212 // LNot always has type int. C99 6.5.3.3p5.
8213 // In C++, it's bool. C++ 5.3.1p8
8214 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
8215 break;
8216 case UO_Real:
8217 case UO_Imag:
8218 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8219 // _Real and _Imag map ordinary l-values into ordinary l-values.
8220 if (Input->getValueKind() != VK_RValue &&
8221 Input->getObjectKind() == OK_Ordinary)
8222 VK = Input->getValueKind();
8223 break;
8224 case UO_Extension:
8225 resultType = Input->getType();
8226 VK = Input->getValueKind();
8227 OK = Input->getObjectKind();
8228 break;
8230 if (resultType.isNull())
8231 return ExprError();
8233 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
8234 VK, OK, OpLoc));
8237 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8238 UnaryOperatorKind Opc,
8239 Expr *Input) {
8240 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
8241 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
8242 // Find all of the overloaded operators visible from this
8243 // point. We perform both an operator-name lookup from the local
8244 // scope and an argument-dependent lookup based on the types of
8245 // the arguments.
8246 UnresolvedSet<16> Functions;
8247 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8248 if (S && OverOp != OO_None)
8249 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8250 Functions);
8252 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8255 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8258 // Unary Operators. 'Tok' is the token for the operator.
8259 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8260 tok::TokenKind Op, Expr *Input) {
8261 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8264 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8265 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
8266 SourceLocation LabLoc,
8267 IdentifierInfo *LabelII) {
8268 // Look up the record for this label identifier.
8269 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
8271 // If we haven't seen this label yet, create a forward reference. It
8272 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
8273 if (LabelDecl == 0)
8274 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
8276 LabelDecl->setUsed();
8277 // Create the AST node. The address of a label always has type 'void*'.
8278 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
8279 Context.getPointerType(Context.VoidTy)));
8282 ExprResult
8283 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8284 SourceLocation RPLoc) { // "({..})"
8285 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8286 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8288 bool isFileScope
8289 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8290 if (isFileScope)
8291 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8293 // FIXME: there are a variety of strange constraints to enforce here, for
8294 // example, it is not possible to goto into a stmt expression apparently.
8295 // More semantic analysis is needed.
8297 // If there are sub stmts in the compound stmt, take the type of the last one
8298 // as the type of the stmtexpr.
8299 QualType Ty = Context.VoidTy;
8300 bool StmtExprMayBindToTemp = false;
8301 if (!Compound->body_empty()) {
8302 Stmt *LastStmt = Compound->body_back();
8303 LabelStmt *LastLabelStmt = 0;
8304 // If LastStmt is a label, skip down through into the body.
8305 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8306 LastLabelStmt = Label;
8307 LastStmt = Label->getSubStmt();
8309 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
8310 // Do function/array conversion on the last expression, but not
8311 // lvalue-to-rvalue. However, initialize an unqualified type.
8312 DefaultFunctionArrayConversion(LastExpr);
8313 Ty = LastExpr->getType().getUnqualifiedType();
8315 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8316 ExprResult Res = PerformCopyInitialization(
8317 InitializedEntity::InitializeResult(LPLoc,
8319 false),
8320 SourceLocation(),
8321 Owned(LastExpr));
8322 if (Res.isInvalid())
8323 return ExprError();
8324 if ((LastExpr = Res.takeAs<Expr>())) {
8325 if (!LastLabelStmt)
8326 Compound->setLastStmt(LastExpr);
8327 else
8328 LastLabelStmt->setSubStmt(LastExpr);
8329 StmtExprMayBindToTemp = true;
8335 // FIXME: Check that expression type is complete/non-abstract; statement
8336 // expressions are not lvalues.
8337 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8338 if (StmtExprMayBindToTemp)
8339 return MaybeBindToTemporary(ResStmtExpr);
8340 return Owned(ResStmtExpr);
8343 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8344 TypeSourceInfo *TInfo,
8345 OffsetOfComponent *CompPtr,
8346 unsigned NumComponents,
8347 SourceLocation RParenLoc) {
8348 QualType ArgTy = TInfo->getType();
8349 bool Dependent = ArgTy->isDependentType();
8350 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8352 // We must have at least one component that refers to the type, and the first
8353 // one is known to be a field designator. Verify that the ArgTy represents
8354 // a struct/union/class.
8355 if (!Dependent && !ArgTy->isRecordType())
8356 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8357 << ArgTy << TypeRange);
8359 // Type must be complete per C99 7.17p3 because a declaring a variable
8360 // with an incomplete type would be ill-formed.
8361 if (!Dependent
8362 && RequireCompleteType(BuiltinLoc, ArgTy,
8363 PDiag(diag::err_offsetof_incomplete_type)
8364 << TypeRange))
8365 return ExprError();
8367 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8368 // GCC extension, diagnose them.
8369 // FIXME: This diagnostic isn't actually visible because the location is in
8370 // a system header!
8371 if (NumComponents != 1)
8372 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8373 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
8375 bool DidWarnAboutNonPOD = false;
8376 QualType CurrentType = ArgTy;
8377 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8378 llvm::SmallVector<OffsetOfNode, 4> Comps;
8379 llvm::SmallVector<Expr*, 4> Exprs;
8380 for (unsigned i = 0; i != NumComponents; ++i) {
8381 const OffsetOfComponent &OC = CompPtr[i];
8382 if (OC.isBrackets) {
8383 // Offset of an array sub-field. TODO: Should we allow vector elements?
8384 if (!CurrentType->isDependentType()) {
8385 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8386 if(!AT)
8387 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8388 << CurrentType);
8389 CurrentType = AT->getElementType();
8390 } else
8391 CurrentType = Context.DependentTy;
8393 // The expression must be an integral expression.
8394 // FIXME: An integral constant expression?
8395 Expr *Idx = static_cast<Expr*>(OC.U.E);
8396 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8397 !Idx->getType()->isIntegerType())
8398 return ExprError(Diag(Idx->getLocStart(),
8399 diag::err_typecheck_subscript_not_integer)
8400 << Idx->getSourceRange());
8402 // Record this array index.
8403 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8404 Exprs.push_back(Idx);
8405 continue;
8408 // Offset of a field.
8409 if (CurrentType->isDependentType()) {
8410 // We have the offset of a field, but we can't look into the dependent
8411 // type. Just record the identifier of the field.
8412 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8413 CurrentType = Context.DependentTy;
8414 continue;
8417 // We need to have a complete type to look into.
8418 if (RequireCompleteType(OC.LocStart, CurrentType,
8419 diag::err_offsetof_incomplete_type))
8420 return ExprError();
8422 // Look for the designated field.
8423 const RecordType *RC = CurrentType->getAs<RecordType>();
8424 if (!RC)
8425 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8426 << CurrentType);
8427 RecordDecl *RD = RC->getDecl();
8429 // C++ [lib.support.types]p5:
8430 // The macro offsetof accepts a restricted set of type arguments in this
8431 // International Standard. type shall be a POD structure or a POD union
8432 // (clause 9).
8433 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8434 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8435 DiagRuntimeBehavior(BuiltinLoc,
8436 PDiag(diag::warn_offsetof_non_pod_type)
8437 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8438 << CurrentType))
8439 DidWarnAboutNonPOD = true;
8442 // Look for the field.
8443 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8444 LookupQualifiedName(R, RD);
8445 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
8446 IndirectFieldDecl *IndirectMemberDecl = 0;
8447 if (!MemberDecl) {
8448 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
8449 MemberDecl = IndirectMemberDecl->getAnonField();
8452 if (!MemberDecl)
8453 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8454 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8455 OC.LocEnd));
8457 // C99 7.17p3:
8458 // (If the specified member is a bit-field, the behavior is undefined.)
8460 // We diagnose this as an error.
8461 if (MemberDecl->getBitWidth()) {
8462 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8463 << MemberDecl->getDeclName()
8464 << SourceRange(BuiltinLoc, RParenLoc);
8465 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8466 return ExprError();
8469 RecordDecl *Parent = MemberDecl->getParent();
8470 if (IndirectMemberDecl)
8471 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
8473 // If the member was found in a base class, introduce OffsetOfNodes for
8474 // the base class indirections.
8475 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8476 /*DetectVirtual=*/false);
8477 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
8478 CXXBasePath &Path = Paths.front();
8479 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8480 B != BEnd; ++B)
8481 Comps.push_back(OffsetOfNode(B->Base));
8484 if (IndirectMemberDecl) {
8485 for (IndirectFieldDecl::chain_iterator FI =
8486 IndirectMemberDecl->chain_begin(),
8487 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8488 assert(isa<FieldDecl>(*FI));
8489 Comps.push_back(OffsetOfNode(OC.LocStart,
8490 cast<FieldDecl>(*FI), OC.LocEnd));
8492 } else
8493 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
8495 CurrentType = MemberDecl->getType().getNonReferenceType();
8498 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8499 TInfo, Comps.data(), Comps.size(),
8500 Exprs.data(), Exprs.size(), RParenLoc));
8503 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
8504 SourceLocation BuiltinLoc,
8505 SourceLocation TypeLoc,
8506 ParsedType argty,
8507 OffsetOfComponent *CompPtr,
8508 unsigned NumComponents,
8509 SourceLocation RPLoc) {
8511 TypeSourceInfo *ArgTInfo;
8512 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8513 if (ArgTy.isNull())
8514 return ExprError();
8516 if (!ArgTInfo)
8517 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8519 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8520 RPLoc);
8524 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
8525 Expr *CondExpr,
8526 Expr *LHSExpr, Expr *RHSExpr,
8527 SourceLocation RPLoc) {
8528 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8530 ExprValueKind VK = VK_RValue;
8531 ExprObjectKind OK = OK_Ordinary;
8532 QualType resType;
8533 bool ValueDependent = false;
8534 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
8535 resType = Context.DependentTy;
8536 ValueDependent = true;
8537 } else {
8538 // The conditional expression is required to be a constant expression.
8539 llvm::APSInt condEval(32);
8540 SourceLocation ExpLoc;
8541 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
8542 return ExprError(Diag(ExpLoc,
8543 diag::err_typecheck_choose_expr_requires_constant)
8544 << CondExpr->getSourceRange());
8546 // If the condition is > zero, then the AST type is the same as the LSHExpr.
8547 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8549 resType = ActiveExpr->getType();
8550 ValueDependent = ActiveExpr->isValueDependent();
8551 VK = ActiveExpr->getValueKind();
8552 OK = ActiveExpr->getObjectKind();
8555 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
8556 resType, VK, OK, RPLoc,
8557 resType->isDependentType(),
8558 ValueDependent));
8561 //===----------------------------------------------------------------------===//
8562 // Clang Extensions.
8563 //===----------------------------------------------------------------------===//
8565 /// ActOnBlockStart - This callback is invoked when a block literal is started.
8566 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
8567 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8568 PushBlockScope(BlockScope, Block);
8569 CurContext->addDecl(Block);
8570 if (BlockScope)
8571 PushDeclContext(BlockScope, Block);
8572 else
8573 CurContext = Block;
8576 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
8577 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
8578 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
8579 BlockScopeInfo *CurBlock = getCurBlock();
8581 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
8582 QualType T = Sig->getType();
8584 // GetTypeForDeclarator always produces a function type for a block
8585 // literal signature. Furthermore, it is always a FunctionProtoType
8586 // unless the function was written with a typedef.
8587 assert(T->isFunctionType() &&
8588 "GetTypeForDeclarator made a non-function block signature");
8590 // Look for an explicit signature in that function type.
8591 FunctionProtoTypeLoc ExplicitSignature;
8593 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8594 if (isa<FunctionProtoTypeLoc>(tmp)) {
8595 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8597 // Check whether that explicit signature was synthesized by
8598 // GetTypeForDeclarator. If so, don't save that as part of the
8599 // written signature.
8600 if (ExplicitSignature.getLParenLoc() ==
8601 ExplicitSignature.getRParenLoc()) {
8602 // This would be much cheaper if we stored TypeLocs instead of
8603 // TypeSourceInfos.
8604 TypeLoc Result = ExplicitSignature.getResultLoc();
8605 unsigned Size = Result.getFullDataSize();
8606 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8607 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8609 ExplicitSignature = FunctionProtoTypeLoc();
8613 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8614 CurBlock->FunctionType = T;
8616 const FunctionType *Fn = T->getAs<FunctionType>();
8617 QualType RetTy = Fn->getResultType();
8618 bool isVariadic =
8619 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8621 CurBlock->TheDecl->setIsVariadic(isVariadic);
8623 // Don't allow returning a objc interface by value.
8624 if (RetTy->isObjCObjectType()) {
8625 Diag(ParamInfo.getSourceRange().getBegin(),
8626 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8627 return;
8630 // Context.DependentTy is used as a placeholder for a missing block
8631 // return type. TODO: what should we do with declarators like:
8632 // ^ * { ... }
8633 // If the answer is "apply template argument deduction"....
8634 if (RetTy != Context.DependentTy)
8635 CurBlock->ReturnType = RetTy;
8637 // Push block parameters from the declarator if we had them.
8638 llvm::SmallVector<ParmVarDecl*, 8> Params;
8639 if (ExplicitSignature) {
8640 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8641 ParmVarDecl *Param = ExplicitSignature.getArg(I);
8642 if (Param->getIdentifier() == 0 &&
8643 !Param->isImplicit() &&
8644 !Param->isInvalidDecl() &&
8645 !getLangOptions().CPlusPlus)
8646 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8647 Params.push_back(Param);
8650 // Fake up parameter variables if we have a typedef, like
8651 // ^ fntype { ... }
8652 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8653 for (FunctionProtoType::arg_type_iterator
8654 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8655 ParmVarDecl *Param =
8656 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8657 ParamInfo.getSourceRange().getBegin(),
8658 *I);
8659 Params.push_back(Param);
8663 // Set the parameters on the block decl.
8664 if (!Params.empty()) {
8665 CurBlock->TheDecl->setParams(Params.data(), Params.size());
8666 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8667 CurBlock->TheDecl->param_end(),
8668 /*CheckParameterNames=*/false);
8671 // Finally we can process decl attributes.
8672 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
8674 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
8675 Diag(ParamInfo.getAttributes()->getLoc(),
8676 diag::warn_attribute_sentinel_not_variadic) << 1;
8677 // FIXME: remove the attribute.
8680 // Put the parameter variables in scope. We can bail out immediately
8681 // if we don't have any.
8682 if (Params.empty())
8683 return;
8685 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
8686 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8687 (*AI)->setOwningFunction(CurBlock->TheDecl);
8689 // If this has an identifier, add it to the scope stack.
8690 if ((*AI)->getIdentifier()) {
8691 CheckShadow(CurBlock->TheScope, *AI);
8693 PushOnScopeChains(*AI, CurBlock->TheScope);
8698 /// ActOnBlockError - If there is an error parsing a block, this callback
8699 /// is invoked to pop the information about the block from the action impl.
8700 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
8701 // Pop off CurBlock, handle nested blocks.
8702 PopDeclContext();
8703 PopFunctionOrBlockScope();
8706 /// ActOnBlockStmtExpr - This is called when the body of a block statement
8707 /// literal was successfully completed. ^(int x){...}
8708 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
8709 Stmt *Body, Scope *CurScope) {
8710 // If blocks are disabled, emit an error.
8711 if (!LangOpts.Blocks)
8712 Diag(CaretLoc, diag::err_blocks_disable);
8714 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
8716 PopDeclContext();
8718 QualType RetTy = Context.VoidTy;
8719 if (!BSI->ReturnType.isNull())
8720 RetTy = BSI->ReturnType;
8722 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
8723 QualType BlockTy;
8725 // Set the captured variables on the block.
8726 BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8727 BSI->CapturesCXXThis);
8729 // If the user wrote a function type in some form, try to use that.
8730 if (!BSI->FunctionType.isNull()) {
8731 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8733 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8734 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8736 // Turn protoless block types into nullary block types.
8737 if (isa<FunctionNoProtoType>(FTy)) {
8738 FunctionProtoType::ExtProtoInfo EPI;
8739 EPI.ExtInfo = Ext;
8740 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8742 // Otherwise, if we don't need to change anything about the function type,
8743 // preserve its sugar structure.
8744 } else if (FTy->getResultType() == RetTy &&
8745 (!NoReturn || FTy->getNoReturnAttr())) {
8746 BlockTy = BSI->FunctionType;
8748 // Otherwise, make the minimal modifications to the function type.
8749 } else {
8750 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
8751 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8752 EPI.TypeQuals = 0; // FIXME: silently?
8753 EPI.ExtInfo = Ext;
8754 BlockTy = Context.getFunctionType(RetTy,
8755 FPT->arg_type_begin(),
8756 FPT->getNumArgs(),
8757 EPI);
8760 // If we don't have a function type, just build one from nothing.
8761 } else {
8762 FunctionProtoType::ExtProtoInfo EPI;
8763 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8764 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8767 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8768 BSI->TheDecl->param_end());
8769 BlockTy = Context.getBlockPointerType(BlockTy);
8771 // If needed, diagnose invalid gotos and switches in the block.
8772 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
8773 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
8775 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
8777 bool Good = true;
8778 // Check goto/label use.
8779 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8780 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8781 LabelStmt *L = I->second;
8783 // Verify that we have no forward references left. If so, there was a goto
8784 // or address of a label taken, but no definition of it.
8785 if (L->getSubStmt() != 0) {
8786 if (!L->isUsed())
8787 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
8788 continue;
8791 // Emit error.
8792 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8793 Good = false;
8795 if (!Good) {
8796 PopFunctionOrBlockScope();
8797 return ExprError();
8800 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8802 // Issue any analysis-based warnings.
8803 const sema::AnalysisBasedWarnings::Policy &WP =
8804 AnalysisWarnings.getDefaultPolicy();
8805 AnalysisWarnings.IssueWarnings(WP, Result);
8807 PopFunctionOrBlockScope();
8808 return Owned(Result);
8811 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
8812 Expr *expr, ParsedType type,
8813 SourceLocation RPLoc) {
8814 TypeSourceInfo *TInfo;
8815 GetTypeFromParser(type, &TInfo);
8816 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
8819 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
8820 Expr *E, TypeSourceInfo *TInfo,
8821 SourceLocation RPLoc) {
8822 Expr *OrigExpr = E;
8824 // Get the va_list type
8825 QualType VaListType = Context.getBuiltinVaListType();
8826 if (VaListType->isArrayType()) {
8827 // Deal with implicit array decay; for example, on x86-64,
8828 // va_list is an array, but it's supposed to decay to
8829 // a pointer for va_arg.
8830 VaListType = Context.getArrayDecayedType(VaListType);
8831 // Make sure the input expression also decays appropriately.
8832 UsualUnaryConversions(E);
8833 } else {
8834 // Otherwise, the va_list argument must be an l-value because
8835 // it is modified by va_arg.
8836 if (!E->isTypeDependent() &&
8837 CheckForModifiableLvalue(E, BuiltinLoc, *this))
8838 return ExprError();
8841 if (!E->isTypeDependent() &&
8842 !Context.hasSameType(VaListType, E->getType())) {
8843 return ExprError(Diag(E->getLocStart(),
8844 diag::err_first_argument_to_va_arg_not_of_type_va_list)
8845 << OrigExpr->getType() << E->getSourceRange());
8848 // FIXME: Check that type is complete/non-abstract
8849 // FIXME: Warn if a non-POD type is passed in.
8851 QualType T = TInfo->getType().getNonLValueExprType(Context);
8852 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
8855 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
8856 // The type of __null will be int or long, depending on the size of
8857 // pointers on the target.
8858 QualType Ty;
8859 unsigned pw = Context.Target.getPointerWidth(0);
8860 if (pw == Context.Target.getIntWidth())
8861 Ty = Context.IntTy;
8862 else if (pw == Context.Target.getLongWidth())
8863 Ty = Context.LongTy;
8864 else if (pw == Context.Target.getLongLongWidth())
8865 Ty = Context.LongLongTy;
8866 else {
8867 assert(!"I don't know size of pointer!");
8868 Ty = Context.IntTy;
8871 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
8874 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
8875 Expr *SrcExpr, FixItHint &Hint) {
8876 if (!SemaRef.getLangOptions().ObjC1)
8877 return;
8879 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8880 if (!PT)
8881 return;
8883 // Check if the destination is of type 'id'.
8884 if (!PT->isObjCIdType()) {
8885 // Check if the destination is the 'NSString' interface.
8886 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8887 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8888 return;
8891 // Strip off any parens and casts.
8892 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8893 if (!SL || SL->isWide())
8894 return;
8896 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
8899 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8900 SourceLocation Loc,
8901 QualType DstType, QualType SrcType,
8902 Expr *SrcExpr, AssignmentAction Action,
8903 bool *Complained) {
8904 if (Complained)
8905 *Complained = false;
8907 // Decode the result (notice that AST's are still created for extensions).
8908 bool isInvalid = false;
8909 unsigned DiagKind;
8910 FixItHint Hint;
8912 switch (ConvTy) {
8913 default: assert(0 && "Unknown conversion type");
8914 case Compatible: return false;
8915 case PointerToInt:
8916 DiagKind = diag::ext_typecheck_convert_pointer_int;
8917 break;
8918 case IntToPointer:
8919 DiagKind = diag::ext_typecheck_convert_int_pointer;
8920 break;
8921 case IncompatiblePointer:
8922 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
8923 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8924 break;
8925 case IncompatiblePointerSign:
8926 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8927 break;
8928 case FunctionVoidPointer:
8929 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8930 break;
8931 case IncompatiblePointerDiscardsQualifiers: {
8932 // Perform array-to-pointer decay if necessary.
8933 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8935 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8936 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8937 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8938 DiagKind = diag::err_typecheck_incompatible_address_space;
8939 break;
8942 llvm_unreachable("unknown error case for discarding qualifiers!");
8943 // fallthrough
8945 case CompatiblePointerDiscardsQualifiers:
8946 // If the qualifiers lost were because we were applying the
8947 // (deprecated) C++ conversion from a string literal to a char*
8948 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8949 // Ideally, this check would be performed in
8950 // checkPointerTypesForAssignment. However, that would require a
8951 // bit of refactoring (so that the second argument is an
8952 // expression, rather than a type), which should be done as part
8953 // of a larger effort to fix checkPointerTypesForAssignment for
8954 // C++ semantics.
8955 if (getLangOptions().CPlusPlus &&
8956 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8957 return false;
8958 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8959 break;
8960 case IncompatibleNestedPointerQualifiers:
8961 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
8962 break;
8963 case IntToBlockPointer:
8964 DiagKind = diag::err_int_to_block_pointer;
8965 break;
8966 case IncompatibleBlockPointer:
8967 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
8968 break;
8969 case IncompatibleObjCQualifiedId:
8970 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
8971 // it can give a more specific diagnostic.
8972 DiagKind = diag::warn_incompatible_qualified_id;
8973 break;
8974 case IncompatibleVectors:
8975 DiagKind = diag::warn_incompatible_vectors;
8976 break;
8977 case Incompatible:
8978 DiagKind = diag::err_typecheck_convert_incompatible;
8979 isInvalid = true;
8980 break;
8983 QualType FirstType, SecondType;
8984 switch (Action) {
8985 case AA_Assigning:
8986 case AA_Initializing:
8987 // The destination type comes first.
8988 FirstType = DstType;
8989 SecondType = SrcType;
8990 break;
8992 case AA_Returning:
8993 case AA_Passing:
8994 case AA_Converting:
8995 case AA_Sending:
8996 case AA_Casting:
8997 // The source type comes first.
8998 FirstType = SrcType;
8999 SecondType = DstType;
9000 break;
9003 Diag(Loc, DiagKind) << FirstType << SecondType << Action
9004 << SrcExpr->getSourceRange() << Hint;
9005 if (Complained)
9006 *Complained = true;
9007 return isInvalid;
9010 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
9011 llvm::APSInt ICEResult;
9012 if (E->isIntegerConstantExpr(ICEResult, Context)) {
9013 if (Result)
9014 *Result = ICEResult;
9015 return false;
9018 Expr::EvalResult EvalResult;
9020 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
9021 EvalResult.HasSideEffects) {
9022 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9024 if (EvalResult.Diag) {
9025 // We only show the note if it's not the usual "invalid subexpression"
9026 // or if it's actually in a subexpression.
9027 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9028 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9029 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9032 return true;
9035 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9036 E->getSourceRange();
9038 if (EvalResult.Diag &&
9039 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9040 != Diagnostic::Ignored)
9041 Diag(EvalResult.DiagLoc, EvalResult.Diag);
9043 if (Result)
9044 *Result = EvalResult.Val.getInt();
9045 return false;
9048 void
9049 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
9050 ExprEvalContexts.push_back(
9051 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
9054 void
9055 Sema::PopExpressionEvaluationContext() {
9056 // Pop the current expression evaluation context off the stack.
9057 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9058 ExprEvalContexts.pop_back();
9060 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9061 if (Rec.PotentiallyReferenced) {
9062 // Mark any remaining declarations in the current position of the stack
9063 // as "referenced". If they were not meant to be referenced, semantic
9064 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
9065 for (PotentiallyReferencedDecls::iterator
9066 I = Rec.PotentiallyReferenced->begin(),
9067 IEnd = Rec.PotentiallyReferenced->end();
9068 I != IEnd; ++I)
9069 MarkDeclarationReferenced(I->first, I->second);
9072 if (Rec.PotentiallyDiagnosed) {
9073 // Emit any pending diagnostics.
9074 for (PotentiallyEmittedDiagnostics::iterator
9075 I = Rec.PotentiallyDiagnosed->begin(),
9076 IEnd = Rec.PotentiallyDiagnosed->end();
9077 I != IEnd; ++I)
9078 Diag(I->first, I->second);
9082 // When are coming out of an unevaluated context, clear out any
9083 // temporaries that we may have created as part of the evaluation of
9084 // the expression in that context: they aren't relevant because they
9085 // will never be constructed.
9086 if (Rec.Context == Unevaluated &&
9087 ExprTemporaries.size() > Rec.NumTemporaries)
9088 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9089 ExprTemporaries.end());
9091 // Destroy the popped expression evaluation record.
9092 Rec.Destroy();
9095 /// \brief Note that the given declaration was referenced in the source code.
9097 /// This routine should be invoke whenever a given declaration is referenced
9098 /// in the source code, and where that reference occurred. If this declaration
9099 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9100 /// C99 6.9p3), then the declaration will be marked as used.
9102 /// \param Loc the location where the declaration was referenced.
9104 /// \param D the declaration that has been referenced by the source code.
9105 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9106 assert(D && "No declaration?");
9108 if (D->isUsed(false))
9109 return;
9111 // Mark a parameter or variable declaration "used", regardless of whether we're in a
9112 // template or not. The reason for this is that unevaluated expressions
9113 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
9114 // -Wunused-parameters)
9115 if (isa<ParmVarDecl>(D) ||
9116 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
9117 D->setUsed();
9118 return;
9121 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9122 return;
9124 // Do not mark anything as "used" within a dependent context; wait for
9125 // an instantiation.
9126 if (CurContext->isDependentContext())
9127 return;
9129 switch (ExprEvalContexts.back().Context) {
9130 case Unevaluated:
9131 // We are in an expression that is not potentially evaluated; do nothing.
9132 return;
9134 case PotentiallyEvaluated:
9135 // We are in a potentially-evaluated expression, so this declaration is
9136 // "used"; handle this below.
9137 break;
9139 case PotentiallyPotentiallyEvaluated:
9140 // We are in an expression that may be potentially evaluated; queue this
9141 // declaration reference until we know whether the expression is
9142 // potentially evaluated.
9143 ExprEvalContexts.back().addReferencedDecl(Loc, D);
9144 return;
9146 case PotentiallyEvaluatedIfUsed:
9147 // Referenced declarations will only be used if the construct in the
9148 // containing expression is used.
9149 return;
9152 // Note that this declaration has been used.
9153 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
9154 unsigned TypeQuals;
9155 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
9156 if (Constructor->getParent()->hasTrivialConstructor())
9157 return;
9158 if (!Constructor->isUsed(false))
9159 DefineImplicitDefaultConstructor(Loc, Constructor);
9160 } else if (Constructor->isImplicit() &&
9161 Constructor->isCopyConstructor(TypeQuals)) {
9162 if (!Constructor->isUsed(false))
9163 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
9166 MarkVTableUsed(Loc, Constructor->getParent());
9167 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
9168 if (Destructor->isImplicit() && !Destructor->isUsed(false))
9169 DefineImplicitDestructor(Loc, Destructor);
9170 if (Destructor->isVirtual())
9171 MarkVTableUsed(Loc, Destructor->getParent());
9172 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9173 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
9174 MethodDecl->getOverloadedOperator() == OO_Equal) {
9175 if (!MethodDecl->isUsed(false))
9176 DefineImplicitCopyAssignment(Loc, MethodDecl);
9177 } else if (MethodDecl->isVirtual())
9178 MarkVTableUsed(Loc, MethodDecl->getParent());
9180 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
9181 // Implicit instantiation of function templates and member functions of
9182 // class templates.
9183 if (Function->isImplicitlyInstantiable()) {
9184 bool AlreadyInstantiated = false;
9185 if (FunctionTemplateSpecializationInfo *SpecInfo
9186 = Function->getTemplateSpecializationInfo()) {
9187 if (SpecInfo->getPointOfInstantiation().isInvalid())
9188 SpecInfo->setPointOfInstantiation(Loc);
9189 else if (SpecInfo->getTemplateSpecializationKind()
9190 == TSK_ImplicitInstantiation)
9191 AlreadyInstantiated = true;
9192 } else if (MemberSpecializationInfo *MSInfo
9193 = Function->getMemberSpecializationInfo()) {
9194 if (MSInfo->getPointOfInstantiation().isInvalid())
9195 MSInfo->setPointOfInstantiation(Loc);
9196 else if (MSInfo->getTemplateSpecializationKind()
9197 == TSK_ImplicitInstantiation)
9198 AlreadyInstantiated = true;
9201 if (!AlreadyInstantiated) {
9202 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9203 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9204 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9205 Loc));
9206 else
9207 PendingInstantiations.push_back(std::make_pair(Function, Loc));
9209 } else // Walk redefinitions, as some of them may be instantiable.
9210 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9211 e(Function->redecls_end()); i != e; ++i) {
9212 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9213 MarkDeclarationReferenced(Loc, *i);
9216 // FIXME: keep track of references to static functions
9218 // Recursive functions should be marked when used from another function.
9219 if (CurContext != Function)
9220 Function->setUsed(true);
9222 return;
9225 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
9226 // Implicit instantiation of static data members of class templates.
9227 if (Var->isStaticDataMember() &&
9228 Var->getInstantiatedFromStaticDataMember()) {
9229 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9230 assert(MSInfo && "Missing member specialization information?");
9231 if (MSInfo->getPointOfInstantiation().isInvalid() &&
9232 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9233 MSInfo->setPointOfInstantiation(Loc);
9234 PendingInstantiations.push_back(std::make_pair(Var, Loc));
9238 // FIXME: keep track of references to static data?
9240 D->setUsed(true);
9241 return;
9245 namespace {
9246 // Mark all of the declarations referenced
9247 // FIXME: Not fully implemented yet! We need to have a better understanding
9248 // of when we're entering
9249 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9250 Sema &S;
9251 SourceLocation Loc;
9253 public:
9254 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
9256 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
9258 bool TraverseTemplateArgument(const TemplateArgument &Arg);
9259 bool TraverseRecordType(RecordType *T);
9263 bool MarkReferencedDecls::TraverseTemplateArgument(
9264 const TemplateArgument &Arg) {
9265 if (Arg.getKind() == TemplateArgument::Declaration) {
9266 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9269 return Inherited::TraverseTemplateArgument(Arg);
9272 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
9273 if (ClassTemplateSpecializationDecl *Spec
9274 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9275 const TemplateArgumentList &Args = Spec->getTemplateArgs();
9276 return TraverseTemplateArguments(Args.data(), Args.size());
9279 return true;
9282 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9283 MarkReferencedDecls Marker(*this, Loc);
9284 Marker.TraverseType(Context.getCanonicalType(T));
9287 namespace {
9288 /// \brief Helper class that marks all of the declarations referenced by
9289 /// potentially-evaluated subexpressions as "referenced".
9290 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9291 Sema &S;
9293 public:
9294 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9296 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9298 void VisitDeclRefExpr(DeclRefExpr *E) {
9299 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9302 void VisitMemberExpr(MemberExpr *E) {
9303 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
9304 Inherited::VisitMemberExpr(E);
9307 void VisitCXXNewExpr(CXXNewExpr *E) {
9308 if (E->getConstructor())
9309 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9310 if (E->getOperatorNew())
9311 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9312 if (E->getOperatorDelete())
9313 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9314 Inherited::VisitCXXNewExpr(E);
9317 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9318 if (E->getOperatorDelete())
9319 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9320 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9321 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9322 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9323 S.MarkDeclarationReferenced(E->getLocStart(),
9324 S.LookupDestructor(Record));
9327 Inherited::VisitCXXDeleteExpr(E);
9330 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9331 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9332 Inherited::VisitCXXConstructExpr(E);
9335 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9336 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9339 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9340 Visit(E->getExpr());
9345 /// \brief Mark any declarations that appear within this expression or any
9346 /// potentially-evaluated subexpressions as "referenced".
9347 void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9348 EvaluatedExprMarker(*this).Visit(E);
9351 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
9352 /// of the program being compiled.
9354 /// This routine emits the given diagnostic when the code currently being
9355 /// type-checked is "potentially evaluated", meaning that there is a
9356 /// possibility that the code will actually be executable. Code in sizeof()
9357 /// expressions, code used only during overload resolution, etc., are not
9358 /// potentially evaluated. This routine will suppress such diagnostics or,
9359 /// in the absolutely nutty case of potentially potentially evaluated
9360 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
9361 /// later.
9363 /// This routine should be used for all diagnostics that describe the run-time
9364 /// behavior of a program, such as passing a non-POD value through an ellipsis.
9365 /// Failure to do so will likely result in spurious diagnostics or failures
9366 /// during overload resolution or within sizeof/alignof/typeof/typeid.
9367 bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
9368 const PartialDiagnostic &PD) {
9369 switch (ExprEvalContexts.back().Context ) {
9370 case Unevaluated:
9371 // The argument will never be evaluated, so don't complain.
9372 break;
9374 case PotentiallyEvaluated:
9375 case PotentiallyEvaluatedIfUsed:
9376 Diag(Loc, PD);
9377 return true;
9379 case PotentiallyPotentiallyEvaluated:
9380 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9381 break;
9384 return false;
9387 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9388 CallExpr *CE, FunctionDecl *FD) {
9389 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9390 return false;
9392 PartialDiagnostic Note =
9393 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9394 << FD->getDeclName() : PDiag();
9395 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
9397 if (RequireCompleteType(Loc, ReturnType,
9398 FD ?
9399 PDiag(diag::err_call_function_incomplete_return)
9400 << CE->getSourceRange() << FD->getDeclName() :
9401 PDiag(diag::err_call_incomplete_return)
9402 << CE->getSourceRange(),
9403 std::make_pair(NoteLoc, Note)))
9404 return true;
9406 return false;
9409 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
9410 // will prevent this condition from triggering, which is what we want.
9411 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9412 SourceLocation Loc;
9414 unsigned diagnostic = diag::warn_condition_is_assignment;
9415 bool IsOrAssign = false;
9417 if (isa<BinaryOperator>(E)) {
9418 BinaryOperator *Op = cast<BinaryOperator>(E);
9419 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
9420 return;
9422 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9424 // Greylist some idioms by putting them into a warning subcategory.
9425 if (ObjCMessageExpr *ME
9426 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9427 Selector Sel = ME->getSelector();
9429 // self = [<foo> init...]
9430 if (isSelfExpr(Op->getLHS())
9431 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9432 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9434 // <foo> = [<bar> nextObject]
9435 else if (Sel.isUnarySelector() &&
9436 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9437 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9440 Loc = Op->getOperatorLoc();
9441 } else if (isa<CXXOperatorCallExpr>(E)) {
9442 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
9443 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
9444 return;
9446 IsOrAssign = Op->getOperator() == OO_PipeEqual;
9447 Loc = Op->getOperatorLoc();
9448 } else {
9449 // Not an assignment.
9450 return;
9453 SourceLocation Open = E->getSourceRange().getBegin();
9454 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9456 Diag(Loc, diagnostic) << E->getSourceRange();
9458 if (IsOrAssign)
9459 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9460 << FixItHint::CreateReplacement(Loc, "!=");
9461 else
9462 Diag(Loc, diag::note_condition_assign_to_comparison)
9463 << FixItHint::CreateReplacement(Loc, "==");
9465 Diag(Loc, diag::note_condition_assign_silence)
9466 << FixItHint::CreateInsertion(Open, "(")
9467 << FixItHint::CreateInsertion(Close, ")");
9470 /// \brief Redundant parentheses over an equality comparison can indicate
9471 /// that the user intended an assignment used as condition.
9472 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *parenE) {
9473 // Don't warn if the parens came from a macro.
9474 SourceLocation parenLoc = parenE->getLocStart();
9475 if (parenLoc.isInvalid() || parenLoc.isMacroID())
9476 return;
9478 Expr *E = parenE->IgnoreParens();
9480 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
9481 if (opE->getOpcode() == BO_EQ &&
9482 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9483 == Expr::MLV_Valid) {
9484 SourceLocation Loc = opE->getOperatorLoc();
9486 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9487 Diag(Loc, diag::note_equality_comparison_to_assign)
9488 << FixItHint::CreateReplacement(Loc, "=");
9489 Diag(Loc, diag::note_equality_comparison_silence)
9490 << FixItHint::CreateRemoval(parenE->getSourceRange().getBegin())
9491 << FixItHint::CreateRemoval(parenE->getSourceRange().getEnd());
9495 bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9496 DiagnoseAssignmentAsCondition(E);
9497 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9498 DiagnoseEqualityWithExtraParens(parenE);
9500 if (!E->isTypeDependent()) {
9501 if (E->isBoundMemberFunction(Context))
9502 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9503 << E->getSourceRange();
9505 if (getLangOptions().CPlusPlus)
9506 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9508 DefaultFunctionArrayLvalueConversion(E);
9510 QualType T = E->getType();
9511 if (!T->isScalarType()) // C99 6.8.4.1p1
9512 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9513 << T << E->getSourceRange();
9516 return false;
9519 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9520 Expr *Sub) {
9521 if (!Sub)
9522 return ExprError();
9524 if (CheckBooleanCondition(Sub, Loc))
9525 return ExprError();
9527 return Owned(Sub);
9530 /// Check for operands with placeholder types and complain if found.
9531 /// Returns true if there was an error and no recovery was possible.
9532 ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9533 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9534 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9536 // If this is overload, check for a single overload.
9537 if (BT->getKind() == BuiltinType::Overload) {
9538 if (FunctionDecl *Specialization
9539 = ResolveSingleFunctionTemplateSpecialization(E)) {
9540 // The access doesn't really matter in this case.
9541 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9542 Specialization->getAccess());
9543 E = FixOverloadedFunctionReference(E, Found, Specialization);
9544 if (!E) return ExprError();
9545 return Owned(E);
9548 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
9549 return ExprError();
9552 // Otherwise it's a use of undeduced auto.
9553 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9555 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9556 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9557 << DRE->getDecl() << E->getSourceRange();
9558 return ExprError();