Make Check*PointerTypesForAssignment private and tell them that they're
[clang.git] / lib / Sema / SemaExpr.cpp
blob0cad12c0823b671ed61387a6cb8324be08fe8c7e
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 /// ShouldSnapshotBlockValueReference - Return true if a reference inside of
737 /// CurBlock to VD should cause it to be snapshotted (as we do for auto
738 /// variables defined outside the block) or false if this is not needed (e.g.
739 /// for values inside the block or for globals).
741 /// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
742 /// up-to-date.
744 static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
745 ValueDecl *VD) {
746 // If the value is defined inside the block, we couldn't snapshot it even if
747 // we wanted to.
748 if (CurBlock->TheDecl == VD->getDeclContext())
749 return false;
751 // If this is an enum constant or function, it is constant, don't snapshot.
752 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
753 return false;
755 // If this is a reference to an extern, static, or global variable, no need to
756 // snapshot it.
757 // FIXME: What about 'const' variables in C++?
758 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
759 if (!Var->hasLocalStorage())
760 return false;
762 // Blocks that have these can't be constant.
763 CurBlock->hasBlockDeclRefExprs = true;
765 // If we have nested blocks, the decl may be declared in an outer block (in
766 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
767 // be defined outside all of the current blocks (in which case the blocks do
768 // all get the bit). Walk the nesting chain.
769 for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
770 BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
772 if (!NextBlock)
773 continue;
775 // If we found the defining block for the variable, don't mark the block as
776 // having a reference outside it.
777 if (NextBlock->TheDecl == VD->getDeclContext())
778 break;
780 // Otherwise, the DeclRef from the inner block causes the outer one to need
781 // a snapshot as well.
782 NextBlock->hasBlockDeclRefExprs = true;
785 return true;
789 ExprResult
790 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
791 SourceLocation Loc, const CXXScopeSpec *SS) {
792 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
793 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
796 /// BuildDeclRefExpr - Build a DeclRefExpr.
797 ExprResult
798 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty,
799 ExprValueKind VK,
800 const DeclarationNameInfo &NameInfo,
801 const CXXScopeSpec *SS) {
802 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
803 Diag(NameInfo.getLoc(),
804 diag::err_auto_variable_cannot_appear_in_own_initializer)
805 << D->getDeclName();
806 return ExprError();
809 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
810 if (isa<NonTypeTemplateParmDecl>(VD)) {
811 // Non-type template parameters can be referenced anywhere they are
812 // visible.
813 Ty = Ty.getNonLValueExprType(Context);
814 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
815 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
816 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
817 Diag(NameInfo.getLoc(),
818 diag::err_reference_to_local_var_in_enclosing_function)
819 << D->getIdentifier() << FD->getDeclName();
820 Diag(D->getLocation(), diag::note_local_variable_declared_here)
821 << D->getIdentifier();
822 return ExprError();
826 // This ridiculousness brought to you by 'extern void x;' and the
827 // GNU compiler collection.
828 } else if (!getLangOptions().CPlusPlus && !Ty.hasQualifiers() &&
829 Ty->isVoidType()) {
830 VK = VK_RValue;
834 MarkDeclarationReferenced(NameInfo.getLoc(), D);
836 Expr *E = DeclRefExpr::Create(Context,
837 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
838 SS? SS->getRange() : SourceRange(),
839 D, NameInfo, Ty, VK);
841 // Just in case we're building an illegal pointer-to-member.
842 if (isa<FieldDecl>(D) && cast<FieldDecl>(D)->getBitWidth())
843 E->setObjectKind(OK_BitField);
845 return Owned(E);
848 static ExprResult
849 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
850 const CXXScopeSpec &SS, FieldDecl *Field,
851 DeclAccessPair FoundDecl,
852 const DeclarationNameInfo &MemberNameInfo);
854 ExprResult
855 Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
856 const CXXScopeSpec &SS,
857 IndirectFieldDecl *IndirectField,
858 Expr *BaseObjectExpr,
859 SourceLocation OpLoc) {
860 // Build the expression that refers to the base object, from
861 // which we will build a sequence of member references to each
862 // of the anonymous union objects and, eventually, the field we
863 // found via name lookup.
864 bool BaseObjectIsPointer = false;
865 Qualifiers BaseQuals;
866 VarDecl *BaseObject = IndirectField->getVarDecl();
867 if (BaseObject) {
868 // BaseObject is an anonymous struct/union variable (and is,
869 // therefore, not part of another non-anonymous record).
870 MarkDeclarationReferenced(Loc, BaseObject);
871 BaseObjectExpr =
872 new (Context) DeclRefExpr(BaseObject, BaseObject->getType(),
873 VK_LValue, Loc);
874 BaseQuals
875 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
876 } else if (BaseObjectExpr) {
877 // The caller provided the base object expression. Determine
878 // whether its a pointer and whether it adds any qualifiers to the
879 // anonymous struct/union fields we're looking into.
880 QualType ObjectType = BaseObjectExpr->getType();
881 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
882 BaseObjectIsPointer = true;
883 ObjectType = ObjectPtr->getPointeeType();
885 BaseQuals
886 = Context.getCanonicalType(ObjectType).getQualifiers();
887 } else {
888 // We've found a member of an anonymous struct/union that is
889 // inside a non-anonymous struct/union, so in a well-formed
890 // program our base object expression is "this".
891 DeclContext *DC = getFunctionLevelDeclContext();
892 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
893 if (!MD->isStatic()) {
894 QualType AnonFieldType
895 = Context.getTagDeclType(
896 cast<RecordDecl>(
897 (*IndirectField->chain_begin())->getDeclContext()));
898 QualType ThisType = Context.getTagDeclType(MD->getParent());
899 if ((Context.getCanonicalType(AnonFieldType)
900 == Context.getCanonicalType(ThisType)) ||
901 IsDerivedFrom(ThisType, AnonFieldType)) {
902 // Our base object expression is "this".
903 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
904 MD->getThisType(Context),
905 /*isImplicit=*/true);
906 BaseObjectIsPointer = true;
908 } else {
909 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
910 << IndirectField->getDeclName());
912 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
915 if (!BaseObjectExpr) {
916 // The field is referenced for a pointer-to-member expression, e.g:
918 // struct S {
919 // union {
920 // char c;
921 // };
922 // };
923 // char S::*foo = &S::c;
925 FieldDecl *field = IndirectField->getAnonField();
926 DeclarationNameInfo NameInfo(field->getDeclName(), Loc);
927 return BuildDeclRefExpr(field, field->getType().getNonReferenceType(),
928 VK_LValue, NameInfo, &SS);
932 // Build the implicit member references to the field of the
933 // anonymous struct/union.
934 Expr *Result = BaseObjectExpr;
936 IndirectFieldDecl::chain_iterator FI = IndirectField->chain_begin(),
937 FEnd = IndirectField->chain_end();
939 // Skip the first VarDecl if present.
940 if (BaseObject)
941 FI++;
942 for (; FI != FEnd; FI++) {
943 FieldDecl *Field = cast<FieldDecl>(*FI);
945 // FIXME: these are somewhat meaningless
946 DeclarationNameInfo MemberNameInfo(Field->getDeclName(), Loc);
947 DeclAccessPair FoundDecl = DeclAccessPair::make(Field, Field->getAccess());
949 Result = BuildFieldReferenceExpr(*this, Result, BaseObjectIsPointer,
950 SS, Field, FoundDecl, MemberNameInfo)
951 .take();
953 // All the implicit accesses are dot-accesses.
954 BaseObjectIsPointer = false;
957 return Owned(Result);
960 /// Decomposes the given name into a DeclarationNameInfo, its location, and
961 /// possibly a list of template arguments.
963 /// If this produces template arguments, it is permitted to call
964 /// DecomposeTemplateName.
966 /// This actually loses a lot of source location information for
967 /// non-standard name kinds; we should consider preserving that in
968 /// some way.
969 static void DecomposeUnqualifiedId(Sema &SemaRef,
970 const UnqualifiedId &Id,
971 TemplateArgumentListInfo &Buffer,
972 DeclarationNameInfo &NameInfo,
973 const TemplateArgumentListInfo *&TemplateArgs) {
974 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
975 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
976 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
978 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
979 Id.TemplateId->getTemplateArgs(),
980 Id.TemplateId->NumArgs);
981 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
982 TemplateArgsPtr.release();
984 TemplateName TName = Id.TemplateId->Template.get();
985 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
986 NameInfo = SemaRef.Context.getNameForTemplate(TName, TNameLoc);
987 TemplateArgs = &Buffer;
988 } else {
989 NameInfo = SemaRef.GetNameFromUnqualifiedId(Id);
990 TemplateArgs = 0;
994 /// Determines whether the given record is "fully-formed" at the given
995 /// location, i.e. whether a qualified lookup into it is assured of
996 /// getting consistent results already.
997 static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
998 if (!Record->hasDefinition())
999 return false;
1001 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1002 E = Record->bases_end(); I != E; ++I) {
1003 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1004 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1005 if (!BaseRT) return false;
1007 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
1008 if (!BaseRecord->hasDefinition() ||
1009 !IsFullyFormedScope(SemaRef, BaseRecord))
1010 return false;
1013 return true;
1016 /// Determines if the given class is provably not derived from all of
1017 /// the prospective base classes.
1018 static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
1019 CXXRecordDecl *Record,
1020 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
1021 if (Bases.count(Record->getCanonicalDecl()))
1022 return false;
1024 RecordDecl *RD = Record->getDefinition();
1025 if (!RD) return false;
1026 Record = cast<CXXRecordDecl>(RD);
1028 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
1029 E = Record->bases_end(); I != E; ++I) {
1030 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
1031 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
1032 if (!BaseRT) return false;
1034 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
1035 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
1036 return false;
1039 return true;
1042 enum IMAKind {
1043 /// The reference is definitely not an instance member access.
1044 IMA_Static,
1046 /// The reference may be an implicit instance member access.
1047 IMA_Mixed,
1049 /// The reference may be to an instance member, but it is invalid if
1050 /// so, because the context is not an instance method.
1051 IMA_Mixed_StaticContext,
1053 /// The reference may be to an instance member, but it is invalid if
1054 /// so, because the context is from an unrelated class.
1055 IMA_Mixed_Unrelated,
1057 /// The reference is definitely an implicit instance member access.
1058 IMA_Instance,
1060 /// The reference may be to an unresolved using declaration.
1061 IMA_Unresolved,
1063 /// The reference may be to an unresolved using declaration and the
1064 /// context is not an instance method.
1065 IMA_Unresolved_StaticContext,
1067 /// All possible referrents are instance members and the current
1068 /// context is not an instance method.
1069 IMA_Error_StaticContext,
1071 /// All possible referrents are instance members of an unrelated
1072 /// class.
1073 IMA_Error_Unrelated
1076 /// The given lookup names class member(s) and is not being used for
1077 /// an address-of-member expression. Classify the type of access
1078 /// according to whether it's possible that this reference names an
1079 /// instance member. This is best-effort; it is okay to
1080 /// conservatively answer "yes", in which case some errors will simply
1081 /// not be caught until template-instantiation.
1082 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
1083 const LookupResult &R) {
1084 assert(!R.empty() && (*R.begin())->isCXXClassMember());
1086 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
1087 bool isStaticContext =
1088 (!isa<CXXMethodDecl>(DC) ||
1089 cast<CXXMethodDecl>(DC)->isStatic());
1091 if (R.isUnresolvableResult())
1092 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
1094 // Collect all the declaring classes of instance members we find.
1095 bool hasNonInstance = false;
1096 bool hasField = false;
1097 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
1098 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1099 NamedDecl *D = *I;
1101 if (D->isCXXInstanceMember()) {
1102 if (dyn_cast<FieldDecl>(D))
1103 hasField = true;
1105 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
1106 Classes.insert(R->getCanonicalDecl());
1108 else
1109 hasNonInstance = true;
1112 // If we didn't find any instance members, it can't be an implicit
1113 // member reference.
1114 if (Classes.empty())
1115 return IMA_Static;
1117 // If the current context is not an instance method, it can't be
1118 // an implicit member reference.
1119 if (isStaticContext) {
1120 if (hasNonInstance)
1121 return IMA_Mixed_StaticContext;
1123 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
1124 // C++0x [expr.prim.general]p10:
1125 // An id-expression that denotes a non-static data member or non-static
1126 // member function of a class can only be used:
1127 // (...)
1128 // - if that id-expression denotes a non-static data member and it appears in an unevaluated operand.
1129 const Sema::ExpressionEvaluationContextRecord& record = SemaRef.ExprEvalContexts.back();
1130 bool isUnevaluatedExpression = record.Context == Sema::Unevaluated;
1131 if (isUnevaluatedExpression)
1132 return IMA_Mixed_StaticContext;
1135 return IMA_Error_StaticContext;
1138 // If we can prove that the current context is unrelated to all the
1139 // declaring classes, it can't be an implicit member reference (in
1140 // which case it's an error if any of those members are selected).
1141 if (IsProvablyNotDerivedFrom(SemaRef,
1142 cast<CXXMethodDecl>(DC)->getParent(),
1143 Classes))
1144 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
1146 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
1149 /// Diagnose a reference to a field with no object available.
1150 static void DiagnoseInstanceReference(Sema &SemaRef,
1151 const CXXScopeSpec &SS,
1152 const LookupResult &R) {
1153 SourceLocation Loc = R.getNameLoc();
1154 SourceRange Range(Loc);
1155 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
1157 if (R.getAsSingle<FieldDecl>() || R.getAsSingle<IndirectFieldDecl>()) {
1158 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
1159 if (MD->isStatic()) {
1160 // "invalid use of member 'x' in static member function"
1161 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
1162 << Range << R.getLookupName();
1163 return;
1167 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
1168 << R.getLookupName() << Range;
1169 return;
1172 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
1175 /// Diagnose an empty lookup.
1177 /// \return false if new lookup candidates were found
1178 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1179 CorrectTypoContext CTC) {
1180 DeclarationName Name = R.getLookupName();
1182 unsigned diagnostic = diag::err_undeclared_var_use;
1183 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1184 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1185 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1186 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1187 diagnostic = diag::err_undeclared_use;
1188 diagnostic_suggest = diag::err_undeclared_use_suggest;
1191 // If the original lookup was an unqualified lookup, fake an
1192 // unqualified lookup. This is useful when (for example) the
1193 // original lookup would not have found something because it was a
1194 // dependent name.
1195 for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1196 DC; DC = DC->getParent()) {
1197 if (isa<CXXRecordDecl>(DC)) {
1198 LookupQualifiedName(R, DC);
1200 if (!R.empty()) {
1201 // Don't give errors about ambiguities in this lookup.
1202 R.suppressDiagnostics();
1204 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1205 bool isInstance = CurMethod &&
1206 CurMethod->isInstance() &&
1207 DC == CurMethod->getParent();
1209 // Give a code modification hint to insert 'this->'.
1210 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1211 // Actually quite difficult!
1212 if (isInstance) {
1213 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1214 CallsUndergoingInstantiation.back()->getCallee());
1215 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
1216 CurMethod->getInstantiatedFromMemberFunction());
1217 if (DepMethod) {
1218 Diag(R.getNameLoc(), diagnostic) << Name
1219 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1220 QualType DepThisType = DepMethod->getThisType(Context);
1221 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1222 R.getNameLoc(), DepThisType, false);
1223 TemplateArgumentListInfo TList;
1224 if (ULE->hasExplicitTemplateArgs())
1225 ULE->copyTemplateArgumentsInto(TList);
1226 CXXDependentScopeMemberExpr *DepExpr =
1227 CXXDependentScopeMemberExpr::Create(
1228 Context, DepThis, DepThisType, true, SourceLocation(),
1229 ULE->getQualifier(), ULE->getQualifierRange(), NULL,
1230 R.getLookupNameInfo(), &TList);
1231 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1232 } else {
1233 // FIXME: we should be able to handle this case too. It is correct
1234 // to add this-> here. This is a workaround for PR7947.
1235 Diag(R.getNameLoc(), diagnostic) << Name;
1237 } else {
1238 Diag(R.getNameLoc(), diagnostic) << Name;
1241 // Do we really want to note all of these?
1242 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1243 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1245 // Tell the callee to try to recover.
1246 return false;
1249 R.clear();
1253 // We didn't find anything, so try to correct for a typo.
1254 DeclarationName Corrected;
1255 if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
1256 if (!R.empty()) {
1257 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
1258 if (SS.isEmpty())
1259 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
1260 << FixItHint::CreateReplacement(R.getNameLoc(),
1261 R.getLookupName().getAsString());
1262 else
1263 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1264 << Name << computeDeclContext(SS, false) << R.getLookupName()
1265 << SS.getRange()
1266 << FixItHint::CreateReplacement(R.getNameLoc(),
1267 R.getLookupName().getAsString());
1268 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
1269 Diag(ND->getLocation(), diag::note_previous_decl)
1270 << ND->getDeclName();
1272 // Tell the callee to try to recover.
1273 return false;
1276 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
1277 // FIXME: If we ended up with a typo for a type name or
1278 // Objective-C class name, we're in trouble because the parser
1279 // is in the wrong place to recover. Suggest the typo
1280 // correction, but don't make it a fix-it since we're not going
1281 // to recover well anyway.
1282 if (SS.isEmpty())
1283 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
1284 else
1285 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1286 << Name << computeDeclContext(SS, false) << R.getLookupName()
1287 << SS.getRange();
1289 // Don't try to recover; it won't work.
1290 return true;
1292 } else {
1293 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1294 // because we aren't able to recover.
1295 if (SS.isEmpty())
1296 Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
1297 else
1298 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1299 << Name << computeDeclContext(SS, false) << Corrected
1300 << SS.getRange();
1301 return true;
1303 R.clear();
1306 // Emit a special diagnostic for failed member lookups.
1307 // FIXME: computing the declaration context might fail here (?)
1308 if (!SS.isEmpty()) {
1309 Diag(R.getNameLoc(), diag::err_no_member)
1310 << Name << computeDeclContext(SS, false)
1311 << SS.getRange();
1312 return true;
1315 // Give up, we can't recover.
1316 Diag(R.getNameLoc(), diagnostic) << Name;
1317 return true;
1320 ObjCPropertyDecl *Sema::canSynthesizeProvisionalIvar(IdentifierInfo *II) {
1321 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1322 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1323 if (!IDecl)
1324 return 0;
1325 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1326 if (!ClassImpDecl)
1327 return 0;
1328 ObjCPropertyDecl *property = LookupPropertyDecl(IDecl, II);
1329 if (!property)
1330 return 0;
1331 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II))
1332 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1333 PIDecl->getPropertyIvarDecl())
1334 return 0;
1335 return property;
1338 bool Sema::canSynthesizeProvisionalIvar(ObjCPropertyDecl *Property) {
1339 ObjCMethodDecl *CurMeth = getCurMethodDecl();
1340 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1341 if (!IDecl)
1342 return false;
1343 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1344 if (!ClassImpDecl)
1345 return false;
1346 if (ObjCPropertyImplDecl *PIDecl
1347 = ClassImpDecl->FindPropertyImplDecl(Property->getIdentifier()))
1348 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic ||
1349 PIDecl->getPropertyIvarDecl())
1350 return false;
1352 return true;
1355 static ObjCIvarDecl *SynthesizeProvisionalIvar(Sema &SemaRef,
1356 LookupResult &Lookup,
1357 IdentifierInfo *II,
1358 SourceLocation NameLoc) {
1359 ObjCMethodDecl *CurMeth = SemaRef.getCurMethodDecl();
1360 bool LookForIvars;
1361 if (Lookup.empty())
1362 LookForIvars = true;
1363 else if (CurMeth->isClassMethod())
1364 LookForIvars = false;
1365 else
1366 LookForIvars = (Lookup.isSingleResult() &&
1367 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod() &&
1368 (Lookup.getAsSingle<VarDecl>() != 0));
1369 if (!LookForIvars)
1370 return 0;
1372 ObjCInterfaceDecl *IDecl = CurMeth->getClassInterface();
1373 if (!IDecl)
1374 return 0;
1375 ObjCImplementationDecl *ClassImpDecl = IDecl->getImplementation();
1376 if (!ClassImpDecl)
1377 return 0;
1378 bool DynamicImplSeen = false;
1379 ObjCPropertyDecl *property = SemaRef.LookupPropertyDecl(IDecl, II);
1380 if (!property)
1381 return 0;
1382 if (ObjCPropertyImplDecl *PIDecl = ClassImpDecl->FindPropertyImplDecl(II)) {
1383 DynamicImplSeen =
1384 (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
1385 // property implementation has a designated ivar. No need to assume a new
1386 // one.
1387 if (!DynamicImplSeen && PIDecl->getPropertyIvarDecl())
1388 return 0;
1390 if (!DynamicImplSeen) {
1391 QualType PropType = SemaRef.Context.getCanonicalType(property->getType());
1392 ObjCIvarDecl *Ivar = ObjCIvarDecl::Create(SemaRef.Context, ClassImpDecl,
1393 NameLoc,
1394 II, PropType, /*Dinfo=*/0,
1395 ObjCIvarDecl::Private,
1396 (Expr *)0, true);
1397 ClassImpDecl->addDecl(Ivar);
1398 IDecl->makeDeclVisibleInContext(Ivar, false);
1399 property->setPropertyIvarDecl(Ivar);
1400 return Ivar;
1402 return 0;
1405 ExprResult Sema::ActOnIdExpression(Scope *S,
1406 CXXScopeSpec &SS,
1407 UnqualifiedId &Id,
1408 bool HasTrailingLParen,
1409 bool isAddressOfOperand) {
1410 assert(!(isAddressOfOperand && HasTrailingLParen) &&
1411 "cannot be direct & operand and have a trailing lparen");
1413 if (SS.isInvalid())
1414 return ExprError();
1416 TemplateArgumentListInfo TemplateArgsBuffer;
1418 // Decompose the UnqualifiedId into the following data.
1419 DeclarationNameInfo NameInfo;
1420 const TemplateArgumentListInfo *TemplateArgs;
1421 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1423 DeclarationName Name = NameInfo.getName();
1424 IdentifierInfo *II = Name.getAsIdentifierInfo();
1425 SourceLocation NameLoc = NameInfo.getLoc();
1427 // C++ [temp.dep.expr]p3:
1428 // An id-expression is type-dependent if it contains:
1429 // -- an identifier that was declared with a dependent type,
1430 // (note: handled after lookup)
1431 // -- a template-id that is dependent,
1432 // (note: handled in BuildTemplateIdExpr)
1433 // -- a conversion-function-id that specifies a dependent type,
1434 // -- a nested-name-specifier that contains a class-name that
1435 // names a dependent type.
1436 // Determine whether this is a member of an unknown specialization;
1437 // we need to handle these differently.
1438 bool DependentID = false;
1439 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1440 Name.getCXXNameType()->isDependentType()) {
1441 DependentID = true;
1442 } else if (SS.isSet()) {
1443 DeclContext *DC = computeDeclContext(SS, false);
1444 if (DC) {
1445 if (RequireCompleteDeclContext(SS, DC))
1446 return ExprError();
1447 // FIXME: We should be checking whether DC is the current instantiation.
1448 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC))
1449 DependentID = !IsFullyFormedScope(*this, RD);
1450 } else {
1451 DependentID = true;
1455 if (DependentID) {
1456 return ActOnDependentIdExpression(SS, NameInfo, isAddressOfOperand,
1457 TemplateArgs);
1459 bool IvarLookupFollowUp = false;
1460 // Perform the required lookup.
1461 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1462 if (TemplateArgs) {
1463 // Lookup the template name again to correctly establish the context in
1464 // which it was found. This is really unfortunate as we already did the
1465 // lookup to determine that it was a template name in the first place. If
1466 // this becomes a performance hit, we can work harder to preserve those
1467 // results until we get here but it's likely not worth it.
1468 bool MemberOfUnknownSpecialization;
1469 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1470 MemberOfUnknownSpecialization);
1471 } else {
1472 IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1473 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1475 // If this reference is in an Objective-C method, then we need to do
1476 // some special Objective-C lookup, too.
1477 if (IvarLookupFollowUp) {
1478 ExprResult E(LookupInObjCMethod(R, S, II, true));
1479 if (E.isInvalid())
1480 return ExprError();
1482 Expr *Ex = E.takeAs<Expr>();
1483 if (Ex) return Owned(Ex);
1484 // Synthesize ivars lazily
1485 if (getLangOptions().ObjCDefaultSynthProperties &&
1486 getLangOptions().ObjCNonFragileABI2) {
1487 if (SynthesizeProvisionalIvar(*this, R, II, NameLoc)) {
1488 if (const ObjCPropertyDecl *Property =
1489 canSynthesizeProvisionalIvar(II)) {
1490 Diag(NameLoc, diag::warn_synthesized_ivar_access) << II;
1491 Diag(Property->getLocation(), diag::note_property_declare);
1493 return ActOnIdExpression(S, SS, Id, HasTrailingLParen,
1494 isAddressOfOperand);
1497 // for further use, this must be set to false if in class method.
1498 IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
1502 if (R.isAmbiguous())
1503 return ExprError();
1505 // Determine whether this name might be a candidate for
1506 // argument-dependent lookup.
1507 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1509 if (R.empty() && !ADL) {
1510 // Otherwise, this could be an implicitly declared function reference (legal
1511 // in C90, extension in C99, forbidden in C++).
1512 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1513 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1514 if (D) R.addDecl(D);
1517 // If this name wasn't predeclared and if this is not a function
1518 // call, diagnose the problem.
1519 if (R.empty()) {
1520 if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1521 return ExprError();
1523 assert(!R.empty() &&
1524 "DiagnoseEmptyLookup returned false but added no results");
1526 // If we found an Objective-C instance variable, let
1527 // LookupInObjCMethod build the appropriate expression to
1528 // reference the ivar.
1529 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1530 R.clear();
1531 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1532 assert(E.isInvalid() || E.get());
1533 return move(E);
1538 // This is guaranteed from this point on.
1539 assert(!R.empty() || ADL);
1541 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
1542 if (getLangOptions().ObjCNonFragileABI && IvarLookupFollowUp &&
1543 !(getLangOptions().ObjCDefaultSynthProperties &&
1544 getLangOptions().ObjCNonFragileABI2) &&
1545 Var->isFileVarDecl()) {
1546 ObjCPropertyDecl *Property = canSynthesizeProvisionalIvar(II);
1547 if (Property) {
1548 Diag(NameLoc, diag::warn_ivar_variable_conflict) << Var->getDeclName();
1549 Diag(Property->getLocation(), diag::note_property_declare);
1550 Diag(Var->getLocation(), diag::note_global_declared_at);
1553 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
1554 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1555 // C99 DR 316 says that, if a function type comes from a
1556 // function definition (without a prototype), that type is only
1557 // used for checking compatibility. Therefore, when referencing
1558 // the function, we pretend that we don't have the full function
1559 // type.
1560 if (DiagnoseUseOfDecl(Func, NameLoc))
1561 return ExprError();
1563 QualType T = Func->getType();
1564 QualType NoProtoType = T;
1565 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
1566 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1567 Proto->getExtInfo());
1568 // Note that functions are r-values in C.
1569 return BuildDeclRefExpr(Func, NoProtoType, VK_RValue, NameLoc, &SS);
1573 // Check whether this might be a C++ implicit instance member access.
1574 // C++ [class.mfct.non-static]p3:
1575 // When an id-expression that is not part of a class member access
1576 // syntax and not used to form a pointer to member is used in the
1577 // body of a non-static member function of class X, if name lookup
1578 // resolves the name in the id-expression to a non-static non-type
1579 // member of some class C, the id-expression is transformed into a
1580 // class member access expression using (*this) as the
1581 // postfix-expression to the left of the . operator.
1583 // But we don't actually need to do this for '&' operands if R
1584 // resolved to a function or overloaded function set, because the
1585 // expression is ill-formed if it actually works out to be a
1586 // non-static member function:
1588 // C++ [expr.ref]p4:
1589 // Otherwise, if E1.E2 refers to a non-static member function. . .
1590 // [t]he expression can be used only as the left-hand operand of a
1591 // member function call.
1593 // There are other safeguards against such uses, but it's important
1594 // to get this right here so that we don't end up making a
1595 // spuriously dependent expression if we're inside a dependent
1596 // instance method.
1597 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1598 bool MightBeImplicitMember;
1599 if (!isAddressOfOperand)
1600 MightBeImplicitMember = true;
1601 else if (!SS.isEmpty())
1602 MightBeImplicitMember = false;
1603 else if (R.isOverloadedResult())
1604 MightBeImplicitMember = false;
1605 else if (R.isUnresolvableResult())
1606 MightBeImplicitMember = true;
1607 else
1608 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1609 isa<IndirectFieldDecl>(R.getFoundDecl());
1611 if (MightBeImplicitMember)
1612 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1615 if (TemplateArgs)
1616 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1618 return BuildDeclarationNameExpr(SS, R, ADL);
1621 /// Builds an expression which might be an implicit member expression.
1622 ExprResult
1623 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1624 LookupResult &R,
1625 const TemplateArgumentListInfo *TemplateArgs) {
1626 switch (ClassifyImplicitMemberAccess(*this, R)) {
1627 case IMA_Instance:
1628 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1630 case IMA_Mixed:
1631 case IMA_Mixed_Unrelated:
1632 case IMA_Unresolved:
1633 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1635 case IMA_Static:
1636 case IMA_Mixed_StaticContext:
1637 case IMA_Unresolved_StaticContext:
1638 if (TemplateArgs)
1639 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1640 return BuildDeclarationNameExpr(SS, R, false);
1642 case IMA_Error_StaticContext:
1643 case IMA_Error_Unrelated:
1644 DiagnoseInstanceReference(*this, SS, R);
1645 return ExprError();
1648 llvm_unreachable("unexpected instance member access kind");
1649 return ExprError();
1652 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1653 /// declaration name, generally during template instantiation.
1654 /// There's a large number of things which don't need to be done along
1655 /// this path.
1656 ExprResult
1657 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1658 const DeclarationNameInfo &NameInfo) {
1659 DeclContext *DC;
1660 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1661 return BuildDependentDeclRefExpr(SS, NameInfo, 0);
1663 if (RequireCompleteDeclContext(SS, DC))
1664 return ExprError();
1666 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1667 LookupQualifiedName(R, DC);
1669 if (R.isAmbiguous())
1670 return ExprError();
1672 if (R.empty()) {
1673 Diag(NameInfo.getLoc(), diag::err_no_member)
1674 << NameInfo.getName() << DC << SS.getRange();
1675 return ExprError();
1678 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1681 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1682 /// detected that we're currently inside an ObjC method. Perform some
1683 /// additional lookup.
1685 /// Ideally, most of this would be done by lookup, but there's
1686 /// actually quite a lot of extra work involved.
1688 /// Returns a null sentinel to indicate trivial success.
1689 ExprResult
1690 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1691 IdentifierInfo *II, bool AllowBuiltinCreation) {
1692 SourceLocation Loc = Lookup.getNameLoc();
1693 ObjCMethodDecl *CurMethod = getCurMethodDecl();
1695 // There are two cases to handle here. 1) scoped lookup could have failed,
1696 // in which case we should look for an ivar. 2) scoped lookup could have
1697 // found a decl, but that decl is outside the current instance method (i.e.
1698 // a global variable). In these two cases, we do a lookup for an ivar with
1699 // this name, if the lookup sucedes, we replace it our current decl.
1701 // If we're in a class method, we don't normally want to look for
1702 // ivars. But if we don't find anything else, and there's an
1703 // ivar, that's an error.
1704 bool IsClassMethod = CurMethod->isClassMethod();
1706 bool LookForIvars;
1707 if (Lookup.empty())
1708 LookForIvars = true;
1709 else if (IsClassMethod)
1710 LookForIvars = false;
1711 else
1712 LookForIvars = (Lookup.isSingleResult() &&
1713 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1714 ObjCInterfaceDecl *IFace = 0;
1715 if (LookForIvars) {
1716 IFace = CurMethod->getClassInterface();
1717 ObjCInterfaceDecl *ClassDeclared;
1718 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1719 // Diagnose using an ivar in a class method.
1720 if (IsClassMethod)
1721 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1722 << IV->getDeclName());
1724 // If we're referencing an invalid decl, just return this as a silent
1725 // error node. The error diagnostic was already emitted on the decl.
1726 if (IV->isInvalidDecl())
1727 return ExprError();
1729 // Check if referencing a field with __attribute__((deprecated)).
1730 if (DiagnoseUseOfDecl(IV, Loc))
1731 return ExprError();
1733 // Diagnose the use of an ivar outside of the declaring class.
1734 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1735 ClassDeclared != IFace)
1736 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1738 // FIXME: This should use a new expr for a direct reference, don't
1739 // turn this into Self->ivar, just return a BareIVarExpr or something.
1740 IdentifierInfo &II = Context.Idents.get("self");
1741 UnqualifiedId SelfName;
1742 SelfName.setIdentifier(&II, SourceLocation());
1743 CXXScopeSpec SelfScopeSpec;
1744 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1745 SelfName, false, false);
1746 if (SelfExpr.isInvalid())
1747 return ExprError();
1749 Expr *SelfE = SelfExpr.take();
1750 DefaultLvalueConversion(SelfE);
1752 MarkDeclarationReferenced(Loc, IV);
1753 return Owned(new (Context)
1754 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1755 SelfE, true, true));
1757 } else if (CurMethod->isInstanceMethod()) {
1758 // We should warn if a local variable hides an ivar.
1759 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
1760 ObjCInterfaceDecl *ClassDeclared;
1761 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1762 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1763 IFace == ClassDeclared)
1764 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1768 if (Lookup.empty() && II && AllowBuiltinCreation) {
1769 // FIXME. Consolidate this with similar code in LookupName.
1770 if (unsigned BuiltinID = II->getBuiltinID()) {
1771 if (!(getLangOptions().CPlusPlus &&
1772 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1773 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1774 S, Lookup.isForRedeclaration(),
1775 Lookup.getNameLoc());
1776 if (D) Lookup.addDecl(D);
1780 // Sentinel value saying that we didn't do anything special.
1781 return Owned((Expr*) 0);
1784 /// \brief Cast a base object to a member's actual type.
1786 /// Logically this happens in three phases:
1788 /// * First we cast from the base type to the naming class.
1789 /// The naming class is the class into which we were looking
1790 /// when we found the member; it's the qualifier type if a
1791 /// qualifier was provided, and otherwise it's the base type.
1793 /// * Next we cast from the naming class to the declaring class.
1794 /// If the member we found was brought into a class's scope by
1795 /// a using declaration, this is that class; otherwise it's
1796 /// the class declaring the member.
1798 /// * Finally we cast from the declaring class to the "true"
1799 /// declaring class of the member. This conversion does not
1800 /// obey access control.
1801 bool
1802 Sema::PerformObjectMemberConversion(Expr *&From,
1803 NestedNameSpecifier *Qualifier,
1804 NamedDecl *FoundDecl,
1805 NamedDecl *Member) {
1806 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1807 if (!RD)
1808 return false;
1810 QualType DestRecordType;
1811 QualType DestType;
1812 QualType FromRecordType;
1813 QualType FromType = From->getType();
1814 bool PointerConversions = false;
1815 if (isa<FieldDecl>(Member)) {
1816 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
1818 if (FromType->getAs<PointerType>()) {
1819 DestType = Context.getPointerType(DestRecordType);
1820 FromRecordType = FromType->getPointeeType();
1821 PointerConversions = true;
1822 } else {
1823 DestType = DestRecordType;
1824 FromRecordType = FromType;
1826 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1827 if (Method->isStatic())
1828 return false;
1830 DestType = Method->getThisType(Context);
1831 DestRecordType = DestType->getPointeeType();
1833 if (FromType->getAs<PointerType>()) {
1834 FromRecordType = FromType->getPointeeType();
1835 PointerConversions = true;
1836 } else {
1837 FromRecordType = FromType;
1838 DestType = DestRecordType;
1840 } else {
1841 // No conversion necessary.
1842 return false;
1845 if (DestType->isDependentType() || FromType->isDependentType())
1846 return false;
1848 // If the unqualified types are the same, no conversion is necessary.
1849 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1850 return false;
1852 SourceRange FromRange = From->getSourceRange();
1853 SourceLocation FromLoc = FromRange.getBegin();
1855 ExprValueKind VK = CastCategory(From);
1857 // C++ [class.member.lookup]p8:
1858 // [...] Ambiguities can often be resolved by qualifying a name with its
1859 // class name.
1861 // If the member was a qualified name and the qualified referred to a
1862 // specific base subobject type, we'll cast to that intermediate type
1863 // first and then to the object in which the member is declared. That allows
1864 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1866 // class Base { public: int x; };
1867 // class Derived1 : public Base { };
1868 // class Derived2 : public Base { };
1869 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1871 // void VeryDerived::f() {
1872 // x = 17; // error: ambiguous base subobjects
1873 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1874 // }
1875 if (Qualifier) {
1876 QualType QType = QualType(Qualifier->getAsType(), 0);
1877 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1878 assert(QType->isRecordType() && "lookup done with non-record type");
1880 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1882 // In C++98, the qualifier type doesn't actually have to be a base
1883 // type of the object type, in which case we just ignore it.
1884 // Otherwise build the appropriate casts.
1885 if (IsDerivedFrom(FromRecordType, QRecordType)) {
1886 CXXCastPath BasePath;
1887 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
1888 FromLoc, FromRange, &BasePath))
1889 return true;
1891 if (PointerConversions)
1892 QType = Context.getPointerType(QType);
1893 ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1894 VK, &BasePath);
1896 FromType = QType;
1897 FromRecordType = QRecordType;
1899 // If the qualifier type was the same as the destination type,
1900 // we're done.
1901 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1902 return false;
1906 bool IgnoreAccess = false;
1908 // If we actually found the member through a using declaration, cast
1909 // down to the using declaration's type.
1911 // Pointer equality is fine here because only one declaration of a
1912 // class ever has member declarations.
1913 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1914 assert(isa<UsingShadowDecl>(FoundDecl));
1915 QualType URecordType = Context.getTypeDeclType(
1916 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1918 // We only need to do this if the naming-class to declaring-class
1919 // conversion is non-trivial.
1920 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1921 assert(IsDerivedFrom(FromRecordType, URecordType));
1922 CXXCastPath BasePath;
1923 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
1924 FromLoc, FromRange, &BasePath))
1925 return true;
1927 QualType UType = URecordType;
1928 if (PointerConversions)
1929 UType = Context.getPointerType(UType);
1930 ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
1931 VK, &BasePath);
1932 FromType = UType;
1933 FromRecordType = URecordType;
1936 // We don't do access control for the conversion from the
1937 // declaring class to the true declaring class.
1938 IgnoreAccess = true;
1941 CXXCastPath BasePath;
1942 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1943 FromLoc, FromRange, &BasePath,
1944 IgnoreAccess))
1945 return true;
1947 ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
1948 VK, &BasePath);
1949 return false;
1952 /// \brief Build a MemberExpr AST node.
1953 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
1954 const CXXScopeSpec &SS, ValueDecl *Member,
1955 DeclAccessPair FoundDecl,
1956 const DeclarationNameInfo &MemberNameInfo,
1957 QualType Ty,
1958 ExprValueKind VK, ExprObjectKind OK,
1959 const TemplateArgumentListInfo *TemplateArgs = 0) {
1960 NestedNameSpecifier *Qualifier = 0;
1961 SourceRange QualifierRange;
1962 if (SS.isSet()) {
1963 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1964 QualifierRange = SS.getRange();
1967 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1968 Member, FoundDecl, MemberNameInfo,
1969 TemplateArgs, Ty, VK, OK);
1972 static ExprResult
1973 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1974 const CXXScopeSpec &SS, FieldDecl *Field,
1975 DeclAccessPair FoundDecl,
1976 const DeclarationNameInfo &MemberNameInfo) {
1977 // x.a is an l-value if 'a' has a reference type. Otherwise:
1978 // x.a is an l-value/x-value/pr-value if the base is (and note
1979 // that *x is always an l-value), except that if the base isn't
1980 // an ordinary object then we must have an rvalue.
1981 ExprValueKind VK = VK_LValue;
1982 ExprObjectKind OK = OK_Ordinary;
1983 if (!IsArrow) {
1984 if (BaseExpr->getObjectKind() == OK_Ordinary)
1985 VK = BaseExpr->getValueKind();
1986 else
1987 VK = VK_RValue;
1989 if (VK != VK_RValue && Field->isBitField())
1990 OK = OK_BitField;
1992 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1993 QualType MemberType = Field->getType();
1994 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1995 MemberType = Ref->getPointeeType();
1996 VK = VK_LValue;
1997 } else {
1998 QualType BaseType = BaseExpr->getType();
1999 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2001 Qualifiers BaseQuals = BaseType.getQualifiers();
2003 // GC attributes are never picked up by members.
2004 BaseQuals.removeObjCGCAttr();
2006 // CVR attributes from the base are picked up by members,
2007 // except that 'mutable' members don't pick up 'const'.
2008 if (Field->isMutable()) BaseQuals.removeConst();
2010 Qualifiers MemberQuals
2011 = S.Context.getCanonicalType(MemberType).getQualifiers();
2013 // TR 18037 does not allow fields to be declared with address spaces.
2014 assert(!MemberQuals.hasAddressSpace());
2016 Qualifiers Combined = BaseQuals + MemberQuals;
2017 if (Combined != MemberQuals)
2018 MemberType = S.Context.getQualifiedType(MemberType, Combined);
2021 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
2022 if (S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
2023 FoundDecl, Field))
2024 return ExprError();
2025 return S.Owned(BuildMemberExpr(S.Context, BaseExpr, IsArrow, SS,
2026 Field, FoundDecl, MemberNameInfo,
2027 MemberType, VK, OK));
2030 /// Builds an implicit member access expression. The current context
2031 /// is known to be an instance method, and the given unqualified lookup
2032 /// set is known to contain only instance members, at least one of which
2033 /// is from an appropriate type.
2034 ExprResult
2035 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
2036 LookupResult &R,
2037 const TemplateArgumentListInfo *TemplateArgs,
2038 bool IsKnownInstance) {
2039 assert(!R.empty() && !R.isAmbiguous());
2041 SourceLocation Loc = R.getNameLoc();
2043 // We may have found a field within an anonymous union or struct
2044 // (C++ [class.union]).
2045 // FIXME: This needs to happen post-isImplicitMemberReference?
2046 // FIXME: template-ids inside anonymous structs?
2047 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
2048 return BuildAnonymousStructUnionMemberReference(Loc, SS, FD);
2051 // If this is known to be an instance access, go ahead and build a
2052 // 'this' expression now.
2053 DeclContext *DC = getFunctionLevelDeclContext();
2054 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
2055 Expr *This = 0; // null signifies implicit access
2056 if (IsKnownInstance) {
2057 SourceLocation Loc = R.getNameLoc();
2058 if (SS.getRange().isValid())
2059 Loc = SS.getRange().getBegin();
2060 This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
2063 return BuildMemberReferenceExpr(This, ThisType,
2064 /*OpLoc*/ SourceLocation(),
2065 /*IsArrow*/ true,
2067 /*FirstQualifierInScope*/ 0,
2068 R, TemplateArgs);
2071 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2072 const LookupResult &R,
2073 bool HasTrailingLParen) {
2074 // Only when used directly as the postfix-expression of a call.
2075 if (!HasTrailingLParen)
2076 return false;
2078 // Never if a scope specifier was provided.
2079 if (SS.isSet())
2080 return false;
2082 // Only in C++ or ObjC++.
2083 if (!getLangOptions().CPlusPlus)
2084 return false;
2086 // Turn off ADL when we find certain kinds of declarations during
2087 // normal lookup:
2088 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2089 NamedDecl *D = *I;
2091 // C++0x [basic.lookup.argdep]p3:
2092 // -- a declaration of a class member
2093 // Since using decls preserve this property, we check this on the
2094 // original decl.
2095 if (D->isCXXClassMember())
2096 return false;
2098 // C++0x [basic.lookup.argdep]p3:
2099 // -- a block-scope function declaration that is not a
2100 // using-declaration
2101 // NOTE: we also trigger this for function templates (in fact, we
2102 // don't check the decl type at all, since all other decl types
2103 // turn off ADL anyway).
2104 if (isa<UsingShadowDecl>(D))
2105 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2106 else if (D->getDeclContext()->isFunctionOrMethod())
2107 return false;
2109 // C++0x [basic.lookup.argdep]p3:
2110 // -- a declaration that is neither a function or a function
2111 // template
2112 // And also for builtin functions.
2113 if (isa<FunctionDecl>(D)) {
2114 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2116 // But also builtin functions.
2117 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2118 return false;
2119 } else if (!isa<FunctionTemplateDecl>(D))
2120 return false;
2123 return true;
2127 /// Diagnoses obvious problems with the use of the given declaration
2128 /// as an expression. This is only actually called for lookups that
2129 /// were not overloaded, and it doesn't promise that the declaration
2130 /// will in fact be used.
2131 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2132 if (isa<TypedefDecl>(D)) {
2133 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2134 return true;
2137 if (isa<ObjCInterfaceDecl>(D)) {
2138 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2139 return true;
2142 if (isa<NamespaceDecl>(D)) {
2143 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2144 return true;
2147 return false;
2150 ExprResult
2151 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2152 LookupResult &R,
2153 bool NeedsADL) {
2154 // If this is a single, fully-resolved result and we don't need ADL,
2155 // just build an ordinary singleton decl ref.
2156 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2157 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2158 R.getFoundDecl());
2160 // We only need to check the declaration if there's exactly one
2161 // result, because in the overloaded case the results can only be
2162 // functions and function templates.
2163 if (R.isSingleResult() &&
2164 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2165 return ExprError();
2167 // Otherwise, just build an unresolved lookup expression. Suppress
2168 // any lookup-related diagnostics; we'll hash these out later, when
2169 // we've picked a target.
2170 R.suppressDiagnostics();
2172 UnresolvedLookupExpr *ULE
2173 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2174 (NestedNameSpecifier*) SS.getScopeRep(),
2175 SS.getRange(), R.getLookupNameInfo(),
2176 NeedsADL, R.isOverloadedResult(),
2177 R.begin(), R.end());
2179 return Owned(ULE);
2182 static ExprValueKind getValueKindForDecl(ASTContext &Context,
2183 const ValueDecl *D) {
2184 // FIXME: It's not clear to me why NonTypeTemplateParmDecl is a VarDecl.
2185 if (isa<VarDecl>(D) && !isa<NonTypeTemplateParmDecl>(D)) return VK_LValue;
2186 if (isa<FieldDecl>(D)) return VK_LValue;
2187 if (!Context.getLangOptions().CPlusPlus) return VK_RValue;
2188 if (isa<FunctionDecl>(D)) {
2189 if (isa<CXXMethodDecl>(D) && cast<CXXMethodDecl>(D)->isInstance())
2190 return VK_RValue;
2191 return VK_LValue;
2193 return Expr::getValueKindForType(D->getType());
2197 /// \brief Complete semantic analysis for a reference to the given declaration.
2198 ExprResult
2199 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2200 const DeclarationNameInfo &NameInfo,
2201 NamedDecl *D) {
2202 assert(D && "Cannot refer to a NULL declaration");
2203 assert(!isa<FunctionTemplateDecl>(D) &&
2204 "Cannot refer unambiguously to a function template");
2206 SourceLocation Loc = NameInfo.getLoc();
2207 if (CheckDeclInExpr(*this, Loc, D))
2208 return ExprError();
2210 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2211 // Specifically diagnose references to class templates that are missing
2212 // a template argument list.
2213 Diag(Loc, diag::err_template_decl_ref)
2214 << Template << SS.getRange();
2215 Diag(Template->getLocation(), diag::note_template_decl_here);
2216 return ExprError();
2219 // Make sure that we're referring to a value.
2220 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2221 if (!VD) {
2222 Diag(Loc, diag::err_ref_non_value)
2223 << D << SS.getRange();
2224 Diag(D->getLocation(), diag::note_declared_at);
2225 return ExprError();
2228 // Check whether this declaration can be used. Note that we suppress
2229 // this check when we're going to perform argument-dependent lookup
2230 // on this function name, because this might not be the function
2231 // that overload resolution actually selects.
2232 if (DiagnoseUseOfDecl(VD, Loc))
2233 return ExprError();
2235 // Only create DeclRefExpr's for valid Decl's.
2236 if (VD->isInvalidDecl())
2237 return ExprError();
2239 // Handle anonymous.
2240 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(VD))
2241 return BuildAnonymousStructUnionMemberReference(Loc, SS, FD);
2243 ExprValueKind VK = getValueKindForDecl(Context, VD);
2245 // If the identifier reference is inside a block, and it refers to a value
2246 // that is outside the block, create a BlockDeclRefExpr instead of a
2247 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
2248 // the block is formed.
2250 // We do not do this for things like enum constants, global variables, etc,
2251 // as they do not get snapshotted.
2253 if (getCurBlock() &&
2254 ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
2255 if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
2256 Diag(Loc, diag::err_ref_vm_type);
2257 Diag(D->getLocation(), diag::note_declared_at);
2258 return ExprError();
2261 if (VD->getType()->isArrayType()) {
2262 Diag(Loc, diag::err_ref_array_type);
2263 Diag(D->getLocation(), diag::note_declared_at);
2264 return ExprError();
2267 MarkDeclarationReferenced(Loc, VD);
2268 QualType ExprTy = VD->getType().getNonReferenceType();
2270 // The BlocksAttr indicates the variable is bound by-reference.
2271 bool byrefVar = (VD->getAttr<BlocksAttr>() != 0);
2272 QualType T = VD->getType();
2273 BlockDeclRefExpr *BDRE;
2275 if (!byrefVar) {
2276 // This is to record that a 'const' was actually synthesize and added.
2277 bool constAdded = !ExprTy.isConstQualified();
2278 // Variable will be bound by-copy, make it const within the closure.
2279 ExprTy.addConst();
2280 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK,
2281 Loc, false, constAdded);
2283 else
2284 BDRE = new (Context) BlockDeclRefExpr(VD, ExprTy, VK, Loc, true);
2286 if (getLangOptions().CPlusPlus) {
2287 if (!T->isDependentType() && !T->isReferenceType()) {
2288 Expr *E = new (Context)
2289 DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
2290 VK, SourceLocation());
2291 if (T->getAs<RecordType>())
2292 if (!T->isUnionType()) {
2293 ExprResult Res = PerformCopyInitialization(
2294 InitializedEntity::InitializeBlock(VD->getLocation(),
2295 T, false),
2296 SourceLocation(),
2297 Owned(E));
2298 if (!Res.isInvalid()) {
2299 Res = MaybeCreateExprWithCleanups(Res);
2300 Expr *Init = Res.takeAs<Expr>();
2301 BDRE->setCopyConstructorExpr(Init);
2306 return Owned(BDRE);
2308 // If this reference is not in a block or if the referenced variable is
2309 // within the block, create a normal DeclRefExpr.
2311 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), VK,
2312 NameInfo, &SS);
2315 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
2316 tok::TokenKind Kind) {
2317 PredefinedExpr::IdentType IT;
2319 switch (Kind) {
2320 default: assert(0 && "Unknown simple primary expr!");
2321 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2322 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2323 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2326 // Pre-defined identifiers are of type char[x], where x is the length of the
2327 // string.
2329 Decl *currentDecl = getCurFunctionOrMethodDecl();
2330 if (!currentDecl && getCurBlock())
2331 currentDecl = getCurBlock()->TheDecl;
2332 if (!currentDecl) {
2333 Diag(Loc, diag::ext_predef_outside_function);
2334 currentDecl = Context.getTranslationUnitDecl();
2337 QualType ResTy;
2338 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2339 ResTy = Context.DependentTy;
2340 } else {
2341 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2343 llvm::APInt LengthI(32, Length + 1);
2344 ResTy = Context.CharTy.withConst();
2345 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2347 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2350 ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
2351 llvm::SmallString<16> CharBuffer;
2352 bool Invalid = false;
2353 llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2354 if (Invalid)
2355 return ExprError();
2357 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2358 PP);
2359 if (Literal.hadError())
2360 return ExprError();
2362 QualType Ty;
2363 if (!getLangOptions().CPlusPlus)
2364 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
2365 else if (Literal.isWide())
2366 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
2367 else if (Literal.isMultiChar())
2368 Ty = Context.IntTy; // 'wxyz' -> int in C++.
2369 else
2370 Ty = Context.CharTy; // 'x' -> char in C++
2372 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
2373 Literal.isWide(),
2374 Ty, Tok.getLocation()));
2377 ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
2378 // Fast path for a single digit (which is quite common). A single digit
2379 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2380 if (Tok.getLength() == 1) {
2381 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2382 unsigned IntSize = Context.Target.getIntWidth();
2383 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
2384 Context.IntTy, Tok.getLocation()));
2387 llvm::SmallString<512> IntegerBuffer;
2388 // Add padding so that NumericLiteralParser can overread by one character.
2389 IntegerBuffer.resize(Tok.getLength()+1);
2390 const char *ThisTokBegin = &IntegerBuffer[0];
2392 // Get the spelling of the token, which eliminates trigraphs, etc.
2393 bool Invalid = false;
2394 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2395 if (Invalid)
2396 return ExprError();
2398 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2399 Tok.getLocation(), PP);
2400 if (Literal.hadError)
2401 return ExprError();
2403 Expr *Res;
2405 if (Literal.isFloatingLiteral()) {
2406 QualType Ty;
2407 if (Literal.isFloat)
2408 Ty = Context.FloatTy;
2409 else if (!Literal.isLong)
2410 Ty = Context.DoubleTy;
2411 else
2412 Ty = Context.LongDoubleTy;
2414 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2416 using llvm::APFloat;
2417 APFloat Val(Format);
2419 APFloat::opStatus result = Literal.GetFloatValue(Val);
2421 // Overflow is always an error, but underflow is only an error if
2422 // we underflowed to zero (APFloat reports denormals as underflow).
2423 if ((result & APFloat::opOverflow) ||
2424 ((result & APFloat::opUnderflow) && Val.isZero())) {
2425 unsigned diagnostic;
2426 llvm::SmallString<20> buffer;
2427 if (result & APFloat::opOverflow) {
2428 diagnostic = diag::warn_float_overflow;
2429 APFloat::getLargest(Format).toString(buffer);
2430 } else {
2431 diagnostic = diag::warn_float_underflow;
2432 APFloat::getSmallest(Format).toString(buffer);
2435 Diag(Tok.getLocation(), diagnostic)
2436 << Ty
2437 << llvm::StringRef(buffer.data(), buffer.size());
2440 bool isExact = (result == APFloat::opOK);
2441 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
2443 if (getLangOptions().SinglePrecisionConstants && Ty == Context.DoubleTy)
2444 ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast);
2446 } else if (!Literal.isIntegerLiteral()) {
2447 return ExprError();
2448 } else {
2449 QualType Ty;
2451 // long long is a C99 feature.
2452 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
2453 Literal.isLongLong)
2454 Diag(Tok.getLocation(), diag::ext_longlong);
2456 // Get the value in the widest-possible width.
2457 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
2459 if (Literal.GetIntegerValue(ResultVal)) {
2460 // If this value didn't fit into uintmax_t, warn and force to ull.
2461 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2462 Ty = Context.UnsignedLongLongTy;
2463 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2464 "long long is not intmax_t?");
2465 } else {
2466 // If this value fits into a ULL, try to figure out what else it fits into
2467 // according to the rules of C99 6.4.4.1p5.
2469 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2470 // be an unsigned int.
2471 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2473 // Check from smallest to largest, picking the smallest type we can.
2474 unsigned Width = 0;
2475 if (!Literal.isLong && !Literal.isLongLong) {
2476 // Are int/unsigned possibilities?
2477 unsigned IntSize = Context.Target.getIntWidth();
2479 // Does it fit in a unsigned int?
2480 if (ResultVal.isIntN(IntSize)) {
2481 // Does it fit in a signed int?
2482 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2483 Ty = Context.IntTy;
2484 else if (AllowUnsigned)
2485 Ty = Context.UnsignedIntTy;
2486 Width = IntSize;
2490 // Are long/unsigned long possibilities?
2491 if (Ty.isNull() && !Literal.isLongLong) {
2492 unsigned LongSize = Context.Target.getLongWidth();
2494 // Does it fit in a unsigned long?
2495 if (ResultVal.isIntN(LongSize)) {
2496 // Does it fit in a signed long?
2497 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2498 Ty = Context.LongTy;
2499 else if (AllowUnsigned)
2500 Ty = Context.UnsignedLongTy;
2501 Width = LongSize;
2505 // Finally, check long long if needed.
2506 if (Ty.isNull()) {
2507 unsigned LongLongSize = Context.Target.getLongLongWidth();
2509 // Does it fit in a unsigned long long?
2510 if (ResultVal.isIntN(LongLongSize)) {
2511 // Does it fit in a signed long long?
2512 // To be compatible with MSVC, hex integer literals ending with the
2513 // LL or i64 suffix are always signed in Microsoft mode.
2514 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2515 (getLangOptions().Microsoft && Literal.isLongLong)))
2516 Ty = Context.LongLongTy;
2517 else if (AllowUnsigned)
2518 Ty = Context.UnsignedLongLongTy;
2519 Width = LongLongSize;
2523 // If we still couldn't decide a type, we probably have something that
2524 // does not fit in a signed long long, but has no U suffix.
2525 if (Ty.isNull()) {
2526 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2527 Ty = Context.UnsignedLongLongTy;
2528 Width = Context.Target.getLongLongWidth();
2531 if (ResultVal.getBitWidth() != Width)
2532 ResultVal = ResultVal.trunc(Width);
2534 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2537 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2538 if (Literal.isImaginary)
2539 Res = new (Context) ImaginaryLiteral(Res,
2540 Context.getComplexType(Res->getType()));
2542 return Owned(Res);
2545 ExprResult Sema::ActOnParenExpr(SourceLocation L,
2546 SourceLocation R, Expr *E) {
2547 assert((E != 0) && "ActOnParenExpr() missing expr");
2548 return Owned(new (Context) ParenExpr(L, R, E));
2551 /// The UsualUnaryConversions() function is *not* called by this routine.
2552 /// See C99 6.3.2.1p[2-4] for more details.
2553 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
2554 SourceLocation OpLoc,
2555 SourceRange ExprRange,
2556 bool isSizeof) {
2557 if (exprType->isDependentType())
2558 return false;
2560 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2561 // the result is the size of the referenced type."
2562 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2563 // result shall be the alignment of the referenced type."
2564 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2565 exprType = Ref->getPointeeType();
2567 // C99 6.5.3.4p1:
2568 if (exprType->isFunctionType()) {
2569 // alignof(function) is allowed as an extension.
2570 if (isSizeof)
2571 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2572 return false;
2575 // Allow sizeof(void)/alignof(void) as an extension.
2576 if (exprType->isVoidType()) {
2577 Diag(OpLoc, diag::ext_sizeof_void_type)
2578 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
2579 return false;
2582 if (RequireCompleteType(OpLoc, exprType,
2583 PDiag(diag::err_sizeof_alignof_incomplete_type)
2584 << int(!isSizeof) << ExprRange))
2585 return true;
2587 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2588 if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
2589 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
2590 << exprType << isSizeof << ExprRange;
2591 return true;
2594 return false;
2597 static bool CheckAlignOfExpr(Sema &S, Expr *E, SourceLocation OpLoc,
2598 SourceRange ExprRange) {
2599 E = E->IgnoreParens();
2601 // alignof decl is always ok.
2602 if (isa<DeclRefExpr>(E))
2603 return false;
2605 // Cannot know anything else if the expression is dependent.
2606 if (E->isTypeDependent())
2607 return false;
2609 if (E->getBitField()) {
2610 S. Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2611 return true;
2614 // Alignment of a field access is always okay, so long as it isn't a
2615 // bit-field.
2616 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2617 if (isa<FieldDecl>(ME->getMemberDecl()))
2618 return false;
2620 return S.CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2623 /// \brief Build a sizeof or alignof expression given a type operand.
2624 ExprResult
2625 Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
2626 SourceLocation OpLoc,
2627 bool isSizeOf, SourceRange R) {
2628 if (!TInfo)
2629 return ExprError();
2631 QualType T = TInfo->getType();
2633 if (!T->isDependentType() &&
2634 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2635 return ExprError();
2637 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2638 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
2639 Context.getSizeType(), OpLoc,
2640 R.getEnd()));
2643 /// \brief Build a sizeof or alignof expression given an expression
2644 /// operand.
2645 ExprResult
2646 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
2647 bool isSizeOf, SourceRange R) {
2648 // Verify that the operand is valid.
2649 bool isInvalid = false;
2650 if (E->isTypeDependent()) {
2651 // Delay type-checking for type-dependent expressions.
2652 } else if (!isSizeOf) {
2653 isInvalid = CheckAlignOfExpr(*this, E, OpLoc, R);
2654 } else if (E->getBitField()) { // C99 6.5.3.4p1.
2655 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2656 isInvalid = true;
2657 } else if (E->getType()->isPlaceholderType()) {
2658 ExprResult PE = CheckPlaceholderExpr(E, OpLoc);
2659 if (PE.isInvalid()) return ExprError();
2660 return CreateSizeOfAlignOfExpr(PE.take(), OpLoc, isSizeOf, R);
2661 } else {
2662 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2665 if (isInvalid)
2666 return ExprError();
2668 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2669 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2670 Context.getSizeType(), OpLoc,
2671 R.getEnd()));
2674 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2675 /// the same for @c alignof and @c __alignof
2676 /// Note that the ArgRange is invalid if isType is false.
2677 ExprResult
2678 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2679 void *TyOrEx, const SourceRange &ArgRange) {
2680 // If error parsing type, ignore.
2681 if (TyOrEx == 0) return ExprError();
2683 if (isType) {
2684 TypeSourceInfo *TInfo;
2685 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
2686 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
2689 Expr *ArgEx = (Expr *)TyOrEx;
2690 ExprResult Result
2691 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2693 return move(Result);
2696 static QualType CheckRealImagOperand(Sema &S, Expr *&V, SourceLocation Loc,
2697 bool isReal) {
2698 if (V->isTypeDependent())
2699 return S.Context.DependentTy;
2701 // _Real and _Imag are only l-values for normal l-values.
2702 if (V->getObjectKind() != OK_Ordinary)
2703 S.DefaultLvalueConversion(V);
2705 // These operators return the element type of a complex type.
2706 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
2707 return CT->getElementType();
2709 // Otherwise they pass through real integer and floating point types here.
2710 if (V->getType()->isArithmeticType())
2711 return V->getType();
2713 // Test for placeholders.
2714 ExprResult PR = S.CheckPlaceholderExpr(V, Loc);
2715 if (PR.isInvalid()) return QualType();
2716 if (PR.take() != V) {
2717 V = PR.take();
2718 return CheckRealImagOperand(S, V, Loc, isReal);
2721 // Reject anything else.
2722 S.Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2723 << (isReal ? "__real" : "__imag");
2724 return QualType();
2729 ExprResult
2730 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2731 tok::TokenKind Kind, Expr *Input) {
2732 UnaryOperatorKind Opc;
2733 switch (Kind) {
2734 default: assert(0 && "Unknown unary op!");
2735 case tok::plusplus: Opc = UO_PostInc; break;
2736 case tok::minusminus: Opc = UO_PostDec; break;
2739 return BuildUnaryOp(S, OpLoc, Opc, Input);
2742 /// Expressions of certain arbitrary types are forbidden by C from
2743 /// having l-value type. These are:
2744 /// - 'void', but not qualified void
2745 /// - function types
2747 /// The exact rule here is C99 6.3.2.1:
2748 /// An lvalue is an expression with an object type or an incomplete
2749 /// type other than void.
2750 static bool IsCForbiddenLValueType(ASTContext &C, QualType T) {
2751 return ((T->isVoidType() && !T.hasQualifiers()) ||
2752 T->isFunctionType());
2755 ExprResult
2756 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2757 Expr *Idx, SourceLocation RLoc) {
2758 // Since this might be a postfix expression, get rid of ParenListExprs.
2759 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
2760 if (Result.isInvalid()) return ExprError();
2761 Base = Result.take();
2763 Expr *LHSExp = Base, *RHSExp = Idx;
2765 if (getLangOptions().CPlusPlus &&
2766 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2767 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2768 Context.DependentTy,
2769 VK_LValue, OK_Ordinary,
2770 RLoc));
2773 if (getLangOptions().CPlusPlus &&
2774 (LHSExp->getType()->isRecordType() ||
2775 LHSExp->getType()->isEnumeralType() ||
2776 RHSExp->getType()->isRecordType() ||
2777 RHSExp->getType()->isEnumeralType())) {
2778 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
2781 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
2785 ExprResult
2786 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
2787 Expr *Idx, SourceLocation RLoc) {
2788 Expr *LHSExp = Base;
2789 Expr *RHSExp = Idx;
2791 // Perform default conversions.
2792 if (!LHSExp->getType()->getAs<VectorType>())
2793 DefaultFunctionArrayLvalueConversion(LHSExp);
2794 DefaultFunctionArrayLvalueConversion(RHSExp);
2796 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
2797 ExprValueKind VK = VK_LValue;
2798 ExprObjectKind OK = OK_Ordinary;
2800 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
2801 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
2802 // in the subscript position. As a result, we need to derive the array base
2803 // and index from the expression types.
2804 Expr *BaseExpr, *IndexExpr;
2805 QualType ResultType;
2806 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2807 BaseExpr = LHSExp;
2808 IndexExpr = RHSExp;
2809 ResultType = Context.DependentTy;
2810 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
2811 BaseExpr = LHSExp;
2812 IndexExpr = RHSExp;
2813 ResultType = PTy->getPointeeType();
2814 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
2815 // Handle the uncommon case of "123[Ptr]".
2816 BaseExpr = RHSExp;
2817 IndexExpr = LHSExp;
2818 ResultType = PTy->getPointeeType();
2819 } else if (const ObjCObjectPointerType *PTy =
2820 LHSTy->getAs<ObjCObjectPointerType>()) {
2821 BaseExpr = LHSExp;
2822 IndexExpr = RHSExp;
2823 ResultType = PTy->getPointeeType();
2824 } else if (const ObjCObjectPointerType *PTy =
2825 RHSTy->getAs<ObjCObjectPointerType>()) {
2826 // Handle the uncommon case of "123[Ptr]".
2827 BaseExpr = RHSExp;
2828 IndexExpr = LHSExp;
2829 ResultType = PTy->getPointeeType();
2830 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
2831 BaseExpr = LHSExp; // vectors: V[123]
2832 IndexExpr = RHSExp;
2833 VK = LHSExp->getValueKind();
2834 if (VK != VK_RValue)
2835 OK = OK_VectorComponent;
2837 // FIXME: need to deal with const...
2838 ResultType = VTy->getElementType();
2839 } else if (LHSTy->isArrayType()) {
2840 // If we see an array that wasn't promoted by
2841 // DefaultFunctionArrayLvalueConversion, it must be an array that
2842 // wasn't promoted because of the C90 rule that doesn't
2843 // allow promoting non-lvalue arrays. Warn, then
2844 // force the promotion here.
2845 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2846 LHSExp->getSourceRange();
2847 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2848 CK_ArrayToPointerDecay);
2849 LHSTy = LHSExp->getType();
2851 BaseExpr = LHSExp;
2852 IndexExpr = RHSExp;
2853 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
2854 } else if (RHSTy->isArrayType()) {
2855 // Same as previous, except for 123[f().a] case
2856 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2857 RHSExp->getSourceRange();
2858 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2859 CK_ArrayToPointerDecay);
2860 RHSTy = RHSExp->getType();
2862 BaseExpr = RHSExp;
2863 IndexExpr = LHSExp;
2864 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
2865 } else {
2866 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2867 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
2869 // C99 6.5.2.1p1
2870 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
2871 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2872 << IndexExpr->getSourceRange());
2874 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
2875 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2876 && !IndexExpr->isTypeDependent())
2877 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2879 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
2880 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2881 // type. Note that Functions are not objects, and that (in C99 parlance)
2882 // incomplete types are not object types.
2883 if (ResultType->isFunctionType()) {
2884 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2885 << ResultType << BaseExpr->getSourceRange();
2886 return ExprError();
2889 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
2890 // GNU extension: subscripting on pointer to void
2891 Diag(LLoc, diag::ext_gnu_void_ptr)
2892 << BaseExpr->getSourceRange();
2894 // C forbids expressions of unqualified void type from being l-values.
2895 // See IsCForbiddenLValueType.
2896 if (!ResultType.hasQualifiers()) VK = VK_RValue;
2897 } else if (!ResultType->isDependentType() &&
2898 RequireCompleteType(LLoc, ResultType,
2899 PDiag(diag::err_subscript_incomplete_type)
2900 << BaseExpr->getSourceRange()))
2901 return ExprError();
2903 // Diagnose bad cases where we step over interface counts.
2904 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
2905 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2906 << ResultType << BaseExpr->getSourceRange();
2907 return ExprError();
2910 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
2911 !IsCForbiddenLValueType(Context, ResultType));
2913 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2914 ResultType, VK, OK, RLoc));
2917 /// Check an ext-vector component access expression.
2919 /// VK should be set in advance to the value kind of the base
2920 /// expression.
2921 static QualType
2922 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
2923 SourceLocation OpLoc, const IdentifierInfo *CompName,
2924 SourceLocation CompLoc) {
2925 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2926 // see FIXME there.
2928 // FIXME: This logic can be greatly simplified by splitting it along
2929 // halving/not halving and reworking the component checking.
2930 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
2932 // The vector accessor can't exceed the number of elements.
2933 const char *compStr = CompName->getNameStart();
2935 // This flag determines whether or not the component is one of the four
2936 // special names that indicate a subset of exactly half the elements are
2937 // to be selected.
2938 bool HalvingSwizzle = false;
2940 // This flag determines whether or not CompName has an 's' char prefix,
2941 // indicating that it is a string of hex values to be used as vector indices.
2942 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
2944 bool HasRepeated = false;
2945 bool HasIndex[16] = {};
2947 int Idx;
2949 // Check that we've found one of the special components, or that the component
2950 // names must come from the same set.
2951 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
2952 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2953 HalvingSwizzle = true;
2954 } else if (!HexSwizzle &&
2955 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
2956 do {
2957 if (HasIndex[Idx]) HasRepeated = true;
2958 HasIndex[Idx] = true;
2959 compStr++;
2960 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
2961 } else {
2962 if (HexSwizzle) compStr++;
2963 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
2964 if (HasIndex[Idx]) HasRepeated = true;
2965 HasIndex[Idx] = true;
2966 compStr++;
2970 if (!HalvingSwizzle && *compStr) {
2971 // We didn't get to the end of the string. This means the component names
2972 // didn't come from the same set *or* we encountered an illegal name.
2973 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2974 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
2975 return QualType();
2978 // Ensure no component accessor exceeds the width of the vector type it
2979 // operates on.
2980 if (!HalvingSwizzle) {
2981 compStr = CompName->getNameStart();
2983 if (HexSwizzle)
2984 compStr++;
2986 while (*compStr) {
2987 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2988 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2989 << baseType << SourceRange(CompLoc);
2990 return QualType();
2995 // The component accessor looks fine - now we need to compute the actual type.
2996 // The vector type is implied by the component accessor. For example,
2997 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
2998 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
2999 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
3000 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
3001 : CompName->getLength();
3002 if (HexSwizzle)
3003 CompSize--;
3005 if (CompSize == 1)
3006 return vecType->getElementType();
3008 if (HasRepeated) VK = VK_RValue;
3010 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
3011 // Now look up the TypeDefDecl from the vector type. Without this,
3012 // diagostics look bad. We want extended vector types to appear built-in.
3013 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
3014 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
3015 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
3017 return VT; // should never get here (a typedef type should always be found).
3020 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
3021 IdentifierInfo *Member,
3022 const Selector &Sel,
3023 ASTContext &Context) {
3024 if (Member)
3025 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
3026 return PD;
3027 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
3028 return OMD;
3030 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
3031 E = PDecl->protocol_end(); I != E; ++I) {
3032 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3033 Context))
3034 return D;
3036 return 0;
3039 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
3040 IdentifierInfo *Member,
3041 const Selector &Sel,
3042 ASTContext &Context) {
3043 // Check protocols on qualified interfaces.
3044 Decl *GDecl = 0;
3045 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3046 E = QIdTy->qual_end(); I != E; ++I) {
3047 if (Member)
3048 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
3049 GDecl = PD;
3050 break;
3052 // Also must look for a getter or setter name which uses property syntax.
3053 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
3054 GDecl = OMD;
3055 break;
3058 if (!GDecl) {
3059 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
3060 E = QIdTy->qual_end(); I != E; ++I) {
3061 // Search in the protocol-qualifier list of current protocol.
3062 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
3063 Context);
3064 if (GDecl)
3065 return GDecl;
3068 return GDecl;
3071 ExprResult
3072 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
3073 bool IsArrow, SourceLocation OpLoc,
3074 const CXXScopeSpec &SS,
3075 NamedDecl *FirstQualifierInScope,
3076 const DeclarationNameInfo &NameInfo,
3077 const TemplateArgumentListInfo *TemplateArgs) {
3078 // Even in dependent contexts, try to diagnose base expressions with
3079 // obviously wrong types, e.g.:
3081 // T* t;
3082 // t.f;
3084 // In Obj-C++, however, the above expression is valid, since it could be
3085 // accessing the 'f' property if T is an Obj-C interface. The extra check
3086 // allows this, while still reporting an error if T is a struct pointer.
3087 if (!IsArrow) {
3088 const PointerType *PT = BaseType->getAs<PointerType>();
3089 if (PT && (!getLangOptions().ObjC1 ||
3090 PT->getPointeeType()->isRecordType())) {
3091 assert(BaseExpr && "cannot happen with implicit member accesses");
3092 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
3093 << BaseType << BaseExpr->getSourceRange();
3094 return ExprError();
3098 assert(BaseType->isDependentType() ||
3099 NameInfo.getName().isDependentName() ||
3100 isDependentScopeSpecifier(SS));
3102 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
3103 // must have pointer type, and the accessed type is the pointee.
3104 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
3105 IsArrow, OpLoc,
3106 SS.getScopeRep(),
3107 SS.getRange(),
3108 FirstQualifierInScope,
3109 NameInfo, TemplateArgs));
3112 /// We know that the given qualified member reference points only to
3113 /// declarations which do not belong to the static type of the base
3114 /// expression. Diagnose the problem.
3115 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
3116 Expr *BaseExpr,
3117 QualType BaseType,
3118 const CXXScopeSpec &SS,
3119 const LookupResult &R) {
3120 // If this is an implicit member access, use a different set of
3121 // diagnostics.
3122 if (!BaseExpr)
3123 return DiagnoseInstanceReference(SemaRef, SS, R);
3125 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
3126 << SS.getRange() << R.getRepresentativeDecl() << BaseType;
3129 // Check whether the declarations we found through a nested-name
3130 // specifier in a member expression are actually members of the base
3131 // type. The restriction here is:
3133 // C++ [expr.ref]p2:
3134 // ... In these cases, the id-expression shall name a
3135 // member of the class or of one of its base classes.
3137 // So it's perfectly legitimate for the nested-name specifier to name
3138 // an unrelated class, and for us to find an overload set including
3139 // decls from classes which are not superclasses, as long as the decl
3140 // we actually pick through overload resolution is from a superclass.
3141 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
3142 QualType BaseType,
3143 const CXXScopeSpec &SS,
3144 const LookupResult &R) {
3145 const RecordType *BaseRT = BaseType->getAs<RecordType>();
3146 if (!BaseRT) {
3147 // We can't check this yet because the base type is still
3148 // dependent.
3149 assert(BaseType->isDependentType());
3150 return false;
3152 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
3154 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3155 // If this is an implicit member reference and we find a
3156 // non-instance member, it's not an error.
3157 if (!BaseExpr && !(*I)->isCXXInstanceMember())
3158 return false;
3160 // Note that we use the DC of the decl, not the underlying decl.
3161 DeclContext *DC = (*I)->getDeclContext();
3162 while (DC->isTransparentContext())
3163 DC = DC->getParent();
3165 if (!DC->isRecord())
3166 continue;
3168 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
3169 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
3171 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
3172 return false;
3175 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
3176 return true;
3179 static bool
3180 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
3181 SourceRange BaseRange, const RecordType *RTy,
3182 SourceLocation OpLoc, CXXScopeSpec &SS,
3183 bool HasTemplateArgs) {
3184 RecordDecl *RDecl = RTy->getDecl();
3185 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
3186 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
3187 << BaseRange))
3188 return true;
3190 if (HasTemplateArgs) {
3191 // LookupTemplateName doesn't expect these both to exist simultaneously.
3192 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
3194 bool MOUS;
3195 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
3196 return false;
3199 DeclContext *DC = RDecl;
3200 if (SS.isSet()) {
3201 // If the member name was a qualified-id, look into the
3202 // nested-name-specifier.
3203 DC = SemaRef.computeDeclContext(SS, false);
3205 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
3206 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
3207 << SS.getRange() << DC;
3208 return true;
3211 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
3213 if (!isa<TypeDecl>(DC)) {
3214 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
3215 << DC << SS.getRange();
3216 return true;
3220 // The record definition is complete, now look up the member.
3221 SemaRef.LookupQualifiedName(R, DC);
3223 if (!R.empty())
3224 return false;
3226 // We didn't find anything with the given name, so try to correct
3227 // for typos.
3228 DeclarationName Name = R.getLookupName();
3229 if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
3230 !R.empty() &&
3231 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
3232 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
3233 << Name << DC << R.getLookupName() << SS.getRange()
3234 << FixItHint::CreateReplacement(R.getNameLoc(),
3235 R.getLookupName().getAsString());
3236 if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
3237 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
3238 << ND->getDeclName();
3239 return false;
3240 } else {
3241 R.clear();
3242 R.setLookupName(Name);
3245 return false;
3248 ExprResult
3249 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
3250 SourceLocation OpLoc, bool IsArrow,
3251 CXXScopeSpec &SS,
3252 NamedDecl *FirstQualifierInScope,
3253 const DeclarationNameInfo &NameInfo,
3254 const TemplateArgumentListInfo *TemplateArgs) {
3255 if (BaseType->isDependentType() ||
3256 (SS.isSet() && isDependentScopeSpecifier(SS)))
3257 return ActOnDependentMemberExpr(Base, BaseType,
3258 IsArrow, OpLoc,
3259 SS, FirstQualifierInScope,
3260 NameInfo, TemplateArgs);
3262 LookupResult R(*this, NameInfo, LookupMemberName);
3264 // Implicit member accesses.
3265 if (!Base) {
3266 QualType RecordTy = BaseType;
3267 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
3268 if (LookupMemberExprInRecord(*this, R, SourceRange(),
3269 RecordTy->getAs<RecordType>(),
3270 OpLoc, SS, TemplateArgs != 0))
3271 return ExprError();
3273 // Explicit member accesses.
3274 } else {
3275 ExprResult Result =
3276 LookupMemberExpr(R, Base, IsArrow, OpLoc,
3277 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
3279 if (Result.isInvalid()) {
3280 Owned(Base);
3281 return ExprError();
3284 if (Result.get())
3285 return move(Result);
3287 // LookupMemberExpr can modify Base, and thus change BaseType
3288 BaseType = Base->getType();
3291 return BuildMemberReferenceExpr(Base, BaseType,
3292 OpLoc, IsArrow, SS, FirstQualifierInScope,
3293 R, TemplateArgs);
3296 ExprResult
3297 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
3298 SourceLocation OpLoc, bool IsArrow,
3299 const CXXScopeSpec &SS,
3300 NamedDecl *FirstQualifierInScope,
3301 LookupResult &R,
3302 const TemplateArgumentListInfo *TemplateArgs,
3303 bool SuppressQualifierCheck) {
3304 QualType BaseType = BaseExprType;
3305 if (IsArrow) {
3306 assert(BaseType->isPointerType());
3307 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
3309 R.setBaseObjectType(BaseType);
3311 NestedNameSpecifier *Qualifier = SS.getScopeRep();
3312 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
3313 DeclarationName MemberName = MemberNameInfo.getName();
3314 SourceLocation MemberLoc = MemberNameInfo.getLoc();
3316 if (R.isAmbiguous())
3317 return ExprError();
3319 if (R.empty()) {
3320 // Rederive where we looked up.
3321 DeclContext *DC = (SS.isSet()
3322 ? computeDeclContext(SS, false)
3323 : BaseType->getAs<RecordType>()->getDecl());
3325 Diag(R.getNameLoc(), diag::err_no_member)
3326 << MemberName << DC
3327 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
3328 return ExprError();
3331 // Diagnose lookups that find only declarations from a non-base
3332 // type. This is possible for either qualified lookups (which may
3333 // have been qualified with an unrelated type) or implicit member
3334 // expressions (which were found with unqualified lookup and thus
3335 // may have come from an enclosing scope). Note that it's okay for
3336 // lookup to find declarations from a non-base type as long as those
3337 // aren't the ones picked by overload resolution.
3338 if ((SS.isSet() || !BaseExpr ||
3339 (isa<CXXThisExpr>(BaseExpr) &&
3340 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
3341 !SuppressQualifierCheck &&
3342 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
3343 return ExprError();
3345 // Construct an unresolved result if we in fact got an unresolved
3346 // result.
3347 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
3348 // Suppress any lookup-related diagnostics; we'll do these when we
3349 // pick a member.
3350 R.suppressDiagnostics();
3352 UnresolvedMemberExpr *MemExpr
3353 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
3354 BaseExpr, BaseExprType,
3355 IsArrow, OpLoc,
3356 Qualifier, SS.getRange(),
3357 MemberNameInfo,
3358 TemplateArgs, R.begin(), R.end());
3360 return Owned(MemExpr);
3363 assert(R.isSingleResult());
3364 DeclAccessPair FoundDecl = R.begin().getPair();
3365 NamedDecl *MemberDecl = R.getFoundDecl();
3367 // FIXME: diagnose the presence of template arguments now.
3369 // If the decl being referenced had an error, return an error for this
3370 // sub-expr without emitting another error, in order to avoid cascading
3371 // error cases.
3372 if (MemberDecl->isInvalidDecl())
3373 return ExprError();
3375 // Handle the implicit-member-access case.
3376 if (!BaseExpr) {
3377 // If this is not an instance member, convert to a non-member access.
3378 if (!MemberDecl->isCXXInstanceMember())
3379 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
3381 SourceLocation Loc = R.getNameLoc();
3382 if (SS.getRange().isValid())
3383 Loc = SS.getRange().getBegin();
3384 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
3387 bool ShouldCheckUse = true;
3388 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3389 // Don't diagnose the use of a virtual member function unless it's
3390 // explicitly qualified.
3391 if (MD->isVirtual() && !SS.isSet())
3392 ShouldCheckUse = false;
3395 // Check the use of this member.
3396 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
3397 Owned(BaseExpr);
3398 return ExprError();
3401 // Perform a property load on the base regardless of whether we
3402 // actually need it for the declaration.
3403 if (BaseExpr->getObjectKind() == OK_ObjCProperty)
3404 ConvertPropertyForRValue(BaseExpr);
3406 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
3407 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
3408 SS, FD, FoundDecl, MemberNameInfo);
3410 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
3411 // We may have found a field within an anonymous union or struct
3412 // (C++ [class.union]).
3413 return BuildAnonymousStructUnionMemberReference(MemberLoc, SS, FD,
3414 BaseExpr, OpLoc);
3416 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
3417 MarkDeclarationReferenced(MemberLoc, Var);
3418 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3419 Var, FoundDecl, MemberNameInfo,
3420 Var->getType().getNonReferenceType(),
3421 VK_LValue, OK_Ordinary));
3424 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
3425 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3426 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3427 MemberFn, FoundDecl, MemberNameInfo,
3428 MemberFn->getType(),
3429 MemberFn->isInstance() ? VK_RValue : VK_LValue,
3430 OK_Ordinary));
3432 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
3434 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
3435 MarkDeclarationReferenced(MemberLoc, MemberDecl);
3436 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
3437 Enum, FoundDecl, MemberNameInfo,
3438 Enum->getType(), VK_RValue, OK_Ordinary));
3441 Owned(BaseExpr);
3443 // We found something that we didn't expect. Complain.
3444 if (isa<TypeDecl>(MemberDecl))
3445 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
3446 << MemberName << BaseType << int(IsArrow);
3447 else
3448 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
3449 << MemberName << BaseType << int(IsArrow);
3451 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
3452 << MemberName;
3453 R.suppressDiagnostics();
3454 return ExprError();
3457 /// Given that normal member access failed on the given expression,
3458 /// and given that the expression's type involves builtin-id or
3459 /// builtin-Class, decide whether substituting in the redefinition
3460 /// types would be profitable. The redefinition type is whatever
3461 /// this translation unit tried to typedef to id/Class; we store
3462 /// it to the side and then re-use it in places like this.
3463 static bool ShouldTryAgainWithRedefinitionType(Sema &S, Expr *&base) {
3464 const ObjCObjectPointerType *opty
3465 = base->getType()->getAs<ObjCObjectPointerType>();
3466 if (!opty) return false;
3468 const ObjCObjectType *ty = opty->getObjectType();
3470 QualType redef;
3471 if (ty->isObjCId()) {
3472 redef = S.Context.ObjCIdRedefinitionType;
3473 } else if (ty->isObjCClass()) {
3474 redef = S.Context.ObjCClassRedefinitionType;
3475 } else {
3476 return false;
3479 // Do the substitution as long as the redefinition type isn't just a
3480 // possibly-qualified pointer to builtin-id or builtin-Class again.
3481 opty = redef->getAs<ObjCObjectPointerType>();
3482 if (opty && !opty->getObjectType()->getInterface() != 0)
3483 return false;
3485 S.ImpCastExprToType(base, redef, CK_BitCast);
3486 return true;
3489 /// Look up the given member of the given non-type-dependent
3490 /// expression. This can return in one of two ways:
3491 /// * If it returns a sentinel null-but-valid result, the caller will
3492 /// assume that lookup was performed and the results written into
3493 /// the provided structure. It will take over from there.
3494 /// * Otherwise, the returned expression will be produced in place of
3495 /// an ordinary member expression.
3497 /// The ObjCImpDecl bit is a gross hack that will need to be properly
3498 /// fixed for ObjC++.
3499 ExprResult
3500 Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
3501 bool &IsArrow, SourceLocation OpLoc,
3502 CXXScopeSpec &SS,
3503 Decl *ObjCImpDecl, bool HasTemplateArgs) {
3504 assert(BaseExpr && "no base expression");
3506 // Perform default conversions.
3507 DefaultFunctionArrayConversion(BaseExpr);
3508 if (IsArrow) DefaultLvalueConversion(BaseExpr);
3510 QualType BaseType = BaseExpr->getType();
3511 assert(!BaseType->isDependentType());
3513 DeclarationName MemberName = R.getLookupName();
3514 SourceLocation MemberLoc = R.getNameLoc();
3516 // For later type-checking purposes, turn arrow accesses into dot
3517 // accesses. The only access type we support that doesn't follow
3518 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
3519 // and those never use arrows, so this is unaffected.
3520 if (IsArrow) {
3521 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
3522 BaseType = Ptr->getPointeeType();
3523 else if (const ObjCObjectPointerType *Ptr
3524 = BaseType->getAs<ObjCObjectPointerType>())
3525 BaseType = Ptr->getPointeeType();
3526 else if (BaseType->isRecordType()) {
3527 // Recover from arrow accesses to records, e.g.:
3528 // struct MyRecord foo;
3529 // foo->bar
3530 // This is actually well-formed in C++ if MyRecord has an
3531 // overloaded operator->, but that should have been dealt with
3532 // by now.
3533 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3534 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3535 << FixItHint::CreateReplacement(OpLoc, ".");
3536 IsArrow = false;
3537 } else {
3538 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3539 << BaseType << BaseExpr->getSourceRange();
3540 return ExprError();
3544 // Handle field access to simple records.
3545 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3546 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3547 RTy, OpLoc, SS, HasTemplateArgs))
3548 return ExprError();
3550 // Returning valid-but-null is how we indicate to the caller that
3551 // the lookup result was filled in.
3552 return Owned((Expr*) 0);
3555 // Handle ivar access to Objective-C objects.
3556 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
3557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3559 // There are three cases for the base type:
3560 // - builtin id (qualified or unqualified)
3561 // - builtin Class (qualified or unqualified)
3562 // - an interface
3563 ObjCInterfaceDecl *IDecl = OTy->getInterface();
3564 if (!IDecl) {
3565 // There's an implicit 'isa' ivar on all objects.
3566 // But we only actually find it this way on objects of type 'id',
3567 // apparently.
3568 if (OTy->isObjCId() && Member->isStr("isa"))
3569 return Owned(new (Context) ObjCIsaExpr(BaseExpr, IsArrow, MemberLoc,
3570 Context.getObjCClassType()));
3572 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3573 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3574 ObjCImpDecl, HasTemplateArgs);
3575 goto fail;
3578 ObjCInterfaceDecl *ClassDeclared;
3579 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3581 if (!IV) {
3582 // Attempt to correct for typos in ivar names.
3583 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3584 LookupMemberName);
3585 if (CorrectTypo(Res, 0, 0, IDecl, false,
3586 IsArrow ? CTC_ObjCIvarLookup
3587 : CTC_ObjCPropertyLookup) &&
3588 (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3589 Diag(R.getNameLoc(),
3590 diag::err_typecheck_member_reference_ivar_suggest)
3591 << IDecl->getDeclName() << MemberName << IV->getDeclName()
3592 << FixItHint::CreateReplacement(R.getNameLoc(),
3593 IV->getNameAsString());
3594 Diag(IV->getLocation(), diag::note_previous_decl)
3595 << IV->getDeclName();
3596 } else {
3597 Res.clear();
3598 Res.setLookupName(Member);
3600 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3601 << IDecl->getDeclName() << MemberName
3602 << BaseExpr->getSourceRange();
3603 return ExprError();
3607 // If the decl being referenced had an error, return an error for this
3608 // sub-expr without emitting another error, in order to avoid cascading
3609 // error cases.
3610 if (IV->isInvalidDecl())
3611 return ExprError();
3613 // Check whether we can reference this field.
3614 if (DiagnoseUseOfDecl(IV, MemberLoc))
3615 return ExprError();
3616 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3617 IV->getAccessControl() != ObjCIvarDecl::Package) {
3618 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3619 if (ObjCMethodDecl *MD = getCurMethodDecl())
3620 ClassOfMethodDecl = MD->getClassInterface();
3621 else if (ObjCImpDecl && getCurFunctionDecl()) {
3622 // Case of a c-function declared inside an objc implementation.
3623 // FIXME: For a c-style function nested inside an objc implementation
3624 // class, there is no implementation context available, so we pass
3625 // down the context as argument to this routine. Ideally, this context
3626 // need be passed down in the AST node and somehow calculated from the
3627 // AST for a function decl.
3628 if (ObjCImplementationDecl *IMPD =
3629 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
3630 ClassOfMethodDecl = IMPD->getClassInterface();
3631 else if (ObjCCategoryImplDecl* CatImplClass =
3632 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
3633 ClassOfMethodDecl = CatImplClass->getClassInterface();
3636 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3637 if (ClassDeclared != IDecl ||
3638 ClassOfMethodDecl != ClassDeclared)
3639 Diag(MemberLoc, diag::error_private_ivar_access)
3640 << IV->getDeclName();
3641 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3642 // @protected
3643 Diag(MemberLoc, diag::error_protected_ivar_access)
3644 << IV->getDeclName();
3647 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3648 MemberLoc, BaseExpr,
3649 IsArrow));
3652 // Objective-C property access.
3653 const ObjCObjectPointerType *OPT;
3654 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
3655 // This actually uses the base as an r-value.
3656 DefaultLvalueConversion(BaseExpr);
3657 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr->getType()));
3659 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3661 const ObjCObjectType *OT = OPT->getObjectType();
3663 // id, with and without qualifiers.
3664 if (OT->isObjCId()) {
3665 // Check protocols on qualified interfaces.
3666 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3667 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
3668 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3669 // Check the use of this declaration
3670 if (DiagnoseUseOfDecl(PD, MemberLoc))
3671 return ExprError();
3673 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3674 VK_LValue,
3675 OK_ObjCProperty,
3676 MemberLoc,
3677 BaseExpr));
3680 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3681 // Check the use of this method.
3682 if (DiagnoseUseOfDecl(OMD, MemberLoc))
3683 return ExprError();
3684 Selector SetterSel =
3685 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3686 PP.getSelectorTable(), Member);
3687 ObjCMethodDecl *SMD = 0;
3688 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
3689 SetterSel, Context))
3690 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
3691 QualType PType = OMD->getSendResultType();
3693 ExprValueKind VK = VK_LValue;
3694 if (!getLangOptions().CPlusPlus &&
3695 IsCForbiddenLValueType(Context, PType))
3696 VK = VK_RValue;
3697 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3699 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
3700 VK, OK,
3701 MemberLoc, BaseExpr));
3705 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3706 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3707 ObjCImpDecl, HasTemplateArgs);
3709 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3710 << MemberName << BaseType);
3713 // 'Class', unqualified only.
3714 if (OT->isObjCClass()) {
3715 // Only works in a method declaration (??!).
3716 ObjCMethodDecl *MD = getCurMethodDecl();
3717 if (!MD) {
3718 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3719 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3720 ObjCImpDecl, HasTemplateArgs);
3722 goto fail;
3725 // Also must look for a getter name which uses property syntax.
3726 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3727 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3728 ObjCMethodDecl *Getter;
3729 if ((Getter = IFace->lookupClassMethod(Sel))) {
3730 // Check the use of this method.
3731 if (DiagnoseUseOfDecl(Getter, MemberLoc))
3732 return ExprError();
3733 } else
3734 Getter = IFace->lookupPrivateMethod(Sel, false);
3735 // If we found a getter then this may be a valid dot-reference, we
3736 // will look for the matching setter, in case it is needed.
3737 Selector SetterSel =
3738 SelectorTable::constructSetterName(PP.getIdentifierTable(),
3739 PP.getSelectorTable(), Member);
3740 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
3741 if (!Setter) {
3742 // If this reference is in an @implementation, also check for 'private'
3743 // methods.
3744 Setter = IFace->lookupPrivateMethod(SetterSel, false);
3746 // Look through local category implementations associated with the class.
3747 if (!Setter)
3748 Setter = IFace->getCategoryClassMethod(SetterSel);
3750 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3751 return ExprError();
3753 if (Getter || Setter) {
3754 QualType PType;
3756 ExprValueKind VK = VK_LValue;
3757 if (Getter) {
3758 PType = Getter->getSendResultType();
3759 if (!getLangOptions().CPlusPlus &&
3760 IsCForbiddenLValueType(Context, PType))
3761 VK = VK_RValue;
3762 } else {
3763 // Get the expression type from Setter's incoming parameter.
3764 PType = (*(Setter->param_end() -1))->getType();
3766 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
3768 // FIXME: we must check that the setter has property type.
3769 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
3770 PType, VK, OK,
3771 MemberLoc, BaseExpr));
3774 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
3775 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3776 ObjCImpDecl, HasTemplateArgs);
3778 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3779 << MemberName << BaseType);
3782 // Normal property access.
3783 return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc,
3784 SourceLocation(), QualType(), false);
3787 // Handle 'field access' to vectors, such as 'V.xx'.
3788 if (BaseType->isExtVectorType()) {
3789 // FIXME: this expr should store IsArrow.
3790 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3791 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr->getValueKind());
3792 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
3793 Member, MemberLoc);
3794 if (ret.isNull())
3795 return ExprError();
3797 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr,
3798 *Member, MemberLoc));
3801 // Adjust builtin-sel to the appropriate redefinition type if that's
3802 // not just a pointer to builtin-sel again.
3803 if (IsArrow &&
3804 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
3805 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
3806 ImpCastExprToType(BaseExpr, Context.ObjCSelRedefinitionType, CK_BitCast);
3807 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3808 ObjCImpDecl, HasTemplateArgs);
3811 // Failure cases.
3812 fail:
3814 // There's a possible road to recovery for function types.
3815 const FunctionType *Fun = 0;
3817 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
3818 if ((Fun = Ptr->getPointeeType()->getAs<FunctionType>())) {
3819 // fall out, handled below.
3821 // Recover from dot accesses to pointers, e.g.:
3822 // type *foo;
3823 // foo.bar
3824 // This is actually well-formed in two cases:
3825 // - 'type' is an Objective C type
3826 // - 'bar' is a pseudo-destructor name which happens to refer to
3827 // the appropriate pointer type
3828 } else if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
3829 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3830 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3831 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3832 << FixItHint::CreateReplacement(OpLoc, "->");
3834 // Recurse as an -> access.
3835 IsArrow = true;
3836 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3837 ObjCImpDecl, HasTemplateArgs);
3839 } else {
3840 Fun = BaseType->getAs<FunctionType>();
3843 // If the user is trying to apply -> or . to a function pointer
3844 // type, it's probably because they forgot parentheses to call that
3845 // function. Suggest the addition of those parentheses, build the
3846 // call, and continue on.
3847 if (Fun || BaseType == Context.OverloadTy) {
3848 bool TryCall;
3849 if (BaseType == Context.OverloadTy) {
3850 TryCall = true;
3851 } else {
3852 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Fun)) {
3853 TryCall = (FPT->getNumArgs() == 0);
3854 } else {
3855 TryCall = true;
3858 if (TryCall) {
3859 QualType ResultTy = Fun->getResultType();
3860 TryCall = (!IsArrow && ResultTy->isRecordType()) ||
3861 (IsArrow && ResultTy->isPointerType() &&
3862 ResultTy->getAs<PointerType>()->getPointeeType()->isRecordType());
3867 if (TryCall) {
3868 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
3869 Diag(BaseExpr->getExprLoc(), diag::err_member_reference_needs_call)
3870 << QualType(Fun, 0)
3871 << FixItHint::CreateInsertion(Loc, "()");
3873 ExprResult NewBase
3874 = ActOnCallExpr(0, BaseExpr, Loc, MultiExprArg(*this, 0, 0), Loc);
3875 if (NewBase.isInvalid())
3876 return ExprError();
3877 BaseExpr = NewBase.takeAs<Expr>();
3880 DefaultFunctionArrayConversion(BaseExpr);
3881 BaseType = BaseExpr->getType();
3883 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
3884 ObjCImpDecl, HasTemplateArgs);
3888 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3889 << BaseType << BaseExpr->getSourceRange();
3891 return ExprError();
3894 /// The main callback when the parser finds something like
3895 /// expression . [nested-name-specifier] identifier
3896 /// expression -> [nested-name-specifier] identifier
3897 /// where 'identifier' encompasses a fairly broad spectrum of
3898 /// possibilities, including destructor and operator references.
3900 /// \param OpKind either tok::arrow or tok::period
3901 /// \param HasTrailingLParen whether the next token is '(', which
3902 /// is used to diagnose mis-uses of special members that can
3903 /// only be called
3904 /// \param ObjCImpDecl the current ObjC @implementation decl;
3905 /// this is an ugly hack around the fact that ObjC @implementations
3906 /// aren't properly put in the context chain
3907 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
3908 SourceLocation OpLoc,
3909 tok::TokenKind OpKind,
3910 CXXScopeSpec &SS,
3911 UnqualifiedId &Id,
3912 Decl *ObjCImpDecl,
3913 bool HasTrailingLParen) {
3914 if (SS.isSet() && SS.isInvalid())
3915 return ExprError();
3917 // Warn about the explicit constructor calls Microsoft extension.
3918 if (getLangOptions().Microsoft &&
3919 Id.getKind() == UnqualifiedId::IK_ConstructorName)
3920 Diag(Id.getSourceRange().getBegin(),
3921 diag::ext_ms_explicit_constructor_call);
3923 TemplateArgumentListInfo TemplateArgsBuffer;
3925 // Decompose the name into its component parts.
3926 DeclarationNameInfo NameInfo;
3927 const TemplateArgumentListInfo *TemplateArgs;
3928 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3929 NameInfo, TemplateArgs);
3931 DeclarationName Name = NameInfo.getName();
3932 bool IsArrow = (OpKind == tok::arrow);
3934 NamedDecl *FirstQualifierInScope
3935 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3936 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3938 // This is a postfix expression, so get rid of ParenListExprs.
3939 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3940 if (Result.isInvalid()) return ExprError();
3941 Base = Result.take();
3943 if (Base->getType()->isDependentType() || Name.isDependentName() ||
3944 isDependentScopeSpecifier(SS)) {
3945 Result = ActOnDependentMemberExpr(Base, Base->getType(),
3946 IsArrow, OpLoc,
3947 SS, FirstQualifierInScope,
3948 NameInfo, TemplateArgs);
3949 } else {
3950 LookupResult R(*this, NameInfo, LookupMemberName);
3951 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3952 SS, ObjCImpDecl, TemplateArgs != 0);
3954 if (Result.isInvalid()) {
3955 Owned(Base);
3956 return ExprError();
3959 if (Result.get()) {
3960 // The only way a reference to a destructor can be used is to
3961 // immediately call it, which falls into this case. If the
3962 // next token is not a '(', produce a diagnostic and build the
3963 // call now.
3964 if (!HasTrailingLParen &&
3965 Id.getKind() == UnqualifiedId::IK_DestructorName)
3966 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
3968 return move(Result);
3971 Result = BuildMemberReferenceExpr(Base, Base->getType(),
3972 OpLoc, IsArrow, SS, FirstQualifierInScope,
3973 R, TemplateArgs);
3976 return move(Result);
3979 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3980 FunctionDecl *FD,
3981 ParmVarDecl *Param) {
3982 if (Param->hasUnparsedDefaultArg()) {
3983 Diag(CallLoc,
3984 diag::err_use_of_default_argument_to_function_declared_later) <<
3985 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3986 Diag(UnparsedDefaultArgLocs[Param],
3987 diag::note_default_argument_declared_here);
3988 return ExprError();
3991 if (Param->hasUninstantiatedDefaultArg()) {
3992 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3994 // Instantiate the expression.
3995 MultiLevelTemplateArgumentList ArgList
3996 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3998 std::pair<const TemplateArgument *, unsigned> Innermost
3999 = ArgList.getInnermost();
4000 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
4001 Innermost.second);
4003 ExprResult Result;
4005 // C++ [dcl.fct.default]p5:
4006 // The names in the [default argument] expression are bound, and
4007 // the semantic constraints are checked, at the point where the
4008 // default argument expression appears.
4009 ContextRAII SavedContext(*this, FD);
4010 Result = SubstExpr(UninstExpr, ArgList);
4012 if (Result.isInvalid())
4013 return ExprError();
4015 // Check the expression as an initializer for the parameter.
4016 InitializedEntity Entity
4017 = InitializedEntity::InitializeParameter(Context, Param);
4018 InitializationKind Kind
4019 = InitializationKind::CreateCopy(Param->getLocation(),
4020 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
4021 Expr *ResultE = Result.takeAs<Expr>();
4023 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
4024 Result = InitSeq.Perform(*this, Entity, Kind,
4025 MultiExprArg(*this, &ResultE, 1));
4026 if (Result.isInvalid())
4027 return ExprError();
4029 // Build the default argument expression.
4030 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
4031 Result.takeAs<Expr>()));
4034 // If the default expression creates temporaries, we need to
4035 // push them to the current stack of expression temporaries so they'll
4036 // be properly destroyed.
4037 // FIXME: We should really be rebuilding the default argument with new
4038 // bound temporaries; see the comment in PR5810.
4039 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
4040 CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
4041 MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(),
4042 const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
4043 ExprTemporaries.push_back(Temporary);
4046 // We already type-checked the argument, so we know it works.
4047 // Just mark all of the declarations in this potentially-evaluated expression
4048 // as being "referenced".
4049 MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
4050 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
4053 /// ConvertArgumentsForCall - Converts the arguments specified in
4054 /// Args/NumArgs to the parameter types of the function FDecl with
4055 /// function prototype Proto. Call is the call expression itself, and
4056 /// Fn is the function expression. For a C++ member function, this
4057 /// routine does not attempt to convert the object argument. Returns
4058 /// true if the call is ill-formed.
4059 bool
4060 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4061 FunctionDecl *FDecl,
4062 const FunctionProtoType *Proto,
4063 Expr **Args, unsigned NumArgs,
4064 SourceLocation RParenLoc) {
4065 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4066 // assignment, to the types of the corresponding parameter, ...
4067 unsigned NumArgsInProto = Proto->getNumArgs();
4068 bool Invalid = false;
4070 // If too few arguments are available (and we don't have default
4071 // arguments for the remaining parameters), don't make the call.
4072 if (NumArgs < NumArgsInProto) {
4073 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
4074 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4075 << Fn->getType()->isBlockPointerType()
4076 << NumArgsInProto << NumArgs << Fn->getSourceRange();
4077 Call->setNumArgs(Context, NumArgsInProto);
4080 // If too many are passed and not variadic, error on the extras and drop
4081 // them.
4082 if (NumArgs > NumArgsInProto) {
4083 if (!Proto->isVariadic()) {
4084 Diag(Args[NumArgsInProto]->getLocStart(),
4085 diag::err_typecheck_call_too_many_args)
4086 << Fn->getType()->isBlockPointerType()
4087 << NumArgsInProto << NumArgs << Fn->getSourceRange()
4088 << SourceRange(Args[NumArgsInProto]->getLocStart(),
4089 Args[NumArgs-1]->getLocEnd());
4090 // This deletes the extra arguments.
4091 Call->setNumArgs(Context, NumArgsInProto);
4092 return true;
4095 llvm::SmallVector<Expr *, 8> AllArgs;
4096 VariadicCallType CallType =
4097 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
4098 if (Fn->getType()->isBlockPointerType())
4099 CallType = VariadicBlock; // Block
4100 else if (isa<MemberExpr>(Fn))
4101 CallType = VariadicMethod;
4102 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
4103 Proto, 0, Args, NumArgs, AllArgs, CallType);
4104 if (Invalid)
4105 return true;
4106 unsigned TotalNumArgs = AllArgs.size();
4107 for (unsigned i = 0; i < TotalNumArgs; ++i)
4108 Call->setArg(i, AllArgs[i]);
4110 return false;
4113 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
4114 FunctionDecl *FDecl,
4115 const FunctionProtoType *Proto,
4116 unsigned FirstProtoArg,
4117 Expr **Args, unsigned NumArgs,
4118 llvm::SmallVector<Expr *, 8> &AllArgs,
4119 VariadicCallType CallType) {
4120 unsigned NumArgsInProto = Proto->getNumArgs();
4121 unsigned NumArgsToCheck = NumArgs;
4122 bool Invalid = false;
4123 if (NumArgs != NumArgsInProto)
4124 // Use default arguments for missing arguments
4125 NumArgsToCheck = NumArgsInProto;
4126 unsigned ArgIx = 0;
4127 // Continue to check argument types (even if we have too few/many args).
4128 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
4129 QualType ProtoArgType = Proto->getArgType(i);
4131 Expr *Arg;
4132 if (ArgIx < NumArgs) {
4133 Arg = Args[ArgIx++];
4135 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4136 ProtoArgType,
4137 PDiag(diag::err_call_incomplete_argument)
4138 << Arg->getSourceRange()))
4139 return true;
4141 // Pass the argument
4142 ParmVarDecl *Param = 0;
4143 if (FDecl && i < FDecl->getNumParams())
4144 Param = FDecl->getParamDecl(i);
4146 InitializedEntity Entity =
4147 Param? InitializedEntity::InitializeParameter(Context, Param)
4148 : InitializedEntity::InitializeParameter(Context, ProtoArgType);
4149 ExprResult ArgE = PerformCopyInitialization(Entity,
4150 SourceLocation(),
4151 Owned(Arg));
4152 if (ArgE.isInvalid())
4153 return true;
4155 Arg = ArgE.takeAs<Expr>();
4156 } else {
4157 ParmVarDecl *Param = FDecl->getParamDecl(i);
4159 ExprResult ArgExpr =
4160 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4161 if (ArgExpr.isInvalid())
4162 return true;
4164 Arg = ArgExpr.takeAs<Expr>();
4166 AllArgs.push_back(Arg);
4169 // If this is a variadic call, handle args passed through "...".
4170 if (CallType != VariadicDoesNotApply) {
4171 // Promote the arguments (C99 6.5.2.2p7).
4172 for (unsigned i = ArgIx; i != NumArgs; ++i) {
4173 Expr *Arg = Args[i];
4174 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
4175 AllArgs.push_back(Arg);
4178 return Invalid;
4181 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4182 /// This provides the location of the left/right parens and a list of comma
4183 /// locations.
4184 ExprResult
4185 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4186 MultiExprArg args, SourceLocation RParenLoc) {
4187 unsigned NumArgs = args.size();
4189 // Since this might be a postfix expression, get rid of ParenListExprs.
4190 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4191 if (Result.isInvalid()) return ExprError();
4192 Fn = Result.take();
4194 Expr **Args = args.release();
4196 if (getLangOptions().CPlusPlus) {
4197 // If this is a pseudo-destructor expression, build the call immediately.
4198 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4199 if (NumArgs > 0) {
4200 // Pseudo-destructor calls should not have any arguments.
4201 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4202 << FixItHint::CreateRemoval(
4203 SourceRange(Args[0]->getLocStart(),
4204 Args[NumArgs-1]->getLocEnd()));
4206 NumArgs = 0;
4209 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
4210 VK_RValue, RParenLoc));
4213 // Determine whether this is a dependent call inside a C++ template,
4214 // in which case we won't do any semantic analysis now.
4215 // FIXME: Will need to cache the results of name lookup (including ADL) in
4216 // Fn.
4217 bool Dependent = false;
4218 if (Fn->isTypeDependent())
4219 Dependent = true;
4220 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
4221 Dependent = true;
4223 if (Dependent)
4224 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
4225 Context.DependentTy, VK_RValue,
4226 RParenLoc));
4228 // Determine whether this is a call to an object (C++ [over.call.object]).
4229 if (Fn->getType()->isRecordType())
4230 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
4231 RParenLoc));
4233 Expr *NakedFn = Fn->IgnoreParens();
4235 // Determine whether this is a call to an unresolved member function.
4236 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
4237 // If lookup was unresolved but not dependent (i.e. didn't find
4238 // an unresolved using declaration), it has to be an overloaded
4239 // function set, which means it must contain either multiple
4240 // declarations (all methods or method templates) or a single
4241 // method template.
4242 assert((MemE->getNumDecls() > 1) ||
4243 isa<FunctionTemplateDecl>(
4244 (*MemE->decls_begin())->getUnderlyingDecl()));
4245 (void)MemE;
4247 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
4248 RParenLoc);
4251 // Determine whether this is a call to a member function.
4252 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
4253 NamedDecl *MemDecl = MemExpr->getMemberDecl();
4254 if (isa<CXXMethodDecl>(MemDecl))
4255 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
4256 RParenLoc);
4259 // Determine whether this is a call to a pointer-to-member function.
4260 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
4261 if (BO->getOpcode() == BO_PtrMemD ||
4262 BO->getOpcode() == BO_PtrMemI) {
4263 if (const FunctionProtoType *FPT
4264 = BO->getType()->getAs<FunctionProtoType>()) {
4265 QualType ResultTy = FPT->getCallResultType(Context);
4266 ExprValueKind VK = Expr::getValueKindForType(FPT->getResultType());
4268 CXXMemberCallExpr *TheCall
4269 = new (Context) CXXMemberCallExpr(Context, Fn, Args,
4270 NumArgs, ResultTy, VK,
4271 RParenLoc);
4273 if (CheckCallReturnType(FPT->getResultType(),
4274 BO->getRHS()->getSourceRange().getBegin(),
4275 TheCall, 0))
4276 return ExprError();
4278 if (ConvertArgumentsForCall(TheCall, BO, 0, FPT, Args, NumArgs,
4279 RParenLoc))
4280 return ExprError();
4282 return MaybeBindToTemporary(TheCall);
4284 return ExprError(Diag(Fn->getLocStart(),
4285 diag::err_typecheck_call_not_function)
4286 << Fn->getType() << Fn->getSourceRange());
4291 // If we're directly calling a function, get the appropriate declaration.
4292 // Also, in C++, keep track of whether we should perform argument-dependent
4293 // lookup and whether there were any explicitly-specified template arguments.
4295 Expr *NakedFn = Fn->IgnoreParens();
4296 if (isa<UnresolvedLookupExpr>(NakedFn)) {
4297 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
4298 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
4299 RParenLoc);
4302 NamedDecl *NDecl = 0;
4303 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4304 if (UnOp->getOpcode() == UO_AddrOf)
4305 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4307 if (isa<DeclRefExpr>(NakedFn))
4308 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4310 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
4313 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4314 /// i.e. an expression not of \p OverloadTy. The expression should
4315 /// unary-convert to an expression of function-pointer or
4316 /// block-pointer type.
4318 /// \param NDecl the declaration being called, if available
4319 ExprResult
4320 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4321 SourceLocation LParenLoc,
4322 Expr **Args, unsigned NumArgs,
4323 SourceLocation RParenLoc) {
4324 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4326 // Promote the function operand.
4327 UsualUnaryConversions(Fn);
4329 // Make the call expr early, before semantic checks. This guarantees cleanup
4330 // of arguments and function on error.
4331 CallExpr *TheCall = new (Context) CallExpr(Context, Fn,
4332 Args, NumArgs,
4333 Context.BoolTy,
4334 VK_RValue,
4335 RParenLoc);
4337 const FunctionType *FuncT;
4338 if (!Fn->getType()->isBlockPointerType()) {
4339 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4340 // have type pointer to function".
4341 const PointerType *PT = Fn->getType()->getAs<PointerType>();
4342 if (PT == 0)
4343 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4344 << Fn->getType() << Fn->getSourceRange());
4345 FuncT = PT->getPointeeType()->getAs<FunctionType>();
4346 } else { // This is a block call.
4347 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
4348 getAs<FunctionType>();
4350 if (FuncT == 0)
4351 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4352 << Fn->getType() << Fn->getSourceRange());
4354 // Check for a valid return type
4355 if (CheckCallReturnType(FuncT->getResultType(),
4356 Fn->getSourceRange().getBegin(), TheCall,
4357 FDecl))
4358 return ExprError();
4360 // We know the result type of the call, set it.
4361 TheCall->setType(FuncT->getCallResultType(Context));
4362 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4364 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
4365 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4366 RParenLoc))
4367 return ExprError();
4368 } else {
4369 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4371 if (FDecl) {
4372 // Check if we have too few/too many template arguments, based
4373 // on our knowledge of the function definition.
4374 const FunctionDecl *Def = 0;
4375 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4376 const FunctionProtoType *Proto
4377 = Def->getType()->getAs<FunctionProtoType>();
4378 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4379 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4380 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4383 // If the function we're calling isn't a function prototype, but we have
4384 // a function prototype from a prior declaratiom, use that prototype.
4385 if (!FDecl->hasPrototype())
4386 Proto = FDecl->getType()->getAs<FunctionProtoType>();
4389 // Promote the arguments (C99 6.5.2.2p6).
4390 for (unsigned i = 0; i != NumArgs; i++) {
4391 Expr *Arg = Args[i];
4393 if (Proto && i < Proto->getNumArgs()) {
4394 InitializedEntity Entity
4395 = InitializedEntity::InitializeParameter(Context,
4396 Proto->getArgType(i));
4397 ExprResult ArgE = PerformCopyInitialization(Entity,
4398 SourceLocation(),
4399 Owned(Arg));
4400 if (ArgE.isInvalid())
4401 return true;
4403 Arg = ArgE.takeAs<Expr>();
4405 } else {
4406 DefaultArgumentPromotion(Arg);
4409 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
4410 Arg->getType(),
4411 PDiag(diag::err_call_incomplete_argument)
4412 << Arg->getSourceRange()))
4413 return ExprError();
4415 TheCall->setArg(i, Arg);
4419 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4420 if (!Method->isStatic())
4421 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4422 << Fn->getSourceRange());
4424 // Check for sentinels
4425 if (NDecl)
4426 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4428 // Do special checking on direct calls to functions.
4429 if (FDecl) {
4430 if (CheckFunctionCall(FDecl, TheCall))
4431 return ExprError();
4433 if (unsigned BuiltinID = FDecl->getBuiltinID())
4434 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4435 } else if (NDecl) {
4436 if (CheckBlockCall(NDecl, TheCall))
4437 return ExprError();
4440 return MaybeBindToTemporary(TheCall);
4443 ExprResult
4444 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4445 SourceLocation RParenLoc, Expr *InitExpr) {
4446 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4447 // FIXME: put back this assert when initializers are worked out.
4448 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4450 TypeSourceInfo *TInfo;
4451 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4452 if (!TInfo)
4453 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4455 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4458 ExprResult
4459 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4460 SourceLocation RParenLoc, Expr *literalExpr) {
4461 QualType literalType = TInfo->getType();
4463 if (literalType->isArrayType()) {
4464 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4465 PDiag(diag::err_illegal_decl_array_incomplete_type)
4466 << SourceRange(LParenLoc,
4467 literalExpr->getSourceRange().getEnd())))
4468 return ExprError();
4469 if (literalType->isVariableArrayType())
4470 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4471 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
4472 } else if (!literalType->isDependentType() &&
4473 RequireCompleteType(LParenLoc, literalType,
4474 PDiag(diag::err_typecheck_decl_incomplete_type)
4475 << SourceRange(LParenLoc,
4476 literalExpr->getSourceRange().getEnd())))
4477 return ExprError();
4479 InitializedEntity Entity
4480 = InitializedEntity::InitializeTemporary(literalType);
4481 InitializationKind Kind
4482 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
4483 /*IsCStyleCast=*/true);
4484 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
4485 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
4486 MultiExprArg(*this, &literalExpr, 1),
4487 &literalType);
4488 if (Result.isInvalid())
4489 return ExprError();
4490 literalExpr = Result.get();
4492 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4493 if (isFileScope) { // 6.5.2.5p3
4494 if (CheckForConstantInitializer(literalExpr, literalType))
4495 return ExprError();
4498 // In C, compound literals are l-values for some reason.
4499 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
4501 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4502 VK, literalExpr, isFileScope));
4505 ExprResult
4506 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
4507 SourceLocation RBraceLoc) {
4508 unsigned NumInit = initlist.size();
4509 Expr **InitList = initlist.release();
4511 // Semantic analysis for initializers is done by ActOnDeclarator() and
4512 // CheckInitializer() - it requires knowledge of the object being intialized.
4514 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4515 NumInit, RBraceLoc);
4516 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4517 return Owned(E);
4520 /// Prepares for a scalar cast, performing all the necessary stages
4521 /// except the final cast and returning the kind required.
4522 static CastKind PrepareScalarCast(Sema &S, Expr *&Src, QualType DestTy) {
4523 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4524 // Also, callers should have filtered out the invalid cases with
4525 // pointers. Everything else should be possible.
4527 QualType SrcTy = Src->getType();
4528 if (S.Context.hasSameUnqualifiedType(SrcTy, DestTy))
4529 return CK_NoOp;
4531 switch (SrcTy->getScalarTypeKind()) {
4532 case Type::STK_MemberPointer:
4533 llvm_unreachable("member pointer type in C");
4535 case Type::STK_Pointer:
4536 switch (DestTy->getScalarTypeKind()) {
4537 case Type::STK_Pointer:
4538 return DestTy->isObjCObjectPointerType() ?
4539 CK_AnyPointerToObjCPointerCast :
4540 CK_BitCast;
4541 case Type::STK_Bool:
4542 return CK_PointerToBoolean;
4543 case Type::STK_Integral:
4544 return CK_PointerToIntegral;
4545 case Type::STK_Floating:
4546 case Type::STK_FloatingComplex:
4547 case Type::STK_IntegralComplex:
4548 case Type::STK_MemberPointer:
4549 llvm_unreachable("illegal cast from pointer");
4551 break;
4553 case Type::STK_Bool: // casting from bool is like casting from an integer
4554 case Type::STK_Integral:
4555 switch (DestTy->getScalarTypeKind()) {
4556 case Type::STK_Pointer:
4557 if (Src->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNull))
4558 return CK_NullToPointer;
4559 return CK_IntegralToPointer;
4560 case Type::STK_Bool:
4561 return CK_IntegralToBoolean;
4562 case Type::STK_Integral:
4563 return CK_IntegralCast;
4564 case Type::STK_Floating:
4565 return CK_IntegralToFloating;
4566 case Type::STK_IntegralComplex:
4567 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4568 CK_IntegralCast);
4569 return CK_IntegralRealToComplex;
4570 case Type::STK_FloatingComplex:
4571 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4572 CK_IntegralToFloating);
4573 return CK_FloatingRealToComplex;
4574 case Type::STK_MemberPointer:
4575 llvm_unreachable("member pointer type in C");
4577 break;
4579 case Type::STK_Floating:
4580 switch (DestTy->getScalarTypeKind()) {
4581 case Type::STK_Floating:
4582 return CK_FloatingCast;
4583 case Type::STK_Bool:
4584 return CK_FloatingToBoolean;
4585 case Type::STK_Integral:
4586 return CK_FloatingToIntegral;
4587 case Type::STK_FloatingComplex:
4588 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4589 CK_FloatingCast);
4590 return CK_FloatingRealToComplex;
4591 case Type::STK_IntegralComplex:
4592 S.ImpCastExprToType(Src, DestTy->getAs<ComplexType>()->getElementType(),
4593 CK_FloatingToIntegral);
4594 return CK_IntegralRealToComplex;
4595 case Type::STK_Pointer:
4596 llvm_unreachable("valid float->pointer cast?");
4597 case Type::STK_MemberPointer:
4598 llvm_unreachable("member pointer type in C");
4600 break;
4602 case Type::STK_FloatingComplex:
4603 switch (DestTy->getScalarTypeKind()) {
4604 case Type::STK_FloatingComplex:
4605 return CK_FloatingComplexCast;
4606 case Type::STK_IntegralComplex:
4607 return CK_FloatingComplexToIntegralComplex;
4608 case Type::STK_Floating: {
4609 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
4610 if (S.Context.hasSameType(ET, DestTy))
4611 return CK_FloatingComplexToReal;
4612 S.ImpCastExprToType(Src, ET, CK_FloatingComplexToReal);
4613 return CK_FloatingCast;
4615 case Type::STK_Bool:
4616 return CK_FloatingComplexToBoolean;
4617 case Type::STK_Integral:
4618 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
4619 CK_FloatingComplexToReal);
4620 return CK_FloatingToIntegral;
4621 case Type::STK_Pointer:
4622 llvm_unreachable("valid complex float->pointer cast?");
4623 case Type::STK_MemberPointer:
4624 llvm_unreachable("member pointer type in C");
4626 break;
4628 case Type::STK_IntegralComplex:
4629 switch (DestTy->getScalarTypeKind()) {
4630 case Type::STK_FloatingComplex:
4631 return CK_IntegralComplexToFloatingComplex;
4632 case Type::STK_IntegralComplex:
4633 return CK_IntegralComplexCast;
4634 case Type::STK_Integral: {
4635 QualType ET = SrcTy->getAs<ComplexType>()->getElementType();
4636 if (S.Context.hasSameType(ET, DestTy))
4637 return CK_IntegralComplexToReal;
4638 S.ImpCastExprToType(Src, ET, CK_IntegralComplexToReal);
4639 return CK_IntegralCast;
4641 case Type::STK_Bool:
4642 return CK_IntegralComplexToBoolean;
4643 case Type::STK_Floating:
4644 S.ImpCastExprToType(Src, SrcTy->getAs<ComplexType>()->getElementType(),
4645 CK_IntegralComplexToReal);
4646 return CK_IntegralToFloating;
4647 case Type::STK_Pointer:
4648 llvm_unreachable("valid complex int->pointer cast?");
4649 case Type::STK_MemberPointer:
4650 llvm_unreachable("member pointer type in C");
4652 break;
4655 llvm_unreachable("Unhandled scalar cast");
4656 return CK_BitCast;
4659 /// CheckCastTypes - Check type constraints for casting between types.
4660 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType,
4661 Expr *&castExpr, CastKind& Kind, ExprValueKind &VK,
4662 CXXCastPath &BasePath, bool FunctionalStyle) {
4663 if (getLangOptions().CPlusPlus)
4664 return CXXCheckCStyleCast(SourceRange(TyR.getBegin(),
4665 castExpr->getLocEnd()),
4666 castType, VK, castExpr, Kind, BasePath,
4667 FunctionalStyle);
4669 // We only support r-value casts in C.
4670 VK = VK_RValue;
4672 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
4673 // type needs to be scalar.
4674 if (castType->isVoidType()) {
4675 // We don't necessarily do lvalue-to-rvalue conversions on this.
4676 IgnoredValueConversions(castExpr);
4678 // Cast to void allows any expr type.
4679 Kind = CK_ToVoid;
4680 return false;
4683 DefaultFunctionArrayLvalueConversion(castExpr);
4685 if (RequireCompleteType(TyR.getBegin(), castType,
4686 diag::err_typecheck_cast_to_incomplete))
4687 return true;
4689 if (!castType->isScalarType() && !castType->isVectorType()) {
4690 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
4691 (castType->isStructureType() || castType->isUnionType())) {
4692 // GCC struct/union extension: allow cast to self.
4693 // FIXME: Check that the cast destination type is complete.
4694 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
4695 << castType << castExpr->getSourceRange();
4696 Kind = CK_NoOp;
4697 return false;
4700 if (castType->isUnionType()) {
4701 // GCC cast to union extension
4702 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
4703 RecordDecl::field_iterator Field, FieldEnd;
4704 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
4705 Field != FieldEnd; ++Field) {
4706 if (Context.hasSameUnqualifiedType(Field->getType(),
4707 castExpr->getType()) &&
4708 !Field->isUnnamedBitfield()) {
4709 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
4710 << castExpr->getSourceRange();
4711 break;
4714 if (Field == FieldEnd)
4715 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
4716 << castExpr->getType() << castExpr->getSourceRange();
4717 Kind = CK_ToUnion;
4718 return false;
4721 // Reject any other conversions to non-scalar types.
4722 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
4723 << castType << castExpr->getSourceRange();
4726 // The type we're casting to is known to be a scalar or vector.
4728 // Require the operand to be a scalar or vector.
4729 if (!castExpr->getType()->isScalarType() &&
4730 !castExpr->getType()->isVectorType()) {
4731 return Diag(castExpr->getLocStart(),
4732 diag::err_typecheck_expect_scalar_operand)
4733 << castExpr->getType() << castExpr->getSourceRange();
4736 if (castType->isExtVectorType())
4737 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
4739 if (castType->isVectorType())
4740 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
4741 if (castExpr->getType()->isVectorType())
4742 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
4744 // The source and target types are both scalars, i.e.
4745 // - arithmetic types (fundamental, enum, and complex)
4746 // - all kinds of pointers
4747 // Note that member pointers were filtered out with C++, above.
4749 if (isa<ObjCSelectorExpr>(castExpr))
4750 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
4752 // If either type is a pointer, the other type has to be either an
4753 // integer or a pointer.
4754 if (!castType->isArithmeticType()) {
4755 QualType castExprType = castExpr->getType();
4756 if (!castExprType->isIntegralType(Context) &&
4757 castExprType->isArithmeticType())
4758 return Diag(castExpr->getLocStart(),
4759 diag::err_cast_pointer_from_non_pointer_int)
4760 << castExprType << castExpr->getSourceRange();
4761 } else if (!castExpr->getType()->isArithmeticType()) {
4762 if (!castType->isIntegralType(Context) && castType->isArithmeticType())
4763 return Diag(castExpr->getLocStart(),
4764 diag::err_cast_pointer_to_non_pointer_int)
4765 << castType << castExpr->getSourceRange();
4768 Kind = PrepareScalarCast(*this, castExpr, castType);
4770 if (Kind == CK_BitCast)
4771 CheckCastAlign(castExpr, castType, TyR);
4773 return false;
4776 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4777 CastKind &Kind) {
4778 assert(VectorTy->isVectorType() && "Not a vector type!");
4780 if (Ty->isVectorType() || Ty->isIntegerType()) {
4781 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4782 return Diag(R.getBegin(),
4783 Ty->isVectorType() ?
4784 diag::err_invalid_conversion_between_vectors :
4785 diag::err_invalid_conversion_between_vector_and_integer)
4786 << VectorTy << Ty << R;
4787 } else
4788 return Diag(R.getBegin(),
4789 diag::err_invalid_conversion_between_vector_and_scalar)
4790 << VectorTy << Ty << R;
4792 Kind = CK_BitCast;
4793 return false;
4796 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
4797 CastKind &Kind) {
4798 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4800 QualType SrcTy = CastExpr->getType();
4802 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4803 // an ExtVectorType.
4804 if (SrcTy->isVectorType()) {
4805 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
4806 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4807 << DestTy << SrcTy << R;
4808 Kind = CK_BitCast;
4809 return false;
4812 // All non-pointer scalars can be cast to ExtVector type. The appropriate
4813 // conversion will take place first from scalar to elt type, and then
4814 // splat from elt type to vector.
4815 if (SrcTy->isPointerType())
4816 return Diag(R.getBegin(),
4817 diag::err_invalid_conversion_between_vector_and_scalar)
4818 << DestTy << SrcTy << R;
4820 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4821 ImpCastExprToType(CastExpr, DestElemTy,
4822 PrepareScalarCast(*this, CastExpr, DestElemTy));
4824 Kind = CK_VectorSplat;
4825 return false;
4828 ExprResult
4829 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, ParsedType Ty,
4830 SourceLocation RParenLoc, Expr *castExpr) {
4831 assert((Ty != 0) && (castExpr != 0) &&
4832 "ActOnCastExpr(): missing type or expr");
4834 TypeSourceInfo *castTInfo;
4835 QualType castType = GetTypeFromParser(Ty, &castTInfo);
4836 if (!castTInfo)
4837 castTInfo = Context.getTrivialTypeSourceInfo(castType);
4839 // If the Expr being casted is a ParenListExpr, handle it specially.
4840 if (isa<ParenListExpr>(castExpr))
4841 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, castExpr,
4842 castTInfo);
4844 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, castExpr);
4847 ExprResult
4848 Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
4849 SourceLocation RParenLoc, Expr *castExpr) {
4850 CastKind Kind = CK_Invalid;
4851 ExprValueKind VK = VK_RValue;
4852 CXXCastPath BasePath;
4853 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
4854 Kind, VK, BasePath))
4855 return ExprError();
4857 return Owned(CStyleCastExpr::Create(Context,
4858 Ty->getType().getNonLValueExprType(Context),
4859 VK, Kind, castExpr, &BasePath, Ty,
4860 LParenLoc, RParenLoc));
4863 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4864 /// of comma binary operators.
4865 ExprResult
4866 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *expr) {
4867 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4868 if (!E)
4869 return Owned(expr);
4871 ExprResult Result(E->getExpr(0));
4873 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4874 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4875 E->getExpr(i));
4877 if (Result.isInvalid()) return ExprError();
4879 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4882 ExprResult
4883 Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4884 SourceLocation RParenLoc, Expr *Op,
4885 TypeSourceInfo *TInfo) {
4886 ParenListExpr *PE = cast<ParenListExpr>(Op);
4887 QualType Ty = TInfo->getType();
4888 bool isAltiVecLiteral = false;
4890 // Check for an altivec literal,
4891 // i.e. all the elements are integer constants.
4892 if (getLangOptions().AltiVec && Ty->isVectorType()) {
4893 if (PE->getNumExprs() == 0) {
4894 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4895 return ExprError();
4897 if (PE->getNumExprs() == 1) {
4898 if (!PE->getExpr(0)->getType()->isVectorType())
4899 isAltiVecLiteral = true;
4901 else
4902 isAltiVecLiteral = true;
4905 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4906 // then handle it as such.
4907 if (isAltiVecLiteral) {
4908 llvm::SmallVector<Expr *, 8> initExprs;
4909 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4910 initExprs.push_back(PE->getExpr(i));
4912 // FIXME: This means that pretty-printing the final AST will produce curly
4913 // braces instead of the original commas.
4914 InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4915 &initExprs[0],
4916 initExprs.size(), RParenLoc);
4917 E->setType(Ty);
4918 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, E);
4919 } else {
4920 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4921 // sequence of BinOp comma operators.
4922 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Op);
4923 if (Result.isInvalid()) return ExprError();
4924 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Result.take());
4928 ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
4929 SourceLocation R,
4930 MultiExprArg Val,
4931 ParsedType TypeOfCast) {
4932 unsigned nexprs = Val.size();
4933 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4934 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4935 Expr *expr;
4936 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4937 expr = new (Context) ParenExpr(L, R, exprs[0]);
4938 else
4939 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
4940 return Owned(expr);
4943 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4944 /// In that case, lhs = cond.
4945 /// C99 6.5.15
4946 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4947 Expr *&SAVE, ExprValueKind &VK,
4948 ExprObjectKind &OK,
4949 SourceLocation QuestionLoc) {
4950 // If both LHS and RHS are overloaded functions, try to resolve them.
4951 if (Context.hasSameType(LHS->getType(), RHS->getType()) &&
4952 LHS->getType()->isSpecificBuiltinType(BuiltinType::Overload)) {
4953 ExprResult LHSResult = CheckPlaceholderExpr(LHS, QuestionLoc);
4954 if (LHSResult.isInvalid())
4955 return QualType();
4957 ExprResult RHSResult = CheckPlaceholderExpr(RHS, QuestionLoc);
4958 if (RHSResult.isInvalid())
4959 return QualType();
4961 LHS = LHSResult.take();
4962 RHS = RHSResult.take();
4965 // C++ is sufficiently different to merit its own checker.
4966 if (getLangOptions().CPlusPlus)
4967 return CXXCheckConditionalOperands(Cond, LHS, RHS, SAVE,
4968 VK, OK, QuestionLoc);
4970 VK = VK_RValue;
4971 OK = OK_Ordinary;
4973 UsualUnaryConversions(Cond);
4974 if (SAVE) {
4975 SAVE = LHS = Cond;
4977 else
4978 UsualUnaryConversions(LHS);
4979 UsualUnaryConversions(RHS);
4980 QualType CondTy = Cond->getType();
4981 QualType LHSTy = LHS->getType();
4982 QualType RHSTy = RHS->getType();
4984 // first, check the condition.
4985 if (!CondTy->isScalarType()) { // C99 6.5.15p2
4986 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4987 // Throw an error if its not either.
4988 if (getLangOptions().OpenCL) {
4989 if (!CondTy->isVectorType()) {
4990 Diag(Cond->getLocStart(),
4991 diag::err_typecheck_cond_expect_scalar_or_vector)
4992 << CondTy;
4993 return QualType();
4996 else {
4997 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4998 << CondTy;
4999 return QualType();
5003 // Now check the two expressions.
5004 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5005 return CheckVectorOperands(QuestionLoc, LHS, RHS);
5007 // OpenCL: If the condition is a vector, and both operands are scalar,
5008 // attempt to implicity convert them to the vector type to act like the
5009 // built in select.
5010 if (getLangOptions().OpenCL && CondTy->isVectorType()) {
5011 // Both operands should be of scalar type.
5012 if (!LHSTy->isScalarType()) {
5013 Diag(LHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5014 << CondTy;
5015 return QualType();
5017 if (!RHSTy->isScalarType()) {
5018 Diag(RHS->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5019 << CondTy;
5020 return QualType();
5022 // Implicity convert these scalars to the type of the condition.
5023 ImpCastExprToType(LHS, CondTy, CK_IntegralCast);
5024 ImpCastExprToType(RHS, CondTy, CK_IntegralCast);
5027 // If both operands have arithmetic type, do the usual arithmetic conversions
5028 // to find a common type: C99 6.5.15p3,5.
5029 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5030 UsualArithmeticConversions(LHS, RHS);
5031 return LHS->getType();
5034 // If both operands are the same structure or union type, the result is that
5035 // type.
5036 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5037 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5038 if (LHSRT->getDecl() == RHSRT->getDecl())
5039 // "If both the operands have structure or union type, the result has
5040 // that type." This implies that CV qualifiers are dropped.
5041 return LHSTy.getUnqualifiedType();
5042 // FIXME: Type of conditional expression must be complete in C mode.
5045 // C99 6.5.15p5: "If both operands have void type, the result has void type."
5046 // The following || allows only one side to be void (a GCC-ism).
5047 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5048 if (!LHSTy->isVoidType())
5049 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5050 << RHS->getSourceRange();
5051 if (!RHSTy->isVoidType())
5052 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
5053 << LHS->getSourceRange();
5054 ImpCastExprToType(LHS, Context.VoidTy, CK_ToVoid);
5055 ImpCastExprToType(RHS, Context.VoidTy, CK_ToVoid);
5056 return Context.VoidTy;
5058 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5059 // the type of the other operand."
5060 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
5061 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5062 // promote the null to a pointer.
5063 ImpCastExprToType(RHS, LHSTy, CK_NullToPointer);
5064 return LHSTy;
5066 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
5067 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5068 ImpCastExprToType(LHS, RHSTy, CK_NullToPointer);
5069 return RHSTy;
5072 // All objective-c pointer type analysis is done here.
5073 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5074 QuestionLoc);
5075 if (!compositeType.isNull())
5076 return compositeType;
5079 // Handle block pointer types.
5080 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
5081 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5082 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5083 QualType destType = Context.getPointerType(Context.VoidTy);
5084 ImpCastExprToType(LHS, destType, CK_BitCast);
5085 ImpCastExprToType(RHS, destType, CK_BitCast);
5086 return destType;
5088 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5089 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5090 return QualType();
5092 // We have 2 block pointer types.
5093 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5094 // Two identical block pointer types are always compatible.
5095 return LHSTy;
5097 // The block pointer types aren't identical, continue checking.
5098 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
5099 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
5101 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5102 rhptee.getUnqualifiedType())) {
5103 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5104 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5105 // In this situation, we assume void* type. No especially good
5106 // reason, but this is what gcc does, and we do have to pick
5107 // to get a consistent AST.
5108 QualType incompatTy = Context.getPointerType(Context.VoidTy);
5109 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5110 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5111 return incompatTy;
5113 // The block pointer types are compatible.
5114 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5115 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5116 return LHSTy;
5119 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5120 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
5121 // get the "pointed to" types
5122 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5123 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5125 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5126 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5127 // Figure out necessary qualifiers (C99 6.5.15p6)
5128 QualType destPointee
5129 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5130 QualType destType = Context.getPointerType(destPointee);
5131 // Add qualifiers if necessary.
5132 ImpCastExprToType(LHS, destType, CK_NoOp);
5133 // Promote to void*.
5134 ImpCastExprToType(RHS, destType, CK_BitCast);
5135 return destType;
5137 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5138 QualType destPointee
5139 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5140 QualType destType = Context.getPointerType(destPointee);
5141 // Add qualifiers if necessary.
5142 ImpCastExprToType(RHS, destType, CK_NoOp);
5143 // Promote to void*.
5144 ImpCastExprToType(LHS, destType, CK_BitCast);
5145 return destType;
5148 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5149 // Two identical pointer types are always compatible.
5150 return LHSTy;
5152 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
5153 rhptee.getUnqualifiedType())) {
5154 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
5155 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5156 // In this situation, we assume void* type. No especially good
5157 // reason, but this is what gcc does, and we do have to pick
5158 // to get a consistent AST.
5159 QualType incompatTy = Context.getPointerType(Context.VoidTy);
5160 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5161 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5162 return incompatTy;
5164 // The pointer types are compatible.
5165 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
5166 // differently qualified versions of compatible types, the result type is
5167 // a pointer to an appropriately qualified version of the *composite*
5168 // type.
5169 // FIXME: Need to calculate the composite type.
5170 // FIXME: Need to add qualifiers
5171 ImpCastExprToType(LHS, LHSTy, CK_BitCast);
5172 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5173 return LHSTy;
5176 // GCC compatibility: soften pointer/integer mismatch. Note that
5177 // null pointers have been filtered out by this point.
5178 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
5179 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5180 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5181 ImpCastExprToType(LHS, RHSTy, CK_IntegralToPointer);
5182 return RHSTy;
5184 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
5185 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5186 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5187 ImpCastExprToType(RHS, LHSTy, CK_IntegralToPointer);
5188 return LHSTy;
5191 // Otherwise, the operands are not compatible.
5192 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5193 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
5194 return QualType();
5197 /// FindCompositeObjCPointerType - Helper method to find composite type of
5198 /// two objective-c pointer types of the two input expressions.
5199 QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
5200 SourceLocation QuestionLoc) {
5201 QualType LHSTy = LHS->getType();
5202 QualType RHSTy = RHS->getType();
5204 // Handle things like Class and struct objc_class*. Here we case the result
5205 // to the pseudo-builtin, because that will be implicitly cast back to the
5206 // redefinition type if an attempt is made to access its fields.
5207 if (LHSTy->isObjCClassType() &&
5208 (Context.hasSameType(RHSTy, Context.ObjCClassRedefinitionType))) {
5209 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5210 return LHSTy;
5212 if (RHSTy->isObjCClassType() &&
5213 (Context.hasSameType(LHSTy, Context.ObjCClassRedefinitionType))) {
5214 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5215 return RHSTy;
5217 // And the same for struct objc_object* / id
5218 if (LHSTy->isObjCIdType() &&
5219 (Context.hasSameType(RHSTy, Context.ObjCIdRedefinitionType))) {
5220 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5221 return LHSTy;
5223 if (RHSTy->isObjCIdType() &&
5224 (Context.hasSameType(LHSTy, Context.ObjCIdRedefinitionType))) {
5225 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5226 return RHSTy;
5228 // And the same for struct objc_selector* / SEL
5229 if (Context.isObjCSelType(LHSTy) &&
5230 (Context.hasSameType(RHSTy, Context.ObjCSelRedefinitionType))) {
5231 ImpCastExprToType(RHS, LHSTy, CK_BitCast);
5232 return LHSTy;
5234 if (Context.isObjCSelType(RHSTy) &&
5235 (Context.hasSameType(LHSTy, Context.ObjCSelRedefinitionType))) {
5236 ImpCastExprToType(LHS, RHSTy, CK_BitCast);
5237 return RHSTy;
5239 // Check constraints for Objective-C object pointers types.
5240 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5242 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5243 // Two identical object pointer types are always compatible.
5244 return LHSTy;
5246 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
5247 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
5248 QualType compositeType = LHSTy;
5250 // If both operands are interfaces and either operand can be
5251 // assigned to the other, use that type as the composite
5252 // type. This allows
5253 // xxx ? (A*) a : (B*) b
5254 // where B is a subclass of A.
5256 // Additionally, as for assignment, if either type is 'id'
5257 // allow silent coercion. Finally, if the types are
5258 // incompatible then make sure to use 'id' as the composite
5259 // type so the result is acceptable for sending messages to.
5261 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5262 // It could return the composite type.
5263 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5264 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5265 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5266 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5267 } else if ((LHSTy->isObjCQualifiedIdType() ||
5268 RHSTy->isObjCQualifiedIdType()) &&
5269 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5270 // Need to handle "id<xx>" explicitly.
5271 // GCC allows qualified id and any Objective-C type to devolve to
5272 // id. Currently localizing to here until clear this should be
5273 // part of ObjCQualifiedIdTypesAreCompatible.
5274 compositeType = Context.getObjCIdType();
5275 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5276 compositeType = Context.getObjCIdType();
5277 } else if (!(compositeType =
5278 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5280 else {
5281 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5282 << LHSTy << RHSTy
5283 << LHS->getSourceRange() << RHS->getSourceRange();
5284 QualType incompatTy = Context.getObjCIdType();
5285 ImpCastExprToType(LHS, incompatTy, CK_BitCast);
5286 ImpCastExprToType(RHS, incompatTy, CK_BitCast);
5287 return incompatTy;
5289 // The object pointer types are compatible.
5290 ImpCastExprToType(LHS, compositeType, CK_BitCast);
5291 ImpCastExprToType(RHS, compositeType, CK_BitCast);
5292 return compositeType;
5294 // Check Objective-C object pointer types and 'void *'
5295 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5296 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5297 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5298 QualType destPointee
5299 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5300 QualType destType = Context.getPointerType(destPointee);
5301 // Add qualifiers if necessary.
5302 ImpCastExprToType(LHS, destType, CK_NoOp);
5303 // Promote to void*.
5304 ImpCastExprToType(RHS, destType, CK_BitCast);
5305 return destType;
5307 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5308 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5309 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5310 QualType destPointee
5311 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5312 QualType destType = Context.getPointerType(destPointee);
5313 // Add qualifiers if necessary.
5314 ImpCastExprToType(RHS, destType, CK_NoOp);
5315 // Promote to void*.
5316 ImpCastExprToType(LHS, destType, CK_BitCast);
5317 return destType;
5319 return QualType();
5322 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5323 /// in the case of a the GNU conditional expr extension.
5324 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5325 SourceLocation ColonLoc,
5326 Expr *CondExpr, Expr *LHSExpr,
5327 Expr *RHSExpr) {
5328 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5329 // was the condition.
5330 bool isLHSNull = LHSExpr == 0;
5331 Expr *SAVEExpr = 0;
5332 if (isLHSNull) {
5333 LHSExpr = SAVEExpr = CondExpr;
5336 ExprValueKind VK = VK_RValue;
5337 ExprObjectKind OK = OK_Ordinary;
5338 QualType result = CheckConditionalOperands(CondExpr, LHSExpr, RHSExpr,
5339 SAVEExpr, VK, OK, QuestionLoc);
5340 if (result.isNull())
5341 return ExprError();
5343 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
5344 LHSExpr, ColonLoc,
5345 RHSExpr, SAVEExpr,
5346 result, VK, OK));
5349 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5350 // being closely modeled after the C99 spec:-). The odd characteristic of this
5351 // routine is it effectively iqnores the qualifiers on the top level pointee.
5352 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5353 // FIXME: add a couple examples in this comment.
5354 static Sema::AssignConvertType
5355 checkPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5356 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5357 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5359 QualType lhptee, rhptee;
5361 // get the "pointed to" type (ignoring qualifiers at the top level)
5362 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
5363 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
5365 Sema::AssignConvertType ConvTy = Sema::Compatible;
5367 // C99 6.5.16.1p1: This following citation is common to constraints
5368 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5369 // qualifiers of the type *pointed to* by the right;
5370 // FIXME: Handle ExtQualType
5371 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5372 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5374 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5375 // incomplete type and the other is a pointer to a qualified or unqualified
5376 // version of void...
5377 if (lhptee->isVoidType()) {
5378 if (rhptee->isIncompleteOrObjectType())
5379 return ConvTy;
5381 // As an extension, we allow cast to/from void* to function pointer.
5382 assert(rhptee->isFunctionType());
5383 return Sema::FunctionVoidPointer;
5386 if (rhptee->isVoidType()) {
5387 if (lhptee->isIncompleteOrObjectType())
5388 return ConvTy;
5390 // As an extension, we allow cast to/from void* to function pointer.
5391 assert(lhptee->isFunctionType());
5392 return Sema::FunctionVoidPointer;
5394 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5395 // unqualified versions of compatible types, ...
5396 lhptee = lhptee.getUnqualifiedType();
5397 rhptee = rhptee.getUnqualifiedType();
5398 if (!S.Context.typesAreCompatible(lhptee, rhptee)) {
5399 // Check if the pointee types are compatible ignoring the sign.
5400 // We explicitly check for char so that we catch "char" vs
5401 // "unsigned char" on systems where "char" is unsigned.
5402 if (lhptee->isCharType())
5403 lhptee = S.Context.UnsignedCharTy;
5404 else if (lhptee->hasSignedIntegerRepresentation())
5405 lhptee = S.Context.getCorrespondingUnsignedType(lhptee);
5407 if (rhptee->isCharType())
5408 rhptee = S.Context.UnsignedCharTy;
5409 else if (rhptee->hasSignedIntegerRepresentation())
5410 rhptee = S.Context.getCorrespondingUnsignedType(rhptee);
5412 if (lhptee == rhptee) {
5413 // Types are compatible ignoring the sign. Qualifier incompatibility
5414 // takes priority over sign incompatibility because the sign
5415 // warning can be disabled.
5416 if (ConvTy != Sema::Compatible)
5417 return ConvTy;
5418 return Sema::IncompatiblePointerSign;
5421 // If we are a multi-level pointer, it's possible that our issue is simply
5422 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5423 // the eventual target type is the same and the pointers have the same
5424 // level of indirection, this must be the issue.
5425 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5426 do {
5427 lhptee = cast<PointerType>(lhptee)->getPointeeType();
5428 rhptee = cast<PointerType>(rhptee)->getPointeeType();
5429 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5431 if (S.Context.hasSameUnqualifiedType(lhptee, rhptee))
5432 return Sema::IncompatibleNestedPointerQualifiers;
5435 // General pointer incompatibility takes priority over qualifiers.
5436 return Sema::IncompatiblePointer;
5438 return ConvTy;
5441 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5442 /// block pointer types are compatible or whether a block and normal pointer
5443 /// are compatible. It is more restrict than comparing two function pointer
5444 // types.
5445 static Sema::AssignConvertType
5446 checkBlockPointerTypesForAssignment(Sema &S, QualType lhsType,
5447 QualType rhsType) {
5448 assert(lhsType.isCanonical() && "LHS not canonicalized!");
5449 assert(rhsType.isCanonical() && "RHS not canonicalized!");
5451 QualType lhptee, rhptee;
5453 // get the "pointed to" type (ignoring qualifiers at the top level)
5454 lhptee = cast<BlockPointerType>(lhsType)->getPointeeType();
5455 rhptee = cast<BlockPointerType>(rhsType)->getPointeeType();
5457 // In C++, the types have to match exactly.
5458 if (S.getLangOptions().CPlusPlus)
5459 return Sema::IncompatibleBlockPointer;
5461 Sema::AssignConvertType ConvTy = Sema::Compatible;
5463 // For blocks we enforce that qualifiers are identical.
5464 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5465 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5467 if (!S.Context.typesAreBlockPointerCompatible(lhsType, rhsType))
5468 return Sema::IncompatibleBlockPointer;
5470 return ConvTy;
5473 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5474 /// for assignment compatibility.
5475 static Sema::AssignConvertType
5476 checkObjCPointerTypesForAssignment(Sema &S, QualType lhsType, QualType rhsType) {
5477 assert(lhsType.isCanonical() && "LHS was not canonicalized!");
5478 assert(rhsType.isCanonical() && "RHS was not canonicalized!");
5480 if (lhsType->isObjCBuiltinType()) {
5481 // Class is not compatible with ObjC object pointers.
5482 if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
5483 !rhsType->isObjCQualifiedClassType())
5484 return Sema::IncompatiblePointer;
5485 return Sema::Compatible;
5487 if (rhsType->isObjCBuiltinType()) {
5488 // Class is not compatible with ObjC object pointers.
5489 if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
5490 !lhsType->isObjCQualifiedClassType())
5491 return Sema::IncompatiblePointer;
5492 return Sema::Compatible;
5494 QualType lhptee =
5495 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5496 QualType rhptee =
5497 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
5499 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5500 return Sema::CompatiblePointerDiscardsQualifiers;
5502 if (S.Context.typesAreCompatible(lhsType, rhsType))
5503 return Sema::Compatible;
5504 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
5505 return Sema::IncompatibleObjCQualifiedId;
5506 return Sema::IncompatiblePointer;
5509 Sema::AssignConvertType
5510 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5511 QualType lhsType, QualType rhsType) {
5512 // Fake up an opaque expression. We don't actually care about what
5513 // cast operations are required, so if CheckAssignmentConstraints
5514 // adds casts to this they'll be wasted, but fortunately that doesn't
5515 // usually happen on valid code.
5516 OpaqueValueExpr rhs(Loc, rhsType, VK_RValue);
5517 Expr *rhsPtr = &rhs;
5518 CastKind K = CK_Invalid;
5520 return CheckAssignmentConstraints(lhsType, rhsPtr, K);
5523 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5524 /// has code to accommodate several GCC extensions when type checking
5525 /// pointers. Here are some objectionable examples that GCC considers warnings:
5527 /// int a, *pint;
5528 /// short *pshort;
5529 /// struct foo *pfoo;
5531 /// pint = pshort; // warning: assignment from incompatible pointer type
5532 /// a = pint; // warning: assignment makes integer from pointer without a cast
5533 /// pint = a; // warning: assignment makes pointer from integer without a cast
5534 /// pint = pfoo; // warning: assignment from incompatible pointer type
5536 /// As a result, the code for dealing with pointers is more complex than the
5537 /// C99 spec dictates.
5539 /// Sets 'Kind' for any result kind except Incompatible.
5540 Sema::AssignConvertType
5541 Sema::CheckAssignmentConstraints(QualType lhsType, Expr *&rhs,
5542 CastKind &Kind) {
5543 QualType rhsType = rhs->getType();
5545 // Get canonical types. We're not formatting these types, just comparing
5546 // them.
5547 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
5548 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
5550 // Common case: no conversion required.
5551 if (lhsType == rhsType) {
5552 Kind = CK_NoOp;
5553 return Compatible;
5556 // If the left-hand side is a reference type, then we are in a
5557 // (rare!) case where we've allowed the use of references in C,
5558 // e.g., as a parameter type in a built-in function. In this case,
5559 // just make sure that the type referenced is compatible with the
5560 // right-hand side type. The caller is responsible for adjusting
5561 // lhsType so that the resulting expression does not have reference
5562 // type.
5563 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
5564 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType)) {
5565 Kind = CK_LValueBitCast;
5566 return Compatible;
5568 return Incompatible;
5571 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5572 // to the same ExtVector type.
5573 if (lhsType->isExtVectorType()) {
5574 if (rhsType->isExtVectorType())
5575 return Incompatible;
5576 if (rhsType->isArithmeticType()) {
5577 // CK_VectorSplat does T -> vector T, so first cast to the
5578 // element type.
5579 QualType elType = cast<ExtVectorType>(lhsType)->getElementType();
5580 if (elType != rhsType) {
5581 Kind = PrepareScalarCast(*this, rhs, elType);
5582 ImpCastExprToType(rhs, elType, Kind);
5584 Kind = CK_VectorSplat;
5585 return Compatible;
5589 // Conversions to or from vector type.
5590 if (lhsType->isVectorType() || rhsType->isVectorType()) {
5591 if (lhsType->isVectorType() && rhsType->isVectorType()) {
5592 // Allow assignments of an AltiVec vector type to an equivalent GCC
5593 // vector type and vice versa
5594 if (Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5595 Kind = CK_BitCast;
5596 return Compatible;
5599 // If we are allowing lax vector conversions, and LHS and RHS are both
5600 // vectors, the total size only needs to be the same. This is a bitcast;
5601 // no bits are changed but the result type is different.
5602 if (getLangOptions().LaxVectorConversions &&
5603 (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))) {
5604 Kind = CK_BitCast;
5605 return IncompatibleVectors;
5608 return Incompatible;
5611 // Arithmetic conversions.
5612 if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
5613 !(getLangOptions().CPlusPlus && lhsType->isEnumeralType())) {
5614 Kind = PrepareScalarCast(*this, rhs, lhsType);
5615 return Compatible;
5618 // Conversions to normal pointers.
5619 if (const PointerType *lhsPointer = dyn_cast<PointerType>(lhsType)) {
5620 // U* -> T*
5621 if (isa<PointerType>(rhsType)) {
5622 Kind = CK_BitCast;
5623 return checkPointerTypesForAssignment(*this, lhsType, rhsType);
5626 // int -> T*
5627 if (rhsType->isIntegerType()) {
5628 Kind = CK_IntegralToPointer; // FIXME: null?
5629 return IntToPointer;
5632 // C pointers are not compatible with ObjC object pointers,
5633 // with two exceptions:
5634 if (isa<ObjCObjectPointerType>(rhsType)) {
5635 // - conversions to void*
5636 if (lhsPointer->getPointeeType()->isVoidType()) {
5637 Kind = CK_AnyPointerToObjCPointerCast;
5638 return Compatible;
5641 // - conversions from 'Class' to the redefinition type
5642 if (rhsType->isObjCClassType() &&
5643 Context.hasSameType(lhsType, Context.ObjCClassRedefinitionType)) {
5644 Kind = CK_BitCast;
5645 return Compatible;
5648 Kind = CK_BitCast;
5649 return IncompatiblePointer;
5652 // U^ -> void*
5653 if (rhsType->getAs<BlockPointerType>()) {
5654 if (lhsPointer->getPointeeType()->isVoidType()) {
5655 Kind = CK_BitCast;
5656 return Compatible;
5660 return Incompatible;
5663 // Conversions to block pointers.
5664 if (isa<BlockPointerType>(lhsType)) {
5665 // U^ -> T^
5666 if (rhsType->isBlockPointerType()) {
5667 Kind = CK_AnyPointerToBlockPointerCast;
5668 return checkBlockPointerTypesForAssignment(*this, lhsType, rhsType);
5671 // int or null -> T^
5672 if (rhsType->isIntegerType()) {
5673 Kind = CK_IntegralToPointer; // FIXME: null
5674 return IntToBlockPointer;
5677 // id -> T^
5678 if (getLangOptions().ObjC1 && rhsType->isObjCIdType()) {
5679 Kind = CK_AnyPointerToBlockPointerCast;
5680 return Compatible;
5683 // void* -> T^
5684 if (const PointerType *RHSPT = rhsType->getAs<PointerType>())
5685 if (RHSPT->getPointeeType()->isVoidType()) {
5686 Kind = CK_AnyPointerToBlockPointerCast;
5687 return Compatible;
5690 return Incompatible;
5693 // Conversions to Objective-C pointers.
5694 if (isa<ObjCObjectPointerType>(lhsType)) {
5695 // A* -> B*
5696 if (rhsType->isObjCObjectPointerType()) {
5697 Kind = CK_BitCast;
5698 return checkObjCPointerTypesForAssignment(*this, lhsType, rhsType);
5701 // int or null -> A*
5702 if (rhsType->isIntegerType()) {
5703 Kind = CK_IntegralToPointer; // FIXME: null
5704 return IntToPointer;
5707 // In general, C pointers are not compatible with ObjC object pointers,
5708 // with two exceptions:
5709 if (isa<PointerType>(rhsType)) {
5710 // - conversions from 'void*'
5711 if (rhsType->isVoidPointerType()) {
5712 Kind = CK_AnyPointerToObjCPointerCast;
5713 return Compatible;
5716 // - conversions to 'Class' from its redefinition type
5717 if (lhsType->isObjCClassType() &&
5718 Context.hasSameType(rhsType, Context.ObjCClassRedefinitionType)) {
5719 Kind = CK_BitCast;
5720 return Compatible;
5723 Kind = CK_AnyPointerToObjCPointerCast;
5724 return IncompatiblePointer;
5727 // T^ -> A*
5728 if (rhsType->isBlockPointerType()) {
5729 Kind = CK_AnyPointerToObjCPointerCast;
5730 return Compatible;
5733 return Incompatible;
5736 // Conversions from pointers that are not covered by the above.
5737 if (isa<PointerType>(rhsType)) {
5738 // T* -> _Bool
5739 if (lhsType == Context.BoolTy) {
5740 Kind = CK_PointerToBoolean;
5741 return Compatible;
5744 // T* -> int
5745 if (lhsType->isIntegerType()) {
5746 Kind = CK_PointerToIntegral;
5747 return PointerToInt;
5750 return Incompatible;
5753 // Conversions from Objective-C pointers that are not covered by the above.
5754 if (isa<ObjCObjectPointerType>(rhsType)) {
5755 // T* -> _Bool
5756 if (lhsType == Context.BoolTy) {
5757 Kind = CK_PointerToBoolean;
5758 return Compatible;
5761 // T* -> int
5762 if (lhsType->isIntegerType()) {
5763 Kind = CK_PointerToIntegral;
5764 return PointerToInt;
5767 return Incompatible;
5770 // struct A -> struct B
5771 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
5772 if (Context.typesAreCompatible(lhsType, rhsType)) {
5773 Kind = CK_NoOp;
5774 return Compatible;
5778 return Incompatible;
5781 /// \brief Constructs a transparent union from an expression that is
5782 /// used to initialize the transparent union.
5783 static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
5784 QualType UnionType, FieldDecl *Field) {
5785 // Build an initializer list that designates the appropriate member
5786 // of the transparent union.
5787 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5788 &E, 1,
5789 SourceLocation());
5790 Initializer->setType(UnionType);
5791 Initializer->setInitializedFieldInUnion(Field);
5793 // Build a compound literal constructing a value of the transparent
5794 // union type from this initializer list.
5795 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5796 E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5797 VK_RValue, Initializer, false);
5800 Sema::AssignConvertType
5801 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
5802 QualType FromType = rExpr->getType();
5804 // If the ArgType is a Union type, we want to handle a potential
5805 // transparent_union GCC extension.
5806 const RecordType *UT = ArgType->getAsUnionType();
5807 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5808 return Incompatible;
5810 // The field to initialize within the transparent union.
5811 RecordDecl *UD = UT->getDecl();
5812 FieldDecl *InitField = 0;
5813 // It's compatible if the expression matches any of the fields.
5814 for (RecordDecl::field_iterator it = UD->field_begin(),
5815 itend = UD->field_end();
5816 it != itend; ++it) {
5817 if (it->getType()->isPointerType()) {
5818 // If the transparent union contains a pointer type, we allow:
5819 // 1) void pointer
5820 // 2) null pointer constant
5821 if (FromType->isPointerType())
5822 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
5823 ImpCastExprToType(rExpr, it->getType(), CK_BitCast);
5824 InitField = *it;
5825 break;
5828 if (rExpr->isNullPointerConstant(Context,
5829 Expr::NPC_ValueDependentIsNull)) {
5830 ImpCastExprToType(rExpr, it->getType(), CK_NullToPointer);
5831 InitField = *it;
5832 break;
5836 Expr *rhs = rExpr;
5837 CastKind Kind = CK_Invalid;
5838 if (CheckAssignmentConstraints(it->getType(), rhs, Kind)
5839 == Compatible) {
5840 ImpCastExprToType(rhs, it->getType(), Kind);
5841 rExpr = rhs;
5842 InitField = *it;
5843 break;
5847 if (!InitField)
5848 return Incompatible;
5850 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
5851 return Compatible;
5854 Sema::AssignConvertType
5855 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
5856 if (getLangOptions().CPlusPlus) {
5857 if (!lhsType->isRecordType()) {
5858 // C++ 5.17p3: If the left operand is not of class type, the
5859 // expression is implicitly converted (C++ 4) to the
5860 // cv-unqualified type of the left operand.
5861 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
5862 AA_Assigning))
5863 return Incompatible;
5864 return Compatible;
5867 // FIXME: Currently, we fall through and treat C++ classes like C
5868 // structures.
5871 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5872 // a null pointer constant.
5873 if ((lhsType->isPointerType() ||
5874 lhsType->isObjCObjectPointerType() ||
5875 lhsType->isBlockPointerType())
5876 && rExpr->isNullPointerConstant(Context,
5877 Expr::NPC_ValueDependentIsNull)) {
5878 ImpCastExprToType(rExpr, lhsType, CK_NullToPointer);
5879 return Compatible;
5882 // This check seems unnatural, however it is necessary to ensure the proper
5883 // conversion of functions/arrays. If the conversion were done for all
5884 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5885 // expressions that suppress this implicit conversion (&, sizeof).
5887 // Suppress this for references: C++ 8.5.3p5.
5888 if (!lhsType->isReferenceType())
5889 DefaultFunctionArrayLvalueConversion(rExpr);
5891 CastKind Kind = CK_Invalid;
5892 Sema::AssignConvertType result =
5893 CheckAssignmentConstraints(lhsType, rExpr, Kind);
5895 // C99 6.5.16.1p2: The value of the right operand is converted to the
5896 // type of the assignment expression.
5897 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5898 // so that we can use references in built-in functions even in C.
5899 // The getNonReferenceType() call makes sure that the resulting expression
5900 // does not have reference type.
5901 if (result != Incompatible && rExpr->getType() != lhsType)
5902 ImpCastExprToType(rExpr, lhsType.getNonLValueExprType(Context), Kind);
5903 return result;
5906 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
5907 Diag(Loc, diag::err_typecheck_invalid_operands)
5908 << lex->getType() << rex->getType()
5909 << lex->getSourceRange() << rex->getSourceRange();
5910 return QualType();
5913 QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
5914 // For conversion purposes, we ignore any qualifiers.
5915 // For example, "const float" and "float" are equivalent.
5916 QualType lhsType =
5917 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
5918 QualType rhsType =
5919 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
5921 // If the vector types are identical, return.
5922 if (lhsType == rhsType)
5923 return lhsType;
5925 // Handle the case of a vector & extvector type of the same size and element
5926 // type. It would be nice if we only had one vector type someday.
5927 if (getLangOptions().LaxVectorConversions) {
5928 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
5929 if (const VectorType *RV = rhsType->getAs<VectorType>()) {
5930 if (LV->getElementType() == RV->getElementType() &&
5931 LV->getNumElements() == RV->getNumElements()) {
5932 if (lhsType->isExtVectorType()) {
5933 ImpCastExprToType(rex, lhsType, CK_BitCast);
5934 return lhsType;
5937 ImpCastExprToType(lex, rhsType, CK_BitCast);
5938 return rhsType;
5939 } else if (Context.getTypeSize(lhsType) ==Context.getTypeSize(rhsType)){
5940 // If we are allowing lax vector conversions, and LHS and RHS are both
5941 // vectors, the total size only needs to be the same. This is a
5942 // bitcast; no bits are changed but the result type is different.
5943 ImpCastExprToType(rex, lhsType, CK_BitCast);
5944 return lhsType;
5950 // Handle the case of equivalent AltiVec and GCC vector types
5951 if (lhsType->isVectorType() && rhsType->isVectorType() &&
5952 Context.areCompatibleVectorTypes(lhsType, rhsType)) {
5953 ImpCastExprToType(lex, rhsType, CK_BitCast);
5954 return rhsType;
5957 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5958 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5959 bool swapped = false;
5960 if (rhsType->isExtVectorType()) {
5961 swapped = true;
5962 std::swap(rex, lex);
5963 std::swap(rhsType, lhsType);
5966 // Handle the case of an ext vector and scalar.
5967 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
5968 QualType EltTy = LV->getElementType();
5969 if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
5970 int order = Context.getIntegerTypeOrder(EltTy, rhsType);
5971 if (order > 0)
5972 ImpCastExprToType(rex, EltTy, CK_IntegralCast);
5973 if (order >= 0) {
5974 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
5975 if (swapped) std::swap(rex, lex);
5976 return lhsType;
5979 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
5980 rhsType->isRealFloatingType()) {
5981 int order = Context.getFloatingTypeOrder(EltTy, rhsType);
5982 if (order > 0)
5983 ImpCastExprToType(rex, EltTy, CK_FloatingCast);
5984 if (order >= 0) {
5985 ImpCastExprToType(rex, lhsType, CK_VectorSplat);
5986 if (swapped) std::swap(rex, lex);
5987 return lhsType;
5992 // Vectors of different size or scalar and non-ext-vector are errors.
5993 Diag(Loc, diag::err_typecheck_vector_not_convertable)
5994 << lex->getType() << rex->getType()
5995 << lex->getSourceRange() << rex->getSourceRange();
5996 return QualType();
5999 QualType Sema::CheckMultiplyDivideOperands(
6000 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
6001 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6002 return CheckVectorOperands(Loc, lex, rex);
6004 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6006 if (!lex->getType()->isArithmeticType() ||
6007 !rex->getType()->isArithmeticType())
6008 return InvalidOperands(Loc, lex, rex);
6010 // Check for division by zero.
6011 if (isDiv &&
6012 rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6013 DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
6014 << rex->getSourceRange());
6016 return compType;
6019 QualType Sema::CheckRemainderOperands(
6020 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
6021 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6022 if (lex->getType()->hasIntegerRepresentation() &&
6023 rex->getType()->hasIntegerRepresentation())
6024 return CheckVectorOperands(Loc, lex, rex);
6025 return InvalidOperands(Loc, lex, rex);
6028 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6030 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
6031 return InvalidOperands(Loc, lex, rex);
6033 // Check for remainder by zero.
6034 if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
6035 DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
6036 << rex->getSourceRange());
6038 return compType;
6041 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6042 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
6043 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6044 QualType compType = CheckVectorOperands(Loc, lex, rex);
6045 if (CompLHSTy) *CompLHSTy = compType;
6046 return compType;
6049 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
6051 // handle the common case first (both operands are arithmetic).
6052 if (lex->getType()->isArithmeticType() &&
6053 rex->getType()->isArithmeticType()) {
6054 if (CompLHSTy) *CompLHSTy = compType;
6055 return compType;
6058 // Put any potential pointer into PExp
6059 Expr* PExp = lex, *IExp = rex;
6060 if (IExp->getType()->isAnyPointerType())
6061 std::swap(PExp, IExp);
6063 if (PExp->getType()->isAnyPointerType()) {
6065 if (IExp->getType()->isIntegerType()) {
6066 QualType PointeeTy = PExp->getType()->getPointeeType();
6068 // Check for arithmetic on pointers to incomplete types.
6069 if (PointeeTy->isVoidType()) {
6070 if (getLangOptions().CPlusPlus) {
6071 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6072 << lex->getSourceRange() << rex->getSourceRange();
6073 return QualType();
6076 // GNU extension: arithmetic on pointer to void
6077 Diag(Loc, diag::ext_gnu_void_ptr)
6078 << lex->getSourceRange() << rex->getSourceRange();
6079 } else if (PointeeTy->isFunctionType()) {
6080 if (getLangOptions().CPlusPlus) {
6081 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6082 << lex->getType() << lex->getSourceRange();
6083 return QualType();
6086 // GNU extension: arithmetic on pointer to function
6087 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6088 << lex->getType() << lex->getSourceRange();
6089 } else {
6090 // Check if we require a complete type.
6091 if (((PExp->getType()->isPointerType() &&
6092 !PExp->getType()->isDependentType()) ||
6093 PExp->getType()->isObjCObjectPointerType()) &&
6094 RequireCompleteType(Loc, PointeeTy,
6095 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6096 << PExp->getSourceRange()
6097 << PExp->getType()))
6098 return QualType();
6100 // Diagnose bad cases where we step over interface counts.
6101 if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6102 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6103 << PointeeTy << PExp->getSourceRange();
6104 return QualType();
6107 if (CompLHSTy) {
6108 QualType LHSTy = Context.isPromotableBitField(lex);
6109 if (LHSTy.isNull()) {
6110 LHSTy = lex->getType();
6111 if (LHSTy->isPromotableIntegerType())
6112 LHSTy = Context.getPromotedIntegerType(LHSTy);
6114 *CompLHSTy = LHSTy;
6116 return PExp->getType();
6120 return InvalidOperands(Loc, lex, rex);
6123 // C99 6.5.6
6124 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
6125 SourceLocation Loc, QualType* CompLHSTy) {
6126 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6127 QualType compType = CheckVectorOperands(Loc, lex, rex);
6128 if (CompLHSTy) *CompLHSTy = compType;
6129 return compType;
6132 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
6134 // Enforce type constraints: C99 6.5.6p3.
6136 // Handle the common case first (both operands are arithmetic).
6137 if (lex->getType()->isArithmeticType()
6138 && rex->getType()->isArithmeticType()) {
6139 if (CompLHSTy) *CompLHSTy = compType;
6140 return compType;
6143 // Either ptr - int or ptr - ptr.
6144 if (lex->getType()->isAnyPointerType()) {
6145 QualType lpointee = lex->getType()->getPointeeType();
6147 // The LHS must be an completely-defined object type.
6149 bool ComplainAboutVoid = false;
6150 Expr *ComplainAboutFunc = 0;
6151 if (lpointee->isVoidType()) {
6152 if (getLangOptions().CPlusPlus) {
6153 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6154 << lex->getSourceRange() << rex->getSourceRange();
6155 return QualType();
6158 // GNU C extension: arithmetic on pointer to void
6159 ComplainAboutVoid = true;
6160 } else if (lpointee->isFunctionType()) {
6161 if (getLangOptions().CPlusPlus) {
6162 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6163 << lex->getType() << lex->getSourceRange();
6164 return QualType();
6167 // GNU C extension: arithmetic on pointer to function
6168 ComplainAboutFunc = lex;
6169 } else if (!lpointee->isDependentType() &&
6170 RequireCompleteType(Loc, lpointee,
6171 PDiag(diag::err_typecheck_sub_ptr_object)
6172 << lex->getSourceRange()
6173 << lex->getType()))
6174 return QualType();
6176 // Diagnose bad cases where we step over interface counts.
6177 if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
6178 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
6179 << lpointee << lex->getSourceRange();
6180 return QualType();
6183 // The result type of a pointer-int computation is the pointer type.
6184 if (rex->getType()->isIntegerType()) {
6185 if (ComplainAboutVoid)
6186 Diag(Loc, diag::ext_gnu_void_ptr)
6187 << lex->getSourceRange() << rex->getSourceRange();
6188 if (ComplainAboutFunc)
6189 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6190 << ComplainAboutFunc->getType()
6191 << ComplainAboutFunc->getSourceRange();
6193 if (CompLHSTy) *CompLHSTy = lex->getType();
6194 return lex->getType();
6197 // Handle pointer-pointer subtractions.
6198 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
6199 QualType rpointee = RHSPTy->getPointeeType();
6201 // RHS must be a completely-type object type.
6202 // Handle the GNU void* extension.
6203 if (rpointee->isVoidType()) {
6204 if (getLangOptions().CPlusPlus) {
6205 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
6206 << lex->getSourceRange() << rex->getSourceRange();
6207 return QualType();
6210 ComplainAboutVoid = true;
6211 } else if (rpointee->isFunctionType()) {
6212 if (getLangOptions().CPlusPlus) {
6213 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
6214 << rex->getType() << rex->getSourceRange();
6215 return QualType();
6218 // GNU extension: arithmetic on pointer to function
6219 if (!ComplainAboutFunc)
6220 ComplainAboutFunc = rex;
6221 } else if (!rpointee->isDependentType() &&
6222 RequireCompleteType(Loc, rpointee,
6223 PDiag(diag::err_typecheck_sub_ptr_object)
6224 << rex->getSourceRange()
6225 << rex->getType()))
6226 return QualType();
6228 if (getLangOptions().CPlusPlus) {
6229 // Pointee types must be the same: C++ [expr.add]
6230 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6231 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6232 << lex->getType() << rex->getType()
6233 << lex->getSourceRange() << rex->getSourceRange();
6234 return QualType();
6236 } else {
6237 // Pointee types must be compatible C99 6.5.6p3
6238 if (!Context.typesAreCompatible(
6239 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6240 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6241 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6242 << lex->getType() << rex->getType()
6243 << lex->getSourceRange() << rex->getSourceRange();
6244 return QualType();
6248 if (ComplainAboutVoid)
6249 Diag(Loc, diag::ext_gnu_void_ptr)
6250 << lex->getSourceRange() << rex->getSourceRange();
6251 if (ComplainAboutFunc)
6252 Diag(Loc, diag::ext_gnu_ptr_func_arith)
6253 << ComplainAboutFunc->getType()
6254 << ComplainAboutFunc->getSourceRange();
6256 if (CompLHSTy) *CompLHSTy = lex->getType();
6257 return Context.getPointerDiffType();
6261 return InvalidOperands(Loc, lex, rex);
6264 static bool isScopedEnumerationType(QualType T) {
6265 if (const EnumType *ET = dyn_cast<EnumType>(T))
6266 return ET->getDecl()->isScoped();
6267 return false;
6270 // C99 6.5.7
6271 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
6272 bool isCompAssign) {
6273 // C99 6.5.7p2: Each of the operands shall have integer type.
6274 if (!lex->getType()->hasIntegerRepresentation() ||
6275 !rex->getType()->hasIntegerRepresentation())
6276 return InvalidOperands(Loc, lex, rex);
6278 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6279 // hasIntegerRepresentation() above instead of this.
6280 if (isScopedEnumerationType(lex->getType()) ||
6281 isScopedEnumerationType(rex->getType())) {
6282 return InvalidOperands(Loc, lex, rex);
6285 // Vector shifts promote their scalar inputs to vector type.
6286 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6287 return CheckVectorOperands(Loc, lex, rex);
6289 // Shifts don't perform usual arithmetic conversions, they just do integer
6290 // promotions on each operand. C99 6.5.7p3
6292 // For the LHS, do usual unary conversions, but then reset them away
6293 // if this is a compound assignment.
6294 Expr *old_lex = lex;
6295 UsualUnaryConversions(lex);
6296 QualType LHSTy = lex->getType();
6297 if (isCompAssign) lex = old_lex;
6299 // The RHS is simpler.
6300 UsualUnaryConversions(rex);
6302 // Sanity-check shift operands
6303 llvm::APSInt Right;
6304 // Check right/shifter operand
6305 if (!rex->isValueDependent() &&
6306 rex->isIntegerConstantExpr(Right, Context)) {
6307 if (Right.isNegative())
6308 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
6309 else {
6310 llvm::APInt LeftBits(Right.getBitWidth(),
6311 Context.getTypeSize(lex->getType()));
6312 if (Right.uge(LeftBits))
6313 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
6317 // "The type of the result is that of the promoted left operand."
6318 return LHSTy;
6321 static bool IsWithinTemplateSpecialization(Decl *D) {
6322 if (DeclContext *DC = D->getDeclContext()) {
6323 if (isa<ClassTemplateSpecializationDecl>(DC))
6324 return true;
6325 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6326 return FD->isFunctionTemplateSpecialization();
6328 return false;
6331 // C99 6.5.8, C++ [expr.rel]
6332 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
6333 unsigned OpaqueOpc, bool isRelational) {
6334 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6336 // Handle vector comparisons separately.
6337 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
6338 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
6340 QualType lType = lex->getType();
6341 QualType rType = rex->getType();
6343 if (!lType->hasFloatingRepresentation() &&
6344 !(lType->isBlockPointerType() && isRelational) &&
6345 !lex->getLocStart().isMacroID() &&
6346 !rex->getLocStart().isMacroID()) {
6347 // For non-floating point types, check for self-comparisons of the form
6348 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6349 // often indicate logic errors in the program.
6351 // NOTE: Don't warn about comparison expressions resulting from macro
6352 // expansion. Also don't warn about comparisons which are only self
6353 // comparisons within a template specialization. The warnings should catch
6354 // obvious cases in the definition of the template anyways. The idea is to
6355 // warn when the typed comparison operator will always evaluate to the same
6356 // result.
6357 Expr *LHSStripped = lex->IgnoreParenImpCasts();
6358 Expr *RHSStripped = rex->IgnoreParenImpCasts();
6359 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6360 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6361 if (DRL->getDecl() == DRR->getDecl() &&
6362 !IsWithinTemplateSpecialization(DRL->getDecl())) {
6363 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6364 << 0 // self-
6365 << (Opc == BO_EQ
6366 || Opc == BO_LE
6367 || Opc == BO_GE));
6368 } else if (lType->isArrayType() && rType->isArrayType() &&
6369 !DRL->getDecl()->getType()->isReferenceType() &&
6370 !DRR->getDecl()->getType()->isReferenceType()) {
6371 // what is it always going to eval to?
6372 char always_evals_to;
6373 switch(Opc) {
6374 case BO_EQ: // e.g. array1 == array2
6375 always_evals_to = 0; // false
6376 break;
6377 case BO_NE: // e.g. array1 != array2
6378 always_evals_to = 1; // true
6379 break;
6380 default:
6381 // best we can say is 'a constant'
6382 always_evals_to = 2; // e.g. array1 <= array2
6383 break;
6385 DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
6386 << 1 // array
6387 << always_evals_to);
6392 if (isa<CastExpr>(LHSStripped))
6393 LHSStripped = LHSStripped->IgnoreParenCasts();
6394 if (isa<CastExpr>(RHSStripped))
6395 RHSStripped = RHSStripped->IgnoreParenCasts();
6397 // Warn about comparisons against a string constant (unless the other
6398 // operand is null), the user probably wants strcmp.
6399 Expr *literalString = 0;
6400 Expr *literalStringStripped = 0;
6401 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6402 !RHSStripped->isNullPointerConstant(Context,
6403 Expr::NPC_ValueDependentIsNull)) {
6404 literalString = lex;
6405 literalStringStripped = LHSStripped;
6406 } else if ((isa<StringLiteral>(RHSStripped) ||
6407 isa<ObjCEncodeExpr>(RHSStripped)) &&
6408 !LHSStripped->isNullPointerConstant(Context,
6409 Expr::NPC_ValueDependentIsNull)) {
6410 literalString = rex;
6411 literalStringStripped = RHSStripped;
6414 if (literalString) {
6415 std::string resultComparison;
6416 switch (Opc) {
6417 case BO_LT: resultComparison = ") < 0"; break;
6418 case BO_GT: resultComparison = ") > 0"; break;
6419 case BO_LE: resultComparison = ") <= 0"; break;
6420 case BO_GE: resultComparison = ") >= 0"; break;
6421 case BO_EQ: resultComparison = ") == 0"; break;
6422 case BO_NE: resultComparison = ") != 0"; break;
6423 default: assert(false && "Invalid comparison operator");
6426 DiagRuntimeBehavior(Loc,
6427 PDiag(diag::warn_stringcompare)
6428 << isa<ObjCEncodeExpr>(literalStringStripped)
6429 << literalString->getSourceRange());
6433 // C99 6.5.8p3 / C99 6.5.9p4
6434 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
6435 UsualArithmeticConversions(lex, rex);
6436 else {
6437 UsualUnaryConversions(lex);
6438 UsualUnaryConversions(rex);
6441 lType = lex->getType();
6442 rType = rex->getType();
6444 // The result of comparisons is 'bool' in C++, 'int' in C.
6445 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
6447 if (isRelational) {
6448 if (lType->isRealType() && rType->isRealType())
6449 return ResultTy;
6450 } else {
6451 // Check for comparisons of floating point operands using != and ==.
6452 if (lType->hasFloatingRepresentation())
6453 CheckFloatComparison(Loc,lex,rex);
6455 if (lType->isArithmeticType() && rType->isArithmeticType())
6456 return ResultTy;
6459 bool LHSIsNull = lex->isNullPointerConstant(Context,
6460 Expr::NPC_ValueDependentIsNull);
6461 bool RHSIsNull = rex->isNullPointerConstant(Context,
6462 Expr::NPC_ValueDependentIsNull);
6464 // All of the following pointer-related warnings are GCC extensions, except
6465 // when handling null pointer constants.
6466 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
6467 QualType LCanPointeeTy =
6468 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
6469 QualType RCanPointeeTy =
6470 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
6472 if (getLangOptions().CPlusPlus) {
6473 if (LCanPointeeTy == RCanPointeeTy)
6474 return ResultTy;
6475 if (!isRelational &&
6476 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6477 // Valid unless comparison between non-null pointer and function pointer
6478 // This is a gcc extension compatibility comparison.
6479 // In a SFINAE context, we treat this as a hard error to maintain
6480 // conformance with the C++ standard.
6481 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6482 && !LHSIsNull && !RHSIsNull) {
6483 Diag(Loc,
6484 isSFINAEContext()?
6485 diag::err_typecheck_comparison_of_fptr_to_void
6486 : diag::ext_typecheck_comparison_of_fptr_to_void)
6487 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6489 if (isSFINAEContext())
6490 return QualType();
6492 ImpCastExprToType(rex, lType, CK_BitCast);
6493 return ResultTy;
6497 // C++ [expr.rel]p2:
6498 // [...] Pointer conversions (4.10) and qualification
6499 // conversions (4.4) are performed on pointer operands (or on
6500 // a pointer operand and a null pointer constant) to bring
6501 // them to their composite pointer type. [...]
6503 // C++ [expr.eq]p1 uses the same notion for (in)equality
6504 // comparisons of pointers.
6505 bool NonStandardCompositeType = false;
6506 QualType T = FindCompositePointerType(Loc, lex, rex,
6507 isSFINAEContext()? 0 : &NonStandardCompositeType);
6508 if (T.isNull()) {
6509 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6510 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6511 return QualType();
6512 } else if (NonStandardCompositeType) {
6513 Diag(Loc,
6514 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6515 << lType << rType << T
6516 << lex->getSourceRange() << rex->getSourceRange();
6519 ImpCastExprToType(lex, T, CK_BitCast);
6520 ImpCastExprToType(rex, T, CK_BitCast);
6521 return ResultTy;
6523 // C99 6.5.9p2 and C99 6.5.8p2
6524 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6525 RCanPointeeTy.getUnqualifiedType())) {
6526 // Valid unless a relational comparison of function pointers
6527 if (isRelational && LCanPointeeTy->isFunctionType()) {
6528 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6529 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6531 } else if (!isRelational &&
6532 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6533 // Valid unless comparison between non-null pointer and function pointer
6534 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6535 && !LHSIsNull && !RHSIsNull) {
6536 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
6537 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6539 } else {
6540 // Invalid
6541 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6542 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6544 if (LCanPointeeTy != RCanPointeeTy)
6545 ImpCastExprToType(rex, lType, CK_BitCast);
6546 return ResultTy;
6549 if (getLangOptions().CPlusPlus) {
6550 // Comparison of nullptr_t with itself.
6551 if (lType->isNullPtrType() && rType->isNullPtrType())
6552 return ResultTy;
6554 // Comparison of pointers with null pointer constants and equality
6555 // comparisons of member pointers to null pointer constants.
6556 if (RHSIsNull &&
6557 ((lType->isPointerType() || lType->isNullPtrType()) ||
6558 (!isRelational && lType->isMemberPointerType()))) {
6559 ImpCastExprToType(rex, lType,
6560 lType->isMemberPointerType()
6561 ? CK_NullToMemberPointer
6562 : CK_NullToPointer);
6563 return ResultTy;
6565 if (LHSIsNull &&
6566 ((rType->isPointerType() || rType->isNullPtrType()) ||
6567 (!isRelational && rType->isMemberPointerType()))) {
6568 ImpCastExprToType(lex, rType,
6569 rType->isMemberPointerType()
6570 ? CK_NullToMemberPointer
6571 : CK_NullToPointer);
6572 return ResultTy;
6575 // Comparison of member pointers.
6576 if (!isRelational &&
6577 lType->isMemberPointerType() && rType->isMemberPointerType()) {
6578 // C++ [expr.eq]p2:
6579 // In addition, pointers to members can be compared, or a pointer to
6580 // member and a null pointer constant. Pointer to member conversions
6581 // (4.11) and qualification conversions (4.4) are performed to bring
6582 // them to a common type. If one operand is a null pointer constant,
6583 // the common type is the type of the other operand. Otherwise, the
6584 // common type is a pointer to member type similar (4.4) to the type
6585 // of one of the operands, with a cv-qualification signature (4.4)
6586 // that is the union of the cv-qualification signatures of the operand
6587 // types.
6588 bool NonStandardCompositeType = false;
6589 QualType T = FindCompositePointerType(Loc, lex, rex,
6590 isSFINAEContext()? 0 : &NonStandardCompositeType);
6591 if (T.isNull()) {
6592 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
6593 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6594 return QualType();
6595 } else if (NonStandardCompositeType) {
6596 Diag(Loc,
6597 diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6598 << lType << rType << T
6599 << lex->getSourceRange() << rex->getSourceRange();
6602 ImpCastExprToType(lex, T, CK_BitCast);
6603 ImpCastExprToType(rex, T, CK_BitCast);
6604 return ResultTy;
6608 // Handle block pointer types.
6609 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
6610 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
6611 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
6613 if (!LHSIsNull && !RHSIsNull &&
6614 !Context.typesAreCompatible(lpointee, rpointee)) {
6615 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6616 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6618 ImpCastExprToType(rex, lType, CK_BitCast);
6619 return ResultTy;
6621 // Allow block pointers to be compared with null pointer constants.
6622 if (!isRelational
6623 && ((lType->isBlockPointerType() && rType->isPointerType())
6624 || (lType->isPointerType() && rType->isBlockPointerType()))) {
6625 if (!LHSIsNull && !RHSIsNull) {
6626 if (!((rType->isPointerType() && rType->getAs<PointerType>()
6627 ->getPointeeType()->isVoidType())
6628 || (lType->isPointerType() && lType->getAs<PointerType>()
6629 ->getPointeeType()->isVoidType())))
6630 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6631 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6633 ImpCastExprToType(rex, lType, CK_BitCast);
6634 return ResultTy;
6637 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
6638 if (lType->isPointerType() || rType->isPointerType()) {
6639 const PointerType *LPT = lType->getAs<PointerType>();
6640 const PointerType *RPT = rType->getAs<PointerType>();
6641 bool LPtrToVoid = LPT ?
6642 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
6643 bool RPtrToVoid = RPT ?
6644 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
6646 if (!LPtrToVoid && !RPtrToVoid &&
6647 !Context.typesAreCompatible(lType, rType)) {
6648 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6649 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6651 ImpCastExprToType(rex, lType, CK_BitCast);
6652 return ResultTy;
6654 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
6655 if (!Context.areComparableObjCPointerTypes(lType, rType))
6656 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
6657 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6658 ImpCastExprToType(rex, lType, CK_BitCast);
6659 return ResultTy;
6662 if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
6663 (lType->isIntegerType() && rType->isAnyPointerType())) {
6664 unsigned DiagID = 0;
6665 bool isError = false;
6666 if ((LHSIsNull && lType->isIntegerType()) ||
6667 (RHSIsNull && rType->isIntegerType())) {
6668 if (isRelational && !getLangOptions().CPlusPlus)
6669 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
6670 } else if (isRelational && !getLangOptions().CPlusPlus)
6671 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
6672 else if (getLangOptions().CPlusPlus) {
6673 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6674 isError = true;
6675 } else
6676 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
6678 if (DiagID) {
6679 Diag(Loc, DiagID)
6680 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
6681 if (isError)
6682 return QualType();
6685 if (lType->isIntegerType())
6686 ImpCastExprToType(lex, rType,
6687 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6688 else
6689 ImpCastExprToType(rex, lType,
6690 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6691 return ResultTy;
6694 // Handle block pointers.
6695 if (!isRelational && RHSIsNull
6696 && lType->isBlockPointerType() && rType->isIntegerType()) {
6697 ImpCastExprToType(rex, lType, CK_NullToPointer);
6698 return ResultTy;
6700 if (!isRelational && LHSIsNull
6701 && lType->isIntegerType() && rType->isBlockPointerType()) {
6702 ImpCastExprToType(lex, rType, CK_NullToPointer);
6703 return ResultTy;
6705 return InvalidOperands(Loc, lex, rex);
6708 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
6709 /// operates on extended vector types. Instead of producing an IntTy result,
6710 /// like a scalar comparison, a vector comparison produces a vector of integer
6711 /// types.
6712 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
6713 SourceLocation Loc,
6714 bool isRelational) {
6715 // Check to make sure we're operating on vectors of the same type and width,
6716 // Allowing one side to be a scalar of element type.
6717 QualType vType = CheckVectorOperands(Loc, lex, rex);
6718 if (vType.isNull())
6719 return vType;
6721 // If AltiVec, the comparison results in a numeric type, i.e.
6722 // bool for C++, int for C
6723 if (getLangOptions().AltiVec)
6724 return (getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy);
6726 QualType lType = lex->getType();
6727 QualType rType = rex->getType();
6729 // For non-floating point types, check for self-comparisons of the form
6730 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6731 // often indicate logic errors in the program.
6732 if (!lType->hasFloatingRepresentation()) {
6733 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
6734 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
6735 if (DRL->getDecl() == DRR->getDecl())
6736 DiagRuntimeBehavior(Loc,
6737 PDiag(diag::warn_comparison_always)
6738 << 0 // self-
6739 << 2 // "a constant"
6743 // Check for comparisons of floating point operands using != and ==.
6744 if (!isRelational && lType->hasFloatingRepresentation()) {
6745 assert (rType->hasFloatingRepresentation());
6746 CheckFloatComparison(Loc,lex,rex);
6749 // Return the type for the comparison, which is the same as vector type for
6750 // integer vectors, or an integer type of identical size and number of
6751 // elements for floating point vectors.
6752 if (lType->hasIntegerRepresentation())
6753 return lType;
6755 const VectorType *VTy = lType->getAs<VectorType>();
6756 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6757 if (TypeSize == Context.getTypeSize(Context.IntTy))
6758 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6759 if (TypeSize == Context.getTypeSize(Context.LongTy))
6760 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6762 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6763 "Unhandled vector element size in vector compare");
6764 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6767 inline QualType Sema::CheckBitwiseOperands(
6768 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
6769 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
6770 if (lex->getType()->hasIntegerRepresentation() &&
6771 rex->getType()->hasIntegerRepresentation())
6772 return CheckVectorOperands(Loc, lex, rex);
6774 return InvalidOperands(Loc, lex, rex);
6777 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
6779 if (lex->getType()->isIntegralOrUnscopedEnumerationType() &&
6780 rex->getType()->isIntegralOrUnscopedEnumerationType())
6781 return compType;
6782 return InvalidOperands(Loc, lex, rex);
6785 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
6786 Expr *&lex, Expr *&rex, SourceLocation Loc, unsigned Opc) {
6788 // Diagnose cases where the user write a logical and/or but probably meant a
6789 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6790 // is a constant.
6791 if (lex->getType()->isIntegerType() && !lex->getType()->isBooleanType() &&
6792 rex->getType()->isIntegerType() && !rex->isValueDependent() &&
6793 // Don't warn in macros.
6794 !Loc.isMacroID()) {
6795 // If the RHS can be constant folded, and if it constant folds to something
6796 // that isn't 0 or 1 (which indicate a potential logical operation that
6797 // happened to fold to true/false) then warn.
6798 Expr::EvalResult Result;
6799 if (rex->Evaluate(Result, Context) && !Result.HasSideEffects &&
6800 Result.Val.getInt() != 0 && Result.Val.getInt() != 1) {
6801 Diag(Loc, diag::warn_logical_instead_of_bitwise)
6802 << rex->getSourceRange()
6803 << (Opc == BO_LAnd ? "&&" : "||")
6804 << (Opc == BO_LAnd ? "&" : "|");
6808 if (!Context.getLangOptions().CPlusPlus) {
6809 UsualUnaryConversions(lex);
6810 UsualUnaryConversions(rex);
6812 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
6813 return InvalidOperands(Loc, lex, rex);
6815 return Context.IntTy;
6818 // The following is safe because we only use this method for
6819 // non-overloadable operands.
6821 // C++ [expr.log.and]p1
6822 // C++ [expr.log.or]p1
6823 // The operands are both contextually converted to type bool.
6824 if (PerformContextuallyConvertToBool(lex) ||
6825 PerformContextuallyConvertToBool(rex))
6826 return InvalidOperands(Loc, lex, rex);
6828 // C++ [expr.log.and]p2
6829 // C++ [expr.log.or]p2
6830 // The result is a bool.
6831 return Context.BoolTy;
6834 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6835 /// is a read-only property; return true if so. A readonly property expression
6836 /// depends on various declarations and thus must be treated specially.
6838 static bool IsReadonlyProperty(Expr *E, Sema &S) {
6839 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6840 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6841 if (PropExpr->isImplicitProperty()) return false;
6843 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6844 QualType BaseType = PropExpr->isSuperReceiver() ?
6845 PropExpr->getSuperReceiverType() :
6846 PropExpr->getBase()->getType();
6848 if (const ObjCObjectPointerType *OPT =
6849 BaseType->getAsObjCInterfacePointerType())
6850 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6851 if (S.isPropertyReadonly(PDecl, IFace))
6852 return true;
6854 return false;
6857 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
6858 /// emit an error and return true. If so, return false.
6859 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
6860 SourceLocation OrigLoc = Loc;
6861 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
6862 &Loc);
6863 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6864 IsLV = Expr::MLV_ReadonlyProperty;
6865 if (IsLV == Expr::MLV_Valid)
6866 return false;
6868 unsigned Diag = 0;
6869 bool NeedType = false;
6870 switch (IsLV) { // C99 6.5.16p2
6871 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
6872 case Expr::MLV_ArrayType:
6873 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6874 NeedType = true;
6875 break;
6876 case Expr::MLV_NotObjectType:
6877 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6878 NeedType = true;
6879 break;
6880 case Expr::MLV_LValueCast:
6881 Diag = diag::err_typecheck_lvalue_casts_not_supported;
6882 break;
6883 case Expr::MLV_Valid:
6884 llvm_unreachable("did not take early return for MLV_Valid");
6885 case Expr::MLV_InvalidExpression:
6886 case Expr::MLV_MemberFunction:
6887 case Expr::MLV_ClassTemporary:
6888 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6889 break;
6890 case Expr::MLV_IncompleteType:
6891 case Expr::MLV_IncompleteVoidType:
6892 return S.RequireCompleteType(Loc, E->getType(),
6893 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
6894 << E->getSourceRange());
6895 case Expr::MLV_DuplicateVectorComponents:
6896 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6897 break;
6898 case Expr::MLV_NotBlockQualified:
6899 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6900 break;
6901 case Expr::MLV_ReadonlyProperty:
6902 Diag = diag::error_readonly_property_assignment;
6903 break;
6904 case Expr::MLV_NoSetterProperty:
6905 Diag = diag::error_nosetter_property_assignment;
6906 break;
6907 case Expr::MLV_SubObjCPropertySetting:
6908 Diag = diag::error_no_subobject_property_setting;
6909 break;
6912 SourceRange Assign;
6913 if (Loc != OrigLoc)
6914 Assign = SourceRange(OrigLoc, OrigLoc);
6915 if (NeedType)
6916 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
6917 else
6918 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6919 return true;
6924 // C99 6.5.16.1
6925 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
6926 SourceLocation Loc,
6927 QualType CompoundType) {
6928 // Verify that LHS is a modifiable lvalue, and emit error if not.
6929 if (CheckForModifiableLvalue(LHS, Loc, *this))
6930 return QualType();
6932 QualType LHSType = LHS->getType();
6933 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
6934 AssignConvertType ConvTy;
6935 if (CompoundType.isNull()) {
6936 QualType LHSTy(LHSType);
6937 // Simple assignment "x = y".
6938 if (LHS->getObjectKind() == OK_ObjCProperty)
6939 ConvertPropertyForLValue(LHS, RHS, LHSTy);
6940 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
6941 // Special case of NSObject attributes on c-style pointer types.
6942 if (ConvTy == IncompatiblePointer &&
6943 ((Context.isObjCNSObjectType(LHSType) &&
6944 RHSType->isObjCObjectPointerType()) ||
6945 (Context.isObjCNSObjectType(RHSType) &&
6946 LHSType->isObjCObjectPointerType())))
6947 ConvTy = Compatible;
6949 if (ConvTy == Compatible &&
6950 getLangOptions().ObjCNonFragileABI &&
6951 LHSType->isObjCObjectType())
6952 Diag(Loc, diag::err_assignment_requires_nonfragile_object)
6953 << LHSType;
6955 // If the RHS is a unary plus or minus, check to see if they = and + are
6956 // right next to each other. If so, the user may have typo'd "x =+ 4"
6957 // instead of "x += 4".
6958 Expr *RHSCheck = RHS;
6959 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
6960 RHSCheck = ICE->getSubExpr();
6961 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
6962 if ((UO->getOpcode() == UO_Plus ||
6963 UO->getOpcode() == UO_Minus) &&
6964 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
6965 // Only if the two operators are exactly adjacent.
6966 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
6967 // And there is a space or other character before the subexpr of the
6968 // unary +/-. We don't want to warn on "x=-1".
6969 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
6970 UO->getSubExpr()->getLocStart().isFileID()) {
6971 Diag(Loc, diag::warn_not_compound_assign)
6972 << (UO->getOpcode() == UO_Plus ? "+" : "-")
6973 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
6976 } else {
6977 // Compound assignment "x += y"
6978 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
6981 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
6982 RHS, AA_Assigning))
6983 return QualType();
6986 // Check to see if the destination operand is a dereferenced null pointer. If
6987 // so, and if not volatile-qualified, this is undefined behavior that the
6988 // optimizer will delete, so warn about it. People sometimes try to use this
6989 // to get a deterministic trap and are surprised by clang's behavior. This
6990 // only handles the pattern "*null = whatever", which is a very syntactic
6991 // check.
6992 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS->IgnoreParenCasts()))
6993 if (UO->getOpcode() == UO_Deref &&
6994 UO->getSubExpr()->IgnoreParenCasts()->
6995 isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) &&
6996 !UO->getType().isVolatileQualified()) {
6997 Diag(UO->getOperatorLoc(), diag::warn_indirection_through_null)
6998 << UO->getSubExpr()->getSourceRange();
6999 Diag(UO->getOperatorLoc(), diag::note_indirection_through_null);
7002 // C99 6.5.16p3: The type of an assignment expression is the type of the
7003 // left operand unless the left operand has qualified type, in which case
7004 // it is the unqualified version of the type of the left operand.
7005 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7006 // is converted to the type of the assignment expression (above).
7007 // C++ 5.17p1: the type of the assignment expression is that of its left
7008 // operand.
7009 return (getLangOptions().CPlusPlus
7010 ? LHSType : LHSType.getUnqualifiedType());
7013 // C99 6.5.17
7014 static QualType CheckCommaOperands(Sema &S, Expr *&LHS, Expr *&RHS,
7015 SourceLocation Loc) {
7016 S.DiagnoseUnusedExprResult(LHS);
7018 ExprResult LHSResult = S.CheckPlaceholderExpr(LHS, Loc);
7019 if (LHSResult.isInvalid())
7020 return QualType();
7022 ExprResult RHSResult = S.CheckPlaceholderExpr(RHS, Loc);
7023 if (RHSResult.isInvalid())
7024 return QualType();
7025 RHS = RHSResult.take();
7027 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7028 // operands, but not unary promotions.
7029 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7031 // So we treat the LHS as a ignored value, and in C++ we allow the
7032 // containing site to determine what should be done with the RHS.
7033 S.IgnoredValueConversions(LHS);
7035 if (!S.getLangOptions().CPlusPlus) {
7036 S.DefaultFunctionArrayLvalueConversion(RHS);
7037 if (!RHS->getType()->isVoidType())
7038 S.RequireCompleteType(Loc, RHS->getType(), diag::err_incomplete_type);
7041 return RHS->getType();
7044 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7045 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7046 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7047 ExprValueKind &VK,
7048 SourceLocation OpLoc,
7049 bool isInc, bool isPrefix) {
7050 if (Op->isTypeDependent())
7051 return S.Context.DependentTy;
7053 QualType ResType = Op->getType();
7054 assert(!ResType.isNull() && "no type for increment/decrement expression");
7056 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
7057 // Decrement of bool is not allowed.
7058 if (!isInc) {
7059 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7060 return QualType();
7062 // Increment of bool sets it to true, but is deprecated.
7063 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7064 } else if (ResType->isRealType()) {
7065 // OK!
7066 } else if (ResType->isAnyPointerType()) {
7067 QualType PointeeTy = ResType->getPointeeType();
7069 // C99 6.5.2.4p2, 6.5.6p2
7070 if (PointeeTy->isVoidType()) {
7071 if (S.getLangOptions().CPlusPlus) {
7072 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
7073 << Op->getSourceRange();
7074 return QualType();
7077 // Pointer to void is a GNU extension in C.
7078 S.Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
7079 } else if (PointeeTy->isFunctionType()) {
7080 if (S.getLangOptions().CPlusPlus) {
7081 S.Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
7082 << Op->getType() << Op->getSourceRange();
7083 return QualType();
7086 S.Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
7087 << ResType << Op->getSourceRange();
7088 } else if (S.RequireCompleteType(OpLoc, PointeeTy,
7089 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
7090 << Op->getSourceRange()
7091 << ResType))
7092 return QualType();
7093 // Diagnose bad cases where we step over interface counts.
7094 else if (PointeeTy->isObjCObjectType() && S.LangOpts.ObjCNonFragileABI) {
7095 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
7096 << PointeeTy << Op->getSourceRange();
7097 return QualType();
7099 } else if (ResType->isAnyComplexType()) {
7100 // C99 does not support ++/-- on complex types, we allow as an extension.
7101 S.Diag(OpLoc, diag::ext_integer_increment_complex)
7102 << ResType << Op->getSourceRange();
7103 } else if (ResType->isPlaceholderType()) {
7104 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
7105 if (PR.isInvalid()) return QualType();
7106 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7107 isInc, isPrefix);
7108 } else {
7109 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7110 << ResType << int(isInc) << Op->getSourceRange();
7111 return QualType();
7113 // At this point, we know we have a real, complex or pointer type.
7114 // Now make sure the operand is a modifiable lvalue.
7115 if (CheckForModifiableLvalue(Op, OpLoc, S))
7116 return QualType();
7117 // In C++, a prefix increment is the same type as the operand. Otherwise
7118 // (in C or with postfix), the increment is the unqualified type of the
7119 // operand.
7120 if (isPrefix && S.getLangOptions().CPlusPlus) {
7121 VK = VK_LValue;
7122 return ResType;
7123 } else {
7124 VK = VK_RValue;
7125 return ResType.getUnqualifiedType();
7129 void Sema::ConvertPropertyForRValue(Expr *&E) {
7130 assert(E->getValueKind() == VK_LValue &&
7131 E->getObjectKind() == OK_ObjCProperty);
7132 const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7134 ExprValueKind VK = VK_RValue;
7135 if (PRE->isImplicitProperty()) {
7136 if (const ObjCMethodDecl *GetterMethod =
7137 PRE->getImplicitPropertyGetter()) {
7138 QualType Result = GetterMethod->getResultType();
7139 VK = Expr::getValueKindForType(Result);
7141 else {
7142 Diag(PRE->getLocation(), diag::err_getter_not_found)
7143 << PRE->getBase()->getType();
7147 E = ImplicitCastExpr::Create(Context, E->getType(), CK_GetObjCProperty,
7148 E, 0, VK);
7150 ExprResult Result = MaybeBindToTemporary(E);
7151 if (!Result.isInvalid())
7152 E = Result.take();
7155 void Sema::ConvertPropertyForLValue(Expr *&LHS, Expr *&RHS, QualType &LHSTy) {
7156 assert(LHS->getValueKind() == VK_LValue &&
7157 LHS->getObjectKind() == OK_ObjCProperty);
7158 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7160 if (PRE->isImplicitProperty()) {
7161 // If using property-dot syntax notation for assignment, and there is a
7162 // setter, RHS expression is being passed to the setter argument. So,
7163 // type conversion (and comparison) is RHS to setter's argument type.
7164 if (const ObjCMethodDecl *SetterMD = PRE->getImplicitPropertySetter()) {
7165 ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
7166 LHSTy = (*P)->getType();
7168 // Otherwise, if the getter returns an l-value, just call that.
7169 } else {
7170 QualType Result = PRE->getImplicitPropertyGetter()->getResultType();
7171 ExprValueKind VK = Expr::getValueKindForType(Result);
7172 if (VK == VK_LValue) {
7173 LHS = ImplicitCastExpr::Create(Context, LHS->getType(),
7174 CK_GetObjCProperty, LHS, 0, VK);
7175 return;
7180 if (getLangOptions().CPlusPlus && LHSTy->isRecordType()) {
7181 InitializedEntity Entity =
7182 InitializedEntity::InitializeParameter(Context, LHSTy);
7183 Expr *Arg = RHS;
7184 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(),
7185 Owned(Arg));
7186 if (!ArgE.isInvalid())
7187 RHS = ArgE.takeAs<Expr>();
7192 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7193 /// This routine allows us to typecheck complex/recursive expressions
7194 /// where the declaration is needed for type checking. We only need to
7195 /// handle cases when the expression references a function designator
7196 /// or is an lvalue. Here are some examples:
7197 /// - &(x) => x
7198 /// - &*****f => f for f a function designator.
7199 /// - &s.xx => s
7200 /// - &s.zz[1].yy -> s, if zz is an array
7201 /// - *(x + 1) -> x, if x is an array
7202 /// - &"123"[2] -> 0
7203 /// - & __real__ x -> x
7204 static NamedDecl *getPrimaryDecl(Expr *E) {
7205 switch (E->getStmtClass()) {
7206 case Stmt::DeclRefExprClass:
7207 return cast<DeclRefExpr>(E)->getDecl();
7208 case Stmt::MemberExprClass:
7209 // If this is an arrow operator, the address is an offset from
7210 // the base's value, so the object the base refers to is
7211 // irrelevant.
7212 if (cast<MemberExpr>(E)->isArrow())
7213 return 0;
7214 // Otherwise, the expression refers to a part of the base
7215 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7216 case Stmt::ArraySubscriptExprClass: {
7217 // FIXME: This code shouldn't be necessary! We should catch the implicit
7218 // promotion of register arrays earlier.
7219 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7220 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7221 if (ICE->getSubExpr()->getType()->isArrayType())
7222 return getPrimaryDecl(ICE->getSubExpr());
7224 return 0;
7226 case Stmt::UnaryOperatorClass: {
7227 UnaryOperator *UO = cast<UnaryOperator>(E);
7229 switch(UO->getOpcode()) {
7230 case UO_Real:
7231 case UO_Imag:
7232 case UO_Extension:
7233 return getPrimaryDecl(UO->getSubExpr());
7234 default:
7235 return 0;
7238 case Stmt::ParenExprClass:
7239 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7240 case Stmt::ImplicitCastExprClass:
7241 // If the result of an implicit cast is an l-value, we care about
7242 // the sub-expression; otherwise, the result here doesn't matter.
7243 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7244 default:
7245 return 0;
7249 /// CheckAddressOfOperand - The operand of & must be either a function
7250 /// designator or an lvalue designating an object. If it is an lvalue, the
7251 /// object cannot be declared with storage class register or be a bit field.
7252 /// Note: The usual conversions are *not* applied to the operand of the &
7253 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7254 /// In C++, the operand might be an overloaded function name, in which case
7255 /// we allow the '&' but retain the overloaded-function type.
7256 static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7257 SourceLocation OpLoc) {
7258 if (OrigOp->isTypeDependent())
7259 return S.Context.DependentTy;
7260 if (OrigOp->getType() == S.Context.OverloadTy)
7261 return S.Context.OverloadTy;
7263 ExprResult PR = S.CheckPlaceholderExpr(OrigOp, OpLoc);
7264 if (PR.isInvalid()) return QualType();
7265 OrigOp = PR.take();
7267 // Make sure to ignore parentheses in subsequent checks
7268 Expr *op = OrigOp->IgnoreParens();
7270 if (S.getLangOptions().C99) {
7271 // Implement C99-only parts of addressof rules.
7272 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7273 if (uOp->getOpcode() == UO_Deref)
7274 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7275 // (assuming the deref expression is valid).
7276 return uOp->getSubExpr()->getType();
7278 // Technically, there should be a check for array subscript
7279 // expressions here, but the result of one is always an lvalue anyway.
7281 NamedDecl *dcl = getPrimaryDecl(op);
7282 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7284 if (lval == Expr::LV_ClassTemporary) {
7285 bool sfinae = S.isSFINAEContext();
7286 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7287 : diag::ext_typecheck_addrof_class_temporary)
7288 << op->getType() << op->getSourceRange();
7289 if (sfinae)
7290 return QualType();
7291 } else if (isa<ObjCSelectorExpr>(op)) {
7292 return S.Context.getPointerType(op->getType());
7293 } else if (lval == Expr::LV_MemberFunction) {
7294 // If it's an instance method, make a member pointer.
7295 // The expression must have exactly the form &A::foo.
7297 // If the underlying expression isn't a decl ref, give up.
7298 if (!isa<DeclRefExpr>(op)) {
7299 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7300 << OrigOp->getSourceRange();
7301 return QualType();
7303 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7304 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7306 // The id-expression was parenthesized.
7307 if (OrigOp != DRE) {
7308 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7309 << OrigOp->getSourceRange();
7311 // The method was named without a qualifier.
7312 } else if (!DRE->getQualifier()) {
7313 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7314 << op->getSourceRange();
7317 return S.Context.getMemberPointerType(op->getType(),
7318 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7319 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7320 // C99 6.5.3.2p1
7321 // The operand must be either an l-value or a function designator
7322 if (!op->getType()->isFunctionType()) {
7323 // FIXME: emit more specific diag...
7324 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7325 << op->getSourceRange();
7326 return QualType();
7328 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7329 // The operand cannot be a bit-field
7330 S.Diag(OpLoc, diag::err_typecheck_address_of)
7331 << "bit-field" << op->getSourceRange();
7332 return QualType();
7333 } else if (op->getObjectKind() == OK_VectorComponent) {
7334 // The operand cannot be an element of a vector
7335 S.Diag(OpLoc, diag::err_typecheck_address_of)
7336 << "vector element" << op->getSourceRange();
7337 return QualType();
7338 } else if (op->getObjectKind() == OK_ObjCProperty) {
7339 // cannot take address of a property expression.
7340 S.Diag(OpLoc, diag::err_typecheck_address_of)
7341 << "property expression" << op->getSourceRange();
7342 return QualType();
7343 } else if (dcl) { // C99 6.5.3.2p1
7344 // We have an lvalue with a decl. Make sure the decl is not declared
7345 // with the register storage-class specifier.
7346 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
7347 // in C++ it is not error to take address of a register
7348 // variable (c++03 7.1.1P3)
7349 if (vd->getStorageClass() == SC_Register &&
7350 !S.getLangOptions().CPlusPlus) {
7351 S.Diag(OpLoc, diag::err_typecheck_address_of)
7352 << "register variable" << op->getSourceRange();
7353 return QualType();
7355 } else if (isa<FunctionTemplateDecl>(dcl)) {
7356 return S.Context.OverloadTy;
7357 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
7358 // Okay: we can take the address of a field.
7359 // Could be a pointer to member, though, if there is an explicit
7360 // scope qualifier for the class.
7361 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
7362 DeclContext *Ctx = dcl->getDeclContext();
7363 if (Ctx && Ctx->isRecord()) {
7364 if (FD->getType()->isReferenceType()) {
7365 S.Diag(OpLoc,
7366 diag::err_cannot_form_pointer_to_member_of_reference_type)
7367 << FD->getDeclName() << FD->getType();
7368 return QualType();
7371 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7372 Ctx = Ctx->getParent();
7373 return S.Context.getMemberPointerType(op->getType(),
7374 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
7377 } else if (!isa<FunctionDecl>(dcl))
7378 assert(0 && "Unknown/unexpected decl type");
7381 if (lval == Expr::LV_IncompleteVoidType) {
7382 // Taking the address of a void variable is technically illegal, but we
7383 // allow it in cases which are otherwise valid.
7384 // Example: "extern void x; void* y = &x;".
7385 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
7388 // If the operand has type "type", the result has type "pointer to type".
7389 if (op->getType()->isObjCObjectType())
7390 return S.Context.getObjCObjectPointerType(op->getType());
7391 return S.Context.getPointerType(op->getType());
7394 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
7395 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7396 SourceLocation OpLoc) {
7397 if (Op->isTypeDependent())
7398 return S.Context.DependentTy;
7400 S.UsualUnaryConversions(Op);
7401 QualType OpTy = Op->getType();
7402 QualType Result;
7404 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7405 // is an incomplete type or void. It would be possible to warn about
7406 // dereferencing a void pointer, but it's completely well-defined, and such a
7407 // warning is unlikely to catch any mistakes.
7408 if (const PointerType *PT = OpTy->getAs<PointerType>())
7409 Result = PT->getPointeeType();
7410 else if (const ObjCObjectPointerType *OPT =
7411 OpTy->getAs<ObjCObjectPointerType>())
7412 Result = OPT->getPointeeType();
7413 else {
7414 ExprResult PR = S.CheckPlaceholderExpr(Op, OpLoc);
7415 if (PR.isInvalid()) return QualType();
7416 if (PR.take() != Op)
7417 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
7420 if (Result.isNull()) {
7421 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
7422 << OpTy << Op->getSourceRange();
7423 return QualType();
7426 // Dereferences are usually l-values...
7427 VK = VK_LValue;
7429 // ...except that certain expressions are never l-values in C.
7430 if (!S.getLangOptions().CPlusPlus &&
7431 IsCForbiddenLValueType(S.Context, Result))
7432 VK = VK_RValue;
7434 return Result;
7437 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
7438 tok::TokenKind Kind) {
7439 BinaryOperatorKind Opc;
7440 switch (Kind) {
7441 default: assert(0 && "Unknown binop!");
7442 case tok::periodstar: Opc = BO_PtrMemD; break;
7443 case tok::arrowstar: Opc = BO_PtrMemI; break;
7444 case tok::star: Opc = BO_Mul; break;
7445 case tok::slash: Opc = BO_Div; break;
7446 case tok::percent: Opc = BO_Rem; break;
7447 case tok::plus: Opc = BO_Add; break;
7448 case tok::minus: Opc = BO_Sub; break;
7449 case tok::lessless: Opc = BO_Shl; break;
7450 case tok::greatergreater: Opc = BO_Shr; break;
7451 case tok::lessequal: Opc = BO_LE; break;
7452 case tok::less: Opc = BO_LT; break;
7453 case tok::greaterequal: Opc = BO_GE; break;
7454 case tok::greater: Opc = BO_GT; break;
7455 case tok::exclaimequal: Opc = BO_NE; break;
7456 case tok::equalequal: Opc = BO_EQ; break;
7457 case tok::amp: Opc = BO_And; break;
7458 case tok::caret: Opc = BO_Xor; break;
7459 case tok::pipe: Opc = BO_Or; break;
7460 case tok::ampamp: Opc = BO_LAnd; break;
7461 case tok::pipepipe: Opc = BO_LOr; break;
7462 case tok::equal: Opc = BO_Assign; break;
7463 case tok::starequal: Opc = BO_MulAssign; break;
7464 case tok::slashequal: Opc = BO_DivAssign; break;
7465 case tok::percentequal: Opc = BO_RemAssign; break;
7466 case tok::plusequal: Opc = BO_AddAssign; break;
7467 case tok::minusequal: Opc = BO_SubAssign; break;
7468 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7469 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7470 case tok::ampequal: Opc = BO_AndAssign; break;
7471 case tok::caretequal: Opc = BO_XorAssign; break;
7472 case tok::pipeequal: Opc = BO_OrAssign; break;
7473 case tok::comma: Opc = BO_Comma; break;
7475 return Opc;
7478 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
7479 tok::TokenKind Kind) {
7480 UnaryOperatorKind Opc;
7481 switch (Kind) {
7482 default: assert(0 && "Unknown unary op!");
7483 case tok::plusplus: Opc = UO_PreInc; break;
7484 case tok::minusminus: Opc = UO_PreDec; break;
7485 case tok::amp: Opc = UO_AddrOf; break;
7486 case tok::star: Opc = UO_Deref; break;
7487 case tok::plus: Opc = UO_Plus; break;
7488 case tok::minus: Opc = UO_Minus; break;
7489 case tok::tilde: Opc = UO_Not; break;
7490 case tok::exclaim: Opc = UO_LNot; break;
7491 case tok::kw___real: Opc = UO_Real; break;
7492 case tok::kw___imag: Opc = UO_Imag; break;
7493 case tok::kw___extension__: Opc = UO_Extension; break;
7495 return Opc;
7498 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7499 /// This warning is only emitted for builtin assignment operations. It is also
7500 /// suppressed in the event of macro expansions.
7501 static void DiagnoseSelfAssignment(Sema &S, Expr *lhs, Expr *rhs,
7502 SourceLocation OpLoc) {
7503 if (!S.ActiveTemplateInstantiations.empty())
7504 return;
7505 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7506 return;
7507 lhs = lhs->IgnoreParenImpCasts();
7508 rhs = rhs->IgnoreParenImpCasts();
7509 const DeclRefExpr *LeftDeclRef = dyn_cast<DeclRefExpr>(lhs);
7510 const DeclRefExpr *RightDeclRef = dyn_cast<DeclRefExpr>(rhs);
7511 if (!LeftDeclRef || !RightDeclRef ||
7512 LeftDeclRef->getLocation().isMacroID() ||
7513 RightDeclRef->getLocation().isMacroID())
7514 return;
7515 const ValueDecl *LeftDecl =
7516 cast<ValueDecl>(LeftDeclRef->getDecl()->getCanonicalDecl());
7517 const ValueDecl *RightDecl =
7518 cast<ValueDecl>(RightDeclRef->getDecl()->getCanonicalDecl());
7519 if (LeftDecl != RightDecl)
7520 return;
7521 if (LeftDecl->getType().isVolatileQualified())
7522 return;
7523 if (const ReferenceType *RefTy = LeftDecl->getType()->getAs<ReferenceType>())
7524 if (RefTy->getPointeeType().isVolatileQualified())
7525 return;
7527 S.Diag(OpLoc, diag::warn_self_assignment)
7528 << LeftDeclRef->getType()
7529 << lhs->getSourceRange() << rhs->getSourceRange();
7532 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7533 /// operator @p Opc at location @c TokLoc. This routine only supports
7534 /// built-in operations; ActOnBinOp handles overloaded operators.
7535 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
7536 BinaryOperatorKind Opc,
7537 Expr *lhs, Expr *rhs) {
7538 QualType ResultTy; // Result type of the binary operator.
7539 // The following two variables are used for compound assignment operators
7540 QualType CompLHSTy; // Type of LHS after promotions for computation
7541 QualType CompResultTy; // Type of computation result
7542 ExprValueKind VK = VK_RValue;
7543 ExprObjectKind OK = OK_Ordinary;
7545 switch (Opc) {
7546 case BO_Assign:
7547 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
7548 if (getLangOptions().CPlusPlus &&
7549 lhs->getObjectKind() != OK_ObjCProperty) {
7550 VK = lhs->getValueKind();
7551 OK = lhs->getObjectKind();
7553 if (!ResultTy.isNull())
7554 DiagnoseSelfAssignment(*this, lhs, rhs, OpLoc);
7555 break;
7556 case BO_PtrMemD:
7557 case BO_PtrMemI:
7558 ResultTy = CheckPointerToMemberOperands(lhs, rhs, VK, OpLoc,
7559 Opc == BO_PtrMemI);
7560 break;
7561 case BO_Mul:
7562 case BO_Div:
7563 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
7564 Opc == BO_Div);
7565 break;
7566 case BO_Rem:
7567 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
7568 break;
7569 case BO_Add:
7570 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
7571 break;
7572 case BO_Sub:
7573 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
7574 break;
7575 case BO_Shl:
7576 case BO_Shr:
7577 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
7578 break;
7579 case BO_LE:
7580 case BO_LT:
7581 case BO_GE:
7582 case BO_GT:
7583 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
7584 break;
7585 case BO_EQ:
7586 case BO_NE:
7587 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
7588 break;
7589 case BO_And:
7590 case BO_Xor:
7591 case BO_Or:
7592 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
7593 break;
7594 case BO_LAnd:
7595 case BO_LOr:
7596 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc, Opc);
7597 break;
7598 case BO_MulAssign:
7599 case BO_DivAssign:
7600 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
7601 Opc == BO_DivAssign);
7602 CompLHSTy = CompResultTy;
7603 if (!CompResultTy.isNull())
7604 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7605 break;
7606 case BO_RemAssign:
7607 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
7608 CompLHSTy = CompResultTy;
7609 if (!CompResultTy.isNull())
7610 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7611 break;
7612 case BO_AddAssign:
7613 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7614 if (!CompResultTy.isNull())
7615 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7616 break;
7617 case BO_SubAssign:
7618 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
7619 if (!CompResultTy.isNull())
7620 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7621 break;
7622 case BO_ShlAssign:
7623 case BO_ShrAssign:
7624 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
7625 CompLHSTy = CompResultTy;
7626 if (!CompResultTy.isNull())
7627 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7628 break;
7629 case BO_AndAssign:
7630 case BO_XorAssign:
7631 case BO_OrAssign:
7632 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
7633 CompLHSTy = CompResultTy;
7634 if (!CompResultTy.isNull())
7635 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
7636 break;
7637 case BO_Comma:
7638 ResultTy = CheckCommaOperands(*this, lhs, rhs, OpLoc);
7639 if (getLangOptions().CPlusPlus) {
7640 VK = rhs->getValueKind();
7641 OK = rhs->getObjectKind();
7643 break;
7645 if (ResultTy.isNull())
7646 return ExprError();
7647 if (CompResultTy.isNull())
7648 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy,
7649 VK, OK, OpLoc));
7651 if (getLangOptions().CPlusPlus && lhs->getObjectKind() != OK_ObjCProperty) {
7652 VK = VK_LValue;
7653 OK = lhs->getObjectKind();
7655 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
7656 VK, OK, CompLHSTy,
7657 CompResultTy, OpLoc));
7660 /// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
7661 /// ParenRange in parentheses.
7662 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7663 const PartialDiagnostic &PD,
7664 const PartialDiagnostic &FirstNote,
7665 SourceRange FirstParenRange,
7666 const PartialDiagnostic &SecondNote,
7667 SourceRange SecondParenRange) {
7668 Self.Diag(Loc, PD);
7670 if (!FirstNote.getDiagID())
7671 return;
7673 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
7674 if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7675 // We can't display the parentheses, so just return.
7676 return;
7679 Self.Diag(Loc, FirstNote)
7680 << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
7681 << FixItHint::CreateInsertion(EndLoc, ")");
7683 if (!SecondNote.getDiagID())
7684 return;
7686 EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
7687 if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
7688 // We can't display the parentheses, so just dig the
7689 // warning/error and return.
7690 Self.Diag(Loc, SecondNote);
7691 return;
7694 Self.Diag(Loc, SecondNote)
7695 << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
7696 << FixItHint::CreateInsertion(EndLoc, ")");
7699 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7700 /// operators are mixed in a way that suggests that the programmer forgot that
7701 /// comparison operators have higher precedence. The most typical example of
7702 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
7703 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
7704 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
7705 typedef BinaryOperator BinOp;
7706 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
7707 rhsopc = static_cast<BinOp::Opcode>(-1);
7708 if (BinOp *BO = dyn_cast<BinOp>(lhs))
7709 lhsopc = BO->getOpcode();
7710 if (BinOp *BO = dyn_cast<BinOp>(rhs))
7711 rhsopc = BO->getOpcode();
7713 // Subs are not binary operators.
7714 if (lhsopc == -1 && rhsopc == -1)
7715 return;
7717 // Bitwise operations are sometimes used as eager logical ops.
7718 // Don't diagnose this.
7719 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
7720 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
7721 return;
7723 if (BinOp::isComparisonOp(lhsopc))
7724 SuggestParentheses(Self, OpLoc,
7725 Self.PDiag(diag::warn_precedence_bitwise_rel)
7726 << SourceRange(lhs->getLocStart(), OpLoc)
7727 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
7728 Self.PDiag(diag::note_precedence_bitwise_first)
7729 << BinOp::getOpcodeStr(Opc),
7730 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
7731 Self.PDiag(diag::note_precedence_bitwise_silence)
7732 << BinOp::getOpcodeStr(lhsopc),
7733 lhs->getSourceRange());
7734 else if (BinOp::isComparisonOp(rhsopc))
7735 SuggestParentheses(Self, OpLoc,
7736 Self.PDiag(diag::warn_precedence_bitwise_rel)
7737 << SourceRange(OpLoc, rhs->getLocEnd())
7738 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
7739 Self.PDiag(diag::note_precedence_bitwise_first)
7740 << BinOp::getOpcodeStr(Opc),
7741 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
7742 Self.PDiag(diag::note_precedence_bitwise_silence)
7743 << BinOp::getOpcodeStr(rhsopc),
7744 rhs->getSourceRange());
7747 /// \brief It accepts a '&&' expr that is inside a '||' one.
7748 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7749 /// in parentheses.
7750 static void
7751 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7752 Expr *E) {
7753 assert(isa<BinaryOperator>(E) &&
7754 cast<BinaryOperator>(E)->getOpcode() == BO_LAnd);
7755 SuggestParentheses(Self, OpLoc,
7756 Self.PDiag(diag::warn_logical_and_in_logical_or)
7757 << E->getSourceRange(),
7758 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7759 E->getSourceRange(),
7760 Self.PDiag(0), SourceRange());
7763 /// \brief Returns true if the given expression can be evaluated as a constant
7764 /// 'true'.
7765 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7766 bool Res;
7767 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7770 /// \brief Returns true if the given expression can be evaluated as a constant
7771 /// 'false'.
7772 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7773 bool Res;
7774 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7777 /// \brief Look for '&&' in the left hand of a '||' expr.
7778 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
7779 Expr *OrLHS, Expr *OrRHS) {
7780 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrLHS)) {
7781 if (Bop->getOpcode() == BO_LAnd) {
7782 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7783 if (EvaluatesAsFalse(S, OrRHS))
7784 return;
7785 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7786 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7787 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7788 } else if (Bop->getOpcode() == BO_LOr) {
7789 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7790 // If it's "a || b && 1 || c" we didn't warn earlier for
7791 // "a || b && 1", but warn now.
7792 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7793 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7799 /// \brief Look for '&&' in the right hand of a '||' expr.
7800 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
7801 Expr *OrLHS, Expr *OrRHS) {
7802 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrRHS)) {
7803 if (Bop->getOpcode() == BO_LAnd) {
7804 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7805 if (EvaluatesAsFalse(S, OrLHS))
7806 return;
7807 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7808 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7809 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7814 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
7815 /// precedence.
7816 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
7817 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
7818 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
7819 if (BinaryOperator::isBitwiseOp(Opc))
7820 return DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
7822 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7823 // We don't warn for 'assert(a || b && "bad")' since this is safe.
7824 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7825 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, lhs, rhs);
7826 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, lhs, rhs);
7830 // Binary Operators. 'Tok' is the token for the operator.
7831 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
7832 tok::TokenKind Kind,
7833 Expr *lhs, Expr *rhs) {
7834 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
7835 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
7836 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
7838 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7839 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
7841 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
7844 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
7845 BinaryOperatorKind Opc,
7846 Expr *lhs, Expr *rhs) {
7847 if (getLangOptions().CPlusPlus) {
7848 bool UseBuiltinOperator;
7850 if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
7851 UseBuiltinOperator = false;
7852 } else if (Opc == BO_Assign && lhs->getObjectKind() == OK_ObjCProperty) {
7853 UseBuiltinOperator = true;
7854 } else {
7855 UseBuiltinOperator = !lhs->getType()->isOverloadableType() &&
7856 !rhs->getType()->isOverloadableType();
7859 if (!UseBuiltinOperator) {
7860 // Find all of the overloaded operators visible from this
7861 // point. We perform both an operator-name lookup from the local
7862 // scope and an argument-dependent lookup based on the types of
7863 // the arguments.
7864 UnresolvedSet<16> Functions;
7865 OverloadedOperatorKind OverOp
7866 = BinaryOperator::getOverloadedOperator(Opc);
7867 if (S && OverOp != OO_None)
7868 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
7869 Functions);
7871 // Build the (potentially-overloaded, potentially-dependent)
7872 // binary operation.
7873 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
7877 // Build a built-in binary operation.
7878 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
7881 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
7882 UnaryOperatorKind Opc,
7883 Expr *Input) {
7884 ExprValueKind VK = VK_RValue;
7885 ExprObjectKind OK = OK_Ordinary;
7886 QualType resultType;
7887 switch (Opc) {
7888 case UO_PreInc:
7889 case UO_PreDec:
7890 case UO_PostInc:
7891 case UO_PostDec:
7892 resultType = CheckIncrementDecrementOperand(*this, Input, VK, OpLoc,
7893 Opc == UO_PreInc ||
7894 Opc == UO_PostInc,
7895 Opc == UO_PreInc ||
7896 Opc == UO_PreDec);
7897 break;
7898 case UO_AddrOf:
7899 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
7900 break;
7901 case UO_Deref:
7902 DefaultFunctionArrayLvalueConversion(Input);
7903 resultType = CheckIndirectionOperand(*this, Input, VK, OpLoc);
7904 break;
7905 case UO_Plus:
7906 case UO_Minus:
7907 UsualUnaryConversions(Input);
7908 resultType = Input->getType();
7909 if (resultType->isDependentType())
7910 break;
7911 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
7912 resultType->isVectorType())
7913 break;
7914 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
7915 resultType->isEnumeralType())
7916 break;
7917 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
7918 Opc == UO_Plus &&
7919 resultType->isPointerType())
7920 break;
7921 else if (resultType->isPlaceholderType()) {
7922 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7923 if (PR.isInvalid()) return ExprError();
7924 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
7927 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7928 << resultType << Input->getSourceRange());
7929 case UO_Not: // bitwise complement
7930 UsualUnaryConversions(Input);
7931 resultType = Input->getType();
7932 if (resultType->isDependentType())
7933 break;
7934 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
7935 if (resultType->isComplexType() || resultType->isComplexIntegerType())
7936 // C99 does not support '~' for complex conjugation.
7937 Diag(OpLoc, diag::ext_integer_complement_complex)
7938 << resultType << Input->getSourceRange();
7939 else if (resultType->hasIntegerRepresentation())
7940 break;
7941 else if (resultType->isPlaceholderType()) {
7942 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7943 if (PR.isInvalid()) return ExprError();
7944 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
7945 } else {
7946 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7947 << resultType << Input->getSourceRange());
7949 break;
7950 case UO_LNot: // logical negation
7951 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
7952 DefaultFunctionArrayLvalueConversion(Input);
7953 resultType = Input->getType();
7954 if (resultType->isDependentType())
7955 break;
7956 if (resultType->isScalarType()) { // C99 6.5.3.3p1
7957 // ok, fallthrough
7958 } else if (resultType->isPlaceholderType()) {
7959 ExprResult PR = CheckPlaceholderExpr(Input, OpLoc);
7960 if (PR.isInvalid()) return ExprError();
7961 return CreateBuiltinUnaryOp(OpLoc, Opc, PR.take());
7962 } else {
7963 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
7964 << resultType << Input->getSourceRange());
7967 // LNot always has type int. C99 6.5.3.3p5.
7968 // In C++, it's bool. C++ 5.3.1p8
7969 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
7970 break;
7971 case UO_Real:
7972 case UO_Imag:
7973 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
7974 // _Real and _Imag map ordinary l-values into ordinary l-values.
7975 if (Input->getValueKind() != VK_RValue &&
7976 Input->getObjectKind() == OK_Ordinary)
7977 VK = Input->getValueKind();
7978 break;
7979 case UO_Extension:
7980 resultType = Input->getType();
7981 VK = Input->getValueKind();
7982 OK = Input->getObjectKind();
7983 break;
7985 if (resultType.isNull())
7986 return ExprError();
7988 return Owned(new (Context) UnaryOperator(Input, Opc, resultType,
7989 VK, OK, OpLoc));
7992 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
7993 UnaryOperatorKind Opc,
7994 Expr *Input) {
7995 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
7996 UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
7997 // Find all of the overloaded operators visible from this
7998 // point. We perform both an operator-name lookup from the local
7999 // scope and an argument-dependent lookup based on the types of
8000 // the arguments.
8001 UnresolvedSet<16> Functions;
8002 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8003 if (S && OverOp != OO_None)
8004 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8005 Functions);
8007 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8010 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8013 // Unary Operators. 'Tok' is the token for the operator.
8014 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8015 tok::TokenKind Op, Expr *Input) {
8016 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8019 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8020 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
8021 SourceLocation LabLoc,
8022 IdentifierInfo *LabelII) {
8023 // Look up the record for this label identifier.
8024 LabelStmt *&LabelDecl = getCurFunction()->LabelMap[LabelII];
8026 // If we haven't seen this label yet, create a forward reference. It
8027 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
8028 if (LabelDecl == 0)
8029 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
8031 LabelDecl->setUsed();
8032 // Create the AST node. The address of a label always has type 'void*'.
8033 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
8034 Context.getPointerType(Context.VoidTy)));
8037 ExprResult
8038 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8039 SourceLocation RPLoc) { // "({..})"
8040 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8041 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8043 bool isFileScope
8044 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8045 if (isFileScope)
8046 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8048 // FIXME: there are a variety of strange constraints to enforce here, for
8049 // example, it is not possible to goto into a stmt expression apparently.
8050 // More semantic analysis is needed.
8052 // If there are sub stmts in the compound stmt, take the type of the last one
8053 // as the type of the stmtexpr.
8054 QualType Ty = Context.VoidTy;
8055 bool StmtExprMayBindToTemp = false;
8056 if (!Compound->body_empty()) {
8057 Stmt *LastStmt = Compound->body_back();
8058 LabelStmt *LastLabelStmt = 0;
8059 // If LastStmt is a label, skip down through into the body.
8060 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8061 LastLabelStmt = Label;
8062 LastStmt = Label->getSubStmt();
8064 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt)) {
8065 // Do function/array conversion on the last expression, but not
8066 // lvalue-to-rvalue. However, initialize an unqualified type.
8067 DefaultFunctionArrayConversion(LastExpr);
8068 Ty = LastExpr->getType().getUnqualifiedType();
8070 if (!Ty->isDependentType() && !LastExpr->isTypeDependent()) {
8071 ExprResult Res = PerformCopyInitialization(
8072 InitializedEntity::InitializeResult(LPLoc,
8074 false),
8075 SourceLocation(),
8076 Owned(LastExpr));
8077 if (Res.isInvalid())
8078 return ExprError();
8079 if ((LastExpr = Res.takeAs<Expr>())) {
8080 if (!LastLabelStmt)
8081 Compound->setLastStmt(LastExpr);
8082 else
8083 LastLabelStmt->setSubStmt(LastExpr);
8084 StmtExprMayBindToTemp = true;
8090 // FIXME: Check that expression type is complete/non-abstract; statement
8091 // expressions are not lvalues.
8092 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8093 if (StmtExprMayBindToTemp)
8094 return MaybeBindToTemporary(ResStmtExpr);
8095 return Owned(ResStmtExpr);
8098 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8099 TypeSourceInfo *TInfo,
8100 OffsetOfComponent *CompPtr,
8101 unsigned NumComponents,
8102 SourceLocation RParenLoc) {
8103 QualType ArgTy = TInfo->getType();
8104 bool Dependent = ArgTy->isDependentType();
8105 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8107 // We must have at least one component that refers to the type, and the first
8108 // one is known to be a field designator. Verify that the ArgTy represents
8109 // a struct/union/class.
8110 if (!Dependent && !ArgTy->isRecordType())
8111 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8112 << ArgTy << TypeRange);
8114 // Type must be complete per C99 7.17p3 because a declaring a variable
8115 // with an incomplete type would be ill-formed.
8116 if (!Dependent
8117 && RequireCompleteType(BuiltinLoc, ArgTy,
8118 PDiag(diag::err_offsetof_incomplete_type)
8119 << TypeRange))
8120 return ExprError();
8122 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8123 // GCC extension, diagnose them.
8124 // FIXME: This diagnostic isn't actually visible because the location is in
8125 // a system header!
8126 if (NumComponents != 1)
8127 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8128 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
8130 bool DidWarnAboutNonPOD = false;
8131 QualType CurrentType = ArgTy;
8132 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8133 llvm::SmallVector<OffsetOfNode, 4> Comps;
8134 llvm::SmallVector<Expr*, 4> Exprs;
8135 for (unsigned i = 0; i != NumComponents; ++i) {
8136 const OffsetOfComponent &OC = CompPtr[i];
8137 if (OC.isBrackets) {
8138 // Offset of an array sub-field. TODO: Should we allow vector elements?
8139 if (!CurrentType->isDependentType()) {
8140 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8141 if(!AT)
8142 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8143 << CurrentType);
8144 CurrentType = AT->getElementType();
8145 } else
8146 CurrentType = Context.DependentTy;
8148 // The expression must be an integral expression.
8149 // FIXME: An integral constant expression?
8150 Expr *Idx = static_cast<Expr*>(OC.U.E);
8151 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8152 !Idx->getType()->isIntegerType())
8153 return ExprError(Diag(Idx->getLocStart(),
8154 diag::err_typecheck_subscript_not_integer)
8155 << Idx->getSourceRange());
8157 // Record this array index.
8158 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8159 Exprs.push_back(Idx);
8160 continue;
8163 // Offset of a field.
8164 if (CurrentType->isDependentType()) {
8165 // We have the offset of a field, but we can't look into the dependent
8166 // type. Just record the identifier of the field.
8167 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8168 CurrentType = Context.DependentTy;
8169 continue;
8172 // We need to have a complete type to look into.
8173 if (RequireCompleteType(OC.LocStart, CurrentType,
8174 diag::err_offsetof_incomplete_type))
8175 return ExprError();
8177 // Look for the designated field.
8178 const RecordType *RC = CurrentType->getAs<RecordType>();
8179 if (!RC)
8180 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8181 << CurrentType);
8182 RecordDecl *RD = RC->getDecl();
8184 // C++ [lib.support.types]p5:
8185 // The macro offsetof accepts a restricted set of type arguments in this
8186 // International Standard. type shall be a POD structure or a POD union
8187 // (clause 9).
8188 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8189 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8190 DiagRuntimeBehavior(BuiltinLoc,
8191 PDiag(diag::warn_offsetof_non_pod_type)
8192 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8193 << CurrentType))
8194 DidWarnAboutNonPOD = true;
8197 // Look for the field.
8198 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8199 LookupQualifiedName(R, RD);
8200 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
8201 IndirectFieldDecl *IndirectMemberDecl = 0;
8202 if (!MemberDecl) {
8203 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
8204 MemberDecl = IndirectMemberDecl->getAnonField();
8207 if (!MemberDecl)
8208 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8209 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8210 OC.LocEnd));
8212 // C99 7.17p3:
8213 // (If the specified member is a bit-field, the behavior is undefined.)
8215 // We diagnose this as an error.
8216 if (MemberDecl->getBitWidth()) {
8217 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8218 << MemberDecl->getDeclName()
8219 << SourceRange(BuiltinLoc, RParenLoc);
8220 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8221 return ExprError();
8224 RecordDecl *Parent = MemberDecl->getParent();
8225 if (IndirectMemberDecl)
8226 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
8228 // If the member was found in a base class, introduce OffsetOfNodes for
8229 // the base class indirections.
8230 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8231 /*DetectVirtual=*/false);
8232 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
8233 CXXBasePath &Path = Paths.front();
8234 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8235 B != BEnd; ++B)
8236 Comps.push_back(OffsetOfNode(B->Base));
8239 if (IndirectMemberDecl) {
8240 for (IndirectFieldDecl::chain_iterator FI =
8241 IndirectMemberDecl->chain_begin(),
8242 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8243 assert(isa<FieldDecl>(*FI));
8244 Comps.push_back(OffsetOfNode(OC.LocStart,
8245 cast<FieldDecl>(*FI), OC.LocEnd));
8247 } else
8248 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
8250 CurrentType = MemberDecl->getType().getNonReferenceType();
8253 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8254 TInfo, Comps.data(), Comps.size(),
8255 Exprs.data(), Exprs.size(), RParenLoc));
8258 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
8259 SourceLocation BuiltinLoc,
8260 SourceLocation TypeLoc,
8261 ParsedType argty,
8262 OffsetOfComponent *CompPtr,
8263 unsigned NumComponents,
8264 SourceLocation RPLoc) {
8266 TypeSourceInfo *ArgTInfo;
8267 QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
8268 if (ArgTy.isNull())
8269 return ExprError();
8271 if (!ArgTInfo)
8272 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8274 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
8275 RPLoc);
8279 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
8280 Expr *CondExpr,
8281 Expr *LHSExpr, Expr *RHSExpr,
8282 SourceLocation RPLoc) {
8283 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8285 ExprValueKind VK = VK_RValue;
8286 ExprObjectKind OK = OK_Ordinary;
8287 QualType resType;
8288 bool ValueDependent = false;
8289 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
8290 resType = Context.DependentTy;
8291 ValueDependent = true;
8292 } else {
8293 // The conditional expression is required to be a constant expression.
8294 llvm::APSInt condEval(32);
8295 SourceLocation ExpLoc;
8296 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
8297 return ExprError(Diag(ExpLoc,
8298 diag::err_typecheck_choose_expr_requires_constant)
8299 << CondExpr->getSourceRange());
8301 // If the condition is > zero, then the AST type is the same as the LSHExpr.
8302 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8304 resType = ActiveExpr->getType();
8305 ValueDependent = ActiveExpr->isValueDependent();
8306 VK = ActiveExpr->getValueKind();
8307 OK = ActiveExpr->getObjectKind();
8310 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
8311 resType, VK, OK, RPLoc,
8312 resType->isDependentType(),
8313 ValueDependent));
8316 //===----------------------------------------------------------------------===//
8317 // Clang Extensions.
8318 //===----------------------------------------------------------------------===//
8320 /// ActOnBlockStart - This callback is invoked when a block literal is started.
8321 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
8322 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8323 PushBlockScope(BlockScope, Block);
8324 CurContext->addDecl(Block);
8325 if (BlockScope)
8326 PushDeclContext(BlockScope, Block);
8327 else
8328 CurContext = Block;
8331 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
8332 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
8333 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
8334 BlockScopeInfo *CurBlock = getCurBlock();
8336 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
8337 QualType T = Sig->getType();
8339 // GetTypeForDeclarator always produces a function type for a block
8340 // literal signature. Furthermore, it is always a FunctionProtoType
8341 // unless the function was written with a typedef.
8342 assert(T->isFunctionType() &&
8343 "GetTypeForDeclarator made a non-function block signature");
8345 // Look for an explicit signature in that function type.
8346 FunctionProtoTypeLoc ExplicitSignature;
8348 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8349 if (isa<FunctionProtoTypeLoc>(tmp)) {
8350 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8352 // Check whether that explicit signature was synthesized by
8353 // GetTypeForDeclarator. If so, don't save that as part of the
8354 // written signature.
8355 if (ExplicitSignature.getLParenLoc() ==
8356 ExplicitSignature.getRParenLoc()) {
8357 // This would be much cheaper if we stored TypeLocs instead of
8358 // TypeSourceInfos.
8359 TypeLoc Result = ExplicitSignature.getResultLoc();
8360 unsigned Size = Result.getFullDataSize();
8361 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8362 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8364 ExplicitSignature = FunctionProtoTypeLoc();
8368 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8369 CurBlock->FunctionType = T;
8371 const FunctionType *Fn = T->getAs<FunctionType>();
8372 QualType RetTy = Fn->getResultType();
8373 bool isVariadic =
8374 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8376 CurBlock->TheDecl->setIsVariadic(isVariadic);
8378 // Don't allow returning a objc interface by value.
8379 if (RetTy->isObjCObjectType()) {
8380 Diag(ParamInfo.getSourceRange().getBegin(),
8381 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8382 return;
8385 // Context.DependentTy is used as a placeholder for a missing block
8386 // return type. TODO: what should we do with declarators like:
8387 // ^ * { ... }
8388 // If the answer is "apply template argument deduction"....
8389 if (RetTy != Context.DependentTy)
8390 CurBlock->ReturnType = RetTy;
8392 // Push block parameters from the declarator if we had them.
8393 llvm::SmallVector<ParmVarDecl*, 8> Params;
8394 if (ExplicitSignature) {
8395 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8396 ParmVarDecl *Param = ExplicitSignature.getArg(I);
8397 if (Param->getIdentifier() == 0 &&
8398 !Param->isImplicit() &&
8399 !Param->isInvalidDecl() &&
8400 !getLangOptions().CPlusPlus)
8401 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8402 Params.push_back(Param);
8405 // Fake up parameter variables if we have a typedef, like
8406 // ^ fntype { ... }
8407 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8408 for (FunctionProtoType::arg_type_iterator
8409 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8410 ParmVarDecl *Param =
8411 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8412 ParamInfo.getSourceRange().getBegin(),
8413 *I);
8414 Params.push_back(Param);
8418 // Set the parameters on the block decl.
8419 if (!Params.empty()) {
8420 CurBlock->TheDecl->setParams(Params.data(), Params.size());
8421 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8422 CurBlock->TheDecl->param_end(),
8423 /*CheckParameterNames=*/false);
8426 // Finally we can process decl attributes.
8427 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
8429 if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
8430 Diag(ParamInfo.getAttributes()->getLoc(),
8431 diag::warn_attribute_sentinel_not_variadic) << 1;
8432 // FIXME: remove the attribute.
8435 // Put the parameter variables in scope. We can bail out immediately
8436 // if we don't have any.
8437 if (Params.empty())
8438 return;
8440 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
8441 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8442 (*AI)->setOwningFunction(CurBlock->TheDecl);
8444 // If this has an identifier, add it to the scope stack.
8445 if ((*AI)->getIdentifier()) {
8446 CheckShadow(CurBlock->TheScope, *AI);
8448 PushOnScopeChains(*AI, CurBlock->TheScope);
8453 /// ActOnBlockError - If there is an error parsing a block, this callback
8454 /// is invoked to pop the information about the block from the action impl.
8455 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
8456 // Pop off CurBlock, handle nested blocks.
8457 PopDeclContext();
8458 PopFunctionOrBlockScope();
8461 /// ActOnBlockStmtExpr - This is called when the body of a block statement
8462 /// literal was successfully completed. ^(int x){...}
8463 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
8464 Stmt *Body, Scope *CurScope) {
8465 // If blocks are disabled, emit an error.
8466 if (!LangOpts.Blocks)
8467 Diag(CaretLoc, diag::err_blocks_disable);
8469 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
8471 PopDeclContext();
8473 QualType RetTy = Context.VoidTy;
8474 if (!BSI->ReturnType.isNull())
8475 RetTy = BSI->ReturnType;
8477 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
8478 QualType BlockTy;
8480 // If the user wrote a function type in some form, try to use that.
8481 if (!BSI->FunctionType.isNull()) {
8482 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8484 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8485 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8487 // Turn protoless block types into nullary block types.
8488 if (isa<FunctionNoProtoType>(FTy)) {
8489 FunctionProtoType::ExtProtoInfo EPI;
8490 EPI.ExtInfo = Ext;
8491 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8493 // Otherwise, if we don't need to change anything about the function type,
8494 // preserve its sugar structure.
8495 } else if (FTy->getResultType() == RetTy &&
8496 (!NoReturn || FTy->getNoReturnAttr())) {
8497 BlockTy = BSI->FunctionType;
8499 // Otherwise, make the minimal modifications to the function type.
8500 } else {
8501 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
8502 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8503 EPI.TypeQuals = 0; // FIXME: silently?
8504 EPI.ExtInfo = Ext;
8505 BlockTy = Context.getFunctionType(RetTy,
8506 FPT->arg_type_begin(),
8507 FPT->getNumArgs(),
8508 EPI);
8511 // If we don't have a function type, just build one from nothing.
8512 } else {
8513 FunctionProtoType::ExtProtoInfo EPI;
8514 EPI.ExtInfo = FunctionType::ExtInfo(NoReturn, 0, CC_Default);
8515 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8518 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8519 BSI->TheDecl->param_end());
8520 BlockTy = Context.getBlockPointerType(BlockTy);
8522 // If needed, diagnose invalid gotos and switches in the block.
8523 if (getCurFunction()->NeedsScopeChecking() && !hasAnyErrorsInThisFunction())
8524 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
8526 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
8528 bool Good = true;
8529 // Check goto/label use.
8530 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
8531 I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
8532 LabelStmt *L = I->second;
8534 // Verify that we have no forward references left. If so, there was a goto
8535 // or address of a label taken, but no definition of it.
8536 if (L->getSubStmt() != 0) {
8537 if (!L->isUsed())
8538 Diag(L->getIdentLoc(), diag::warn_unused_label) << L->getName();
8539 continue;
8542 // Emit error.
8543 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
8544 Good = false;
8546 if (!Good) {
8547 PopFunctionOrBlockScope();
8548 return ExprError();
8551 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
8552 BSI->hasBlockDeclRefExprs);
8554 // Issue any analysis-based warnings.
8555 const sema::AnalysisBasedWarnings::Policy &WP =
8556 AnalysisWarnings.getDefaultPolicy();
8557 AnalysisWarnings.IssueWarnings(WP, Result);
8559 PopFunctionOrBlockScope();
8560 return Owned(Result);
8563 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
8564 Expr *expr, ParsedType type,
8565 SourceLocation RPLoc) {
8566 TypeSourceInfo *TInfo;
8567 GetTypeFromParser(type, &TInfo);
8568 return BuildVAArgExpr(BuiltinLoc, expr, TInfo, RPLoc);
8571 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
8572 Expr *E, TypeSourceInfo *TInfo,
8573 SourceLocation RPLoc) {
8574 Expr *OrigExpr = E;
8576 // Get the va_list type
8577 QualType VaListType = Context.getBuiltinVaListType();
8578 if (VaListType->isArrayType()) {
8579 // Deal with implicit array decay; for example, on x86-64,
8580 // va_list is an array, but it's supposed to decay to
8581 // a pointer for va_arg.
8582 VaListType = Context.getArrayDecayedType(VaListType);
8583 // Make sure the input expression also decays appropriately.
8584 UsualUnaryConversions(E);
8585 } else {
8586 // Otherwise, the va_list argument must be an l-value because
8587 // it is modified by va_arg.
8588 if (!E->isTypeDependent() &&
8589 CheckForModifiableLvalue(E, BuiltinLoc, *this))
8590 return ExprError();
8593 if (!E->isTypeDependent() &&
8594 !Context.hasSameType(VaListType, E->getType())) {
8595 return ExprError(Diag(E->getLocStart(),
8596 diag::err_first_argument_to_va_arg_not_of_type_va_list)
8597 << OrigExpr->getType() << E->getSourceRange());
8600 // FIXME: Check that type is complete/non-abstract
8601 // FIXME: Warn if a non-POD type is passed in.
8603 QualType T = TInfo->getType().getNonLValueExprType(Context);
8604 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
8607 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
8608 // The type of __null will be int or long, depending on the size of
8609 // pointers on the target.
8610 QualType Ty;
8611 unsigned pw = Context.Target.getPointerWidth(0);
8612 if (pw == Context.Target.getIntWidth())
8613 Ty = Context.IntTy;
8614 else if (pw == Context.Target.getLongWidth())
8615 Ty = Context.LongTy;
8616 else if (pw == Context.Target.getLongLongWidth())
8617 Ty = Context.LongLongTy;
8618 else {
8619 assert(!"I don't know size of pointer!");
8620 Ty = Context.IntTy;
8623 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
8626 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
8627 Expr *SrcExpr, FixItHint &Hint) {
8628 if (!SemaRef.getLangOptions().ObjC1)
8629 return;
8631 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8632 if (!PT)
8633 return;
8635 // Check if the destination is of type 'id'.
8636 if (!PT->isObjCIdType()) {
8637 // Check if the destination is the 'NSString' interface.
8638 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8639 if (!ID || !ID->getIdentifier()->isStr("NSString"))
8640 return;
8643 // Strip off any parens and casts.
8644 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8645 if (!SL || SL->isWide())
8646 return;
8648 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
8651 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8652 SourceLocation Loc,
8653 QualType DstType, QualType SrcType,
8654 Expr *SrcExpr, AssignmentAction Action,
8655 bool *Complained) {
8656 if (Complained)
8657 *Complained = false;
8659 // Decode the result (notice that AST's are still created for extensions).
8660 bool isInvalid = false;
8661 unsigned DiagKind;
8662 FixItHint Hint;
8664 switch (ConvTy) {
8665 default: assert(0 && "Unknown conversion type");
8666 case Compatible: return false;
8667 case PointerToInt:
8668 DiagKind = diag::ext_typecheck_convert_pointer_int;
8669 break;
8670 case IntToPointer:
8671 DiagKind = diag::ext_typecheck_convert_int_pointer;
8672 break;
8673 case IncompatiblePointer:
8674 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
8675 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8676 break;
8677 case IncompatiblePointerSign:
8678 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8679 break;
8680 case FunctionVoidPointer:
8681 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8682 break;
8683 case CompatiblePointerDiscardsQualifiers:
8684 // If the qualifiers lost were because we were applying the
8685 // (deprecated) C++ conversion from a string literal to a char*
8686 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
8687 // Ideally, this check would be performed in
8688 // checkPointerTypesForAssignment. However, that would require a
8689 // bit of refactoring (so that the second argument is an
8690 // expression, rather than a type), which should be done as part
8691 // of a larger effort to fix checkPointerTypesForAssignment for
8692 // C++ semantics.
8693 if (getLangOptions().CPlusPlus &&
8694 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8695 return false;
8696 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8697 break;
8698 case IncompatibleNestedPointerQualifiers:
8699 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
8700 break;
8701 case IntToBlockPointer:
8702 DiagKind = diag::err_int_to_block_pointer;
8703 break;
8704 case IncompatibleBlockPointer:
8705 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
8706 break;
8707 case IncompatibleObjCQualifiedId:
8708 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
8709 // it can give a more specific diagnostic.
8710 DiagKind = diag::warn_incompatible_qualified_id;
8711 break;
8712 case IncompatibleVectors:
8713 DiagKind = diag::warn_incompatible_vectors;
8714 break;
8715 case Incompatible:
8716 DiagKind = diag::err_typecheck_convert_incompatible;
8717 isInvalid = true;
8718 break;
8721 QualType FirstType, SecondType;
8722 switch (Action) {
8723 case AA_Assigning:
8724 case AA_Initializing:
8725 // The destination type comes first.
8726 FirstType = DstType;
8727 SecondType = SrcType;
8728 break;
8730 case AA_Returning:
8731 case AA_Passing:
8732 case AA_Converting:
8733 case AA_Sending:
8734 case AA_Casting:
8735 // The source type comes first.
8736 FirstType = SrcType;
8737 SecondType = DstType;
8738 break;
8741 Diag(Loc, DiagKind) << FirstType << SecondType << Action
8742 << SrcExpr->getSourceRange() << Hint;
8743 if (Complained)
8744 *Complained = true;
8745 return isInvalid;
8748 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
8749 llvm::APSInt ICEResult;
8750 if (E->isIntegerConstantExpr(ICEResult, Context)) {
8751 if (Result)
8752 *Result = ICEResult;
8753 return false;
8756 Expr::EvalResult EvalResult;
8758 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
8759 EvalResult.HasSideEffects) {
8760 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
8762 if (EvalResult.Diag) {
8763 // We only show the note if it's not the usual "invalid subexpression"
8764 // or if it's actually in a subexpression.
8765 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
8766 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
8767 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8770 return true;
8773 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
8774 E->getSourceRange();
8776 if (EvalResult.Diag &&
8777 Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
8778 != Diagnostic::Ignored)
8779 Diag(EvalResult.DiagLoc, EvalResult.Diag);
8781 if (Result)
8782 *Result = EvalResult.Val.getInt();
8783 return false;
8786 void
8787 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
8788 ExprEvalContexts.push_back(
8789 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
8792 void
8793 Sema::PopExpressionEvaluationContext() {
8794 // Pop the current expression evaluation context off the stack.
8795 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
8796 ExprEvalContexts.pop_back();
8798 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
8799 if (Rec.PotentiallyReferenced) {
8800 // Mark any remaining declarations in the current position of the stack
8801 // as "referenced". If they were not meant to be referenced, semantic
8802 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
8803 for (PotentiallyReferencedDecls::iterator
8804 I = Rec.PotentiallyReferenced->begin(),
8805 IEnd = Rec.PotentiallyReferenced->end();
8806 I != IEnd; ++I)
8807 MarkDeclarationReferenced(I->first, I->second);
8810 if (Rec.PotentiallyDiagnosed) {
8811 // Emit any pending diagnostics.
8812 for (PotentiallyEmittedDiagnostics::iterator
8813 I = Rec.PotentiallyDiagnosed->begin(),
8814 IEnd = Rec.PotentiallyDiagnosed->end();
8815 I != IEnd; ++I)
8816 Diag(I->first, I->second);
8820 // When are coming out of an unevaluated context, clear out any
8821 // temporaries that we may have created as part of the evaluation of
8822 // the expression in that context: they aren't relevant because they
8823 // will never be constructed.
8824 if (Rec.Context == Unevaluated &&
8825 ExprTemporaries.size() > Rec.NumTemporaries)
8826 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
8827 ExprTemporaries.end());
8829 // Destroy the popped expression evaluation record.
8830 Rec.Destroy();
8833 /// \brief Note that the given declaration was referenced in the source code.
8835 /// This routine should be invoke whenever a given declaration is referenced
8836 /// in the source code, and where that reference occurred. If this declaration
8837 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
8838 /// C99 6.9p3), then the declaration will be marked as used.
8840 /// \param Loc the location where the declaration was referenced.
8842 /// \param D the declaration that has been referenced by the source code.
8843 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
8844 assert(D && "No declaration?");
8846 if (D->isUsed(false))
8847 return;
8849 // Mark a parameter or variable declaration "used", regardless of whether we're in a
8850 // template or not. The reason for this is that unevaluated expressions
8851 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
8852 // -Wunused-parameters)
8853 if (isa<ParmVarDecl>(D) ||
8854 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
8855 D->setUsed();
8856 return;
8859 if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
8860 return;
8862 // Do not mark anything as "used" within a dependent context; wait for
8863 // an instantiation.
8864 if (CurContext->isDependentContext())
8865 return;
8867 switch (ExprEvalContexts.back().Context) {
8868 case Unevaluated:
8869 // We are in an expression that is not potentially evaluated; do nothing.
8870 return;
8872 case PotentiallyEvaluated:
8873 // We are in a potentially-evaluated expression, so this declaration is
8874 // "used"; handle this below.
8875 break;
8877 case PotentiallyPotentiallyEvaluated:
8878 // We are in an expression that may be potentially evaluated; queue this
8879 // declaration reference until we know whether the expression is
8880 // potentially evaluated.
8881 ExprEvalContexts.back().addReferencedDecl(Loc, D);
8882 return;
8884 case PotentiallyEvaluatedIfUsed:
8885 // Referenced declarations will only be used if the construct in the
8886 // containing expression is used.
8887 return;
8890 // Note that this declaration has been used.
8891 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
8892 unsigned TypeQuals;
8893 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
8894 if (Constructor->getParent()->hasTrivialConstructor())
8895 return;
8896 if (!Constructor->isUsed(false))
8897 DefineImplicitDefaultConstructor(Loc, Constructor);
8898 } else if (Constructor->isImplicit() &&
8899 Constructor->isCopyConstructor(TypeQuals)) {
8900 if (!Constructor->isUsed(false))
8901 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
8904 MarkVTableUsed(Loc, Constructor->getParent());
8905 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
8906 if (Destructor->isImplicit() && !Destructor->isUsed(false))
8907 DefineImplicitDestructor(Loc, Destructor);
8908 if (Destructor->isVirtual())
8909 MarkVTableUsed(Loc, Destructor->getParent());
8910 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
8911 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
8912 MethodDecl->getOverloadedOperator() == OO_Equal) {
8913 if (!MethodDecl->isUsed(false))
8914 DefineImplicitCopyAssignment(Loc, MethodDecl);
8915 } else if (MethodDecl->isVirtual())
8916 MarkVTableUsed(Loc, MethodDecl->getParent());
8918 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
8919 // Implicit instantiation of function templates and member functions of
8920 // class templates.
8921 if (Function->isImplicitlyInstantiable()) {
8922 bool AlreadyInstantiated = false;
8923 if (FunctionTemplateSpecializationInfo *SpecInfo
8924 = Function->getTemplateSpecializationInfo()) {
8925 if (SpecInfo->getPointOfInstantiation().isInvalid())
8926 SpecInfo->setPointOfInstantiation(Loc);
8927 else if (SpecInfo->getTemplateSpecializationKind()
8928 == TSK_ImplicitInstantiation)
8929 AlreadyInstantiated = true;
8930 } else if (MemberSpecializationInfo *MSInfo
8931 = Function->getMemberSpecializationInfo()) {
8932 if (MSInfo->getPointOfInstantiation().isInvalid())
8933 MSInfo->setPointOfInstantiation(Loc);
8934 else if (MSInfo->getTemplateSpecializationKind()
8935 == TSK_ImplicitInstantiation)
8936 AlreadyInstantiated = true;
8939 if (!AlreadyInstantiated) {
8940 if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
8941 cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
8942 PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
8943 Loc));
8944 else
8945 PendingInstantiations.push_back(std::make_pair(Function, Loc));
8947 } else // Walk redefinitions, as some of them may be instantiable.
8948 for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
8949 e(Function->redecls_end()); i != e; ++i) {
8950 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
8951 MarkDeclarationReferenced(Loc, *i);
8954 // FIXME: keep track of references to static functions
8956 // Recursive functions should be marked when used from another function.
8957 if (CurContext != Function)
8958 Function->setUsed(true);
8960 return;
8963 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
8964 // Implicit instantiation of static data members of class templates.
8965 if (Var->isStaticDataMember() &&
8966 Var->getInstantiatedFromStaticDataMember()) {
8967 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
8968 assert(MSInfo && "Missing member specialization information?");
8969 if (MSInfo->getPointOfInstantiation().isInvalid() &&
8970 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
8971 MSInfo->setPointOfInstantiation(Loc);
8972 PendingInstantiations.push_back(std::make_pair(Var, Loc));
8976 // FIXME: keep track of references to static data?
8978 D->setUsed(true);
8979 return;
8983 namespace {
8984 // Mark all of the declarations referenced
8985 // FIXME: Not fully implemented yet! We need to have a better understanding
8986 // of when we're entering
8987 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
8988 Sema &S;
8989 SourceLocation Loc;
8991 public:
8992 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
8994 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
8996 bool TraverseTemplateArgument(const TemplateArgument &Arg);
8997 bool TraverseRecordType(RecordType *T);
9001 bool MarkReferencedDecls::TraverseTemplateArgument(
9002 const TemplateArgument &Arg) {
9003 if (Arg.getKind() == TemplateArgument::Declaration) {
9004 S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9007 return Inherited::TraverseTemplateArgument(Arg);
9010 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
9011 if (ClassTemplateSpecializationDecl *Spec
9012 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9013 const TemplateArgumentList &Args = Spec->getTemplateArgs();
9014 return TraverseTemplateArguments(Args.data(), Args.size());
9017 return true;
9020 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9021 MarkReferencedDecls Marker(*this, Loc);
9022 Marker.TraverseType(Context.getCanonicalType(T));
9025 namespace {
9026 /// \brief Helper class that marks all of the declarations referenced by
9027 /// potentially-evaluated subexpressions as "referenced".
9028 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9029 Sema &S;
9031 public:
9032 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9034 explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9036 void VisitDeclRefExpr(DeclRefExpr *E) {
9037 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9040 void VisitMemberExpr(MemberExpr *E) {
9041 S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
9042 Inherited::VisitMemberExpr(E);
9045 void VisitCXXNewExpr(CXXNewExpr *E) {
9046 if (E->getConstructor())
9047 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9048 if (E->getOperatorNew())
9049 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9050 if (E->getOperatorDelete())
9051 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9052 Inherited::VisitCXXNewExpr(E);
9055 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9056 if (E->getOperatorDelete())
9057 S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9058 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9059 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9060 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9061 S.MarkDeclarationReferenced(E->getLocStart(),
9062 S.LookupDestructor(Record));
9065 Inherited::VisitCXXDeleteExpr(E);
9068 void VisitCXXConstructExpr(CXXConstructExpr *E) {
9069 S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9070 Inherited::VisitCXXConstructExpr(E);
9073 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9074 S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9077 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9078 Visit(E->getExpr());
9083 /// \brief Mark any declarations that appear within this expression or any
9084 /// potentially-evaluated subexpressions as "referenced".
9085 void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9086 EvaluatedExprMarker(*this).Visit(E);
9089 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
9090 /// of the program being compiled.
9092 /// This routine emits the given diagnostic when the code currently being
9093 /// type-checked is "potentially evaluated", meaning that there is a
9094 /// possibility that the code will actually be executable. Code in sizeof()
9095 /// expressions, code used only during overload resolution, etc., are not
9096 /// potentially evaluated. This routine will suppress such diagnostics or,
9097 /// in the absolutely nutty case of potentially potentially evaluated
9098 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
9099 /// later.
9101 /// This routine should be used for all diagnostics that describe the run-time
9102 /// behavior of a program, such as passing a non-POD value through an ellipsis.
9103 /// Failure to do so will likely result in spurious diagnostics or failures
9104 /// during overload resolution or within sizeof/alignof/typeof/typeid.
9105 bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
9106 const PartialDiagnostic &PD) {
9107 switch (ExprEvalContexts.back().Context ) {
9108 case Unevaluated:
9109 // The argument will never be evaluated, so don't complain.
9110 break;
9112 case PotentiallyEvaluated:
9113 case PotentiallyEvaluatedIfUsed:
9114 Diag(Loc, PD);
9115 return true;
9117 case PotentiallyPotentiallyEvaluated:
9118 ExprEvalContexts.back().addDiagnostic(Loc, PD);
9119 break;
9122 return false;
9125 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9126 CallExpr *CE, FunctionDecl *FD) {
9127 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9128 return false;
9130 PartialDiagnostic Note =
9131 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9132 << FD->getDeclName() : PDiag();
9133 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
9135 if (RequireCompleteType(Loc, ReturnType,
9136 FD ?
9137 PDiag(diag::err_call_function_incomplete_return)
9138 << CE->getSourceRange() << FD->getDeclName() :
9139 PDiag(diag::err_call_incomplete_return)
9140 << CE->getSourceRange(),
9141 std::make_pair(NoteLoc, Note)))
9142 return true;
9144 return false;
9147 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
9148 // will prevent this condition from triggering, which is what we want.
9149 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9150 SourceLocation Loc;
9152 unsigned diagnostic = diag::warn_condition_is_assignment;
9153 bool IsOrAssign = false;
9155 if (isa<BinaryOperator>(E)) {
9156 BinaryOperator *Op = cast<BinaryOperator>(E);
9157 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
9158 return;
9160 IsOrAssign = Op->getOpcode() == BO_OrAssign;
9162 // Greylist some idioms by putting them into a warning subcategory.
9163 if (ObjCMessageExpr *ME
9164 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9165 Selector Sel = ME->getSelector();
9167 // self = [<foo> init...]
9168 if (isSelfExpr(Op->getLHS())
9169 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
9170 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9172 // <foo> = [<bar> nextObject]
9173 else if (Sel.isUnarySelector() &&
9174 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
9175 diagnostic = diag::warn_condition_is_idiomatic_assignment;
9178 Loc = Op->getOperatorLoc();
9179 } else if (isa<CXXOperatorCallExpr>(E)) {
9180 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
9181 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
9182 return;
9184 IsOrAssign = Op->getOperator() == OO_PipeEqual;
9185 Loc = Op->getOperatorLoc();
9186 } else {
9187 // Not an assignment.
9188 return;
9191 SourceLocation Open = E->getSourceRange().getBegin();
9192 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9194 Diag(Loc, diagnostic) << E->getSourceRange();
9196 if (IsOrAssign)
9197 Diag(Loc, diag::note_condition_or_assign_to_comparison)
9198 << FixItHint::CreateReplacement(Loc, "!=");
9199 else
9200 Diag(Loc, diag::note_condition_assign_to_comparison)
9201 << FixItHint::CreateReplacement(Loc, "==");
9203 Diag(Loc, diag::note_condition_assign_silence)
9204 << FixItHint::CreateInsertion(Open, "(")
9205 << FixItHint::CreateInsertion(Close, ")");
9208 bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
9209 DiagnoseAssignmentAsCondition(E);
9211 if (!E->isTypeDependent()) {
9212 if (E->isBoundMemberFunction(Context))
9213 return Diag(E->getLocStart(), diag::err_invalid_use_of_bound_member_func)
9214 << E->getSourceRange();
9216 if (getLangOptions().CPlusPlus)
9217 return CheckCXXBooleanCondition(E); // C++ 6.4p4
9219 DefaultFunctionArrayLvalueConversion(E);
9221 QualType T = E->getType();
9222 if (!T->isScalarType()) // C99 6.8.4.1p1
9223 return Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9224 << T << E->getSourceRange();
9227 return false;
9230 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9231 Expr *Sub) {
9232 if (!Sub)
9233 return ExprError();
9235 if (CheckBooleanCondition(Sub, Loc))
9236 return ExprError();
9238 return Owned(Sub);
9241 /// Check for operands with placeholder types and complain if found.
9242 /// Returns true if there was an error and no recovery was possible.
9243 ExprResult Sema::CheckPlaceholderExpr(Expr *E, SourceLocation Loc) {
9244 const BuiltinType *BT = E->getType()->getAs<BuiltinType>();
9245 if (!BT || !BT->isPlaceholderType()) return Owned(E);
9247 // If this is overload, check for a single overload.
9248 if (BT->getKind() == BuiltinType::Overload) {
9249 if (FunctionDecl *Specialization
9250 = ResolveSingleFunctionTemplateSpecialization(E)) {
9251 // The access doesn't really matter in this case.
9252 DeclAccessPair Found = DeclAccessPair::make(Specialization,
9253 Specialization->getAccess());
9254 E = FixOverloadedFunctionReference(E, Found, Specialization);
9255 if (!E) return ExprError();
9256 return Owned(E);
9259 Diag(Loc, diag::err_ovl_unresolvable) << E->getSourceRange();
9260 return ExprError();
9263 // Otherwise it's a use of undeduced auto.
9264 assert(BT->getKind() == BuiltinType::UndeducedAuto);
9266 DeclRefExpr *DRE = cast<DeclRefExpr>(E->IgnoreParens());
9267 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
9268 << DRE->getDecl() << E->getSourceRange();
9269 return ExprError();